Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
//! # Position
//!
//! A [`Position`] is a complete chess game state: the [`Board`] of pieces,
//! the [`History`] (last move, castling rights, half-move clock, repetition
//! hashes), and the [`Color`] to move.
//!
//! Like [`Board`], [`Position`] is persistent and functional — builders and
//! [`Position::mve`] return new values rather than mutating in place.
//!
//! ## Building a position
//!
//! [`Position::new`] returns the standard starting position. Layer builders
//! to override pieces, side to move, or history:
//!
//! ```
//! # use ruchess::position::Position;
//! # use ruchess::color::Color;
//! # use ruchess::mve::Move;
//! let standard = Position::new();
//! assert_eq!(standard.color(), Color::White);
//! let moves = standard.valid_moves();
//! assert_eq!(moves.len(), 20);
//!
//! let black_to_move = Position::new().with_color(Color::Black);
//! assert_eq!(black_to_move.color(), Color::Black);
//! ```
//!
//! ## Generating moves
//!
//! [`Position::valid_moves`] returns every legal move;
//! [`Position::mve`] plays one and returns the resulting position:
//!
//! ```
//! # use ruchess::position::Position;
//! # use ruchess::square;
//! # use ruchess::color::Color;
//! let p = Position::new();
//! let next = p.mve(square::E2, square::E4, None).unwrap();
//! assert_eq!(next.color(), Color::Black);
//! assert!(next.board().is_occupied(square::E4));
//! ```
//!
//! Each move type also has a dedicated generator
//! ([`Position::pawn_moves`], [`Position::knight_moves`], …) that appends
//! into a caller owned buffer; together they partition [`Position::valid_moves`].

use crate::{
    attacks::ATTACKS,
    bitboard::Bitboard,
    board::Board,
    castles::Castles,
    color::Color,
    history::History,
    mve::Move,
    piece::Piece,
    ply::Ply,
    role::{PromotableRole, Role},
    side::Side,
    square::{self, Square},
    uci::Uci,
};

/// A complete chess game state — board, history, and side to move.
///
/// See the [module documentation](self) for an overview.
#[derive(Debug, Clone, PartialEq)]
pub struct Position {
    board: Board,
    history: History,
    color: Color,
    ply: Ply,
}

/// Token returned by [`Position::make`] that captures the prior position
/// state so [`Position::unmake`] can roll back exactly.
///
/// Stack-allocated, opaque to callers; size is dominated by the cached
/// `Board` (one `u64` per role/color bitboard).
#[derive(Debug, Clone)]
pub struct Undo {
    prior_board: Board,
    prior_castles: crate::castles::Castles,
    prior_unmoved_rooks: crate::unmoved_rooks::UnmovedRooks,
    prior_half_move_clock: crate::halfmoveclock::HalfMoveClock,
    prior_last_move: Option<Uci>,
    prior_position_hashes: crate::hash::PositionHash,
}

impl Position {
    /// Returns the standard chess starting position: pieces in their initial
    /// squares, all four castling rights, White to move, no en-passant target.
    ///
    /// # Example
    /// ```
    /// # use ruchess::position::Position;
    /// # use ruchess::color::Color;
    /// # use ruchess::mve::Move;
    /// let p = Position::new();
    /// assert_eq!(p.color(), Color::White);
    /// assert!(!p.is_check());
    /// let moves = p.valid_moves();
    /// assert_eq!(moves.len(), 20);
    /// ```
    pub fn new() -> Self {
        Self {
            board: Board::new(),
            history: History::new(),
            color: Color::White,
            ply: Ply::new(),
        }
    }

    /// Standard starting position with repetition tracking turned off.
    ///
    /// Use this for perft, fixed-depth search, and any workload that never
    /// queries [`History::is_threefold_repetition`] — it skips the Zobrist
    /// hash computation and the per-move `Vec<u8>` growth.
    ///
    /// See [`History::new_no_repetition`].
    pub fn new_no_repetition() -> Self {
        Self {
            board: Board::new(),
            history: History::new_no_repetition(),
            color: Color::White,
            ply: Ply::new(),
        }
    }

    /// Returns a copy of this position with repetition tracking disabled in
    /// its [`History`]. Useful after parsing a FEN to opt the resulting
    /// position chain out of Zobrist hashing.
    #[must_use]
    pub fn without_repetition(self) -> Self {
        Self {
            history: History {
                position_hashes: crate::hash::PositionHash::disabled(),
                ..self.history
            },
            ..self
        }
    }

    /// Returns a new position with the given [`Board`], preserving the
    /// existing color and history.
    ///
    /// # Example
    /// ```
    /// # use ruchess::position::Position;
    /// # use ruchess::board::Board;
    /// # use ruchess::square;
    /// let p = Position::new().with_board(Board::EMPTY);
    /// assert!(!p.board().is_occupied(square::E1));
    /// ```
    pub fn with_board(self, board: Board) -> Self {
        Self { board, ..self }
    }

    /// Returns a new position with the given side to move.
    ///
    /// # Example
    /// ```
    /// # use ruchess::position::Position;
    /// # use ruchess::color::Color;
    /// let p = Position::new().with_color(Color::Black);
    /// assert_eq!(p.color(), Color::Black);
    /// ```
    pub fn with_color(self, color: Color) -> Self {
        Self { color, ..self }
    }

    /// Returns a new position with the opposite side to move.
    ///
    /// # Example
    /// ```
    /// # use ruchess::position::Position;
    /// # use ruchess::color::Color;
    /// let p = Position::new();
    /// assert_eq!(p.color(), Color::White);
    /// let q = p.change_color();
    /// assert_eq!(q.color(), Color::Black);
    /// ```
    pub fn change_color(self) -> Self {
        let color = self.color;
        self.with_color(color.opponent())
    }

    /// Returns a new position with the given [`History`], preserving board
    /// and color.
    ///
    /// # Example
    /// ```
    /// # use ruchess::position::Position;
    /// # use ruchess::history::History;
    /// let p = Position::new().with_history(History::new());
    /// assert!(p.history().last_move.is_none());
    /// ```
    pub fn with_history(self, history: History) -> Self {
        Self { history, ..self }
    }

    /// Returns a new position with the given castling rights, leaving the
    /// rest of [`History`] (last move, half-move clock, …) unchanged.
    ///
    /// # Example
    /// ```
    /// # use ruchess::position::Position;
    /// # use ruchess::castles::Castles;
    /// let p = Position::new().with_castles(Castles::new(false, false, false, false));
    /// assert!(p.history().castles.is_empty());
    /// ```
    pub fn with_castles(self, castles: Castles) -> Self {
        Self {
            history: self.history.with_castles(castles),
            ..self
        }
    }

    /// Returns a new position with the ply, leaving the
    /// rest of [`Position`] unchanged.
    ///
    /// # Example
    /// ```
    /// # use ruchess::position::Position;
    /// # use ruchess::ply::Ply;
    /// let p = Position::new().with_ply(Ply::new());
    /// assert_eq!(p.ply().full_move_number(), 1);
    /// ```
    pub fn with_ply(self, ply: Ply) -> Self {
        Self { ply, ..self }
    }

    /// Returns a new position with `f` applied to the current [`History`].
    ///
    /// `f` receives a reference and returns a fresh value; this is a thin
    /// adapter for functional updates that aren't covered by [`Self::with_castles`]
    /// or [`Self::with_history`].
    ///
    /// # Example
    /// ```
    /// # use ruchess::position::Position;
    /// # use ruchess::castles::Castles;
    /// let p = Position::new().update_history(|h| {
    ///     h.clone().with_castles(Castles::new(true, false, false, false))
    /// });
    /// assert!(p.history().castles.white_king_side());
    /// assert!(!p.history().castles.white_queen_side());
    /// ```
    pub fn update_history<F>(self, f: F) -> Self
    where
        F: FnOnce(&History) -> History,
    {
        Self {
            history: f(&self.history),
            ..self
        }
    }

    /// Plays the move from `orig` to `dest`. Returns the resulting position,
    /// or `None` if no legal move connects those squares.
    ///
    /// On success the side to move is flipped and the [`History`] is updated
    /// (last move, castling rights, half-move clock, position hashes).
    ///
    /// # Example
    /// ```
    /// # use ruchess::position::Position;
    /// # use ruchess::square;
    /// # use ruchess::color::Color;
    /// let p = Position::new();
    /// let next = p.mve(square::E2, square::E4, None).unwrap();
    /// assert_eq!(next.color(), Color::Black);
    /// assert!(next.board().is_occupied(square::E4));
    /// assert!(!next.board().is_occupied(square::E2));
    ///
    /// // Illegal move → None.
    /// assert!(Position::new().mve(square::E2, square::E5, None).is_none());
    /// ```
    pub fn mve(
        mut self,
        orig: Square,
        dest: Square,
        promotion: Option<PromotableRole>,
    ) -> Option<Self> {
        let buf = self.valid_moves();
        let mve = *buf
            .iter()
            .find(|m| m.orig == orig && m.dest == dest && m.promotion == promotion)?;
        self.make(&mve);
        Some(self)
    }

    /// Plays `mve` in place and returns an [`Undo`] token. Pair with
    /// [`Self::unmake`] to step back.
    ///
    /// `mve` must be a legal move for this position. Behavior is undefined
    /// otherwise (typically: an invalid board state).
    ///
    /// The hot path used by perft and search: no allocation, no clone of
    /// the position, the move's already-built `after` board is installed
    /// directly, and the prior state is stashed in `Undo`.
    ///
    /// # Example
    /// ```
    /// # use ruchess::position::Position;
    /// # use ruchess::color::Color;
    /// # use ruchess::mve::Move;
    /// let mut p = Position::new();
    /// let moves = p.valid_moves();
    /// let m = moves[0];
    /// let undo = p.make(&m);
    /// assert_eq!(p.color(), Color::Black);
    /// p.unmake(undo);
    /// assert_eq!(p.color(), Color::White);
    /// ```
    pub fn make(&mut self, mve: &Move) -> Undo {
        let prior_board = self.board;
        let prior_castles = self.history.castles;
        let prior_unmoved_rooks = self.history.unmoved_rooks;
        let prior_half_move_clock = self.history.half_move_clock;
        let prior_last_move = self.history.last_move;

        // Compute the new hash trail before mutating board/color (the hash
        // depends on the prior position state). For Disabled, no work happens.
        let prior_position_hashes = std::mem::replace(
            &mut self.history.position_hashes,
            crate::hash::PositionHash::Disabled,
        );
        let new_hashes = if prior_position_hashes.is_disabled() {
            crate::hash::PositionHash::Disabled
        } else {
            let entry =
                crate::hash::PositionHash::from_hash(crate::hash::Hash::from_position(self));
            entry.combine(&prior_position_hashes)
        };
        self.history.position_hashes = new_hashes;

        // Apply the rest of the history update in place.
        self.history.last_move = Some((*mve).into());
        self.history.castles = self.history.castles.update(mve);
        self.history.unmoved_rooks = self.history.unmoved_rooks.update(mve);
        self.history.half_move_clock = if mve.piece.role == Role::Pawn || mve.capture.is_some() {
            self.history.half_move_clock.reset()
        } else {
            self.history.half_move_clock.incr()
        };

        // Apply the move's bit toggles to the board, then advance side/ply.
        apply_move(&mut self.board, mve);
        self.color = self.color.opponent();
        self.ply = self.ply.incr();

        Undo {
            prior_board,
            prior_castles,
            prior_unmoved_rooks,
            prior_half_move_clock,
            prior_last_move,
            prior_position_hashes,
        }
    }

    /// Reverses the most recent [`Self::make`], restoring the position
    /// exactly to its prior state.
    ///
    /// `undo` must be the value returned by the matching `make` call; pairing
    /// it with anything else (or calling out of order) produces an invalid
    /// position.
    pub fn unmake(&mut self, undo: Undo) {
        self.ply = self.ply.decr();
        self.color = self.color.opponent();
        self.board = undo.prior_board;
        self.history.castles = undo.prior_castles;
        self.history.unmoved_rooks = undo.prior_unmoved_rooks;
        self.history.half_move_clock = undo.prior_half_move_clock;
        self.history.last_move = undo.prior_last_move;
        self.history.position_hashes = undo.prior_position_hashes;
    }

    /// Returns a reference to the underlying [`Board`].
    ///
    /// # Example
    /// ```
    /// # use ruchess::position::Position;
    /// # use ruchess::square;
    /// let p = Position::new();
    /// assert!(p.board().is_occupied(square::E1));
    /// ```
    pub fn board(&self) -> &Board {
        &self.board
    }

    /// Returns the side to move.
    ///
    /// # Example
    /// ```
    /// # use ruchess::position::Position;
    /// # use ruchess::color::Color;
    /// assert_eq!(Position::new().color(), Color::White);
    /// ```
    pub fn color(&self) -> Color {
        self.color
    }

    /// Returns a reference to the [`History`] — last move, castling rights,
    /// unmoved rooks, half-move clock, and position-hash trail.
    ///
    /// # Example
    /// ```
    /// # use ruchess::position::Position;
    /// let p = Position::new();
    /// assert!(p.history().last_move.is_none());
    /// assert!(p.history().castles.white_king_side());
    /// ```
    pub fn history(&self) -> &History {
        &self.history
    }

    /// Returns the current ply (number of half-moves played).
    pub fn ply(&self) -> Ply {
        self.ply
    }

    /// Returns `true` if the side to move is in check.
    ///
    /// # Example
    /// ```
    /// # use ruchess::position::Position;
    /// assert!(!Position::new().is_check());
    /// ```
    pub fn is_check(&self) -> bool {
        self.board.is_check(self.color)
    }

    /// Returns the en-passant target square if the previous move was a
    /// two-square pawn push, otherwise `None`.
    ///
    /// The target is the square the pushing pawn passed *over* — the square
    /// onto which a capturing pawn would land.
    ///
    /// # Example
    /// ```
    /// # use ruchess::position::Position;
    /// // No en-passant target before any move has been played.
    /// assert_eq!(Position::new().enpassant_square(), None);
    /// ```
    pub fn enpassant_square(&self) -> Option<Square> {
        self.history
            .last_move
            .and_then(|lm| potential_enpassant_sq(lm, self.board, self.color))
    }

    /// Returns all valid moves in this position.
    ///
    /// Calls each per-piece-type generator ([`Self::pawn_moves`],
    /// [`Self::enpassant_moves`], [`Self::king_moves`], …) in a fixed order,
    /// then retains only those that satisfy check/pin legality.
    ///
    /// # Example
    /// ```
    /// # use ruchess::position::Position;
    /// let moves = Position::new().valid_moves();
    /// assert_eq!(moves.len(), 20);
    /// ```
    pub fn valid_moves(&self) -> Vec<Move> {
        let mut buf = Vec::with_capacity(MAX_MOVES);
        self.pawn_moves(&mut buf);
        self.enpassant_moves(&mut buf);
        self.king_moves(&mut buf);
        self.knight_moves(&mut buf);
        self.bishop_moves(&mut buf);
        self.rook_moves(&mut buf);
        self.queen_moves(&mut buf);

        let ctx = LegalityContext::compute(self);
        let board = self.board;
        let color = self.color;
        buf.retain(|m| ctx.is_legal(m, board, color));
        buf
    }

    /// Returns `true` if at least one legal move exists from this position.
    ///
    /// # Example
    /// ```
    /// # use ruchess::position::Position;
    /// assert!(Position::new().has_moves());
    /// ```
    pub fn has_moves(&self) -> bool {
        !self.valid_moves().is_empty()
    }

    /// Returns every legal move originating from `orig` to `buf`.
    ///
    /// # Example
    /// ```
    /// # use ruchess::position::Position;
    /// # use ruchess::square;
    /// # use ruchess::mve::Move;
    /// let p = Position::new();
    /// // The E2 pawn has two pushes (one and two squares).
    /// let moves = p.valid_moves_at(square::E2);
    /// assert_eq!(moves.len(), 2);
    ///
    /// // The A1 rook is locked in by its own pieces.
    /// let moves = p.valid_moves_at(square::A1);
    /// assert_eq!(moves.len(), 0);
    /// ```
    pub fn valid_moves_at(&self, orig: Square) -> Vec<Move> {
        let mut buf = self.valid_moves();
        buf.retain(|m| m.orig == orig);
        buf
    }

    /// Appends all pseudo-legal pawn moves to `buf`: pushes, double pushes,
    /// captures, and promotions. En-passant captures are emitted separately
    /// by [`Self::enpassant_moves`].
    ///
    /// "Pseudo-legal" — moves that leave the king in check are *not* filtered
    /// here. [`Self::valid_moves`] applies that filter once over the full
    /// pseudo-legal set.
    ///
    /// # Example
    /// ```
    /// # use ruchess::position::Position;
    /// # use ruchess::mve::Move;
    /// // 8 pawns × (single + double) = 16 from the starting position.
    /// let mut moves: Vec<Move> = Vec::new();
    /// Position::new().pawn_moves(&mut moves);
    /// assert_eq!(moves.len(), 16);
    /// ```
    pub fn pawn_moves(&self, buf: &mut Vec<Move>) {
        let pawns = self.board.bypiece(Piece {
            role: Role::Pawn,
            color: self.color,
        });
        let them = self.board.bycolor(self.color.opponent());

        // Captures.
        for from in pawns {
            for to in ATTACKS.pawn_attacks(self.color, from) & them {
                self.push_pawn_moves(buf, from, to, true);
            }
        }

        // Single pushes.
        let singles = !self.board.occupied()
            & (match self.color {
                Color::White => (self.board.white() & pawns) << 8,
                Color::Black => (self.board.black() & pawns) >> 8,
            });
        for to in singles {
            let from = Square(match self.color {
                Color::White => to.0 - 8,
                Color::Black => to.0 + 8,
            });
            self.push_pawn_moves(buf, from, to, false);
        }

        // Double pushes.
        let doubles = !self.board.occupied()
            & (match self.color {
                Color::White => singles << 8,
                Color::Black => singles >> 8,
            })
            & self.color.fourth_rank();
        for to in doubles {
            let from = Square(match self.color {
                Color::White => to.0 - 16,
                Color::Black => to.0 + 16,
            });
            self.push_pawn_moves(buf, from, to, false);
        }
    }

    /// Appends en-passant captures available to the side to move.
    ///
    /// Adds nothing unless the previous move was a two-square pawn push that
    /// ended next to a friendly pawn.
    ///
    /// # Example
    /// ```
    /// # use ruchess::position::Position;
    /// # use ruchess::mve::Move;
    /// // No en-passant on move 1 (no prior move to react to).
    /// let mut moves: Vec<Move> = Vec::new();
    /// Position::new().enpassant_moves(&mut moves);
    /// assert!(moves.is_empty());
    /// ```
    pub fn enpassant_moves(&self, buf: &mut Vec<Move>) {
        let Some(last_move) = self.history.last_move else {
            return;
        };
        let Some(target) = potential_enpassant_sq(last_move, self.board, self.color) else {
            return;
        };
        let our_pawns = self.board.bypiece(Piece {
            role: Role::Pawn,
            color: self.color,
        });
        for from in ATTACKS.pawn_attacks(self.color.opponent(), target) & our_pawns {
            if let Some(m) = self.enpassant(from, target) {
                buf.push(m);
            }
        }
    }

    /// Appends all legal king moves to `buf`, including castling.
    ///
    /// Destinations attacked by the opponent are filtered out. The check is
    /// performed against the board with our king temporarily removed, so a
    /// king cannot slide along an attacker's ray onto a "safe-looking" square
    /// that the king itself was blocking.
    ///
    /// # Example
    /// ```
    /// # use ruchess::position::Position;
    /// # use ruchess::mve::Move;
    /// // From the starting position the king is hemmed in by its own pieces.
    /// let mut moves: Vec<Move> = Vec::new();
    /// Position::new().king_moves(&mut moves);
    /// assert!(moves.is_empty());
    /// ```
    pub fn king_moves(&self, buf: &mut Vec<Move>) {
        let orig = self.board.king(self.color);
        // Remove our king for attack detection so sliders see through its
        // current square — otherwise the king could slide along an
        // attacker's ray.
        let board_without_king = self.board.pop(orig).0;
        for dest in ATTACKS.king_attacks(orig) {
            if board_without_king.is_attacked(dest, self.color) {
                continue;
            }
            if let Some(m) = self.normal(orig, dest, Role::King) {
                buf.push(m);
            }
        }
        self.push_castling_moves(buf);
    }

    /// Appends all pseudo-legal knight moves to `buf`.
    ///
    /// # Example
    /// ```
    /// # use ruchess::position::Position;
    /// # use ruchess::mve::Move;
    /// // 2 knights × 2 destinations each = 4 from the starting position.
    /// let mut moves: Vec<Move> = Vec::new();
    /// Position::new().knight_moves(&mut moves);
    /// assert_eq!(moves.len(), 4);
    /// ```
    pub fn knight_moves(&self, buf: &mut Vec<Move>) {
        let knights = self.board.bypiece(Piece {
            role: Role::Knight,
            color: self.color,
        });
        for from in knights {
            for to in ATTACKS.knight_attacks(from) {
                if let Some(m) = self.normal(from, to, Role::Knight) {
                    buf.push(m);
                }
            }
        }
    }

    /// Appends all pseudo-legal bishop moves to `buf`.
    ///
    /// # Example
    /// ```
    /// # use ruchess::position::Position;
    /// # use ruchess::mve::Move;
    /// // Bishops are blocked by own pawns at the start.
    /// let mut moves: Vec<Move> = Vec::new();
    /// Position::new().bishop_moves(&mut moves);
    /// assert!(moves.is_empty());
    /// ```
    pub fn bishop_moves(&self, buf: &mut Vec<Move>) {
        let bishops = self.board.bypiece(Piece {
            role: Role::Bishop,
            color: self.color,
        });
        for from in bishops {
            for to in ATTACKS.bishop_attacks(from, self.board.occupied()) {
                if let Some(m) = self.normal(from, to, Role::Bishop) {
                    buf.push(m);
                }
            }
        }
    }

    /// Appends all pseudo-legal rook moves to `buf`.
    ///
    /// # Example
    /// ```
    /// # use ruchess::position::Position;
    /// # use ruchess::mve::Move;
    /// // Rooks are locked in by their own pieces at the start.
    /// let mut moves: Vec<Move> = Vec::new();
    /// Position::new().rook_moves(&mut moves);
    /// assert!(moves.is_empty());
    /// ```
    pub fn rook_moves(&self, buf: &mut Vec<Move>) {
        let rooks = self.board.bypiece(Piece {
            role: Role::Rook,
            color: self.color,
        });
        for from in rooks {
            for to in ATTACKS.rook_attacks(from, self.board.occupied()) {
                if let Some(m) = self.normal(from, to, Role::Rook) {
                    buf.push(m);
                }
            }
        }
    }

    /// Appends all pseudo-legal queen moves to `buf` (bishop-like + rook-like
    /// rays).
    ///
    /// # Example
    /// ```
    /// # use ruchess::position::Position;
    /// # use ruchess::mve::Move;
    /// // The queen has no legal moves from the starting position.
    /// let mut moves: Vec<Move> = Vec::new();
    /// Position::new().queen_moves(&mut moves);
    /// assert!(moves.is_empty());
    /// ```
    pub fn queen_moves(&self, buf: &mut Vec<Move>) {
        let queens = self.board.bypiece(Piece {
            role: Role::Queen,
            color: self.color,
        });
        let occupied = self.board.occupied();
        for from in queens {
            for to in ATTACKS.bishop_attacks(from, occupied) {
                if let Some(m) = self.normal(from, to, Role::Queen) {
                    buf.push(m);
                }
            }
            for to in ATTACKS.rook_attacks(from, occupied) {
                if let Some(m) = self.normal(from, to, Role::Queen) {
                    buf.push(m);
                }
            }
        }
    }

    /// Appends the legal castling moves for the side to move. Adds nothing
    /// if the king is currently in check.
    fn push_castling_moves(&self, buf: &mut Vec<Move>) {
        if self.board.is_check(self.color) {
            return;
        }
        for side in [Side::King, Side::Queen] {
            if let Some(m) = self.castle(side) {
                buf.push(m);
            }
        }
    }

    /// Attempts to build a single castling move on the given [`Side`].
    /// Returns `None` if rights are missing, the rook has moved, squares
    /// between king and rook are occupied, or the king would transit an
    /// attacked square.
    fn castle(&self, side: Side) -> Option<Move> {
        if !self.history.castles.can_side(self.color, side) {
            return None;
        }

        let king_from = self.board.king(self.color);
        let rook_from = self.color.castle_square(side);
        if !self.history.unmoved_rooks.contains(rook_from) {
            return None;
        }
        let (king_to, _rook_to, between, king_path) = castle_squares(self.color, side);

        if (self.board.occupied() & between).is_non_empty() {
            return None;
        }
        if king_path
            .into_iter()
            .any(|sq| self.board.is_attacked(sq, self.color))
        {
            return None;
        }

        Some(Move::castle(self.color, side, king_from, king_to))
    }

    /// Builds a non-special move (quiet push or simple capture) of `role`
    /// from `orig` to `dest`. Returns `None` if the destination holds one
    /// of our own pieces or `orig` is empty.
    fn normal(&self, orig: Square, dest: Square, role: Role) -> Option<Move> {
        let piece = Piece {
            role,
            color: self.color,
        };
        if self.board.is_occupied(dest) {
            if self.board.color_at(dest) == Some(self.color) {
                return None;
            }
            // Captured piece's color is fixed (our opponent — same-color
            // captures rejected just above). Record the role so `make` can
            // apply the capture without re-scanning the board.
            let captured_role = self.board.role_at(dest)?;
            Some(Move::capture(piece, orig, dest, dest, captured_role))
        } else {
            Some(Move::quiet(piece, orig, dest))
        }
    }

    /// Builds an en-passant [`Move`] from `orig` to `dest`. The captured
    /// pawn sits on the file of `dest` and the rank of `orig`.
    fn enpassant(&self, orig: Square, dest: Square) -> Option<Move> {
        let captured_sq = Square::from_file_and_rank(dest.file(), orig.rank());
        Some(Move::enpassant(self.color, orig, dest, captured_sq))
    }

    /// Expands a single pawn step from `from` to `to` into the appropriate
    /// move set and appends it to `buf`: four promotion moves if `from` is on
    /// the seventh rank (relative to the mover), otherwise one ordinary pawn
    /// move.
    fn push_pawn_moves(&self, buf: &mut Vec<Move>, from: Square, to: Square, is_capture: bool) {
        let is_promotion = from.rank() == self.color.seventh_rank();
        if is_promotion {
            let captured = if is_capture {
                self.board.role_at(to).map(|r| (to, r))
            } else {
                None
            };
            for r in PromotableRole::ROLES {
                buf.push(Move::promotion(self.color, from, to, r, captured));
            }
        } else if let Some(m) = self.normal(from, to, Role::Pawn) {
            buf.push(m);
        }
    }
}

/// Upper bound on legal moves in any chess position. The empirical maximum
/// is ~218; 256 is a safe round number that callers can use to preallocate
/// move buffers.
pub const MAX_MOVES: usize = 256;

/// Per-position legality info used to filter pseudo-legal moves without
/// invoking make/is_check on every candidate.
///
/// Computed once per call to [`Position::valid_moves`]. Encodes:
/// - `checkers`: bitboard of opponent pieces attacking our king.
/// - `check_mask`: squares non-king pieces may target. All squares if not
///   in check; squares between king and checker plus the checker's square
///   on single check; empty on double check.
/// - `is_double_check`: true if more than one attacker — only king moves
///   are legal.
/// - `pinned`: bitboard of our pieces pinned to the king by an opponent
///   slider. A pinned piece may only move along the line through king and
///   pinner.
struct LegalityContext {
    king_sq: Square,
    check_mask: Bitboard,
    is_double_check: bool,
    pinned: Bitboard,
}

impl LegalityContext {
    fn compute(pos: &Position) -> Self {
        let board = &pos.board;
        let us = pos.color;
        let them = us.opponent();
        let king_sq = board.king(us);

        let checkers = board.attackers(king_sq, them);
        let n_checkers = checkers.0.count_ones();

        let (check_mask, is_double_check) = if n_checkers == 0 {
            (Bitboard(!0u64), false)
        } else if n_checkers == 1 {
            // Single checker — non-king pieces must capture it or block.
            let checker_sq = Square(checkers.0.trailing_zeros() as u8);
            let between = Bitboard(ATTACKS.between[king_sq.0 as usize][checker_sq.0 as usize]);
            (between | Bitboard::from(checker_sq), false)
        } else {
            (Bitboard::EMPTY, true)
        };

        // Pin detection. For each opponent slider that lies on a ray from our
        // king (ignoring blockers), check whether exactly one of our pieces
        // sits between — that piece is pinned.
        let occupied = board.occupied();
        let our_pieces = board.bycolor(us);
        let opp_rq = board.bycolor(them) & (board.rooks() | board.queens());
        let opp_bq = board.bycolor(them) & (board.bishops() | board.queens());

        let mut pinned = Bitboard::EMPTY;

        // Rook-style pinners (rank/file rays).
        let rook_candidates = ATTACKS.rook_attacks(king_sq, Bitboard::EMPTY) & opp_rq;
        for pinner_sq in rook_candidates {
            let between = Bitboard(ATTACKS.between[king_sq.0 as usize][pinner_sq.0 as usize]);
            let blockers = between & occupied;
            if blockers.0.count_ones() == 1 && (blockers & our_pieces).is_non_empty() {
                pinned |= blockers;
            }
        }

        // Bishop-style pinners (diagonal rays).
        let bishop_candidates = ATTACKS.bishop_attacks(king_sq, Bitboard::EMPTY) & opp_bq;
        for pinner_sq in bishop_candidates {
            let between = Bitboard(ATTACKS.between[king_sq.0 as usize][pinner_sq.0 as usize]);
            let blockers = between & occupied;
            if blockers.0.count_ones() == 1 && (blockers & our_pieces).is_non_empty() {
                pinned |= blockers;
            }
        }

        Self {
            king_sq,
            check_mask,
            is_double_check,
            pinned,
        }
    }

    /// Decides legality of a pseudo-legal `mve`. Mover color is `color` and
    /// `board` is the pre-move board (used only for the en-passant fallback).
    #[inline(always)]
    fn is_legal(&self, mve: &Move, board: Board, color: Color) -> bool {
        // King moves: `king_moves` already filters its own legality (lifts
        // the king and tests attack). Castles are validated at gen time.
        if mve.piece.role == Role::King {
            return true;
        }
        // Under double check only the king can move.
        if self.is_double_check {
            return false;
        }
        // En passant: rare discovered-check via removed pawn on the same
        // rank. Cheap fallback to make/is_check.
        if mve.enpassant.is_some() {
            let mut working = board;
            apply_move(&mut working, mve);
            return !working.is_check(color);
        }
        // Must land on a check-resolving square.
        if !self.check_mask.is_set(mve.dest) {
            return false;
        }
        // Pinned pieces may only move along the king–pinner line.
        if self.pinned.is_set(mve.orig) {
            let ray = Bitboard(ATTACKS.rays[self.king_sq.0 as usize][mve.orig.0 as usize]);
            return ray.is_set(mve.dest);
        }
        true
    }
}

/// Applies `mve` to `board` in place by XOR-toggling exactly the affected
/// bits. Used as the shared make-move primitive by [`Position::make`] and
/// by the legality filter in [`Position::valid_moves`].
///
/// Symmetric: applying twice is a no-op. The move's `captured_role` field
/// (filled at generation time) supplies enough information to apply captures
/// without scanning the board.
#[inline(always)]
pub(crate) fn apply_move(board: &mut Board, mve: &Move) {
    let mover = mve.piece;

    if let Some(side) = mve.castle {
        let color = mover.color;
        let king = Piece {
            role: Role::King,
            color,
        };
        let rook = Piece {
            role: Role::Rook,
            color,
        };
        let rook_from = color.castle_square(side);
        let (king_to, rook_to, _, _) = castle_squares(color, side);
        board.toggle_piece(mve.orig, king);
        board.toggle_piece(king_to, king);
        board.toggle_piece(rook_from, rook);
        board.toggle_piece(rook_to, rook);
        return;
    }

    // Remove captured piece, if any.
    if let (Some(cap_sq), Some(cap_role)) = (mve.capture, mve.captured_role) {
        let captured = Piece {
            role: cap_role,
            color: mover.color.opponent(),
        };
        board.toggle_piece(cap_sq, captured);
    }

    // Lift the mover off its origin square.
    board.toggle_piece(mve.orig, mover);

    // Place the resulting piece at the destination: promoted role on a
    // promotion, otherwise the mover itself.
    let landed = match mve.promotion {
        Some(p) => Piece {
            role: match p {
                PromotableRole::Queen => Role::Queen,
                PromotableRole::Rook => Role::Rook,
                PromotableRole::Bishop => Role::Bishop,
                PromotableRole::Knight => Role::Knight,
            },
            color: mover.color,
        },
        None => mover,
    };
    board.toggle_piece(mve.dest, landed);
}

/// For `color` castling on `side`, returns
/// `(king_destination, rook_destination, must_be_empty, king_path_must_be_safe)`.
///
/// `must_be_empty` covers every square strictly between king and rook;
/// `king_path_must_be_safe` covers the squares the king transits to and
/// lands on (the king's starting square is already covered by the caller's
/// in-check test).
fn castle_squares(color: Color, side: Side) -> (Square, Square, Bitboard, Bitboard) {
    match (color, side) {
        (Color::White, Side::King) => (
            square::G1,
            square::F1,
            Bitboard::from(square::F1) | Bitboard::from(square::G1),
            Bitboard::from(square::F1) | Bitboard::from(square::G1),
        ),
        (Color::White, Side::Queen) => (
            square::C1,
            square::D1,
            Bitboard::from(square::B1) | Bitboard::from(square::C1) | Bitboard::from(square::D1),
            Bitboard::from(square::C1) | Bitboard::from(square::D1),
        ),
        (Color::Black, Side::King) => (
            square::G8,
            square::F8,
            Bitboard::from(square::F8) | Bitboard::from(square::G8),
            Bitboard::from(square::F8) | Bitboard::from(square::G8),
        ),
        (Color::Black, Side::Queen) => (
            square::C8,
            square::D8,
            Bitboard::from(square::B8) | Bitboard::from(square::C8) | Bitboard::from(square::D8),
            Bitboard::from(square::C8) | Bitboard::from(square::D8),
        ),
    }
}
/// Returns the en-passant target square if `last_move` was a two-square
/// pawn push by `color`'s opponent — that is, the square the pushed pawn
/// passed over. Returns `None` otherwise.
fn potential_enpassant_sq(last_move: Uci, board: Board, color: Color) -> Option<Square> {
    board.piece_at(last_move.dest).and_then(|piece| {
        if piece.color != color
            && piece.role == Role::Pawn
            && last_move.orig.ydist(last_move.dest) == 2
        {
            // The target is the square the opponent's pawn passed over —
            // one rank back from the opponent's perspective.
            last_move.dest.prev_rank(piece.color)
        } else {
            None
        }
    })
}

impl Default for Position {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::unmoved_rooks::UnmovedRooks;

    fn pc(role: Role, color: Color) -> Piece {
        Piece { role, color }
    }

    /// Position with the given board, otherwise pristine (standard castles,
    /// unmoved_rooks derived from `b`, white to move).
    fn pos_from(b: Board) -> Position {
        let history = History {
            unmoved_rooks: UnmovedRooks::from_board(b),
            ..History::new()
        };
        Position::new().with_board(b).with_history(history)
    }

    /// Test helper: collect every legal move into a fresh `Vec`.
    fn collect_valid(p: &Position) -> Vec<Move> {
        p.valid_moves()
    }

    /// Test helper: collect every legal move with `orig == s` into a fresh `Vec`.
    fn collect_at(p: &Position, s: Square) -> Vec<Move> {
        p.valid_moves_at(s)
    }

    // ── Starting position sanity ─────────────────────────────────────────

    #[test]
    fn starting_position_has_20_moves() {
        assert_eq!(collect_valid(&Position::new()).len(), 20);
    }

    #[test]
    fn starting_position_pawn_moves_count() {
        // 8 pawns × (1 single push + 1 double push) = 16
        let mut buf = Vec::new();
        Position::new().pawn_moves(&mut buf);
        assert_eq!(buf.len(), 16);
    }

    #[test]
    fn starting_position_knight_moves_count() {
        // 2 knights × 2 destinations each = 4
        let mut buf = Vec::new();
        Position::new().knight_moves(&mut buf);
        assert_eq!(buf.len(), 4);
    }

    #[test]
    fn starting_position_no_castling() {
        let castles: Vec<_> = collect_valid(&Position::new())
            .into_iter()
            .filter(|m| m.castle.is_some())
            .collect();
        assert!(
            castles.is_empty(),
            "no castles legal from start, got {castles:?}"
        );
    }

    #[test]
    fn starting_position_no_enpassant() {
        assert_eq!(Position::new().enpassant_square(), None);
        let mut buf = Vec::new();
        Position::new().enpassant_moves(&mut buf);
        assert!(buf.is_empty());
    }

    #[test]
    fn starting_position_no_promotion() {
        let proms: Vec<_> = collect_valid(&Position::new())
            .into_iter()
            .filter(|m| m.promotion.is_some())
            .collect();
        assert!(proms.is_empty());
    }

    #[test]
    fn starting_position_not_in_check() {
        assert!(!Position::new().is_check());
    }

    #[test]
    fn starting_position_has_moves() {
        assert!(Position::new().has_moves());
    }

    // ── mve / color flip / history ───────────────────────────────────────

    #[test]
    fn mve_flips_color() {
        let after = Position::new().mve(square::E2, square::E4, None).unwrap();
        assert_eq!(after.color(), Color::Black);
    }

    #[test]
    fn mve_applies_move_to_board() {
        let after = Position::new().mve(square::E2, square::E4, None).unwrap();
        assert!(!after.board().is_occupied(square::E2));
        assert_eq!(
            after.board().piece_at(square::E4),
            Some(pc(Role::Pawn, Color::White))
        );
    }

    #[test]
    fn mve_invalid_returns_none() {
        // E2 → E5 is not a legal pawn move (only 1 or 2 squares forward).
        assert!(Position::new().mve(square::E2, square::E5, None).is_none());
    }

    #[test]
    fn mve_from_empty_square_returns_none() {
        assert!(Position::new().mve(square::E4, square::E5, None).is_none());
    }

    #[test]
    fn mve_updates_history_last_move() {
        let after = Position::new().mve(square::E2, square::E4, None).unwrap();
        let lm = after.history().last_move.expect("last_move set after mve");
        assert_eq!(lm.orig, square::E2);
        assert_eq!(lm.dest, square::E4);
    }

    #[test]
    fn change_color_actually_flips() {
        let p = Position::new();
        assert_eq!(p.color(), Color::White);
        // change_color should produce a position whose color is the opponent.
        // The current implementation in position.rs:40-43 is a no-op — this
        // test surfaces the bug.
        let q = p.change_color();
        assert_eq!(q.color(), Color::Black);
    }

    // ── Pawn pushes ──────────────────────────────────────────────────────

    #[test]
    fn pawn_double_push_emits_two_destinations() {
        let moves = collect_at(&Position::new(), square::E2);
        assert_eq!(moves.len(), 2);
        let dests: Vec<_> = moves.iter().map(|m| m.dest).collect();
        assert!(dests.contains(&square::E3));
        assert!(dests.contains(&square::E4));
    }

    #[test]
    fn pawn_blocked_cannot_push() {
        // White pawn on E2 with a black knight directly in front on E3.
        let b = Board::EMPTY
            .set(square::E1, pc(Role::King, Color::White))
            .set(square::E8, pc(Role::King, Color::Black))
            .set(square::E2, pc(Role::Pawn, Color::White))
            .set(square::E3, pc(Role::Knight, Color::Black));
        let p = pos_from(b);
        let pushes: Vec<_> = collect_at(&p, square::E2)
            .into_iter()
            .filter(|m| m.capture.is_none())
            .collect();
        assert!(
            pushes.is_empty(),
            "pawn blocked on E3 cannot push to E3 or E4, got {pushes:?}"
        );
    }

    // ── En passant ───────────────────────────────────────────────────────

    #[test]
    fn enpassant_offered_after_opposing_double_push() {
        // White pawn on E5, black just played D7→D5.
        let b = Board::EMPTY
            .set(square::E1, pc(Role::King, Color::White))
            .set(square::E8, pc(Role::King, Color::Black))
            .set(square::E5, pc(Role::Pawn, Color::White))
            .set(square::D5, pc(Role::Pawn, Color::Black));
        let history = History {
            last_move: Some(crate::uci::Uci {
                orig: square::D7,
                dest: square::D5,
                promotion: None,
            }),
            unmoved_rooks: UnmovedRooks::from_board(b),
            ..History::new()
        };
        let p = Position::new().with_board(b).with_history(history);
        assert_eq!(
            p.enpassant_square(),
            Some(square::D6),
            "en passant target should be D6 (the square the black pawn passed)"
        );
        let mut eps: Vec<Move> = Vec::new();
        p.enpassant_moves(&mut eps);
        assert_eq!(eps.len(), 1, "exactly one en-passant move available");
        let m = eps[0];
        assert_eq!(m.orig, square::E5);
        assert_eq!(m.dest, square::D6);
        assert_eq!(m.capture, Some(square::D5));
        assert!(m.enpassant.is_some());
    }

    #[test]
    fn enpassant_not_offered_after_single_push() {
        // White pawn on E5, black played D6→D5 (single push, not double).
        let b = Board::EMPTY
            .set(square::E1, pc(Role::King, Color::White))
            .set(square::E8, pc(Role::King, Color::Black))
            .set(square::E5, pc(Role::Pawn, Color::White))
            .set(square::D5, pc(Role::Pawn, Color::Black));
        let history = History {
            last_move: Some(crate::uci::Uci {
                orig: square::D6,
                dest: square::D5,
                promotion: None,
            }),
            unmoved_rooks: UnmovedRooks::from_board(b),
            ..History::new()
        };
        let p = Position::new().with_board(b).with_history(history);
        assert_eq!(p.enpassant_square(), None);
        let mut eps: Vec<Move> = Vec::new();
        p.enpassant_moves(&mut eps);
        assert!(eps.is_empty());
    }

    // ── Promotion ────────────────────────────────────────────────────────

    #[test]
    fn pawn_on_seventh_promotes_to_four_pieces() {
        let b = Board::EMPTY
            .set(square::E1, pc(Role::King, Color::White))
            .set(square::H8, pc(Role::King, Color::Black))
            .set(square::A7, pc(Role::Pawn, Color::White));
        let p = pos_from(b);
        let moves = collect_at(&p, square::A7);
        assert_eq!(moves.len(), 4, "4 promotion choices; got {moves:?}");
        let promos: Vec<_> = moves.iter().filter_map(|m| m.promotion).collect();
        assert!(promos.contains(&PromotableRole::Queen));
        assert!(promos.contains(&PromotableRole::Rook));
        assert!(promos.contains(&PromotableRole::Bishop));
        assert!(promos.contains(&PromotableRole::Knight));
        for m in &moves {
            assert_eq!(m.dest, square::A8);
            assert_eq!(m.capture, None);
        }
    }

    #[test]
    fn pawn_pre_promotion_push_has_no_promotion_field() {
        let b = Board::EMPTY
            .set(square::E1, pc(Role::King, Color::White))
            .set(square::E8, pc(Role::King, Color::Black))
            .set(square::A6, pc(Role::Pawn, Color::White));
        let p = pos_from(b);
        let moves = collect_at(&p, square::A6);
        assert!(
            moves.iter().all(|m| m.promotion.is_none()),
            "no promotion on rank-6 push, got {moves:?}"
        );
    }

    // ── Castling ─────────────────────────────────────────────────────────

    fn castling_board() -> Board {
        Board::EMPTY
            .set(square::E1, pc(Role::King, Color::White))
            .set(square::A1, pc(Role::Rook, Color::White))
            .set(square::H1, pc(Role::Rook, Color::White))
            .set(square::E8, pc(Role::King, Color::Black))
            .set(square::A8, pc(Role::Rook, Color::Black))
            .set(square::H8, pc(Role::Rook, Color::Black))
    }

    #[test]
    fn castle_kingside_white_available() {
        let p = pos_from(castling_board());
        let castles: Vec<_> = collect_valid(&p)
            .into_iter()
            .filter(|m| m.castle == Some(Side::King))
            .collect();
        assert_eq!(castles.len(), 1);
        let m = castles[0];
        assert_eq!(m.orig, square::E1);
        assert_eq!(m.dest, square::G1);
    }

    #[test]
    fn castle_queenside_white_available() {
        let p = pos_from(castling_board());
        let castles: Vec<_> = collect_valid(&p)
            .into_iter()
            .filter(|m| m.castle == Some(Side::Queen))
            .collect();
        assert_eq!(castles.len(), 1);
        assert_eq!(castles[0].orig, square::E1);
        assert_eq!(castles[0].dest, square::C1);
    }

    #[test]
    fn cannot_castle_kingside_through_check() {
        // Black rook on F8 attacks F1 (a square the king transits).
        let b = castling_board().set(square::F8, pc(Role::Rook, Color::Black));
        let p = pos_from(b);
        let king_castle = collect_valid(&p)
            .into_iter()
            .find(|m| m.castle == Some(Side::King));
        assert!(
            king_castle.is_none(),
            "F-file rook prevents kingside castle"
        );
    }

    #[test]
    fn cannot_castle_while_in_check() {
        // Black queen on E4 attacks E1 (white king's square) along the E-file.
        let b = castling_board().set(square::E4, pc(Role::Queen, Color::Black));
        let p = pos_from(b);
        assert!(
            p.is_check(),
            "white king on E1 is in check from black Q on E4"
        );
        let any_castle = collect_valid(&p).into_iter().find(|m| m.castle.is_some());
        assert!(
            any_castle.is_none(),
            "no castles allowed while in check, got {any_castle:?}"
        );
    }

    #[test]
    fn cannot_castle_kingside_when_blocked() {
        let b = castling_board().set(square::F1, pc(Role::Bishop, Color::White));
        let p = pos_from(b);
        let king_castle = collect_valid(&p)
            .into_iter()
            .find(|m| m.castle == Some(Side::King));
        assert!(king_castle.is_none(), "bishop on F1 blocks kingside castle");
    }

    #[test]
    fn cannot_castle_without_rights() {
        let p = pos_from(castling_board()).with_castles(Castles::new(false, false, false, false));
        let any_castle = collect_valid(&p).into_iter().find(|m| m.castle.is_some());
        assert!(any_castle.is_none());
    }

    #[test]
    fn cannot_castle_with_moved_rooks() {
        let history = History {
            unmoved_rooks: UnmovedRooks::from_board(Board::EMPTY),
            ..History::new()
        };
        let p = Position::new()
            .with_board(castling_board())
            .with_history(history);
        let any_castle = collect_valid(&p).into_iter().find(|m| m.castle.is_some());
        assert!(any_castle.is_none(), "no castle when rooks have moved");
    }

    // ── is_check ─────────────────────────────────────────────────────────

    #[test]
    fn is_check_detects_back_rank_rook() {
        let b = Board::EMPTY
            .set(square::E1, pc(Role::King, Color::White))
            .set(square::E8, pc(Role::Rook, Color::Black))
            .set(square::A8, pc(Role::King, Color::Black));
        let p = pos_from(b);
        assert!(p.is_check());
    }

    #[test]
    fn is_check_false_when_blocked() {
        let b = Board::EMPTY
            .set(square::E1, pc(Role::King, Color::White))
            .set(square::E4, pc(Role::Pawn, Color::White))
            .set(square::E8, pc(Role::Rook, Color::Black))
            .set(square::A8, pc(Role::King, Color::Black));
        let p = pos_from(b);
        assert!(!p.is_check(), "rook attack blocked by own pawn on E4");
    }

    // ── valid_moves_at consistency (small concrete check) ────────────────

    #[test]
    fn valid_moves_at_matches_filter_on_start() {
        let p = Position::new();
        let all = collect_valid(&p);
        for i in 0u8..64 {
            let s = Square(i);
            let direct = collect_at(&p, s).len();
            let filtered = all.iter().filter(|m| m.orig == s).count();
            assert_eq!(direct, filtered, "mismatch at square {s}");
        }
    }
}

#[cfg(test)]
mod proptests {
    use super::*;
    use crate::unmoved_rooks::UnmovedRooks;
    use proptest::prelude::*;

    // ── Strategies ───────────────────────────────────────────────────────

    fn sq() -> impl Strategy<Value = Square> {
        (0u8..64).prop_map(Square)
    }

    fn color() -> impl Strategy<Value = Color> {
        prop_oneof![Just(Color::White), Just(Color::Black)]
    }

    fn non_king_role() -> impl Strategy<Value = Role> {
        prop_oneof![
            Just(Role::Pawn),
            Just(Role::Knight),
            Just(Role::Bishop),
            Just(Role::Rook),
            Just(Role::Queen),
        ]
    }

    fn non_king_piece() -> impl Strategy<Value = Piece> {
        (non_king_role(), color()).prop_map(|(role, color)| Piece { role, color })
    }

    /// Builds a position with kings on `wk`/`bk`, the listed non-king pieces sprinkled
    /// on top (king squares and illegal pawn ranks skipped), and no castling rights.
    fn build_position(wk: Square, bk: Square, ops: Vec<(Square, Piece)>, c: Color) -> Position {
        let mut b = Board::EMPTY
            .set(
                wk,
                Piece {
                    role: Role::King,
                    color: Color::White,
                },
            )
            .set(
                bk,
                Piece {
                    role: Role::King,
                    color: Color::Black,
                },
            );
        for (s, p) in ops {
            if s == wk || s == bk {
                continue;
            }
            if p.role == Role::Pawn {
                let r = s.rank().as_u8();
                if r == 0 || r == 7 {
                    continue;
                }
            }
            b = b.set(s, p);
        }
        let history = History {
            castles: Castles::new(false, false, false, false),
            unmoved_rooks: UnmovedRooks::from_board(b),
            ..History::new()
        };
        Position::new()
            .with_board(b)
            .with_color(c)
            .with_history(history)
    }

    /// Random "legal-enough" position: exactly one king per color, kings non-adjacent,
    /// side-not-to-move not in check.
    fn random_position() -> impl Strategy<Value = Position> {
        (
            sq(),
            sq(),
            prop::collection::vec((sq(), non_king_piece()), 0..12),
            color(),
        )
            .prop_filter("kings distinct", |(wk, bk, _, _)| wk != bk)
            .prop_filter("kings non-adjacent", |(wk, bk, _, _)| {
                let dx = (wk.file().as_u8() as i32 - bk.file().as_u8() as i32).abs();
                let dy = (wk.rank().as_u8() as i32 - bk.rank().as_u8() as i32).abs();
                dx > 1 || dy > 1
            })
            .prop_map(|(wk, bk, ops, c)| build_position(wk, bk, ops, c))
            .prop_filter("side-not-to-move not in check", |p| {
                !p.board().is_check(p.color().opponent())
            })
    }

    fn piece_count(b: &Board, role: Role, color: Color) -> u32 {
        b.bypiece(Piece { role, color }).0.count_ones()
    }

    /// Apply `mve` to a clone of `p`'s board and return it. Replaces the
    /// pre-Phase-3 `m.after` field that move generation used to materialize.
    fn after_board(p: &Position, mve: &Move) -> Board {
        let mut b = *p.board();
        apply_move(&mut b, mve);
        b
    }

    /// Collect every legal move from `p` into a fresh `Vec`.
    fn collect_valid(p: &Position) -> Vec<Move> {
        p.valid_moves()
    }

    /// Count moves in `buf` that would not leave us in check after apply.
    fn legal_count(p: &Position, buf: &[Move]) -> usize {
        buf.iter()
            .filter(|m| !after_board(p, m).is_check(p.color))
            .count()
    }

    proptest! {
        // Every generated move is for a piece of the side to move.
        #[test]
        fn move_color_matches_side_to_move(p in random_position()) {
            for m in collect_valid(&p) {
                prop_assert_eq!(m.piece.color, p.color());
            }
        }

        // No null moves.
        #[test]
        fn move_orig_not_equal_dest(p in random_position()) {
            for m in collect_valid(&p) {
                prop_assert_ne!(m.orig, m.dest);
            }
        }

        // The origin square holds the piece claimed by the move.
        #[test]
        fn move_origin_holds_claimed_piece(p in random_position()) {
            for m in collect_valid(&p) {
                prop_assert_eq!(p.board().piece_at(m.orig), Some(m.piece));
            }
        }

        // After-board has exactly one king of each color (king cannot be captured).
        #[test]
        fn after_board_keeps_both_kings(p in random_position()) {
            for m in collect_valid(&p) {
                let after = after_board(&p, &m);
                let white_kings = piece_count(&after, Role::King, Color::White);
                let black_kings = piece_count(&after, Role::King, Color::Black);
                prop_assert_eq!(white_kings, 1);
                prop_assert_eq!(black_kings, 1);
            }
        }

        // After-board satisfies bitboard invariants.
        #[test]
        fn after_board_invariants(p in random_position()) {
            for m in collect_valid(&p) {
                let b = after_board(&p, &m);
                let white = b.bycolor(Color::White);
                let black = b.bycolor(Color::Black);
                prop_assert_eq!(b.occupied(), white | black);
                prop_assert_eq!(white & black, crate::bitboard::Bitboard::EMPTY);
            }
        }

        // Move generation is deterministic.
        #[test]
        fn deterministic(p in random_position()) {
            prop_assert_eq!(collect_valid(&p), collect_valid(&p));
        }

        // `valid_moves()` equals the disjoint union of per-piece-type generators filtered by legality.
        #[test]
        fn partition_matches_per_piece_generators(p in random_position()) {
            let total = collect_valid(&p).len();
            let mut pawns = Vec::new();
            p.pawn_moves(&mut pawns);
            let mut ep = Vec::new();
            p.enpassant_moves(&mut ep);
            let mut king = Vec::new();
            p.king_moves(&mut king);
            let mut knight = Vec::new();
            p.knight_moves(&mut knight);
            let mut bishop = Vec::new();
            p.bishop_moves(&mut bishop);
            let mut rook = Vec::new();
            p.rook_moves(&mut rook);
            let mut queen = Vec::new();
            p.queen_moves(&mut queen);
            let sum = legal_count(&p, &pawns)
                + legal_count(&p, &ep)
                + legal_count(&p, &king)
                + legal_count(&p, &knight)
                + legal_count(&p, &bishop)
                + legal_count(&p, &rook)
                + legal_count(&p, &queen);
            prop_assert_eq!(total, sum);
        }

        // `valid_moves_at(s)` is equivalent to filtering `valid_moves()` by `orig==s`.
        #[test]
        fn valid_moves_at_filter_consistent(p in random_position()) {
            let all = collect_valid(&p);
            for i in 0u8..64 {
                let s = Square(i);
                let buf = p.valid_moves_at(s);
                let filtered = all.iter().filter(|m| m.orig == s).count();
                prop_assert_eq!(buf.len(), filtered);
            }
        }

        // has_moves agrees with non-empty valid_moves.
        #[test]
        fn has_moves_iff_any(p in random_position()) {
            prop_assert_eq!(p.has_moves(), !collect_valid(&p).is_empty());
        }

        // `mve()` with a listed move succeeds and flips color.
        #[test]
        fn mve_with_listed_move_works(p in random_position()) {
            if let Some(m) = collect_valid(&p).into_iter().next() {
                let expected_after = after_board(&p, &m);
                let next = p.clone().mve(m.orig, m.dest, m.promotion).expect("listed move must succeed");
                prop_assert_eq!(next.color(), p.color().opponent());
                if m.promotion.is_none() {
                    prop_assert_eq!(*next.board(), expected_after);
                }
            }
        }

        // Promotion moves only land on the opponent's back rank.
        #[test]
        fn promotion_only_on_opponent_back_rank(p in random_position()) {
            let opp_back = p.color().opponent().back_rank();
            for m in collect_valid(&p) {
                if m.promotion.is_some() {
                    prop_assert_eq!(m.dest.rank(), opp_back);
                    prop_assert_eq!(m.piece.role, Role::Pawn);
                }
            }
        }

        // `valid_moves()` does not mutate the position.
        #[test]
        fn valid_moves_does_not_mutate(p in random_position()) {
            let before = p.clone();
            let _ = collect_valid(&p);
            prop_assert_eq!(p, before);
        }

        // make + unmake restores the exact prior position.
        #[test]
        fn make_unmake_round_trip(p in random_position()) {
            let before = p.clone();
            for m in collect_valid(&p) {
                let mut q = before.clone();
                let undo = q.make(&m);
                q.unmake(undo);
                prop_assert_eq!(&q, &before);
            }
        }

        // make produces the same end state as the persistent `mve` for every legal move.
        #[test]
        fn make_matches_persistent_mve(p in random_position()) {
            for m in collect_valid(&p) {
                let persistent = p.clone().mve(m.orig, m.dest, m.promotion).unwrap();
                let mut mutable = p.clone();
                mutable.make(&m);
                prop_assert_eq!(&mutable, &persistent);
            }
        }
    }
}