dealbreaker 1.4.0

A data-driven solver for patience / solitaire card games: describe a game's rules as data, get solutions or proofs of unsolvability.
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
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
//! The engine: rules compiled into lookup tables, positions, legal moves, and reversible play.

mod compile;
mod counters;
mod deal;
mod moves;
mod play;

use std::fmt;

use crate::card::{Card, FACES};
use crate::rules::*;

/// Why a [`Rules`] value can't be used.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RulesError(pub String);

impl fmt::Display for RulesError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "invalid rules: {}", self.0)
    }
}

impl std::error::Error for RulesError {}

fn err<T>(msg: impl Into<String>) -> Result<T, RulesError> {
    Err(RulesError(msg.into()))
}

/// A position: the cards on every pile, bottom first, plus the bits of game state that aren't
/// cards. Piles are numbered across groups in the order the rules list them.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct State {
    pub piles: Vec<Vec<Card>>,
    /// Times the waste has been turned back into the stock.
    pub redeals_used: u32,
    /// The rank set by the deal for [`EmptyRule::DealtBase`] foundations.
    pub base_rank: Option<u8>,
    /// Seed for shuffles during play (shuffling redeals). Fixed for the game.
    pub seed: u64,
    /// The two counters of [`AuxRules`]; always zero in games without them.
    pub aux: [i16; 2],
}

/// What a move does after any talon steps.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Action {
    /// Move the top `count` cards of `from` onto `to`, keeping their order.
    Transfer { from: u16, to: u16, count: u16 },
    /// Deal from the stock, or turn the waste back over if the stock is empty.
    Deal,
    /// Remove the top cards of some piles together, to the rule's discard pile.
    /// `rule` is the index of the removal rule; `piles[..n]` are sorted pile numbers.
    Remove { rule: u8, n: u8, piles: [u16; 4] },
    /// Move the single card at position `index` of `from` (0 = bottom) onto `to`.
    Pick { from: u16, to: u16, index: u16 },
    /// Remove the top cards of `len` consecutive piles starting at `start`, to the rule's
    /// discard pile (used for variable-length contiguous removals longer than 4 piles).
    RemoveRange { rule: u8, start: u16, len: u16 },
    /// Deal one card face up from a secondary stock pile `from` onto `to`.
    DealSecondary { from: u16, to: u16 },
    /// Move the second card from the top of `from` onto `to`, leaving the top card.
    Extract { from: u16, to: u16 },
}

/// A move as the solver plays it: `talon` stock deals (or redeals) first, then the action.
///
/// For games whose stock deals to a waste pile, the solver folds runs of deals into the move
/// that plays the card they turn up, which shortens solutions and searches a great deal.
/// [`Game::steps`] expands moves into single steps for display.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct Move {
    pub talon: u16,
    pub action: Action,
}

impl Move {
    pub fn new(action: Action) -> Move {
        Move { talon: 0, action }
    }
}

/// A primitive, invertible change to a state. The journal of these makes undo exact.
#[derive(Copy, Clone, Debug)]
pub(crate) enum Op {
    /// Move `count` cards as a block.
    Shift { from: u16, to: u16, count: u16 },
    /// Take the card at `index` out of `from` and put it on `to`.
    Pick { from: u16, to: u16, index: u16 },
    /// Move `count` cards one at a time (reversing them), turning each face up or down.
    Turn {
        from: u16,
        to: u16,
        count: u16,
        up: bool,
    },
    /// Turn over the top card of a pile.
    Flip(u16),
    /// `redeals_used += 1`.
    Redeal,
    /// Set `s.base_rank = Some(r)` (undo restores `None`).
    SetBaseRank(u8),
    /// The latch (kept in `base_rank`) goes from `was` to `now`.
    SetLatch { was: bool, now: bool },
    /// Swap two cards of a pile (shuffles are recorded as swaps, so they undo exactly).
    Swap { pile: u16, i: u16, j: u16 },
    /// Swap the entire contents of two piles.
    SwapPiles(u16, u16),
    /// Counter `slot` goes from `was` to `now`.
    SetAux { slot: u8, was: i16, now: i16 },
}

/// Compiled opening base-rank choice rules.
#[derive(Copy, Clone, Debug)]
pub(crate) struct CompiledChooseBase {
    pub from_group: u16,
    pub also_from_group: Option<u16>,
    pub refill_from_stock: bool,
    pub deal_waste: bool,
    pub free_moves: bool,
    pub lock_mask: u64,
}

/// Compiled `from_pile_map` restriction.
#[derive(Clone, Debug)]
pub(crate) struct CompiledFromPileMap {
    pub group: u16,
    pub to: Vec<i16>,
    pub only_when_stock_non_empty: bool,
    pub only_non_empty_dest: bool,
    pub except_ranks: Vec<u8>,
}

/// Compiled `secondary_stock` rule.
#[derive(Copy, Clone, Debug)]
pub(crate) struct CompiledSecondaryStock {
    pub to: u16,
    pub unlock_when_to_empty: bool,
    pub stay_unlocked_below: Option<u16>,
}

/// A compiled group.
#[derive(Clone, Debug)]
pub(crate) struct Group {
    pub name: String,
    pub kind: PileKind,
    pub start: u16,
    pub count: u16,
    /// Bitmask of groups whose cards this group accepts.
    pub accepts_from: u64,
    /// Bitmask of groups whose cards an empty pile of this group accepts.
    pub empty_accepts_from: u64,
    /// Groups to refill an emptied pile from, in order.
    pub refill_from: Vec<u16>,
    /// Cards moved per automatic refill.
    pub refill_count: u16,
    /// Its piles are interchangeable: permuting them gives an equivalent position.
    pub symmetric: bool,
    /// Becomes symmetric once the stock is empty and has no redeals left.
    pub symmetric_when_no_stock: bool,
    /// Becomes symmetric once all tableau redeals have been used.
    pub symmetric_when_no_redeal: bool,
    /// Equivalence classes of interchangeable piles within a non-uniform group (e.g. a
    /// foundation group with per-pile overrides). Empty unless at least one class has > 1 pile.
    pub sym_classes: Vec<Vec<u16>>,
    /// Grid layout: piles per row.
    pub columns: Option<u16>,
    /// Internal scratch pile (for redeals); not part of positions shown to callers.
    pub hidden: bool,
    /// Accept only from piles of this group this many places later.
    pub reach: Option<Vec<u16>>,
    /// With `reach`: also accept from piles earlier in the group.
    pub reach_both_ways: bool,
    pub reach_grid: bool,
    pub empty_needs_group_empty: Option<u16>,
    pub accept_whole_from_group: bool,
    /// A run of several cards put here must also be a valid run under this pile's build rule.
    pub run_must_fit_build: bool,
    /// `[under][over]` tables for `GroupRules::move_runs_by` (empty: the pile's own build).
    pub move_fits: Vec<[u64; FACES]>,
    pub repeat_rank: Option<u16>,
    pub dropdown: bool,
    /// (source group, for each source pile the target index in this group or -1, plus gating flags and except_ranks).
    pub from_pile_map: Option<CompiledFromPileMap>,
    pub clear_tops: Option<(u16, u16)>,
    /// (target pile index in this group, source group, source pile index in that group) banned in the first round.
    pub first_round_bans: Vec<(u16, u16, u16)>,
    pub row_start: Option<u8>,
    /// When placing onto a non-empty pile of this group, move existing cards to this pile first.
    pub replace_on_drop: Option<u16>,
    /// Slide piles forward to close gaps after every move.
    pub compact: bool,
    /// Each pile after the first only accepts ranks present on the previous pile.
    pub requires_rank_on_prev: bool,
    /// Shorter piles must match the rank at the same depth of the longest pile in this group.
    pub match_longest_rank: bool,
    /// Accept cards only when the destination pile is empty.
    pub accept_only_when_empty: bool,
    /// Accept cards only when the stock pile is empty.
    pub accept_when_stock_empty: bool,
    pub accept_when_waste_empty: bool,
    /// Shift the movable face-up run from the next pile into an emptied pile.
    pub compact_face_up: bool,
    /// Pick the largest pile when refilling from a multi-pile group.
    pub refill_largest: bool,
    /// Refill a pile only when a move just emptied it.
    pub refill_on_empty: bool,
    /// Each pile after the first may only start once the previous pile is non-empty.
    pub requires_prev_non_empty: bool,
    /// Most consecutive face-up cards of the same rank allowed at the top of a pile.
    pub max_same_rank: Option<u8>,
    /// Cards may leave piles of this group only once the stock pile is empty.
    pub moves_when_stock_empty: bool,
    /// Cards may leave piles of this group only once at least one pile in this group is empty.
    pub moves_when_any_empty: Option<u16>,
    /// Cards may leave pile `i` of this group only once pile `i` of this group is empty.
    pub moves_when_same_index_empty: Option<u16>,
    /// Cards may leave pile `i` only once every pile of slice `i` of this group is empty.
    pub moves_when_slice_empty: Option<u16>,
    /// Cards may be added to pile `i` only once pile `i` of this group is non-empty.
    pub requires_same_index_non_empty: Option<u16>,
    /// Pile `i` accepts cards (except from the same-index pile of this group) only while that pile is empty.
    pub accept_when_same_index_empty: Option<u16>,
    /// Cards may leave only the first or last non-empty pile.
    pub move_from_frontier: Option<crate::rules::Frontier>,
    /// Empty piles accept any card once this many piles start with the `empty` rank.
    pub empty_open_after_bases: Option<u16>,
    pub empty_open_when_full: Option<u16>,
    pub empty_needs_first_full: bool,
    /// Only auto-flip the top card of a pile when it is the last remaining card.
    pub flip_only_last: bool,
    /// When a pile is one card shy of `max_cards`, its final card must come from the same-index
    /// pile of this group.
    pub final_from_same_index: Option<u16>,
    /// When `build.dir` is `either`, the first two-card pile locks build direction for the group.
    pub lock_build_dir: bool,
    /// Never auto-flip face-down cards in this group.
    pub no_flip: bool,
    /// Refill each emptied pile from the same-index pile of `refill_from`.
    pub refill_same_index: bool,
    /// Refill each emptied pile from the nearest non-empty pile of `refill_from`.
    pub refill_nearest: bool,
    /// Only allow building on a non-empty pile if its bottom card satisfies the pile's `empty` rule.
    pub require_valid_base: bool,
    /// Swap-on-drop mode for piles within this group.
    pub swap_bases: Option<SwapBases>,
    /// See [`GroupRules::swap_on_waste_match`].
    pub swap_on_waste_match: Option<Adjacency>,
    /// Allow moving a complete suit-length run regardless of supermove capacity.
    pub supermove_complete_run: bool,
    /// Source groups whose cards bypass `build` and `empty` rules when dropped onto this group.
    pub unrestricted_from: u64,
    /// When `build.dir` is `either`, each pile locks its own build direction once it has 2 cards.
    pub lock_pile_dir: bool,
    /// No card of this suit may be added, or built on.
    pub exclude_suit: Option<crate::card::Suit>,
    /// A full, fully built pile may not be moved from.
    pub freeze_when_built: bool,
    pub accept_on_face_down: bool,
    pub one_way_split: Option<u16>,
    pub move_face_down_top: bool,
    /// Fixed rank sequence required by pile depth.
    pub rank_sequence: Vec<u8>,
    /// No two non-empty piles in this group may share the same suit on their bottom card.
    pub unique_suits: bool,
    pub unique_ranks: bool,
    pub cyclic_ranks: bool,
    pub same_suit_group: bool,
    pub same_rank_group: bool,
    /// Move every pile's cards to the first pile of this group once all piles hold a card.
    pub clear_when_full: Option<u16>,
    pub clear_same_rank: bool,
    pub run_len: Option<u8>,
    pub compact_when_stock_empty: bool,
    pub flip_when_dealt_out: bool,
    pub spill_when_hollow: bool,
    pub auto_foundation_rank: Option<u8>,
    /// Refill only while every pile of this group is empty.
    pub refill_when_empty: Option<u16>,
    /// While stock is non-empty, forbid building onto or moving from single-card piles onto non-empty piles.
    pub no_build_single_while_stock: bool,
    /// When refilling from stock with `refill_count > 1`, deal the first card face down unless it is the last card.
    pub refill_first_face_down: bool,
    /// Auto-flip pile `i` when pile `i` of this group reaches `max_cards`.
    pub flip_when_same_index_full: Option<u16>,
    /// Auto-flip pile `i` when pile `i` of this group is non-empty.
    pub flip_when_same_index_non_empty: Option<u16>,
    /// Keep the top card of pile `i` face down while pile `i` of this group is non-empty.
    pub face_down_while_same_index_non_empty: Option<u16>,
    /// A face-down top turns up only once the previous pile is empty.
    pub flip_after_prev_empty: bool,
    pub flip_when_all_at_most: Option<u16>,
    /// A face-down top turns up only while some pile of this group is empty.
    pub flip_when_any_empty: Option<u16>,
    /// When the destination pile holds a single card, accept any single card regardless of `build`.
    pub accept_any_on_single: bool,
    /// Empty pile `i` accepts cards only while pile `i % other.count` of this group is non-empty.
    pub empty_requires_same_index_non_empty: Option<u16>,
    /// Empty pile `i` accepts cards only while pile `i % other.count` of this group is non-empty
    /// and the card's suit matches that pile's bottom card's suit.
    pub empty_match_suit_of: Option<u16>,
    /// Only accept cards from a source pile `p` in a grid group when `p % cols > 0` and `p - 1` is empty.
    pub from_requires_left_empty: bool,
    /// `Layout::GridVertical`: pile `i` is blocked iff both vertical neighbours are non-empty.
    pub grid_vertical: bool,
    /// `Layout::GridBottomOpen`: movable iff `i + cols` is out of bounds or empty; accepts iff non-empty and vertically isolated.
    pub grid_bottom_open: bool,
    /// Groups tried in order when pushing `to`'s top card off before placing onto a non-empty pile.
    pub push_off_to: Vec<u16>,
    /// Push-off destinations skip `accepts_from`/`max_accept` checks.
    pub push_off_bypasses_accept: bool,
    /// Shift bottom `k / 2` contiguous piles above an emptied pile down by one row.
    pub fission_shift: bool,
    /// Pile `i` accepts cards only while pile `i % other.count` is non-empty in every listed group.
    pub requires_same_index_groups_non_empty: Vec<u16>,
    /// (source group, for each source pile the allowed destination pile indices in this group).
    pub from_pile_sets: Option<(u16, Vec<Vec<u16>>)>,
    /// Auto-flush when a pile reaches `len` cards.
    pub flush_at_len: Option<CompiledFlushAtLen>,
    /// Placing a card at depth `k` requires matching suit with `other[k]` in this group.
    pub match_depth_suit: bool,
    pub secondary_stock: Option<CompiledSecondaryStock>,
    pub moves_when_group_cards_at_least: Option<(u16, u16)>,
    pub accept_first_round_only: bool,
    pub min_accept_len: Option<u16>,
    /// Accept only while these piles (group, indices; empty = all) are full.
    pub accept_when_piles_full: Option<(u16, Vec<u16>)>,
    pub joker_bomb: bool,
    pub sum_limit: Option<crate::rules::SumLimit>,
    pub refill_divert_ranks: Vec<u8>,
    pub refill_group_on_leave: Option<CompiledLeaveRefill>,
    pub refill_self_on_leave: bool,
    pub staging: Option<CompiledStaging>,
    pub pair_flush: Vec<CompiledPairFlush>,
    pub tiered_set: Option<CompiledTieredSet>,
    /// `(stride, source_group_index)` for [`GroupRules::staged_empty`].
    pub staged_empty: Option<(u16, u16)>,
    pub even_segments: Option<u8>,
    pub refill_when_stock_at_most: Option<u16>,
    /// Precomputed fast-path flag: `movable()` can skip all rare move-gating checks.
    pub simple_movable: bool,
    /// Precomputed fast-path flag: `gen_actions_with_empty` can bypass `can_place_impl` once
    /// `fit_mask`, `accepts_from`, and supermove limits are verified.
    pub simple_accept: bool,
}

#[derive(Copy, Clone, Debug)]
pub(crate) struct CompiledLeaveRefill {
    pub group: u16,
    pub reshuffle_from: Option<u16>,
}

#[derive(Clone, Debug)]
pub(crate) struct CompiledStaging {
    pub to: u16,
    pub court_from: u8,
    pub pip_sum: u16,
    pub pip_courts: u8,
    /// Sorted.
    pub court_set: Vec<u8>,
    pub distinct_ranks: bool,
    pub max_courts: Option<u8>,
    pub cap_pip_sum: bool,
    pub exact_at_pips: Option<u8>,
}

impl CompiledStaging {
    fn pips(&self, rank: u8) -> Option<u16> {
        (rank < self.court_from).then_some(u16::from(rank))
    }

    /// May `card` be added to a staging pile holding `pile`?
    pub(crate) fn accepts(&self, pile: &[Card], card: Card) -> bool {
        if self.distinct_ranks && pile.iter().any(|c| c.rank() == card.rank()) {
            return false;
        }
        match self.pips(card.rank()) {
            None => {
                let courts = pile
                    .iter()
                    .filter(|c| self.pips(c.rank()).is_none())
                    .count();
                self.max_courts.is_none_or(|m| courts < m as usize)
            }
            Some(p) => {
                let (sum, n) = pile
                    .iter()
                    .filter_map(|c| self.pips(c.rank()))
                    .fold((p, 1usize), |(s, n), q| (s + q, n + 1));
                (!self.cap_pip_sum || sum <= self.pip_sum)
                    && self
                        .exact_at_pips
                        .is_none_or(|k| n != k as usize || sum == self.pip_sum)
            }
        }
    }

    /// Does the pile `pile` clear?
    pub(crate) fn clears(&self, pile: &[Card]) -> bool {
        if pile.is_empty() {
            return false;
        }
        if !self.court_set.is_empty() {
            let mut ranks: Vec<u8> = pile.iter().map(|c| c.rank()).collect();
            ranks.sort_unstable();
            if ranks == self.court_set {
                return true;
            }
        }
        let courts = pile
            .iter()
            .filter(|c| self.pips(c.rank()).is_none())
            .count();
        let sum: u16 = pile.iter().filter_map(|c| self.pips(c.rank())).sum();
        courts == self.pip_courts as usize && sum == self.pip_sum
    }
}

/// Cards face up on a tiered-set pile make up the set.
pub(crate) const TIERED_SET_LEN: usize = 4;

#[derive(Copy, Clone, Debug)]
pub(crate) struct CompiledTieredSet {
    pub to: u16,
    pub bonus: u16,
    pub joker_value: u16,
}

impl CompiledTieredSet {
    fn value(&self, c: Card) -> u16 {
        if c.is_joker() {
            self.joker_value
        } else {
            u16::from(c.rank())
        }
    }

    /// May `card` go onto a tiered-set pile holding `pile`?
    pub(crate) fn accepts(&self, pile: &[Card], card: Card) -> bool {
        let up: Vec<Card> = pile.iter().copied().filter(|c| c.is_face_up()).collect();
        let Some(&base) = up.first() else {
            return false;
        };
        match up.len() {
            1 => self.value(card) + self.bonus >= self.value(base),
            2 => self.value(card) + self.value(up[1]) >= self.value(base),
            3 => card.is_joker() || (!base.is_joker() && card.suit() == base.suit()),
            _ => false,
        }
    }
}

#[derive(Clone, Debug)]
pub(crate) struct CompiledPairFlush {
    pub bottom_ranks: Vec<u8>,
    pub to: u16,
    /// Index within the destination group for each suit (indexed by `Suit as usize`).
    pub suit_pos: [u8; 4],
    pub first: Option<u8>,
}

#[derive(Copy, Clone, Debug)]
pub(crate) struct CompiledFlushAtLen {
    pub len: u16,
    pub pull_from: Option<u16>,
    pub to: u16,
}

#[derive(Clone, Debug)]
pub(crate) struct Redeal {
    pub group: u16,
    pub times: u32,
    pub how: RedealHow,
    /// The scratch pile cards are gathered on.
    pub gather: u16,
    /// Where a compaction refills from.
    pub refill: Option<u16>,
}

/// The compiled rules of one pile.
#[derive(Clone, Debug)]
pub(crate) struct PileRules {
    pub build: Build,
    pub empty: EmptyRule,
    pub moves: MoveUnit,
    pub max_cards: u16,
    pub min_cards: u16,
    pub max_accept: u16,
    pub empty_max_accept: u16,
    pub non_empty_max_accept: u16,
    pub complete_runs: bool,
    /// Foundations the solver may play to automatically when safe.
    pub autoplay: bool,
    /// True if another foundation with a different policy can accept some of the same faces.
    pub competing_foundation: bool,
    /// Cards never leave, so only the top card and the count matter to the future.
    pub sink: bool,
    /// Faces this pile accepts at all (suit and colour limits), as a bit set.
    pub admits: u64,
    /// If set, an empty pile accepts only cards of this suit.
    pub empty_suit: Option<crate::card::Suit>,
    /// `fits[under] >> over & 1`: may `over` be built on `under` here? Real cards only: jokers
    /// are handled by [`Game::accept_set`] and friends.
    pub fits: [u64; FACES],
    /// Jokers are wild here.
    pub wild: bool,
    /// Permissive jokers here.
    pub wild_permissive: bool,
    /// Jokers may go on any pile here.
    pub joker_anywhere: bool,
    /// Minimum cards accepted per move.
    pub min_accept: u16,
    /// Resolved target group and rank offset for [`EmptyRule::AfterPile`].
    pub after_pile: Option<(u16, i8)>,
    /// Resolved target group, pile index, and rank offset for [`EmptyRule::AfterPileBottom`].
    pub after_pile_bottom: Option<(u16, u16, i8)>,
}

impl PileRules {
    /// True if two piles have identical rule policies (ignoring derived tables like `fits`,
    /// `autoplay`, and `sink`). Exhaustive destructuring ensures new fields are considered here.
    pub(crate) fn same_policy(&self, other: &PileRules) -> bool {
        let PileRules {
            build,
            empty,
            moves,
            max_cards,
            min_cards,
            max_accept,
            empty_max_accept,
            non_empty_max_accept,
            complete_runs,
            admits,
            empty_suit,
            wild,
            wild_permissive,
            joker_anywhere,
            min_accept,
            after_pile,
            after_pile_bottom,
            autoplay: _,
            competing_foundation: _,
            sink: _,
            fits: _,
        } = self;
        *build == other.build
            && *empty == other.empty
            && *moves == other.moves
            && *max_cards == other.max_cards
            && *min_cards == other.min_cards
            && *max_accept == other.max_accept
            && *empty_max_accept == other.empty_max_accept
            && *non_empty_max_accept == other.non_empty_max_accept
            && *complete_runs == other.complete_runs
            && *admits == other.admits
            && *empty_suit == other.empty_suit
            && *wild == other.wild
            && *wild_permissive == other.wild_permissive
            && *joker_anywhere == other.joker_anywhere
            && *min_accept == other.min_accept
            && *after_pile == other.after_pile
            && *after_pile_bottom == other.after_pile_bottom
    }

    /// True if two foundation piles accept the exact same card sequences (for autoplay conflict
    /// detection).
    pub(crate) fn same_foundation_policy(&self, other: &PileRules) -> bool {
        self.build == other.build
            && self.empty == other.empty
            && self.empty_suit == other.empty_suit
            && self.max_cards == other.max_cards
            && self.admits == other.admits
    }
}

impl Group {
    pub fn piles(&self) -> std::ops::Range<u16> {
        self.start..self.start + self.count
    }

    /// True if pile position/order within this group affects legality or transitions.
    pub(crate) fn has_positional_rules(&self) -> bool {
        self.reach.is_some()
            || self.swap_on_waste_match.is_some()
            || self.compact
            || self.compact_face_up
            || self.requires_rank_on_prev
            || self.requires_prev_non_empty
            || self.final_from_same_index.is_some()
            || self.moves_when_same_index_empty.is_some()
            || self.moves_when_slice_empty.is_some()
            || self.requires_same_index_non_empty.is_some()
            || self.accept_when_same_index_empty.is_some()
            || self.empty_requires_same_index_non_empty.is_some()
            || self.empty_match_suit_of.is_some()
            || self.move_from_frontier.is_some()
            || self.empty_open_after_bases.is_some()
            || self.empty_open_when_full.is_some()
            || self.empty_needs_first_full
            || self.flip_when_same_index_full.is_some()
            || self.flip_when_same_index_non_empty.is_some()
            || self.spill_when_hollow
            || self.face_down_while_same_index_non_empty.is_some()
            || self.flip_after_prev_empty
            || self.flip_when_any_empty.is_some()
            || self.refill_same_index
            || self.refill_nearest
            || self.one_way_split.is_some()
            || self.from_requires_left_empty
            || self.from_pile_map.is_some()
            || self.fission_shift
            || !self.requires_same_index_groups_non_empty.is_empty()
            || self.from_pile_sets.is_some()
            || self.even_segments.is_some()
    }

    /// True if moves to or from this group are gated on the stock being empty.
    pub(crate) fn depends_on_stock_empty(&self) -> bool {
        self.accept_when_stock_empty
            || self.accept_when_waste_empty
            || self.moves_when_stock_empty
            || self.no_build_single_while_stock
            || self.refill_when_stock_at_most.is_some()
            || self
                .from_pile_map
                .as_ref()
                .is_some_and(|m| m.only_when_stock_non_empty)
    }

    /// True if this group participates in automatic post-move compaction or refilling.
    pub(crate) fn needs_settle(&self) -> bool {
        self.compact
            || self.compact_face_up
            || !self.refill_from.is_empty()
            || self.clear_when_full.is_some()
            || self.clear_tops.is_some()
            || self.auto_foundation_rank.is_some()
            || self.flip_when_same_index_full.is_some()
            || self.flip_when_same_index_non_empty.is_some()
            || self.face_down_while_same_index_non_empty.is_some()
            || self.flip_after_prev_empty
            || self.flip_when_all_at_most.is_some()
            || self.flip_when_any_empty.is_some()
            || self.flip_when_dealt_out
            || self.spill_when_hollow
            || self.fission_shift
            || self.flush_at_len.is_some()
            || !self.pair_flush.is_empty()
            || self.staging.is_some()
            || self.tiered_set.is_some()
            || self.staged_empty.is_some()
    }

    /// Internal single-pile scratch group (used for redeal gathering).
    pub(crate) fn hidden_scratch(name: &str, start: u16) -> Group {
        Group {
            name: name.into(),
            kind: PileKind::Reserve,
            start,
            count: 1,
            accepts_from: 0,
            empty_accepts_from: 0,
            refill_from: Vec::new(),
            refill_count: 1,
            symmetric: true,
            symmetric_when_no_stock: false,
            symmetric_when_no_redeal: false,
            sym_classes: Vec::new(),
            columns: None,
            hidden: true,
            reach: None,
            reach_both_ways: false,
            reach_grid: false,
            empty_needs_group_empty: None,
            accept_whole_from_group: false,
            run_must_fit_build: false,
            move_fits: Vec::new(),
            repeat_rank: None,
            dropdown: false,
            from_pile_map: None,
            clear_tops: None,
            first_round_bans: Vec::new(),
            row_start: None,
            replace_on_drop: None,
            compact: false,
            requires_rank_on_prev: false,
            match_longest_rank: false,
            accept_only_when_empty: false,
            accept_when_stock_empty: false,
            accept_when_waste_empty: false,
            compact_face_up: false,
            refill_largest: false,
            refill_on_empty: false,
            requires_prev_non_empty: false,
            max_same_rank: None,
            moves_when_stock_empty: false,
            moves_when_any_empty: None,
            moves_when_same_index_empty: None,
            moves_when_slice_empty: None,
            requires_same_index_non_empty: None,
            accept_when_same_index_empty: None,
            move_from_frontier: None,
            empty_open_after_bases: None,
            empty_open_when_full: None,
            empty_needs_first_full: false,
            flip_only_last: false,
            final_from_same_index: None,
            lock_build_dir: false,
            no_flip: false,
            refill_same_index: false,
            refill_nearest: false,
            require_valid_base: false,
            swap_bases: None,
            swap_on_waste_match: None,
            supermove_complete_run: false,
            unrestricted_from: 0,
            lock_pile_dir: false,
            exclude_suit: None,
            freeze_when_built: false,
            accept_on_face_down: false,
            one_way_split: None,
            move_face_down_top: false,
            rank_sequence: Vec::new(),
            unique_suits: false,
            unique_ranks: false,
            cyclic_ranks: false,
            same_suit_group: false,
            same_rank_group: false,
            clear_when_full: None,
            clear_same_rank: false,
            run_len: None,
            compact_when_stock_empty: false,
            flip_when_dealt_out: false,
            spill_when_hollow: false,
            auto_foundation_rank: None,
            refill_when_empty: None,
            no_build_single_while_stock: false,
            refill_first_face_down: false,
            flip_when_same_index_full: None,
            flip_when_same_index_non_empty: None,
            face_down_while_same_index_non_empty: None,
            flip_after_prev_empty: false,
            flip_when_all_at_most: None,
            flip_when_any_empty: None,
            accept_any_on_single: false,
            empty_requires_same_index_non_empty: None,
            empty_match_suit_of: None,
            from_requires_left_empty: false,
            grid_vertical: false,
            grid_bottom_open: false,
            push_off_to: Vec::new(),
            push_off_bypasses_accept: false,
            fission_shift: false,
            requires_same_index_groups_non_empty: Vec::new(),
            from_pile_sets: None,
            flush_at_len: None,
            match_depth_suit: false,
            secondary_stock: None,
            moves_when_group_cards_at_least: None,
            accept_first_round_only: false,
            accept_when_piles_full: None,
            joker_bomb: false,
            sum_limit: None,
            refill_divert_ranks: Vec::new(),
            min_accept_len: None,
            refill_group_on_leave: None,
            refill_self_on_leave: false,
            staging: None,
            pair_flush: Vec::new(),
            tiered_set: None,
            staged_empty: None,
            even_segments: None,
            refill_when_stock_at_most: None,
            simple_movable: false,
            simple_accept: false,
        }
    }
}

#[derive(Clone, Debug)]
pub(crate) struct Stock {
    pub pile: u16,
    pub target: u16,
    pub target_kind: PileKind,
    pub count: u16,
    pub count_per_round: Vec<u16>,
    pub final_to: Option<u16>,
    /// Resolved target pile indices (either `StockRules::piles` or all piles of `target`).
    pub targets: Vec<u16>,
    pub piles_per_round: Vec<Vec<u16>>,
    pub final_piles: Option<Vec<u16>>,
    pub redeals: u32,
    pub require_no_empty: bool,
    pub auto: bool,
    pub only_when_empty: bool,
    pub first_empty: bool,
    pub skip_empty: bool,
    pub face_up: bool,
    pub deal_per_pile: bool,
    pub drop_to_before_deal: Option<u16>,
    pub deal_down_then_up: bool,
    pub redeal_reverse: bool,
    pub redeal_flip_stock: bool,
    pub redeal_gather_only: bool,
    pub redeal_shuffle: bool,
    pub redeal_deal_all_alternating: bool,
    pub deal_empty_first: bool,
    pub divert_ranks: Vec<u8>,
    pub final_split_to: Option<u16>,
    pub final_also_to: Option<u16>,
    pub require_no_empty_group: Option<u16>,
    pub require_group_empty: Option<u16>,
    pub auto_for_empty: Option<u16>,
    pub skip_built_from: Option<u8>,
    pub max_deals: Option<u32>,
    pub skip_run_with_rank: Option<u8>,
    pub open_next_on_rank: Option<u8>,
    pub fill_grid_holes_then_row: bool,
    pub fill_grid_holes_repeat: bool,
    pub redeal_redistribute_reverse: bool,
    pub skip_when_same_index_full: Option<u16>,
    pub redeal_from_groups: Vec<u16>,
    pub redeal_waste_onto_group: bool,
    pub bookend: Option<u16>,
    pub only_when_empty_first_round: bool,
    pub top_up_group_to: Option<(u16, u16)>,
    pub redeal_switch_to_auto_refill: Option<u16>,
    pub sweep_to_discard_round1: Option<u16>,
    pub sweep_group_on_waste: Option<u16>,
    pub sweep_scratch: Option<u16>,
    pub deal_after_play_to: Option<u16>,
    pub redeal_bottom_count_from: Option<u16>,
    pub fill_empty_or_reshuffle: bool,
    pub reshuffle_at_counter: Option<i16>,
    /// Fan deal: the group of piles whose cards the target group fans out.
    pub fan_rows: Option<u16>,
    pub wrap_mid_deal: bool,
    pub bonus_redeals: Option<CompiledBonusRedeals>,
}

#[derive(Clone, Debug)]
pub(crate) struct CompiledBonusRedeals {
    pub groups: Vec<u16>,
    pub threshold: u16,
    pub max_redeals: Option<u32>,
}

impl Stock {
    #[inline]
    pub fn deal_count(&self, redeals_used: u32) -> u16 {
        if self.count_per_round.is_empty() {
            self.count
        } else {
            let i = (redeals_used as usize).min(self.count_per_round.len() - 1);
            self.count_per_round[i]
        }
    }

    #[inline]
    pub fn round_targets(&self, redeals_used: u32) -> &[u16] {
        if self.piles_per_round.is_empty() {
            &self.targets
        } else {
            let i = (redeals_used as usize).min(self.piles_per_round.len() - 1);
            &self.piles_per_round[i]
        }
    }

    /// True if emptying a target pile can block or alter how a stock deal behaves.
    pub fn sensitive_to_empty_piles(&self) -> bool {
        self.require_no_empty
            || self.require_no_empty_group.is_some()
            || self.require_group_empty.is_some()
            || self.auto_for_empty.is_some()
            || self.skip_built_from.is_some()
            || self.max_deals.is_some()
            || self.skip_run_with_rank.is_some()
            || self.skip_empty
            || self.first_empty
            || self.deal_empty_first
            || self.open_next_on_rank.is_some()
            || self.fill_grid_holes_then_row
            || self.fill_grid_holes_repeat
            || self.redeal_redistribute_reverse
            || self.skip_when_same_index_full.is_some()
            || self.top_up_group_to.is_some()
            || self.redeal_switch_to_auto_refill.is_some()
            || self.sweep_to_discard_round1.is_some()
            || self.sweep_group_on_waste.is_some()
            || self.bookend.is_some()
            || self.fill_empty_or_reshuffle
            || self.reshuffle_at_counter.is_some()
            || self.fan_rows.is_some()
            || self.wrap_mid_deal
            || self.bonus_redeals.is_some()
    }
}

#[derive(Clone, Debug)]
pub(crate) struct Removal {
    pub kind: RemovalKind,
    pub from: u64,
    pub to: u16,
    /// Neighbour rule, with the grid group it applies to.
    pub adjacent: Option<(Adjacency, u16)>,
    pub exclude_ranks: Vec<u8>,
    pub needs_latch: bool,
    pub min_len: Option<u8>,
    pub max_sum: Option<u8>,
    pub face_ten: bool,
}

#[derive(Clone, Debug)]
pub(crate) enum Win {
    AllOnFoundations,
    Empty(Vec<u16>),
    PilesEmpty(u16, Vec<u16>, Vec<u16>),
    /// Group, runs, run length.
    RingRuns(u16, u16, u16),
    Count(u16, u16),
    /// Group, card count, groups that must be empty.
    CountAndEmpty(u16, u16, Vec<u16>),
    /// Group, card count, spread group (every pile holds at most one card).
    CountAndSpread(u16, u16, u16),
    /// Grid group, row length to check, first-column rank.
    Rows(u16, u16, u8),
    /// Group, most non-empty piles.
    AtMostPiles(u16, u16),
    /// At least this many points.
    Score(u32),
    /// A round has been scored and the rounds so far total at least this many points.
    RoundScore(u32),
    /// Every pile in `group` holds `max_cards` cards with a valid base card.
    AllFull(u16),
    /// Group, number of leading piles that must hold only red cards (the rest only black).
    ColorSplit(u16, u16),
    /// Every pile of the group holds the one card the pack's order gives it.
    PackOrder(u16),
    /// Every row of the score grid scores at least this many points.
    EachRowScore(u32),
    /// Non-empty piles of `group` (or single `pile` index) satisfy optional `length` and `build`,
    /// with every group in `empty` empty.
    PilesBuilt {
        group: u16,
        length: Option<u16>,
        has_build: bool,
        empty: Vec<u16>,
        non_empty: bool,
        pile: Option<u16>,
        bottom: Option<u8>,
    },
    /// Every group in `empty` is empty and every non-empty pile in `group` is vertically isolated.
    AllIsolated {
        group: u16,
        empty: Vec<u16>,
    },
    /// `discard` holds at least `cards` cards and the first pile of `group` holds the target face
    /// stored in `aux[0]`.
    TargetCard {
        group: u16,
        discard: u16,
        cards: u16,
        exclude_piles: u16,
    },
}

/// A game ready to play and solve: [`Rules`] compiled into tables.
#[derive(Clone, Debug)]
pub struct Game {
    rules: Rules,
    pub(crate) groups: Vec<Group>,
    pub(crate) pile_group: Vec<u16>,
    pub(crate) pile_rules: Vec<PileRules>,
    pub(crate) covered_by: Vec<Vec<u16>>,
    pub(crate) has_covers: bool,
    pub(crate) stock: Option<Stock>,
    pub(crate) stock_pile: Option<u16>,
    pub(crate) redeal: Option<Redeal>,
    pub(crate) removal: Vec<Removal>,
    pub(crate) win: Win,
    /// Optional compiled fits table overriding the group's build rule in `row_prefix`.
    pub(crate) row_win_fits: Option<[u64; FACES]>,
    /// Position of each rank (1..=13) in the pack's sequence; 255 if not in the pack.
    pub(crate) rank_idx: [u8; 14],
    pub(crate) nranks: u8,
    pub(crate) copies: u8,
    pub(crate) total_cards: u16,
    /// Jokers in the pack.
    pub(crate) jokers: u8,
    pub(crate) in_pack: [bool; FACES],
    /// Real faces of each rank (index 1..=13), and of each suit.
    pub(crate) rank_faces: [u64; 14],
    pub(crate) suit_faces: [u64; 4],
    /// For each face, the faces that could be built on it somewhere other than a foundation.
    pub(crate) dependents: Vec<Vec<u8>>,
    pub(crate) any_autoplay: bool,
    /// The stock deals to a waste pile that cards can be played from.
    pub(crate) compress_talon: bool,
    /// Talon walk can prefilter waste cards with a single 64-bit acceptance mask.
    pub(crate) simple_talon_filter: bool,
    /// Unlimited-redeal draw-1 stock-to-waste talon where every card in stock+waste is freely
    /// playable at any time regardless of split position or order.
    pub(crate) free_draw1_talon: bool,
    /// No compact, refill, auto-stock, or hooks: `settle` only needs `auto_flip`.
    pub(crate) simple_settle: bool,
    /// Piles that can ever be a move source (`moves != MoveUnit::None`).
    pub(crate) movable_piles: Vec<u16>,
    pub(crate) pick_piles: Vec<u16>,
    /// For each source group, the destination piles that could ever accept from it.
    pub(crate) targets_for_group: Vec<Vec<u16>>,
    /// True if any pile uses `MoveUnit::Supermove`.
    pub(crate) has_supermove: bool,
    /// Global equivalence-class index for each pile in a non-uniform group with symmetric
    /// sub-classes (`u16::MAX` if not in a multi-pile sub-class).
    pub(crate) pile_sym_class: Vec<u16>,
    /// Number of multi-pile equivalence classes across all groups.
    pub(crate) num_sym_classes: usize,
    /// True if `RemovalKind::LowerOfSuit` is soundly forced when available.
    pub(crate) force_lower_of_suit: bool,
    pub(crate) waste: Option<u16>,
    pub(crate) choose_base: Option<CompiledChooseBase>,
    pub(crate) latch_group: Option<u16>,
    pub(crate) any_secondary_stock: bool,
    pub(crate) hooks: Option<std::sync::Arc<dyn crate::hooks::Hooks>>,
    pub(crate) score: Option<crate::score::Score>,
    /// Compiled counter rules.
    pub(crate) aux: Option<counters::CompiledAux>,
    /// Starting values of the counters.
    pub(crate) aux_initial: [i16; 2],
    /// Source group and destination groups (in order) of the second-card draw.
    pub(crate) extract: Option<(u16, Vec<u16>)>,
    pub(crate) rounds: Option<Rounds>,
}

/// Compiled [`RoundRules`].
#[derive(Clone, Debug)]
pub(crate) struct Rounds {
    pub crib: u16,
    pub hands: Vec<u16>,
    /// The starter and discard piles.
    pub starter: u16,
    pub discard: u16,
    pub crib_down: u16,
    pub hand_size: u16,
    pub keep: u16,
    pub next_hand_after: u16,
    pub points: CribbagePoints,
}

impl Game {
    pub fn rules(&self) -> &Rules {
        &self.rules
    }

    /// Points for a position, if the game is scored.
    pub fn score(&self, s: &State) -> Option<u32> {
        self.score.as_ref().map(|sc| sc.score(s))
    }

    /// Is the game played for points?
    pub fn is_scored(&self) -> bool {
        self.score.is_some()
    }

    /// The score that wins, for games won by reaching a score.
    pub fn target_score(&self) -> Option<u32> {
        match self.win {
            Win::Score(t) => Some(t),
            _ => None,
        }
    }

    /// The legal moves, leaving out any that a symmetry of the position makes equivalent to an
    /// earlier one (in a scored grid, a card going into a second empty row is no different from
    /// the first).
    pub fn distinct_moves(&self, s: &State) -> Vec<Move> {
        let mut moves = self.legal_moves(s);
        if let Some(sc) = self.score.as_ref().filter(|sc| sc.symmetric) {
            moves.retain(|m| match m.action {
                Action::Transfer { to, .. } => !sc.redundant(self, s, to),
                _ => true,
            });
        }
        moves
    }

    pub fn name(&self) -> &str {
        &self.rules.name
    }

    pub fn num_piles(&self) -> usize {
        self.pile_group.len()
    }

    /// The group name and index within the group of a pile.
    pub fn pile_ref(&self, pile: u16) -> PileRef {
        let g = &self.groups[self.pile_group[pile as usize] as usize];
        PileRef {
            group: g.name.clone(),
            index: pile - g.start,
        }
    }

    /// The pile number for a group name and index.
    pub fn pile_index(&self, group: &str, index: u16) -> Option<u16> {
        let g = self.groups.iter().find(|g| g.name == group)?;
        (index < g.count).then_some(g.start + index)
    }

    pub fn pile_kind(&self, pile: u16) -> PileKind {
        self.group_of(pile).kind
    }

    #[inline]
    pub(crate) fn group_of(&self, pile: u16) -> &Group {
        &self.groups[self.pile_group[pile as usize] as usize]
    }

    /// Group names with their pile counts, in pile order.
    pub fn groups(&self) -> impl Iterator<Item = (&str, PileKind, u16)> {
        self.groups
            .iter()
            .map(|g| (g.name.as_str(), g.kind, g.count))
    }

    // ----- Display --------------------------------------------------------------------------

    /// Expand solver moves into single steps, for display or for driving a UI.
    pub fn steps(&self, start: &State, moves: &[Move]) -> Vec<Step> {
        let mut s = start.clone();
        let mut j = Vec::new();
        let mut out = Vec::new();
        for &mv in moves {
            for _ in 0..mv.talon {
                out.push(self.deal_step_kind(&s));
                self.talon_step(&mut s, &mut j);
            }
            match mv.action {
                Action::Deal => out.push(self.deal_step_kind(&s)),
                Action::Transfer { from, to, count } => out.push(Step::Move {
                    from: self.pile_ref(from),
                    to: self.pile_ref(to),
                    count,
                }),
                Action::Pick { from, to, index } => out.push(Step::Pick {
                    from: self.pile_ref(from),
                    to: self.pile_ref(to),
                    index,
                }),
                Action::Remove { n, piles, .. } => out.push(Step::Remove {
                    piles: piles[..n as usize]
                        .iter()
                        .map(|&p| self.pile_ref(p))
                        .collect(),
                }),
                Action::RemoveRange { start, len, .. } => out.push(Step::Remove {
                    piles: (start..start + len).map(|p| self.pile_ref(p)).collect(),
                }),
                Action::DealSecondary { from, to } => out.push(Step::DealSecondary {
                    from: self.pile_ref(from),
                    to: self.pile_ref(to),
                }),
                Action::Extract { from, to } => out.push(Step::Extract {
                    from: self.pile_ref(from),
                    to: self.pile_ref(to),
                }),
            }
            self.apply(&mut s, Move::new(mv.action), &mut j);
            j.clear();
        }
        out
    }

    /// The move a single step makes in `s`, if it's legal there.
    pub fn step_to_move(&self, s: &State, step: &Step) -> Option<Move> {
        let idx = |r: &PileRef| self.pile_index(&r.group, r.index);
        let mv = match step {
            Step::Deal | Step::Redeal if self.redeal.is_some() => {
                if !matches!(step, Step::Redeal) {
                    return None;
                }
                Move::new(Action::Deal)
            }
            Step::Deal | Step::Redeal => {
                let empty = self
                    .stock
                    .as_ref()
                    .is_some_and(|st| s.piles[st.pile as usize].is_empty());
                if empty != matches!(step, Step::Redeal) {
                    return None;
                }
                Move::new(Action::Deal)
            }
            Step::Move { from, to, count } => Move::new(Action::Transfer {
                from: idx(from)?,
                to: idx(to)?,
                count: *count,
            }),
            Step::Pick { from, to, index } => Move::new(Action::Pick {
                from: idx(from)?,
                to: idx(to)?,
                index: *index,
            }),
            Step::DealSecondary { from, to } => Move::new(Action::DealSecondary {
                from: idx(from)?,
                to: idx(to)?,
            }),
            Step::Extract { from, to } => Move::new(Action::Extract {
                from: idx(from)?,
                to: idx(to)?,
            }),
            Step::Remove { piles } => {
                // Any order names the same set; find the rule that allows it.
                let mut want: Vec<u16> = piles.iter().map(idx).collect::<Option<_>>()?;
                want.sort_unstable();
                let mut moves = Vec::new();
                self.gen_removals(s, None, &mut moves);
                return moves.into_iter().find(|m| match m.action {
                    Action::Remove { n, piles, .. } => piles[..n as usize] == want[..],
                    Action::RemoveRange { start, len, .. } => {
                        want.len() == len as usize
                            && want.iter().enumerate().all(|(i, &p)| p == start + i as u16)
                    }
                    _ => false,
                });
            }
        };
        self.is_legal(s, mv).then_some(mv)
    }

    /// Every legal single step in this position.
    pub fn legal_steps(&self, s: &State) -> Vec<Step> {
        let mut out = Vec::new();
        self.gen_actions_unpruned(s, &mut out);
        let mut steps: Vec<Step> = out.iter().map(|&m| self.steps(s, &[m]).remove(0)).collect();
        if self.can_deal(s) {
            steps.push(self.deal_step_kind(s));
        }
        steps
    }

    /// Play a single step. Returns an error if it isn't legal.
    pub fn play_step(&self, s: &mut State, step: &Step) -> Result<(), IllegalStep> {
        let mv = self
            .step_to_move(s, step)
            .ok_or_else(|| IllegalStep(step.clone()))?;
        let mut j = Vec::new();
        self.apply(s, mv, &mut j);
        Ok(())
    }

    /// Play a single step on a clone of `s`, returning rich player-visible details (cards moved,
    /// destination card, any face-down cards flipped face-up, and human-readable text) together
    /// with the resulting state.
    pub fn describe_step(
        &self,
        s: &State,
        step: &Step,
    ) -> Result<(StepDetails, State), IllegalStep> {
        let mv = self
            .step_to_move(s, step)
            .ok_or_else(|| IllegalStep(step.clone()))?;
        let mut cards = Vec::new();
        let mut onto = None;
        match step {
            Step::Move { from, to, count } => {
                if let Some(fp) = self.pile_index(&from.group, from.index) {
                    let pile = &s.piles[fp as usize];
                    let start = pile.len().saturating_sub(*count as usize);
                    cards.extend(pile[start..].iter().map(|c| c.to_string()));
                }
                if let Some(tp) = self.pile_index(&to.group, to.index) {
                    onto = s.piles[tp as usize].last().map(|c| c.to_string());
                }
            }
            Step::Pick { from, to, index } => {
                if let Some(fp) = self.pile_index(&from.group, from.index) {
                    if let Some(c) = s.piles[fp as usize].get(*index as usize) {
                        cards.push(c.to_string());
                    }
                }
                if let Some(tp) = self.pile_index(&to.group, to.index) {
                    onto = s.piles[tp as usize].last().map(|c| c.to_string());
                }
            }
            Step::Extract { from, to } => {
                if let Some(fp) = self.pile_index(&from.group, from.index) {
                    let pile = &s.piles[fp as usize];
                    if pile.len() >= 2 {
                        cards.push(pile[pile.len() - 2].to_string());
                    }
                }
                if let Some(tp) = self.pile_index(&to.group, to.index) {
                    onto = s.piles[tp as usize].last().map(|c| c.to_string());
                }
            }
            Step::Remove { piles } => {
                for r in piles {
                    if let Some(p) = self.pile_index(&r.group, r.index) {
                        if let Some(c) = s.piles[p as usize].last() {
                            cards.push(c.to_string());
                        }
                    }
                }
            }
            Step::DealSecondary { from, to } => {
                if let Some(fp) = self.pile_index(&from.group, from.index) {
                    if let Some(c) = s.piles[fp as usize].last() {
                        cards.push(c.up().to_string());
                    }
                }
                if let Some(tp) = self.pile_index(&to.group, to.index) {
                    onto = s.piles[tp as usize].last().map(|c| c.to_string());
                }
            }
            Step::Deal | Step::Redeal => {}
        }

        let mut next = s.clone();
        let mut j = Vec::new();
        self.apply(&mut next, mv, &mut j);

        let mut flipped = Vec::new();
        for g in self
            .groups
            .iter()
            .filter(|g| !g.hidden && g.kind != PileKind::Stock)
        {
            for p in g.piles() {
                let before = &s.piles[p as usize];
                let after = &next.piles[p as usize];
                let shared = before.len().min(after.len());
                for i in 0..shared {
                    if !before[i].is_face_up()
                        && after[i].is_face_up()
                        && before[i].face() == after[i].face()
                    {
                        flipped.push(FlippedCard {
                            pile: self.pile_ref(p),
                            card: after[i].to_string(),
                        });
                    }
                }
            }
        }

        let text = format_step_details(step, &cards, onto.as_deref());
        Ok((
            StepDetails {
                step: step.clone(),
                cards,
                onto,
                flipped,
                text,
            },
            next,
        ))
    }

    /// Replay `steps` from `initial` and return rich player-visible details for each step.
    pub fn describe_steps(
        &self,
        initial: &State,
        steps: &[Step],
    ) -> Result<Vec<StepDetails>, IllegalStep> {
        let mut cur = initial.clone();
        let mut out = Vec::with_capacity(steps.len());
        for step in steps {
            let (details, next) = self.describe_step(&cur, step)?;
            out.push(details);
            cur = next;
        }
        Ok(out)
    }

    fn deal_step_kind(&self, s: &State) -> Step {
        if self.redeal.is_some() {
            return Step::Redeal;
        }
        let st = self.stock.as_ref().unwrap();
        if s.piles[st.pile as usize].is_empty() {
            Step::Redeal
        } else {
            Step::Deal
        }
    }

    /// Render a position as text, one pile per line.
    pub fn render(&self, s: &State) -> String {
        let mut out = String::new();
        for g in self.groups.iter().filter(|g| !g.hidden) {
            for p in g.piles() {
                let cards: Vec<String> =
                    s.piles[p as usize].iter().map(|c| c.to_string()).collect();
                let label = if g.count == 1 {
                    g.name.clone()
                } else {
                    format!("{} {}", g.name, p - g.start + 1)
                };
                out.push_str(&format!("{label:>14}: {}\n", cards.join(" ")));
            }
        }
        if s.redeals_used > 0 {
            out.push_str(&format!("{:>14}: {}\n", "redeals used", s.redeals_used));
        }
        out
    }
}

/// A move that isn't legal in the position it was played in.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IllegalMove(pub Move);

impl fmt::Display for IllegalMove {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "illegal move: {:?}", self.0)
    }
}

impl std::error::Error for IllegalMove {}

/// A step that isn't legal in the position it was played in.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IllegalStep(pub Step);

impl fmt::Display for IllegalStep {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "illegal step: {}", self.0)
    }
}

impl std::error::Error for IllegalStep {}

/// A pile, named by its group and its index within the group (from 0).
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct PileRef {
    pub group: String,
    pub index: u16,
}

impl fmt::Display for PileRef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} {}", self.group, self.index + 1)
    }
}

/// One step of a solution, as a player would make it. Automatic actions (turning up exposed
/// cards, refilling from a reserve) follow each step and aren't listed.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "type", rename_all = "snake_case")]
#[non_exhaustive]
pub enum Step {
    /// Deal from the stock.
    Deal,
    /// Turn the waste back over to form a new stock.
    Redeal,
    /// Move `count` cards from the top of `from` onto `to`.
    Move {
        from: PileRef,
        to: PileRef,
        count: u16,
    },
    /// Remove the top cards of these piles.
    Remove { piles: Vec<PileRef> },
    /// Move the single card at position `index` (0 = bottom) of `from` onto `to`.
    Pick {
        from: PileRef,
        to: PileRef,
        index: u16,
    },
    /// Deal one card from a secondary stock `from` onto `to`.
    DealSecondary { from: PileRef, to: PileRef },
    /// Take the second card from the top of `from` and put it on `to`, leaving the top card.
    Extract { from: PileRef, to: PileRef },
}

impl fmt::Display for Step {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Step::Deal => write!(f, "deal"),
            Step::Redeal => write!(f, "redeal"),
            Step::Move { from, to, count: 1 } => write!(f, "{from} -> {to}"),
            Step::Move { from, to, count } => write!(f, "{from} -> {to} ({count} cards)"),
            Step::Pick { from, to, index } => write!(f, "{from}[{index}] -> {to}"),
            Step::Remove { piles } => {
                let names: Vec<String> = piles.iter().map(|p| p.to_string()).collect();
                write!(f, "remove {}", names.join(" + "))
            }
            Step::DealSecondary { from, to } => write!(f, "deal {from} -> {to}"),
            Step::Extract { from, to } => write!(f, "{from} (second card) -> {to}"),
        }
    }
}

/// A card turned face-up as an automatic consequence of a step.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct FlippedCard {
    pub pile: PileRef,
    pub card: String,
}

/// Player-visible details for a single step, including card names and any cards flipped face-up.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct StepDetails {
    pub step: Step,
    /// Cards explicitly moved or removed by this step (bottom to top), when applicable.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub cards: Vec<String>,
    /// Top card of the destination pile before the step, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub onto: Option<String>,
    /// Cards that were face-down before the step and are face-up afterward.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub flipped: Vec<FlippedCard>,
    /// Human-readable description (e.g. `"7H -> 8S (tableau 4 -> tableau 2)"`).
    pub text: String,
}

fn format_step_details(step: &Step, cards: &[String], onto: Option<&str>) -> String {
    let target = onto.unwrap_or("empty");
    match step {
        Step::Deal | Step::Redeal => step.to_string(),
        Step::Move { from, to, count: 1 } if !cards.is_empty() => {
            format!("{} -> {target} ({from} -> {to})", cards[0])
        }
        Step::Move { from, to, count } if !cards.is_empty() => {
            format!("{} ({count} cards) -> {target} ({from} -> {to})", cards[0])
        }
        Step::Pick { from, to, index } if !cards.is_empty() => {
            format!("{} -> {target} ({from}[{index}] -> {to})", cards[0])
        }
        Step::Extract { from, to } if !cards.is_empty() => {
            format!("{} -> {target} ({from} (second card) -> {to})", cards[0])
        }
        Step::DealSecondary { from, to } if !cards.is_empty() => {
            format!("deal {} -> {target} ({from} -> {to})", cards[0])
        }
        Step::Remove { piles } if !cards.is_empty() => {
            let names: Vec<String> = piles.iter().map(|p| p.to_string()).collect();
            format!("remove {} ({})", cards.join(" + "), names.join(" + "))
        }
        _ => step.to_string(),
    }
}

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

    #[test]
    fn game_metadata_render_and_steps() {
        let mut r = presets::klondike1();
        r.stock.as_mut().unwrap().unlimited_redeals = false;
        r.stock.as_mut().unwrap().redeals = 2;
        let g = Game::new(r).unwrap();
        assert_eq!(g.name(), "Klondike");
        assert_eq!(g.groups().count(), 4);
        assert_eq!(g.pile_kind(0), PileKind::Stock);

        let mut s = g.deal(1);
        assert!(g.legal_steps(&s).contains(&Step::Deal));
        g.play_step(&mut s, &Step::Deal).unwrap();
        assert!(g.play_step(&mut s, &Step::Redeal).is_err());

        // Drain stock to test Redeal and render with redeals_used > 0.
        while g.step_to_move(&s, &Step::Deal).is_some() {
            g.play_step(&mut s, &Step::Deal).unwrap();
        }
        assert!(g.legal_steps(&s).contains(&Step::Redeal));
        g.play_step(&mut s, &Step::Redeal).unwrap();
        let rendered = g.render(&s);
        assert!(rendered.contains("redeals used"), "{rendered}");

        // Display impls for Step, IllegalMove, IllegalStep.
        assert_eq!(Step::Deal.to_string(), "deal");
        assert_eq!(Step::Redeal.to_string(), "redeal");
        let p0 = PileRef {
            group: "tableau".into(),
            index: 0,
        };
        let p1 = PileRef {
            group: "tableau".into(),
            index: 1,
        };
        assert_eq!(
            Step::Move {
                from: p0.clone(),
                to: p1.clone(),
                count: 1
            }
            .to_string(),
            "tableau 1 -> tableau 2"
        );
        assert_eq!(
            Step::Move {
                from: p0.clone(),
                to: p1.clone(),
                count: 3
            }
            .to_string(),
            "tableau 1 -> tableau 2 (3 cards)"
        );
        assert_eq!(
            Step::Remove {
                piles: vec![p0, p1]
            }
            .to_string(),
            "remove tableau 1 + tableau 2"
        );
        let im = IllegalMove(Move::new(Action::Deal));
        assert!(im.to_string().contains("illegal move"));
        let is = IllegalStep(Step::Redeal);
        assert!(is.to_string().contains("illegal step"));
    }

    #[test]
    fn step_to_move_handles_redeal_and_remove() {
        let g_lbl = Game::new(presets::la_belle_lucie()).unwrap();
        let s_lbl = g_lbl.deal(1);
        assert!(g_lbl.step_to_move(&s_lbl, &Step::Deal).is_none());
        assert!(g_lbl.step_to_move(&s_lbl, &Step::Redeal).is_some());

        let g_pyr = Game::new(presets::pyramid()).unwrap();
        let s_pyr = g_pyr.deal(1);
        let remove = g_pyr
            .legal_steps(&s_pyr)
            .into_iter()
            .find(|st| matches!(st, Step::Remove { .. }))
            .expect("pyramid seed 1 has a removal");
        assert!(g_pyr.step_to_move(&s_pyr, &remove).is_some());
    }

    #[test]
    fn contiguous_sum_range_and_r1_mechanics() {
        use crate::card::{Card, Suit};

        // 1) Variable-length ContiguousSumMultiple (len = 6 > 4 -> Action::RemoveRange),
        //    min_len = 2, max_sum = 30, face_ten = true.
        let mut t = GroupRules::new("tableau", PileKind::Tableau, 10)
            .empty(EmptyRule::None)
            .moves(MoveUnit::None)
            .max_cards(1);
        t.compact = false;
        let mut r = Rules::new(
            "contiguous_range_test",
            Pack::new(&[Suit::Spades, Suit::Hearts], &[1, 2, 3, 4, 5, 11, 12, 13]),
            vec![
                GroupRules::new("foundation", PileKind::Foundation, 1)
                    .build(BuildBy::None, Dir::Up)
                    .empty(EmptyRule::None),
                t,
                GroupRules::new("stock", PileKind::Stock, 1),
            ],
            vec![
                DealStep::to("tableau").piles(&[0]).each(1),
                DealStep::to("stock").rest().down(),
            ],
        );
        let mut rem = RemovalRules::new(
            RemovalKind::ContiguousSumMultiple {
                divisor: 10,
                max_len: 10,
            },
            &["tableau"],
            "foundation",
        );
        rem.min_len = Some(2);
        rem.max_sum = Some(30);
        rem.face_ten = true;
        r.removal = vec![rem];
        r.win = WinRule::Count {
            group: "foundation".into(),
            cards: 6,
        };
        // Serde round-trip check.
        let json = serde_json::to_string(&r).unwrap();
        let r_back: Rules = serde_json::from_str(&json).unwrap();
        assert_eq!(r, r_back);
        // Existing JSON without new RemovalRules fields deserializes with defaults.
        let legacy_json = r#"{"kind":{"contiguous_sum_multiple":{"divisor":10,"max_len":4}},"from":["tableau"],"to":"foundation"}"#;
        let legacy: RemovalRules = serde_json::from_str(legacy_json).unwrap();
        assert_eq!(
            legacy,
            RemovalRules::new(
                RemovalKind::ContiguousSumMultiple {
                    divisor: 10,
                    max_len: 4,
                },
                &["tableau"],
                "foundation",
            )
        );

        let g = Game::new(r).unwrap();
        assert!(!g.groups[1].symmetric);
        let mut s = g.deal(0);
        for p in &mut s.piles {
            p.clear();
        }
        // Piles 1..=6 (tableau 0..=5): 1 + 2 + 3 + 4 + J(10) + Q(10) = 30 (6 cards).
        // Pile 7 (tableau 6): K(10) -> single K blocked by min_len=2, and 30+10=40 blocked by max_sum=30.
        let tab = g.groups[1].start;
        s.piles[tab as usize].push(Card::new(Suit::Spades, 1));
        s.piles[tab as usize + 1].push(Card::new(Suit::Spades, 2));
        s.piles[tab as usize + 2].push(Card::new(Suit::Spades, 3));
        s.piles[tab as usize + 3].push(Card::new(Suit::Spades, 4));
        s.piles[tab as usize + 4].push(Card::new(Suit::Hearts, 11));
        s.piles[tab as usize + 5].push(Card::new(Suit::Hearts, 12));
        s.piles[tab as usize + 6].push(Card::new(Suit::Hearts, 13));

        let moves = g.legal_moves(&s);
        let range_mv = moves
            .iter()
            .copied()
            .find(|m| matches!(m.action, Action::RemoveRange { len: 6, .. }))
            .expect("6-card contiguous removal totaling 30");
        // 7-card sum is 40 > max_sum(30), and single J/Q/K is < min_len(2).
        assert!(!moves
            .iter()
            .any(|m| matches!(m.action, Action::RemoveRange { len: 7, .. })));
        assert!(!moves
            .iter()
            .any(|m| matches!(m.action, Action::Remove { n: 1, .. })));

        let steps = g.steps(&s, &[range_mv]);
        assert_eq!(
            steps[0],
            Step::Remove {
                piles: (0..6)
                    .map(|index| PileRef {
                        group: "tableau".into(),
                        index,
                    })
                    .collect()
            }
        );
        assert_eq!(g.step_to_move(&s, &steps[0]), Some(range_mv));

        let orig = s.clone();
        let mut j = Vec::new();
        g.apply(&mut s, range_mv, &mut j);
        assert_eq!(s.piles[g.groups[0].start as usize].len(), 6);
        assert!(g.is_won(&s));
        g.undo_to(&mut s, &mut j, 0);
        assert_eq!(s, orig);

        // 2) open_next_on_rank + accept_any_on_single + empty_requires_same_index_non_empty + empty_match_suit_of.
        let mut r2 = Rules::new(
            "r1_gates_test",
            Pack::new(&[Suit::Spades, Suit::Hearts], &[1, 2, 3, 4]),
            vec![
                GroupRules::new("stock", PileKind::Stock, 1),
                GroupRules::new("foundation", PileKind::Foundation, 2)
                    .build(BuildBy::Suit, Dir::Up)
                    .empty(EmptyRule::Rank(1))
                    .max_cards(4),
                GroupRules::new("tableau", PileKind::Tableau, 4)
                    .build(BuildBy::Suit, Dir::Down)
                    .moves(MoveUnit::Top)
                    .empty(EmptyRule::Any)
                    .accept_any_on_single()
                    .empty_requires_same_index_non_empty("foundation")
                    .empty_match_suit_of("foundation"),
            ],
            vec![DealStep::to("stock").rest().down()],
        );
        r2.stock = Some(StockRules::to("tableau").open_next_on_rank(4));
        let g2 = Game::new(r2).unwrap();
        assert!(!g2.compress_talon);
        assert!(!g2.any_autoplay);
        assert!(!g2.groups[1].symmetric);
        assert!(!g2.groups[2].symmetric);

        let mut s2 = g2.deal(0);
        for p in &mut s2.piles {
            p.clear();
        }
        let sp = g2.stock_pile.unwrap() as usize;
        let t0 = g2.groups[2].start as usize;
        let f0 = g2.groups[1].start as usize;
        // Put 2S then 4H on stock (top of stock is 4H, then 2S).
        s2.piles[sp].push(Card::new(Suit::Spades, 2).down());
        s2.piles[sp].push(Card::new(Suit::Hearts, 4).down());

        // Deal 1 (4H == open_next_on_rank 4): goes to first empty pile t0.
        let s2_before = s2.clone();
        let mut j2 = Vec::new();
        g2.apply(&mut s2, Move::new(Action::Deal), &mut j2);
        assert_eq!(s2.piles[t0], vec![Card::new(Suit::Hearts, 4)]);
        // Deal 2 (2S != 4): goes to last non-empty pile t0.
        g2.apply(&mut s2, Move::new(Action::Deal), &mut j2);
        assert_eq!(
            s2.piles[t0],
            vec![Card::new(Suit::Hearts, 4), Card::new(Suit::Spades, 2)]
        );
        g2.undo_to(&mut s2, &mut j2, 0);
        assert_eq!(s2, s2_before);

        // Verify accept_any_on_single and empty_match_suit_of:
        // Put 2H on t1 (single card), 3S on t0, AS on f0.
        s2.piles[sp].clear();
        s2.piles[f0].push(Card::new(Suit::Spades, 1));
        s2.piles[t0].push(Card::new(Suit::Spades, 3));
        s2.piles[t0 + 1].push(Card::new(Suit::Hearts, 2));
        // 3S can go on 2H (len == 1, accept_any_on_single).
        assert!(g2.is_legal(
            &s2,
            Move::new(Action::Transfer {
                from: t0 as u16,
                to: (t0 + 1) as u16,
                count: 1,
            })
        ));
        // 2H CANNOT go on empty t2 (f0 has Spades, t2 % 2 == 0 -> must match Spades).
        assert!(!g2.is_legal(
            &s2,
            Move::new(Action::Transfer {
                from: (t0 + 1) as u16,
                to: (t0 + 2) as u16,
                count: 1,
            })
        ));
        // 3S CAN go on empty t2 (f0 has Spades, t2 % 2 == 0).
        assert!(g2.is_legal(
            &s2,
            Move::new(Action::Transfer {
                from: t0 as u16,
                to: (t0 + 2) as u16,
                count: 1,
            })
        ));
        // 3S CANNOT go on empty t3 (f1 is empty).
        assert!(!g2.is_legal(
            &s2,
            Move::new(Action::Transfer {
                from: t0 as u16,
                to: (t0 + 3) as u16,
                count: 1,
            })
        ));
    }

    #[test]
    fn grid_hole_fill_phases_and_can_deal() {
        use crate::card::Suit;
        let mut r = Rules::new(
            "hole_fill_unit",
            Pack::new(&[Suit::Spades, Suit::Hearts, Suit::Clubs], &[1, 2, 3, 4]),
            vec![
                GroupRules::new("stock", PileKind::Stock, 1),
                GroupRules::new("tableau", PileKind::Tableau, 9)
                    .layout(Layout::GridVertical { columns: 3 })
                    .max_cards(1),
            ],
            vec![DealStep::to("stock").rest().down()],
        );
        let mut st = StockRules::to("tableau");
        st.fill_grid_holes_then_row = true;
        r.stock = Some(st);
        r.win = WinRule::Empty(vec!["tableau".into(), "stock".into()]);
        let g = Game::new(r).unwrap();
        let tab = g.groups[1].start as usize;
        let stk = g.groups[0].start as usize;

        // 1) max_h == 0 -> deals row 0 (0, 1, 2).
        let mut s = g.deal(1);
        assert!(g.can_deal(&s));
        let mut j = Vec::new();
        assert!(g.talon_step(&mut s, &mut j));
        assert_eq!(s.piles[tab].len(), 1);
        assert_eq!(s.piles[tab + 1].len(), 1);
        assert_eq!(s.piles[tab + 2].len(), 1);
        assert!(s.piles[tab + 3].is_empty());

        // 2) All columns height 1 and top row full and max_h < 3 -> deals row 1 (3, 4, 5).
        assert!(g.talon_step(&mut s, &mut j));
        assert_eq!(s.piles[tab + 3].len(), 1);
        assert_eq!(s.piles[tab + 4].len(), 1);
        assert_eq!(s.piles[tab + 5].len(), 1);

        // 3) Deal row 2 (6, 7, 8), now max_h = 3.
        assert!(g.talon_step(&mut s, &mut j));
        for i in 0..9 {
            assert_eq!(s.piles[tab + i].len(), 1);
        }
        // Full grid -> can_deal must be false even with stock non-empty.
        assert!(!s.piles[stk].is_empty());
        assert!(!g.can_deal(&s));

        // 4) Create two holes in col 0 (rows 0 and 1, with row 2 occupied) and one hole in col 1 (row 0, with row 1 occupied and row 2 empty).
        // Put removed cards back into stock so card count is conserved.
        let c0 = s.piles[tab].pop().unwrap().down();
        let c3 = s.piles[tab + 3].pop().unwrap().down();
        let c1 = s.piles[tab + 1].pop().unwrap().down();
        let c7 = s.piles[tab + 7].pop().unwrap().down();
        s.piles[stk].extend([c0, c3, c1, c7]);
        s.piles[stk].truncate(3);
        // max_h = 3 (col 0 has row 2, col 1 has row 1, col 2 has rows 0..=2).
        // Phase 1: col 0 lowest empty r < 2 with (r+1, 0) non-empty -> (1, 0) = tab + 3; col 1 -> (0, 1) = tab + 1.
        // Phase 2 (1 card left): col 0 topmost remaining empty r < 3 -> (0, 0) = tab + 0, leaving tab + 7 empty.
        assert!(g.can_deal(&s));
        let mark = j.len();
        assert!(g.talon_step(&mut s, &mut j));
        assert_eq!(s.piles[tab + 3].len(), 1);
        assert_eq!(s.piles[tab + 1].len(), 1);
        assert_eq!(s.piles[tab].len(), 1);
        assert!(s.piles[tab + 7].is_empty());
        // Undo restores exact state.
        g.undo_to(&mut s, &mut j, mark);
        assert!(s.piles[tab + 3].is_empty());
        assert!(s.piles[tab + 1].is_empty());
        assert!(s.piles[tab].is_empty());
    }

    #[test]
    fn fission_shift_bottom_up_and_undo() {
        use crate::card::Suit;
        let mut tab = GroupRules::new("tableau", PileKind::Tableau, 5)
            .build(BuildBy::Any, Dir::Down)
            .moves(MoveUnit::Top)
            .empty(EmptyRule::None)
            .layout(Layout::GridBottomOpen { columns: 1 });
        tab.fission_shift = true;
        let mut r = Rules::new(
            "fission_unit",
            Pack::new(&[Suit::Spades], &[1, 2, 3, 4, 5]),
            vec![
                GroupRules::new("cell", PileKind::Cell, 1)
                    .empty(EmptyRule::Any)
                    .moves(MoveUnit::Top)
                    .max_cards(1),
                tab,
            ],
            vec![DealStep::to("tableau").each(1)],
        );
        r.win = WinRule::AllIsolated {
            group: "tableau".into(),
            empty: vec!["cell".into()],
        };
        let g = Game::new(r).unwrap();
        let mut s = g.deal(1);
        let orig = s.clone();
        let cell = g.groups[0].start;
        let t = g.groups[1].start;
        // Move bottom pile (row 4) to cell: k = 4 contiguous piles above -> shift = 2 (row 3 -> 4, row 2 -> 3).
        let expect_r2 = s.piles[(t + 2) as usize][0];
        let expect_r3 = s.piles[(t + 3) as usize][0];
        let mut j = Vec::new();
        g.apply(
            &mut s,
            Move::new(Action::Transfer {
                from: t + 4,
                to: cell,
                count: 1,
            }),
            &mut j,
        );
        assert!(s.piles[(t + 2) as usize].is_empty());
        assert_eq!(s.piles[(t + 3) as usize], vec![expect_r2]);
        assert_eq!(s.piles[(t + 4) as usize], vec![expect_r3]);
        assert!(!g.is_won(&s));
        g.undo_to(&mut s, &mut j, 0);
        assert_eq!(s, orig);
    }

    #[test]
    fn compact_columns_noop_and_after_neighbor_wrap() {
        use crate::card::Suit;
        let mut r = Rules::new(
            "cc_unit",
            Pack::new(&[Suit::Spades], &[1, 3, 5, 7]),
            vec![
                GroupRules::new("stock", PileKind::Stock, 1),
                GroupRules::new("tableau", PileKind::Tableau, 4)
                    .build_rule(Build::new(BuildBy::Suit, Dir::Up).wrap())
                    .empty(EmptyRule::AfterNeighbor { first: 0 })
                    .moves(MoveUnit::Top)
                    .max_cards(1)
                    .layout(Layout::Grid { columns: 2 }),
            ],
            vec![DealStep::to("tableau").each(1)],
        );
        r.redeal = Some(RedealRules::new(
            "tableau",
            RedealHow::CompactColumns {
                refill_from: Some("stock".into()),
            },
        ));
        r.win = WinRule::Empty(vec!["tableau".into(), "stock".into()]);
        let g = Game::new(r).unwrap();
        let mut s = g.deal(1);
        // Grid full and stock empty -> CompactColumns is a no-op, so can_deal is false.
        assert!(!g.can_deal(&s));

        // Put col 0 row 0 empty, col 0 row 1 has 1S: AfterNeighbor{first:0} with wrap on [1,3,5,7]
        // accepts 7S on col 0 row 0, and must NOT match col 0 row 1's neighbor across row boundary.
        let t = g.groups[1].start as usize;
        s.piles[t].clear();
        s.piles[t + 1] = vec![Card::new(Suit::Spades, 1).up()];
        s.piles[t + 2] = vec![Card::new(Suit::Spades, 3).up()];
        s.piles[t + 3] = vec![Card::new(Suit::Spades, 5).up()];
        let mask = g.empty_set(t as u16, &s);
        assert_eq!(mask, 1u64 << Card::new(Suit::Spades, 7).face());
        // Row 0 col 1 (t+1) empty: left is t (empty), right is t+2 (next row! must NOT be checked).
        s.piles[t + 1].clear();
        assert_eq!(g.empty_set(t as u16 + 1, &s), 0);
        // Now col 0 row 0 has empty above col 0 row 1 (non-empty) -> CompactColumns can_deal is true.
        assert!(g.can_deal(&s));
    }

    #[test]
    fn describe_step_and_steps_report_cards_onto_and_flips() {
        let fc = Game::new(presets::freecell()).unwrap();
        let s = fc.deal(1);
        let step = fc
            .legal_steps(&s)
            .into_iter()
            .find(|st| matches!(st, Step::Move { .. }))
            .expect("freecell has legal moves");
        let (details, next) = fc.describe_step(&s, &step).unwrap();
        assert_eq!(details.step, step);
        assert_eq!(details.cards.len(), 1);
        assert!(details.text.contains(&details.cards[0]));
        assert!(details.flipped.is_empty());

        // describe_steps matches sequential play_step.
        let mut s2 = s.clone();
        fc.play_step(&mut s2, &step).unwrap();
        assert_eq!(next, s2);
        let list = fc.describe_steps(&s, &[step]).unwrap();
        assert_eq!(list.len(), 1);
        assert_eq!(list[0], details);

        // Klondike flip detection: move a tableau card that exposes a face-down card.
        let kl = Game::new(presets::klondike1()).unwrap();
        let mut found_flip = false;
        for seed in 1..=20 {
            let ks = kl.deal(seed);
            for st in kl.legal_steps(&ks) {
                let (d, _) = kl.describe_step(&ks, &st).unwrap();
                if !d.flipped.is_empty() {
                    assert_eq!(d.flipped[0].pile.group, "tableau");
                    assert!(!d.flipped[0].card.starts_with('~'));
                    found_flip = true;
                    break;
                }
            }
            if found_flip {
                break;
            }
        }
        assert!(
            found_flip,
            "expected at least one Klondike move to flip a face-down card"
        );
    }
}