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
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
//! The rules model: a game is described as data.
//!
//! A [`Rules`] value names the pack, the groups of piles on the table (tableau, foundations,
//! cells, reserves, stock, waste), what each pile accepts and lets go, how the stock deals, how
//! the cards are dealt at the start, any card-removal mechanic (Pyramid's pairs, Aces Up's
//! discards), and what counts as a win.
//!
//! Every field that has a sensible default for its pile kind may be left out, so most games are
//! a dozen lines of JSON. The presets in [`crate::presets`] are written with the same types.

use serde::{Deserialize, Serialize};

use crate::card::{Color, Suit};

/// Accepts an optional `"$schema"` metadata string in JSON files and ignores it.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
struct IgnoredSchema;

impl Serialize for IgnoredSchema {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_none()
    }
}

impl<'de> Deserialize<'de> for IgnoredSchema {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let _: Option<String> = Option::deserialize(d)?;
        Ok(IgnoredSchema)
    }
}

#[cfg(feature = "schema")]
impl schemars::JsonSchema for IgnoredSchema {
    fn schema_name() -> String {
        "SchemaUri".to_string()
    }

    fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
        <Option<String>>::json_schema(gen)
    }
}

/// A complete description of one solitaire game.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct Rules {
    /// Optional JSON Schema URI for editor validation (ignored by the solver).
    #[serde(rename = "$schema", default, skip_serializing)]
    _schema: IgnoredSchema,
    /// Human-readable name, e.g. "FreeCell".
    pub name: String,
    #[serde(default, skip_serializing_if = "is_default_pack")]
    pub pack: Pack,
    /// The piles on the table, in groups of identical piles.
    pub groups: Vec<GroupRules>,
    /// How the stock deals. Needs a group of kind `stock`. A stock without these rules only
    /// feeds refills (`refill_from`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stock: Option<StockRules>,
    /// Gathering the tableau and dealing it out again, as a player action (Cruel, La Belle
    /// Lucie, Montana). Can't be combined with `stock`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub redeal: Option<RedealRules>,
    /// The opening deal, step by step. Cards come off a shuffled pack.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub deal: Vec<DealStep>,
    /// Card-removal mechanics, for games that discard cards instead of (or as well as)
    /// building. One object or a list.
    #[serde(
        default,
        deserialize_with = "one_or_many",
        skip_serializing_if = "Vec::is_empty"
    )]
    pub removal: Vec<RemovalRules>,
    /// Points for the position, for games played for a score (Poker Squares).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub score: Option<ScoreRules>,
    #[serde(default, skip_serializing_if = "is_default_win")]
    pub win: WinRule,
    /// Turn up a face-down card when it becomes the top of an uncovered pile. Default true.
    #[serde(default = "yes", skip_serializing_if = "is_true")]
    pub auto_flip: bool,
    /// Let the solver play cards to foundations automatically when it can prove nothing could
    /// ever need to be built on them. Sound for in-suit foundations; default true.
    #[serde(default = "yes", skip_serializing_if = "is_true")]
    pub safe_autoplay: bool,
    /// Tuning for the solver's heuristic. Changes how fast a win is found, never whether a
    /// position is judged winnable.
    #[serde(default, skip_serializing_if = "SearchHints::is_default")]
    pub search: SearchHints,
    /// Opening choice of the foundation base rank: before a base rank is set, only a single-card
    /// move from this group to a foundation is legal, and its rank becomes the base rank.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub choose_base: Option<ChooseBase>,
    /// A latch that a move from the stock pile resets: afterwards it is set if the stock is empty
    /// or no pile of this group is empty, and clear otherwise. Removals with `needs_latch` work
    /// only while it is set (Camelot: pairs come off only once the grid is full or the stock is
    /// out, and the latch stays set until the next card is played from the stock).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub latch_group: Option<String>,
    /// Cards put on top of the shuffled pack before dealing, in the order they are dealt
    /// (Royal Marriage: the queen of hearts first). Only for seeded deals.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub deck_first: Vec<CardRef>,
    /// Shuffle each copy of the pack on its own, so one whole pack is dealt before the next
    /// (Microbe). Only for seeded deals.
    #[serde(default, skip_serializing_if = "is_false")]
    pub separate_decks: bool,
    /// Cards put at the bottom of the shuffled pack before dealing, in the order they are dealt
    /// (Royal Marriage: the king of hearts last). Only for seeded deals.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub deck_last: Vec<CardRef>,
    /// Move the first card of this rank in the shuffled pack to the bottom, so it is dealt last.
    /// Only for seeded deals.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub deck_last_rank: Option<u8>,
    /// Two general-purpose counters that rules can update on events and test in conditions
    /// (see [`AuxRules`]). Games that use them are never auto-played or talon-compressed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub aux: Option<AuxRules>,
    /// A move that takes the second card from the top of a pile (see [`ExtractSecond`]).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub extract_second: Option<ExtractSecond>,
    /// Rounds of cribbage play: hands discard to a crib, a starter is turned, and the points add
    /// up across rounds (see [`RoundRules`]). Needs stock rules.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rounds: Option<RoundRules>,
}

/// A card named by suit and rank.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct CardRef {
    pub suit: Suit,
    /// 1 = ace, 13 = king.
    pub rank: u8,
}

/// Rules for choosing the foundation base rank on the opening move.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct ChooseBase {
    /// Group whose cards may be played to a foundation to choose the base rank.
    pub from: String,
    /// Immediately deal one card from the stock to the emptied source pile after the choice.
    #[serde(default)]
    pub refill_from_stock: bool,
    /// Immediately deal one card from the stock to the waste after the choice.
    #[serde(default)]
    pub deal_waste: bool,
    /// Until the base is chosen, only foundation plays are restricted (to one card from `from`);
    /// every other move and the stock stay open (Nine Across).
    #[serde(default)]
    pub free_moves: bool,
    /// A second group whose cards may also be played to a foundation to choose the base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub also_from: Option<String>,
    /// Groups whose cards cannot move (and, for the stock, cannot be dealt) until the base is
    /// chosen, even with `free_moves`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub lock_until_base: Vec<String>,
}

impl ChooseBase {
    pub fn from(group: &str) -> ChooseBase {
        ChooseBase {
            from: group.to_string(),
            refill_from_stock: false,
            deal_waste: false,
            free_moves: false,
            also_from: None,
            lock_until_base: Vec::new(),
        }
    }
}

/// Heuristic weights and search tuning. They change how fast the solver finds a win (or how
/// soon it gives up), never whether a position is judged winnable. Every field has a neutral
/// default.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields, default)]
#[non_exhaustive]
pub struct SearchHints {
    /// Cost of each card still to go home, or each step still missing from the win (default 4).
    pub progress_weight: u32,
    /// Cost of each face-down card (default 2).
    pub down_weight: u32,
    /// Cost of each card out of sequence in a building pile, and of each such pile in use
    /// (default 1).
    pub disorder_weight: u32,
    /// Cost of a card resting on a card its foundation needs sooner (default 1).
    pub blocker_weight: u32,
    /// Cost of each card in a free cell (default 1).
    pub cell_weight: u32,
    /// Cost of each card still in a stock that deals to the tableau (default 1).
    pub stock_weight: u32,
    /// Percent of the budget the default strategy spends on its fast, pruned best-first phase
    /// before the sound depth-first search (default 50).
    pub fast_share: u32,
}

impl Default for SearchHints {
    fn default() -> Self {
        SearchHints {
            progress_weight: 4,
            down_weight: 2,
            disorder_weight: 1,
            blocker_weight: 1,
            cell_weight: 1,
            stock_weight: 1,
            fast_share: 50,
        }
    }
}

impl Rules {
    /// Rules with a name, pack, groups and deal; everything else at its default (no stock
    /// rules, redeal, removal or score; won with every card on a foundation). Set the other
    /// fields directly.
    pub fn new(name: &str, pack: Pack, groups: Vec<GroupRules>, deal: Vec<DealStep>) -> Rules {
        Rules {
            _schema: IgnoredSchema,
            name: name.to_string(),
            pack,
            groups,
            stock: None,
            redeal: None,
            deal,
            removal: Vec::new(),
            score: None,
            win: WinRule::AllOnFoundations,
            auto_flip: true,
            safe_autoplay: true,
            search: SearchHints::default(),
            choose_base: None,
            latch_group: None,
            deck_first: Vec::new(),
            separate_decks: false,
            deck_last: Vec::new(),
            deck_last_rank: None,
            aux: None,
            extract_second: None,
            rounds: None,
        }
    }
}

impl SearchHints {
    pub fn is_default(&self) -> bool {
        *self == SearchHints::default()
    }
}

fn yes() -> bool {
    true
}

fn one() -> u16 {
    1
}

/// The cards in play.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct Pack {
    /// Copies of each (suit, rank) card. Two-pack games use 2; one-suit Spider uses 8.
    #[serde(default = "one_u8", skip_serializing_if = "is_one_u8")]
    pub copies: u8,
    /// Suits in use. Default: all four.
    #[serde(default = "all_suits", skip_serializing_if = "is_all_suits")]
    pub suits: Vec<Suit>,
    /// Ranks in use, in sequence order: building goes from each rank to the next one in this
    /// list. Default `[1..=13]` (ace low). Aces high is `[2, 3, …, 13, 1]`; a stripped pack
    /// leaves ranks out.
    #[serde(default = "all_ranks", skip_serializing_if = "is_all_ranks")]
    pub ranks: Vec<u8>,
    /// Jokers in play, in all (not per copy). Jokers are wild: see [`GroupRules::wild`],
    /// [`RemovalKind`] and [`Hands`] for what they stand for where.
    #[serde(default, skip_serializing_if = "is_zero_u8")]
    pub jokers: u8,
}

fn is_false(b: &bool) -> bool {
    !*b
}

fn is_true(b: &bool) -> bool {
    *b
}

fn is_zero_u8(n: &u8) -> bool {
    *n == 0
}

fn is_zero_u16(n: &u16) -> bool {
    *n == 0
}

fn is_zero_u32(n: &u32) -> bool {
    *n == 0
}

fn is_one_u8(n: &u8) -> bool {
    *n == 1
}

fn is_one_u16(n: &u16) -> bool {
    *n == 1
}

fn is_default_pack(p: &Pack) -> bool {
    *p == Pack::default()
}

fn is_default_win(w: &WinRule) -> bool {
    *w == WinRule::AllOnFoundations
}

fn is_all_suits(s: &[Suit]) -> bool {
    s == Suit::ALL
}

fn is_all_ranks(r: &[u8]) -> bool {
    r.len() == 13 && r.iter().enumerate().all(|(i, &x)| x == (i + 1) as u8)
}

fn one_u8() -> u8 {
    1
}

fn all_suits() -> Vec<Suit> {
    Suit::ALL.to_vec()
}

fn all_ranks() -> Vec<u8> {
    (1..=13).collect()
}

impl Default for Pack {
    fn default() -> Self {
        Pack {
            copies: 1,
            suits: all_suits(),
            ranks: all_ranks(),
            jokers: 0,
        }
    }
}

impl Pack {
    /// One copy of each card of these suits and ranks (ranks in sequence order), no jokers.
    pub fn new(suits: &[Suit], ranks: &[u8]) -> Pack {
        Pack {
            copies: 1,
            suits: suits.to_vec(),
            ranks: ranks.to_vec(),
            jokers: 0,
        }
    }

    /// `n` copies of every card.
    pub fn with_copies(mut self, n: u8) -> Pack {
        self.copies = n;
        self
    }

    pub fn decks(n: u8) -> Pack {
        Pack {
            copies: n,
            ..Pack::default()
        }
    }

    /// Cards in the pack, jokers included.
    pub fn len(&self) -> usize {
        self.copies as usize * self.suits.len() * self.ranks.len() + self.jokers as usize
    }

    /// Add `n` jokers.
    pub fn with_jokers(mut self, n: u8) -> Pack {
        self.jokers = n;
        self
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

/// What a group of piles is for. The kind sets defaults and tells the solver how to treat it.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum PileKind {
    /// Main playing piles.
    Tableau,
    /// Where cards are built to win (or discarded to, in removal games).
    Foundation,
    /// Free cells: hold one card each by default.
    Cell,
    /// Cards that may be played from but not onto.
    Reserve,
    /// The face-down stock. At most one pile.
    Stock,
    /// Where the stock deals to. At most one pile.
    Waste,
}

/// One group of identical piles.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct GroupRules {
    /// Name used in deal steps, solutions and states, e.g. "tableau".
    pub name: String,
    pub kind: PileKind,
    #[serde(default = "one", skip_serializing_if = "is_one_u16")]
    pub count: u16,
    /// What may be placed on a pile's top card. Default: foundations build up in suit; every
    /// other kind accepts nothing on a non-empty pile.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub build: Option<Build>,
    /// What an empty pile accepts. Default: foundations take the pack's first rank; tableaux and
    /// cells take any card; reserves, stock and waste take none.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub empty: Option<EmptyRule>,
    /// Which cards may leave a pile. Default: one card for tableaux, cells, reserves and the
    /// waste; none for foundations and the stock.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub moves: Option<MoveUnit>,
    /// Most cards the pile may hold. Default: 1 for cells, unlimited otherwise.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_cards: Option<u16>,
    /// Fewest cards that must remain on the pile (cards at or below this depth cannot leave).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min_cards: Option<u16>,
    /// Most cards the pile accepts in one move. Default: 1 for foundations (a whole suit for
    /// `complete_runs`), unlimited otherwise.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_accept: Option<u16>,
    /// Only cards coming from these groups are accepted (default: any group).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub accepts_from: Option<Vec<String>>,
    /// Only cards coming from these groups are accepted onto an empty pile (default: same as
    /// `accepts_from`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub empty_accepts_from: Option<Vec<String>>,
    /// When a pile in this group empties, refill it automatically with the top card of the
    /// first non-empty pile of these groups, tried in order (Canfield's tableau from its
    /// reserve; many games from the waste, then the stock). Stock cards are turned face up.
    /// Groups to try in order; a group name or a list.
    #[serde(
        default,
        deserialize_with = "one_or_many",
        skip_serializing_if = "Vec::is_empty"
    )]
    pub refill_from: Vec<String>,
    /// Cards moved per automatic refill from `refill_from` (default 1).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub refill_count: Option<u16>,
    /// For piles that overlap (Pyramid, TriPeaks): which piles cover which.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub layout: Option<Layout>,
    /// Foundation only accepts a whole suit sequence at once, moved together (Spider).
    #[serde(default, skip_serializing_if = "is_false")]
    pub complete_runs: bool,
    /// A pile accepts cards only from piles of its own group exactly this many places after
    /// it (Accordion: 1 and 3).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reach: Option<Vec<u16>>,
    /// With `reach`: also accept from piles this many places before the destination pile.
    #[serde(default, skip_serializing_if = "is_false")]
    pub reach_both_ways: bool,
    /// With `reach` on a grid layout: a distance of one place only counts within a row (so a pile
    /// does not reach round the end of a row). With distances of one and the row length the
    /// piles reached are the four neighbours (Rectangular Rovers).
    #[serde(default, skip_serializing_if = "is_false")]
    pub reach_grid: bool,
    /// Empty piles take cards from the waste only while every pile of this named group is empty
    /// (Dutchess: an empty row takes a waste card once the reserves are gone).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub empty_needs_group_empty: Option<String>,
    /// Cards from piles of this same group are taken only as the whole pile (Dutchess).
    #[serde(default, skip_serializing_if = "is_false")]
    pub accept_whole_from_group: bool,
    /// A run of several cards put on a pile of this group must also be a valid run under that
    /// pile's own build rule (a descending run cannot go on a pile that builds up).
    #[serde(default, skip_serializing_if = "is_false")]
    pub run_must_fit_build: bool,
    /// With `moves: run`: cards leave a pile as a run only if each adjacent pair fits at least one
    /// of these builds, instead of the pile's own build (which then governs only what the pile
    /// accepts). Without jokers.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub move_runs_by: Vec<Build>,
    /// A pile takes this many cards of one rank in a row, then goes on to the next rank of the
    /// pack, wrapping round (Four by Four). Use with `build: any/any` so nothing is ruled out
    /// before the pile itself is looked at.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub repeat_rank: Option<u16>,
    /// With a `covers` layout: a pile covered by one pile only may take that whole pile at once
    /// even while it is covered, if the cards build on it (Interlock's drop-down move).
    #[serde(default, skip_serializing_if = "is_false")]
    pub dropdown: bool,
    /// See [`FromPileMap`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub from_pile_map: Option<FromPileMap>,
    /// See [`ClearTops`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub clear_tops: Option<ClearTops>,
    /// While no redeal has happened yet, these bans apply.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub first_round_bans: Vec<FirstRoundBan>,
    /// For a win by rows on a group whose `empty` rule is not `after_left`: the rank each row
    /// starts with (Rectangular Rovers).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub row_start: Option<u8>,
    /// When a card is placed on a non-empty pile of this group, first move the destination pile's
    /// existing cards to this group's first pile.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub replace_on_drop: Option<String>,
    /// Keep the group packed: whenever a pile empties, the piles after it slide forward.
    #[serde(default, skip_serializing_if = "is_false")]
    pub compact: bool,
    /// Piles accept only cards of this suit.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub suit: Option<Suit>,
    /// Piles accept no card of this suit, and nothing may be built on one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exclude_suit: Option<Suit>,
    /// Empty piles accept only cards of this suit (non-empty piles follow `build` as usual).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub empty_suit: Option<Suit>,
    /// Piles accept only cards of this colour.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub color: Option<Color>,
    /// Different rules for particular piles of the group (Calculation's foundations, each
    /// building by a different step from a different base).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub piles: Vec<PileOverride>,
    /// Jokers are wild on these piles: a joker stands for any card that would be legal where
    /// it lies. It may be placed wherever some card could be (by the build rule, or the empty
    /// rule on an empty pile), and a card may be built on it if it could be built on some card
    /// the joker could stand for, given the cards beneath it. The joker's stand-in is never
    /// fixed: it is whatever keeps the pile legal. Where jokers aren't wild, a joker can only
    /// go to an empty pile that takes any card, and nothing is built on it. Default: wild
    /// everywhere but foundations.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub wild: Option<bool>,
    /// Each pile after the first only accepts a card whose rank is already present on the
    /// previous pile in the group (when empty, it must match the previous pile's bottom card).
    #[serde(default, skip_serializing_if = "is_false")]
    pub requires_rank_on_prev: bool,
    /// A pile with fewer cards than the longest pile in this group only accepts a card whose rank
    /// matches the card at the same index in the longest pile.
    #[serde(default, skip_serializing_if = "is_false")]
    pub match_longest_rank: bool,
    /// Most cards that may be placed onto an empty pile in one move. Default: same as `max_accept`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub empty_max_accept: Option<u16>,
    /// Accept cards only when the destination pile is empty (even if `build` is set for moving runs).
    #[serde(default, skip_serializing_if = "is_false")]
    pub accept_only_when_empty: bool,
    /// Accept cards only when the stock pile is empty.
    #[serde(default, skip_serializing_if = "is_false")]
    pub accept_when_stock_empty: bool,
    /// Accept cards only when the waste pile is empty as well (with `accept_when_stock_empty`:
    /// Zodiac's foundations wait until the whole deal is played).
    #[serde(default, skip_serializing_if = "is_false")]
    pub accept_when_waste_empty: bool,
    /// When a pile in this group becomes empty, shift the movable face-up run from the next pile
    /// into it, leaving any face-down cards behind.
    #[serde(default, skip_serializing_if = "is_false")]
    pub compact_face_up: bool,
    /// When refilling from a multi-pile group in `refill_from`, take from the pile with the most
    /// cards (ties broken by lowest index) rather than the first non-empty pile.
    #[serde(default, skip_serializing_if = "is_false")]
    pub refill_largest: bool,
    /// Refill a pile in this group only when a move just emptied it, rather than also filling
    /// pre-existing empty piles when a refill source later receives a card.
    #[serde(default, skip_serializing_if = "is_false")]
    pub refill_on_empty: bool,
    /// Each pile after the first may only be started (while empty) once the previous pile in the
    /// group is non-empty.
    #[serde(default, skip_serializing_if = "is_false")]
    pub requires_prev_non_empty: bool,
    /// Most consecutive face-up cards of the same rank allowed at the top of a pile.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_same_rank: Option<u8>,
    /// Cards may leave piles of this group only once the stock pile is empty.
    #[serde(default, skip_serializing_if = "is_false")]
    pub moves_when_stock_empty: bool,
    /// Cards may leave piles of this group only once at least one pile in the named group is empty.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub moves_when_any_empty: Option<String>,
    /// Cards may leave pile `i` of this group only once pile `i` of the named group is empty.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub moves_when_same_index_empty: Option<String>,
    /// Cards may leave pile `i` of this group only once every pile of the `i`-th equal slice of
    /// the named group is empty (that group's pile count must be a multiple of this group's).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub moves_when_slice_empty: Option<String>,
    /// Cards may be added to pile `i` of this group only once pile `i` of the named group is
    /// non-empty (the groups must have the same pile count).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub requires_same_index_non_empty: Option<String>,
    /// Pile `i` of this group accepts cards only while pile `i` of the named group is empty,
    /// except cards coming from that very pile (the groups must have the same pile count).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub accept_when_same_index_empty: Option<String>,
    /// Cards may leave only the first or last non-empty pile of this group.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub move_from_frontier: Option<Frontier>,
    /// With an `empty` rule of one rank: once this many piles of the group start with a card of
    /// that rank, empty piles accept any card (Scorpion Towers).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub empty_open_after_bases: Option<u16>,
    /// Empty piles take any card once the first pile of the named group is full (The Plot: once
    /// the first foundation holds a whole suit the empty rows are open).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub empty_open_when_full: Option<String>,
    /// Empty piles of this group take nothing until the group's first pile is full (The Plot's
    /// foundations after the first).
    #[serde(default, skip_serializing_if = "is_false")]
    pub empty_needs_first_full: bool,
    /// Only automatically turn a pile's face-down top card face up when it is the sole card left
    /// in the pile.
    #[serde(default, skip_serializing_if = "is_false")]
    pub flip_only_last: bool,
    /// When a pile is one card shy of `max_cards`, its final card must come from the pile at the
    /// same index within this group (overriding `accepts_from`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub final_from_same_index: Option<String>,
    /// When `build.dir` is `either`, the first two-card pile in this group locks the build
    /// direction (up or down) for every pile in the group.
    #[serde(default, skip_serializing_if = "is_false")]
    pub lock_build_dir: bool,
    /// Never automatically turn face-down cards in this group face up (cards may still be drawn
    /// face up by `refill_from`).
    #[serde(default, skip_serializing_if = "is_false")]
    pub no_flip: bool,
    /// When refilling an emptied pile from `refill_from`, take from the pile at the same index
    /// within the source group rather than the first non-empty pile.
    #[serde(default, skip_serializing_if = "is_false")]
    pub refill_same_index: bool,
    /// When refilling an emptied pile from `refill_from`, take from the pile at index `i % m`
    /// within the source group (where `m` is the source group's size), falling back to the nearest
    /// non-empty pile (`+1`, `-1`, `+2`, `-2`, ...).
    #[serde(default, skip_serializing_if = "is_false")]
    pub refill_nearest: bool,
    /// Only allow building onto a non-empty pile if its bottom card satisfies the pile's `empty`
    /// rule.
    #[serde(default, skip_serializing_if = "is_false")]
    pub require_valid_base: bool,
    /// When set, moving from one pile of this group onto another may swap the two piles instead
    /// of building.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub swap_bases: Option<SwapBases>,
    /// A card on a pile of this group may move only while it is the same card (suit and rank) as
    /// the face-up top card of the waste, and then it swaps places with another single-card pile
    /// of the group under this adjacency (a grid group). After a swap the stock acts as if the
    /// player had dealt, or turned the waste back if that is all it can do; if it can do nothing,
    /// the waste's top card is turned face down and no card can move again. Needs a
    /// waste-dealing stock; give the group `moves: none` and `accepts_from: []` so the ordinary
    /// rules offer nothing. The piles are not interchangeable.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub swap_on_waste_match: Option<Adjacency>,
    /// With `moves: supermove`, also allow moving a complete suit-length built run regardless of
    /// empty cells and columns.
    #[serde(default, skip_serializing_if = "is_false")]
    pub supermove_complete_run: bool,
    /// Cards coming from these groups are accepted onto empty or non-empty piles without checking
    /// `build` or `empty` rules (capacity limits still apply).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub unrestricted_from: Option<Vec<String>>,
    /// When `build.dir` is `either`, each pile locks its own build direction (up or down) once it
    /// holds two cards.
    #[serde(default, skip_serializing_if = "is_false")]
    pub lock_pile_dir: bool,
    /// A pile holding `max_cards` cards that all follow its build rule is closed: no card may be moved from it.
    #[serde(default, skip_serializing_if = "is_false")]
    pub freeze_when_built: bool,
    /// A pile whose top card is face down takes any cards at all (Blind Patience).
    #[serde(default, skip_serializing_if = "is_false")]
    pub accept_on_face_down: bool,
    /// Piles of this group from this index on take nothing from the piles of this group before it
    /// (Club: the three top rows never give to the lower eight).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub one_way_split: Option<u16>,
    /// A face-down top card may be moved: it turns face up as it goes (Blind Patience, where the
    /// player turns a card over by hand and then plays it).
    #[serde(default, skip_serializing_if = "is_false")]
    pub move_face_down_top: bool,
    /// Fixed sequence of ranks required at each pile depth (index 0 for the bottom card, index 1
    /// for the second, etc.). Replaces the rank check of `empty` and `build.dir`; `build.by`,
    /// `suit`, `empty_suit`, `color`, and `max_cards` still apply.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub rank_sequence: Vec<u8>,
    /// Maximum cards accepted in a single move onto a non-empty pile of this group.
    /// Defaults to `max_accept`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub non_empty_max_accept: Option<u16>,
    /// No two non-empty piles in this group may share the same suit on their bottom card.
    #[serde(default, skip_serializing_if = "is_false")]
    pub unique_suits: bool,
    /// No two non-empty piles in this group may share the same rank on their bottom card
    /// (Elevens' reserves).
    #[serde(default, skip_serializing_if = "is_false")]
    pub unique_ranks: bool,
    /// The bottom cards of this group's piles must always have different ranks forming one run
    /// of consecutive ranks that may wrap round the pack (Triple Alliance's reserves).
    #[serde(default, skip_serializing_if = "is_false")]
    pub cyclic_ranks: bool,
    /// Every non-empty pile in this group must have the same suit on its bottom card as the
    /// others (Suit Elevens' reserves).
    #[serde(default, skip_serializing_if = "is_false")]
    pub same_suit_group: bool,
    /// Every non-empty pile in this group must have the same rank on its bottom card as the
    /// others (Tens' reserves).
    #[serde(default, skip_serializing_if = "is_false")]
    pub same_rank_group: bool,
    /// As soon as every pile of this group holds a card, move all their cards to the first pile
    /// of the named group (Elevens' reserves going to the discard).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub clear_when_full: Option<String>,
    /// With `clear_when_full`: clear only when every pile's bottom card has the same rank
    /// (Foursome's four reserves).
    #[serde(default, skip_serializing_if = "is_false")]
    pub clear_same_rank: bool,
    /// Whenever the top card of a pile of this group is face up and of this rank (1 = ace), play
    /// it to the first foundation that takes it, whatever that foundation's other conditions
    /// (Strategy +: aces leave the talon by themselves). Rank 0 means any rank (Q.C.: every waste
    /// card that fits a foundation goes there).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub auto_foundation_rank: Option<u8>,
    /// A face-down top card is turned up only once the stock and the waste are both empty
    /// (Last Chance's reserve).
    #[serde(default, skip_serializing_if = "is_false")]
    pub flip_when_dealt_out: bool,
    /// When a move leaves a pile of this group holding exactly one card fewer than the group has
    /// piles, all of them face down, those cards are turned up one by one and each goes onto a
    /// different one of the other piles (in order). The pile is then dealt one face-down card
    /// per other pile from the stock, then one more face up, as far as the stock lasts.
    #[serde(default, skip_serializing_if = "is_false")]
    pub spill_when_hollow: bool,
    /// With `compact`: close gaps only once the stock is empty; until then they are refilled
    /// from it (Quatorze).
    #[serde(default, skip_serializing_if = "is_false")]
    pub compact_when_stock_empty: bool,
    /// With `complete_runs`: how many cards make a complete run (default: the number of ranks).
    /// Simplex: four of a kind.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub run_len: Option<u8>,
    /// Refill emptied piles only while every pile of the named group is empty (Elevens Too:
    /// rows are refilled only when the reserves are empty).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub refill_when_empty: Option<String>,
    /// While the stock is non-empty, forbid building onto a single-card pile in this group and
    /// forbid moving a card from a single-card pile in this group onto another non-empty pile of
    /// this group.
    #[serde(default, skip_serializing_if = "is_false")]
    pub no_build_single_while_stock: bool,
    /// When refilling an emptied pile from the stock with `refill_count > 1`, deal the first card
    /// face down unless it is the last card in the stock, and the remaining cards face up.
    #[serde(default, skip_serializing_if = "is_false")]
    pub refill_first_face_down: bool,
    /// Auto-flip the top card of pile `i` in this group once pile `i` of the named group reaches
    /// its `max_cards` capacity (overrides `no_flip`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub flip_when_same_index_full: Option<String>,
    /// Auto-flip the top card of pile `i` in this group once pile `i` of the named group is
    /// non-empty (overrides `no_flip`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub flip_when_same_index_non_empty: Option<String>,
    /// The top card of pile `i` in this group is kept face down while pile `i` of the named group
    /// is non-empty, and face up otherwise (overrides `no_flip`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub face_down_while_same_index_non_empty: Option<String>,
    /// A face-down top card turns up only once the previous pile of this group is empty (the
    /// first pile always qualifies).
    #[serde(default, skip_serializing_if = "is_false")]
    pub flip_after_prev_empty: bool,
    /// Only turn a face-down top card up once every pile of this group holds at most this many
    /// cards (Striptease: the turned card waits until the reserves are down to two).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub flip_when_all_at_most: Option<u16>,
    /// A face-down top card turns up only while some pile of the named group is empty.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub flip_when_any_empty: Option<String>,
    /// When the destination pile holds a single card, accept any single card regardless of `build`
    /// rules.
    #[serde(default, skip_serializing_if = "is_false")]
    pub accept_any_on_single: bool,
    /// Empty pile `i` of this group accepts cards only while pile `i % other.len()` of the
    /// named group is non-empty.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub empty_requires_same_index_non_empty: Option<String>,
    /// Empty pile `i` of this group accepts cards only while pile `i % other.len()` of the
    /// named group is non-empty and the incoming card's suit matches that pile's bottom card's
    /// suit.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub empty_match_suit_of: Option<String>,
    /// Only accept a card from a pile `p` in a grid group (with `cols` columns) when
    /// `p % cols > 0` and pile `p - 1` in that same source group is empty.
    #[serde(default, skip_serializing_if = "is_false")]
    pub from_requires_left_empty: bool,
    /// Moving a single card onto a non-empty pile `to` of this group pushes `to`'s top card to the
    /// first accepting pile among these groups (tried in order) before placing the moved card.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub push_off_to: Vec<String>,
    /// With `push_off_to`: the pushed-off card is placed on its destination pile by the push-off
    /// itself, so the destination's own acceptance limits do not apply to it. The destination is
    /// still checked for its build rule, empty rule, capacity (`max_cards`) and availability, but
    /// not for `accepts_from`/`empty_accepts_from` membership or `max_accept`/`empty_max_accept`/
    /// `non_empty_max_accept`. This lets a destination refuse direct moves from this group while
    /// still receiving pushed-off cards.
    #[serde(default, skip_serializing_if = "is_false")]
    pub push_off_bypasses_accept: bool,
    /// When a move empties pile `i` in this grid group, count contiguous non-empty piles directly
    /// above `i` (`k` piles) and shift the bottom `k / 2` of them down by one row.
    #[serde(default, skip_serializing_if = "is_false")]
    pub fission_shift: bool,
    /// Permissive jokers: a joker may be placed onto any non-empty face-up pile in this group
    /// (even if the top card is in `blocked_ranks`), and any card or movable run may be placed
    /// onto a pile whose top card is a joker (ignoring build rank/suit/color constraints).
    #[serde(default, skip_serializing_if = "is_false")]
    pub wild_permissive: bool,
    /// A joker (or a unit starting with one) may be placed on any pile of this group, empty or
    /// not, whatever the build and empty rules say. Capacity limits still apply, and nothing
    /// else is let onto a joker by this.
    #[serde(default, skip_serializing_if = "is_false")]
    pub joker_anywhere: bool,
    /// This group takes jokers only; no real card is ever admitted.
    #[serde(default, skip_serializing_if = "is_false")]
    pub joker_only: bool,
    /// This group rejects jokers (even on empty piles).
    #[serde(default, skip_serializing_if = "is_false")]
    pub no_jokers: bool,
    /// Cards are accepted only while the listed piles of another group are all full.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub accept_when_piles_full: Option<PilesFull>,
    /// Moving a joker off the top of a pile of this group sends every card left in that pile,
    /// face down, back to the stock, which is then reshuffled (deterministically from the
    /// game's seed). Needs a stock.
    #[serde(default, skip_serializing_if = "is_false")]
    pub joker_bomb: bool,
    /// Cards are added only while the pile's total stays within a target (Ladybug's rows).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sum_limit: Option<SumLimit>,
    /// When a pile is refilled from another group, a card of these ranks that a foundation
    /// takes goes there instead, and the next card is taken (Intelligence's aces).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub refill_divert_ranks: Vec<u8>,
    /// Fewest cards accepted in a single move onto a pile of this group.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min_accept: Option<u16>,
    /// Pile `i` of this group accepts cards only while pile `i % other.len()` is non-empty in
    /// every listed group.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub requires_same_index_groups_non_empty: Vec<String>,
    /// See [`FromPileSets`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub from_pile_sets: Option<FromPileSets>,
    /// See [`FlushAtLen`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub flush_at_len: Option<FlushAtLen>,
    /// When placing a card onto pile `dst` at depth `k = dst.len()`, require its suit to match
    /// `other[k]` for every pile `other` in this group with `other.len() > k`.
    #[serde(default, skip_serializing_if = "is_false")]
    pub match_depth_suit: bool,
    /// For a single-pile source group: deals one card face up onto `to[0]` via a dedicated action.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub secondary_stock: Option<SecondaryStock>,
    /// Cards in this group may only be moved out when the total number of cards across all piles
    /// of the named group is at least `n`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub moves_when_group_cards_at_least: Option<(String, u16)>,
    /// This group accepts cards only while `redeals_used == 0`.
    #[serde(default, skip_serializing_if = "is_false")]
    pub accept_first_round_only: bool,
    /// A pile in this group accepts cards only when it already holds at least `n` cards.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min_accept_len: Option<u16>,
    /// When a move takes the last card from a pile of this group, every empty pile of another
    /// group is refilled from the stock. See [`LeaveRefill`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub refill_group_on_leave: Option<LeaveRefill>,
    /// Whenever cards leave a pile of this group, the pile is topped up at once with the stock's
    /// top card, face up (if the stock has any), even when cards are left in it.
    #[serde(default, skip_serializing_if = "is_false")]
    pub refill_self_on_leave: bool,
    /// A holding pile whose cards are cleared as a set once their total comes right (the
    /// reserve in games that discard card combinations). See [`Staging`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub staging: Option<Staging>,
    /// When a pile of this group holds exactly two cards whose bottom card has one of the listed
    /// ranks, both go at once to the pile of another group that belongs to the bottom card's
    /// suit. See [`PairFlush`].
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub pair_flush: Vec<PairFlush>,
    /// Piles built in tiers on their first face-up card, one card at a time, and cleared once
    /// four cards are face up. See [`TieredSet`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tiered_set: Option<TieredSet>,
    /// Empty piles open sequentially in suit-mirrored columns with lowest-rank and
    /// no-existing-build guards. See [`StagedEmpty`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub staged_empty: Option<StagedEmpty>,
    /// In a grid of single-card piles, an empty cell accepts a card only if at least one of its
    /// eight neighbours is occupied, no two cards of rank `>= separator_from` are orthogonally
    /// adjacent, and every completed orthogonal run of cards with rank `< separator_from`
    /// (bounded by separators or grid edges, with no empty cells inside) has an even rank sum.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub even_segments: Option<u8>,
    /// Refill empty piles of this group only while the stock pile holds at most this many cards.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub refill_when_stock_at_most: Option<u16>,
}

/// Part of [`GroupRules::staged_empty`]. Empty piles of the group open strictly in index order
/// (`i - 1` must be non-empty). The first `stride` piles must each take a distinct suit, and
/// every pile `i >= stride` must match the suit of pile `i - stride`. In addition, a card may
/// start an empty pile only when:
///
/// - no pile in `source` has a face-up top card of the same suit with a strictly lower rank, and
/// - no non-empty pile in this group can currently accept the card under its build rule.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct StagedEmpty {
    pub stride: u16,
    pub source: String,
}

impl StagedEmpty {
    pub fn new(stride: u16, source: &str) -> StagedEmpty {
        StagedEmpty {
            stride,
            source: source.to_string(),
        }
    }
}

/// Part of [`GroupRules::tiered_set`]. A card is worth its rank (ace 1 to king 13), a joker
/// `joker_value`. The first face-up card of a pile is its base, and what a card needs depends on
/// how many cards are face up on the pile:
///
/// - one: its value plus `bonus` must reach the base's value;
/// - two: its value plus the value of the second card must reach the base's value;
/// - three: it must be of the base's suit, or a joker.
///
/// Nothing goes onto an empty pile. As soon as four cards are face up, those four move to `to`
/// and the card below them (if any) is turned up by the usual flipping. The group needs a build
/// rule other than `none` (`any` is the natural choice); the tiers replace its other tests.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct TieredSet {
    pub to: String,
    pub bonus: u16,
    pub joker_value: u16,
}

impl TieredSet {
    pub fn new(to: &str, bonus: u16, joker_value: u16) -> TieredSet {
        TieredSet {
            to: to.to_string(),
            bonus,
            joker_value,
        }
    }
}

/// Secondary stock rule for a single-pile source group that deals one card face up onto `to[0]`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct SecondaryStock {
    /// Target group whose first pile receives dealt cards.
    pub to: String,
    /// Only allow dealing while `to[0]` is empty (unless `stay_unlocked_below` applies).
    #[serde(default, skip_serializing_if = "is_false")]
    pub unlock_when_to_empty: bool,
    /// With `unlock_when_to_empty`: once this source pile holds fewer than `n` cards, allow
    /// dealing even when `to[0]` is non-empty.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stay_unlocked_below: Option<u16>,
}

impl SecondaryStock {
    /// Deal one card at a time face up onto `group`'s first pile.
    pub fn to(group: &str) -> SecondaryStock {
        SecondaryStock {
            to: group.to_string(),
            unlock_when_to_empty: false,
            stay_unlocked_below: None,
        }
    }

    pub fn unlock_when_to_empty(mut self) -> Self {
        self.unlock_when_to_empty = true;
        self
    }

    pub fn stay_unlocked_below(mut self, n: u16) -> Self {
        self.stay_unlocked_below = Some(n);
        self
    }
}

/// When two piles in the same group may swap their contents on a move from one to the other.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum SwapBases {
    /// Swap two single-card piles when each card satisfies the other pile's `empty` rule.
    BothSingle,
    /// Swap two non-empty piles with different `empty` rules when their bottom cards differ in
    /// rank and at least one bottom card satisfies the other pile's `empty` rule.
    EitherPile,
    /// Swap two single-card piles of groups that both use this mode when the piles take
    /// different kinds of card, each card is one the other pile takes, and the second card is
    /// not one its own pile would take from the first's side (Hemispheres: a red card in the
    /// black half swaps with a black card in the red half).
    Crossing,
}

/// Which pile of a group is the only one whose cards may move.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Frontier {
    /// The last non-empty pile of the group.
    Last,
    /// The first non-empty pile of the group.
    First,
}

/// When every pile of the group holds a card and the top cards' ranks (ace 1 ... king 13) add
/// up to `sum`, each top card goes to the `to` group (Ninety-One).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct ClearTops {
    pub to: String,
    pub sum: u16,
}

impl ClearTops {
    pub fn new(to: &str, sum: u16) -> ClearTops {
        ClearTops {
            to: to.to_string(),
            sum,
        }
    }
}

/// Which pile of this group a pile of `group` may send cards to (Rittenhouse's foundations).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct FromPileMap {
    /// Group the cards come from.
    pub group: String,
    /// For each pile of that group, the only pile of this group it may send cards to, or -1 for
    /// any.
    pub to: Vec<i16>,
    /// Apply this restriction only while the stock pile is non-empty.
    #[serde(default, skip_serializing_if = "is_false")]
    pub only_when_stock_non_empty: bool,
    /// Apply this restriction only when the destination pile is non-empty.
    #[serde(default, skip_serializing_if = "is_false")]
    pub only_non_empty_dest: bool,
    /// Cards whose rank is in this list bypass the pile restriction.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub except_ranks: Vec<u8>,
}

impl FromPileMap {
    pub fn new(group: &str, to: &[i16]) -> FromPileMap {
        FromPileMap {
            group: group.to_string(),
            to: to.to_vec(),
            only_when_stock_non_empty: false,
            only_non_empty_dest: false,
            except_ranks: Vec::new(),
        }
    }

    pub fn only_when_stock_non_empty(mut self) -> Self {
        self.only_when_stock_non_empty = true;
        self
    }

    pub fn only_non_empty_dest(mut self) -> Self {
        self.only_non_empty_dest = true;
        self
    }

    pub fn except_ranks(mut self, ranks: &[u8]) -> Self {
        self.except_ranks = ranks.to_vec();
        self
    }
}

/// A limit on the total of a pile.
///
/// A card adds its `values` entry (ranks 1 to 13) to the pile's total. Cards of a `lift_rank`
/// add nothing, but while the pile holds one, a total below `target` counts as `target`. A
/// card may be added only if the total then stays at most `target`, and a pile that reaches
/// `max_cards` must total exactly `target`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct SumLimit {
    pub target: u16,
    /// What each rank adds, from ace to king (13 entries).
    pub values: Vec<u16>,
    /// Ranks that lift a low total to the target.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub lift_ranks: Vec<u8>,
}

impl SumLimit {
    pub fn new(target: u16, values: &[u16]) -> SumLimit {
        SumLimit {
            target,
            values: values.to_vec(),
            lift_ranks: Vec::new(),
        }
    }

    pub fn lift_ranks(mut self, ranks: &[u8]) -> Self {
        self.lift_ranks = ranks.to_vec();
        self
    }
}

/// A condition on piles of another group being full. A pile is full when it holds one card per
/// rank of the pack, or its `max_cards` if that is lower.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct PilesFull {
    /// The group whose piles are checked.
    pub group: String,
    /// Pile indices within `group`; every pile of the group if empty.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub piles: Vec<u16>,
}

impl PilesFull {
    pub fn new(group: &str, piles: &[u16]) -> PilesFull {
        PilesFull {
            group: group.to_string(),
            piles: piles.to_vec(),
        }
    }
}

/// Which piles of this group each pile of `group` may send cards to.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct FromPileSets {
    /// Group the cards come from.
    pub group: String,
    /// For each pile of that group, the pile indices of this group it may send cards to.
    pub to: Vec<Vec<u16>>,
}

impl FromPileSets {
    pub fn new(group: &str, to: Vec<Vec<u16>>) -> FromPileSets {
        FromPileSets {
            group: group.to_string(),
            to,
        }
    }
}

/// When a pile reaches `len` cards, optionally pull one card from `pull_from` onto it, then flush
/// all cards of the pile (bottom-to-top) onto `to[0]`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct FlushAtLen {
    pub len: u16,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pull_from: Option<String>,
    pub to: String,
}

impl FlushAtLen {
    pub fn new(len: u16, to: &str) -> FlushAtLen {
        FlushAtLen {
            len,
            pull_from: None,
            to: to.to_string(),
        }
    }

    pub fn pull_from(mut self, group: &str) -> Self {
        self.pull_from = Some(group.to_string());
        self
    }
}

/// Part of [`GroupRules::refill_group_on_leave`]: one face-up card from the stock goes onto each
/// empty pile of `group`, in order. If the stock runs out first and `reshuffle_from` still holds
/// cards, they are turned over, shuffled into the stock, and the refilling goes on.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct LeaveRefill {
    /// Group whose empty piles are refilled.
    pub group: String,
    /// Group (its first pile) shuffled back into an exhausted stock.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reshuffle_from: Option<String>,
}

impl LeaveRefill {
    pub fn new(group: &str) -> LeaveRefill {
        LeaveRefill {
            group: group.to_string(),
            reshuffle_from: None,
        }
    }

    pub fn reshuffle_from(mut self, group: &str) -> Self {
        self.reshuffle_from = Some(group.to_string());
        self
    }
}

/// Part of [`GroupRules::staging`]. Cards below `court_from` (rank 1 = ace) are pips and count
/// for their rank; the rest are courts and count for nothing. A pile is cleared, all at once, into
/// the first pile of group `to` when it holds exactly the `court_set` ranks (if given), or when its
/// pips sum to `pip_sum` with `pip_courts` courts among its cards. The pile takes any card,
/// subject to the optional limits below.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct Staging {
    /// Group receiving a cleared pile.
    pub to: String,
    /// Lowest rank that is a court.
    pub court_from: u8,
    /// Pip total that clears the pile.
    pub pip_sum: u16,
    /// Courts the pile must hold alongside a clearing pip total.
    #[serde(default, skip_serializing_if = "is_zero_u8")]
    pub pip_courts: u8,
    /// A pile holding exactly these ranks (one card each) clears whatever the pips.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub court_set: Vec<u8>,
    /// No two cards of one rank may sit on the pile.
    #[serde(default, skip_serializing_if = "is_false")]
    pub distinct_ranks: bool,
    /// At most this many courts may sit on the pile.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_courts: Option<u8>,
    /// A pip may be added only if the pip total stays within `pip_sum`.
    #[serde(default, skip_serializing_if = "is_false")]
    pub cap_pip_sum: bool,
    /// The pip that would be the `n`th on the pile must bring the pip total to exactly `pip_sum`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exact_at_pips: Option<u8>,
}

impl Staging {
    pub fn new(to: &str, court_from: u8, pip_sum: u16) -> Staging {
        Staging {
            to: to.to_string(),
            court_from,
            pip_sum,
            pip_courts: 0,
            court_set: Vec::new(),
            distinct_ranks: false,
            max_courts: None,
            cap_pip_sum: false,
            exact_at_pips: None,
        }
    }

    pub fn pip_courts(mut self, n: u8) -> Self {
        self.pip_courts = n;
        self
    }

    pub fn court_set(mut self, ranks: &[u8]) -> Self {
        self.court_set = ranks.to_vec();
        self
    }

    pub fn distinct_ranks(mut self) -> Self {
        self.distinct_ranks = true;
        self
    }

    pub fn max_courts(mut self, n: u8) -> Self {
        self.max_courts = Some(n);
        self
    }

    pub fn cap_pip_sum(mut self) -> Self {
        self.cap_pip_sum = true;
        self
    }

    pub fn exact_at_pips(mut self, n: u8) -> Self {
        self.exact_at_pips = Some(n);
        self
    }
}

/// Part of [`GroupRules::pair_flush`]: a two-card pile whose bottom card has a rank in
/// `bottom_ranks` is cleared into the pile of group `to` that belongs to the bottom card's suit
/// (`to` has one pile per suit of the pack, in the pack's suit order).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct PairFlush {
    /// Ranks of the bottom card that trigger this flush.
    pub bottom_ranks: Vec<u8>,
    /// Group receiving the pair.
    pub to: String,
    /// If set, the card of this rank ends up underneath the other whichever way round the pair
    /// lay; otherwise the pair keeps its order.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub first: Option<u8>,
}

impl PairFlush {
    pub fn new(bottom_ranks: &[u8], to: &str) -> PairFlush {
        PairFlush {
            bottom_ranks: bottom_ranks.to_vec(),
            to: to.to_string(),
            first: None,
        }
    }

    pub fn first(mut self, rank: u8) -> Self {
        self.first = Some(rank);
        self
    }
}

/// Cards from some piles of a group may not go to some piles of this group until the stock or
/// redeal has been used once (St. Helena's foundations).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct FirstRoundBan {
    /// Piles (indices within the group that holds this ban) that refuse the cards.
    pub to: Vec<u16>,
    /// Group the refused cards come from.
    pub from_group: String,
    /// Piles (indices within `from_group`) whose cards are refused.
    pub from: Vec<u16>,
}

/// Rules for some piles of a group that differ from the group's. Fields left out keep the
/// group's value.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct PileOverride {
    /// Indices within the group.
    pub piles: Vec<u16>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub build: Option<Build>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub empty: Option<EmptyRule>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub moves: Option<MoveUnit>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_cards: Option<u16>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min_cards: Option<u16>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_accept: Option<u16>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub empty_max_accept: Option<u16>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub non_empty_max_accept: Option<u16>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub suit: Option<Suit>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub empty_suit: Option<Suit>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub color: Option<Color>,
}

impl PileOverride {
    pub fn on(piles: &[u16]) -> PileOverride {
        PileOverride {
            piles: piles.to_vec(),
            ..PileOverride::default()
        }
    }

    pub fn build(mut self, b: Build) -> Self {
        self.build = Some(b);
        self
    }

    pub fn empty(mut self, e: EmptyRule) -> Self {
        self.empty = Some(e);
        self
    }

    pub fn suit(mut self, s: Suit) -> Self {
        self.suit = Some(s);
        self
    }

    pub fn empty_suit(mut self, s: Suit) -> Self {
        self.empty_suit = Some(s);
        self
    }
}

/// Accept `"x"` or `["x", "y"]` (or one object or a list of them).
fn one_or_many<'de, D, T>(d: D) -> Result<Vec<T>, D::Error>
where
    D: serde::Deserializer<'de>,
    T: Deserialize<'de>,
{
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum OneOrMany<T> {
        One(T),
        Many(Vec<T>),
    }
    Ok(match OneOrMany::<T>::deserialize(d)? {
        OneOrMany::One(t) => vec![t],
        OneOrMany::Many(v) => v,
    })
}

impl GroupRules {
    /// A group with every optional field at its kind's default.
    pub fn new(name: &str, kind: PileKind, count: u16) -> GroupRules {
        GroupRules {
            name: name.to_string(),
            kind,
            count,
            build: None,
            empty: None,
            moves: None,
            max_cards: None,
            min_cards: None,
            max_accept: None,
            accepts_from: None,
            empty_accepts_from: None,
            refill_from: Vec::new(),
            refill_count: None,
            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_runs_by: 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,
            suit: None,
            empty_suit: None,
            exclude_suit: None,
            color: None,
            piles: Vec::new(),
            layout: None,
            complete_runs: false,
            wild: None,
            requires_rank_on_prev: false,
            match_longest_rank: false,
            empty_max_accept: None,
            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: None,
            lock_pile_dir: false,
            freeze_when_built: false,
            accept_on_face_down: false,
            one_way_split: None,
            move_face_down_top: false,
            rank_sequence: Vec::new(),
            non_empty_max_accept: None,
            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,
            push_off_to: Vec::new(),
            push_off_bypasses_accept: false,
            fission_shift: false,
            wild_permissive: false,
            joker_anywhere: false,
            joker_only: false,
            no_jokers: false,
            accept_when_piles_full: None,
            joker_bomb: false,
            sum_limit: None,
            refill_divert_ranks: Vec::new(),
            min_accept: None,
            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,
            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,
        }
    }

    pub fn build(mut self, by: BuildBy, dir: Dir) -> Self {
        self.build = Some(Build {
            by,
            dir,
            ..Build::default()
        });
        self
    }

    pub fn build_rule(mut self, b: Build) -> Self {
        self.build = Some(b);
        self
    }

    pub fn empty(mut self, e: EmptyRule) -> Self {
        self.empty = Some(e);
        self
    }

    pub fn moves(mut self, m: MoveUnit) -> Self {
        self.moves = Some(m);
        self
    }

    pub fn max_cards(mut self, n: u16) -> Self {
        self.max_cards = Some(n);
        self
    }

    pub fn min_cards(mut self, n: u16) -> Self {
        self.min_cards = Some(n);
        self
    }

    pub fn max_accept(mut self, n: u16) -> Self {
        self.max_accept = Some(n);
        self
    }

    pub fn accepts_from(mut self, groups: &[&str]) -> Self {
        self.accepts_from = Some(groups.iter().map(|s| s.to_string()).collect());
        self
    }

    pub fn empty_accepts_from(mut self, groups: &[&str]) -> Self {
        self.empty_accepts_from = Some(groups.iter().map(|s| s.to_string()).collect());
        self
    }

    pub fn refill_from(mut self, groups: &[&str]) -> Self {
        self.refill_from = groups.iter().map(|s| s.to_string()).collect();
        self
    }

    pub fn refill_count(mut self, n: u16) -> Self {
        self.refill_count = Some(n);
        self
    }

    pub fn suit(mut self, s: Suit) -> Self {
        self.suit = Some(s);
        self
    }

    pub fn empty_suit(mut self, s: Suit) -> Self {
        self.empty_suit = Some(s);
        self
    }

    /// Override rules for some piles of the group.
    pub fn pile(mut self, o: PileOverride) -> Self {
        self.piles.push(o);
        self
    }

    pub fn layout(mut self, l: Layout) -> Self {
        self.layout = Some(l);
        self
    }

    pub fn complete_runs(mut self) -> Self {
        self.complete_runs = true;
        self
    }

    pub fn wild(mut self, wild: bool) -> Self {
        self.wild = Some(wild);
        self
    }

    pub fn requires_rank_on_prev(mut self) -> Self {
        self.requires_rank_on_prev = true;
        self
    }

    pub fn match_longest_rank(mut self) -> Self {
        self.match_longest_rank = true;
        self
    }

    pub fn empty_max_accept(mut self, n: u16) -> Self {
        self.empty_max_accept = Some(n);
        self
    }

    pub fn accept_only_when_empty(mut self) -> Self {
        self.accept_only_when_empty = true;
        self
    }

    pub fn accept_when_stock_empty(mut self) -> Self {
        self.accept_when_stock_empty = true;
        self
    }

    pub fn compact_face_up(mut self) -> Self {
        self.compact_face_up = true;
        self
    }

    pub fn refill_largest(mut self) -> Self {
        self.refill_largest = true;
        self
    }

    pub fn refill_on_empty(mut self) -> Self {
        self.refill_on_empty = true;
        self
    }

    pub fn requires_prev_non_empty(mut self) -> Self {
        self.requires_prev_non_empty = true;
        self
    }

    pub fn max_same_rank(mut self, n: u8) -> Self {
        self.max_same_rank = Some(n);
        self
    }

    pub fn moves_when_stock_empty(mut self) -> Self {
        self.moves_when_stock_empty = true;
        self
    }

    pub fn moves_when_any_empty(mut self, group: &str) -> Self {
        self.moves_when_any_empty = Some(group.to_string());
        self
    }

    pub fn accept_when_same_index_empty(mut self, group: &str) -> Self {
        self.accept_when_same_index_empty = Some(group.to_string());
        self
    }

    pub fn requires_same_index_non_empty(mut self, group: &str) -> Self {
        self.requires_same_index_non_empty = Some(group.to_string());
        self
    }

    pub fn moves_when_same_index_empty(mut self, group: &str) -> Self {
        self.moves_when_same_index_empty = Some(group.to_string());
        self
    }

    pub fn moves_when_slice_empty(mut self, group: &str) -> Self {
        self.moves_when_slice_empty = Some(group.to_string());
        self
    }

    pub fn flip_only_last(mut self) -> Self {
        self.flip_only_last = true;
        self
    }

    pub fn final_from_same_index(mut self, group: &str) -> Self {
        self.final_from_same_index = Some(group.to_string());
        self
    }

    pub fn lock_build_dir(mut self) -> Self {
        self.lock_build_dir = true;
        self
    }

    pub fn no_flip(mut self) -> Self {
        self.no_flip = true;
        self
    }

    pub fn refill_same_index(mut self) -> Self {
        self.refill_same_index = true;
        self
    }

    pub fn refill_nearest(mut self) -> Self {
        self.refill_nearest = true;
        self
    }

    pub fn require_valid_base(mut self) -> Self {
        self.require_valid_base = true;
        self
    }

    pub fn swap_bases(mut self, mode: SwapBases) -> Self {
        self.swap_bases = Some(mode);
        self
    }

    pub fn swap_on_waste_match(mut self, adjacency: Adjacency) -> Self {
        self.swap_on_waste_match = Some(adjacency);
        self
    }

    pub fn supermove_complete_run(mut self) -> Self {
        self.supermove_complete_run = true;
        self
    }

    pub fn unrestricted_from(mut self, groups: &[&str]) -> Self {
        self.unrestricted_from = Some(groups.iter().map(|s| s.to_string()).collect());
        self
    }

    pub fn lock_pile_dir(mut self) -> Self {
        self.lock_pile_dir = true;
        self
    }

    pub fn freeze_when_built(mut self) -> Self {
        self.freeze_when_built = true;
        self
    }

    pub fn rank_sequence(mut self, ranks: &[u8]) -> Self {
        self.rank_sequence = ranks.to_vec();
        self
    }

    pub fn accept_any_on_single(mut self) -> Self {
        self.accept_any_on_single = true;
        self
    }

    pub fn empty_requires_same_index_non_empty(mut self, group: &str) -> Self {
        self.empty_requires_same_index_non_empty = Some(group.to_string());
        self
    }

    pub fn empty_match_suit_of(mut self, group: &str) -> Self {
        self.empty_match_suit_of = Some(group.to_string());
        self
    }

    pub fn from_requires_left_empty(mut self) -> Self {
        self.from_requires_left_empty = true;
        self
    }

    pub fn push_off_to(mut self, groups: &[&str]) -> Self {
        self.push_off_to = groups.iter().map(|s| s.to_string()).collect();
        self
    }

    pub fn push_off_bypasses_accept(mut self) -> Self {
        self.push_off_bypasses_accept = true;
        self
    }

    pub fn fission_shift(mut self) -> Self {
        self.fission_shift = true;
        self
    }

    pub fn wild_permissive(mut self) -> Self {
        self.wild_permissive = true;
        self
    }

    pub fn joker_anywhere(mut self) -> Self {
        self.joker_anywhere = true;
        self
    }

    pub fn joker_only(mut self) -> Self {
        self.joker_only = true;
        self
    }

    pub fn no_jokers(mut self) -> Self {
        self.no_jokers = true;
        self
    }

    /// Accept cards only while piles `piles` (all of them if empty) of `group` are full.
    pub fn accept_when_piles_full(mut self, group: &str, piles: &[u16]) -> Self {
        self.accept_when_piles_full = Some(PilesFull::new(group, piles));
        self
    }

    pub fn refill_divert_ranks(mut self, ranks: &[u8]) -> Self {
        self.refill_divert_ranks = ranks.to_vec();
        self
    }

    pub fn sum_limit(mut self, s: SumLimit) -> Self {
        self.sum_limit = Some(s);
        self
    }

    pub fn joker_bomb(mut self) -> Self {
        self.joker_bomb = true;
        self
    }

    pub fn min_accept(mut self, n: u16) -> Self {
        self.min_accept = Some(n);
        self
    }

    pub fn requires_same_index_groups_non_empty(mut self, groups: &[&str]) -> Self {
        self.requires_same_index_groups_non_empty = groups.iter().map(|s| s.to_string()).collect();
        self
    }

    pub fn from_pile_sets(mut self, sets: FromPileSets) -> Self {
        self.from_pile_sets = Some(sets);
        self
    }

    pub fn flush_at_len(mut self, flush: FlushAtLen) -> Self {
        self.flush_at_len = Some(flush);
        self
    }

    pub fn match_depth_suit(mut self) -> Self {
        self.match_depth_suit = true;
        self
    }

    pub fn secondary_stock(mut self, s: SecondaryStock) -> Self {
        self.secondary_stock = Some(s);
        self
    }

    pub fn moves_when_group_cards_at_least(mut self, group: &str, min_cards: u16) -> Self {
        self.moves_when_group_cards_at_least = Some((group.to_string(), min_cards));
        self
    }

    pub fn accept_first_round_only(mut self) -> Self {
        self.accept_first_round_only = true;
        self
    }

    pub fn pair_flush(mut self, flush: PairFlush) -> Self {
        self.pair_flush.push(flush);
        self
    }

    pub fn tiered_set(mut self, t: TieredSet) -> Self {
        self.tiered_set = Some(t);
        self
    }

    pub fn staged_empty(mut self, s: StagedEmpty) -> Self {
        self.staged_empty = Some(s);
        self
    }

    pub fn even_segments(mut self, separator_from: u8) -> Self {
        self.even_segments = Some(separator_from);
        self
    }

    pub fn refill_when_stock_at_most(mut self, n: u16) -> Self {
        self.refill_when_stock_at_most = Some(n);
        self
    }

    pub fn staging(mut self, staging: Staging) -> Self {
        self.staging = Some(staging);
        self
    }

    pub fn refill_group_on_leave(mut self, refill: LeaveRefill) -> Self {
        self.refill_group_on_leave = Some(refill);
        self
    }

    pub fn min_accept_len(mut self, n: u16) -> Self {
        self.min_accept_len = Some(n);
        self
    }
}

/// How cards are built on one another.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct Build {
    pub by: BuildBy,
    #[serde(default)]
    pub dir: Dir,
    /// The sequence wraps: king to ace and ace to king.
    #[serde(default, skip_serializing_if = "is_false")]
    pub wrap: bool,
    /// Ranks between consecutive cards (default 1).
    #[serde(default = "one_u8", skip_serializing_if = "is_one_u8")]
    pub step: u8,
    /// Per-suit override of `step`, keyed by the suit of the lower card (the build step of a
    /// suit-matched build differing by suit). Suits not listed use `step`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub suit_steps: Vec<(Suit, u8)>,
    /// Nothing may be built on cards of these ranks (Golf: kings).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub blocked_ranks: Vec<u8>,
    /// With a stripped pack: ranks that are not adjacent to the pack rank just below them
    /// (an ace-and-7-to-king pack: `[7]`). Applies to `step` 1 builds.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub gap_ranks: Vec<u8>,
    /// Pairs of ranks that also build on each other, in either order, whatever the direction
    /// (Striptease: jack and king).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub extra_pairs: Vec<(u8, u8)>,
    /// `(under, over)` rank pairs that also build, in that order only, whatever the direction
    /// (Napoleon's Tomb: a six goes on an ace).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub extra_over: Vec<(u8, u8)>,
    /// `(under, over)` rank pairs that never build, in that order, though the step would allow
    /// them (an ace never goes on a three in a step-2 build).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub not_over: Vec<(u8, u8)>,
    /// With `by: suit_cycle`: the suits in the order they follow each other.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub suit_cycle: Vec<Suit>,
}

impl Build {
    /// Build `by` a suit or colour relation in direction `dir`, one rank at a time.
    pub fn new(by: BuildBy, dir: Dir) -> Build {
        Build {
            by,
            dir,
            ..Build::default()
        }
    }

    pub fn wrap(mut self) -> Self {
        self.wrap = true;
        self
    }

    pub fn step(mut self, step: u8) -> Self {
        self.step = step;
        self
    }

    pub fn suit_steps(mut self, steps: &[(Suit, u8)]) -> Self {
        self.suit_steps = steps.to_vec();
        self
    }

    pub fn blocked_ranks(mut self, ranks: &[u8]) -> Self {
        self.blocked_ranks = ranks.to_vec();
        self
    }

    pub fn suit_cycle(mut self, suits: &[Suit]) -> Self {
        self.suit_cycle = suits.to_vec();
        self
    }

    pub fn gap_ranks(mut self, ranks: &[u8]) -> Self {
        self.gap_ranks = ranks.to_vec();
        self
    }
}

impl Default for Build {
    fn default() -> Self {
        Build {
            by: BuildBy::None,
            dir: Dir::Down,
            wrap: false,
            step: 1,
            suit_steps: Vec::new(),
            blocked_ranks: Vec::new(),
            gap_ranks: Vec::new(),
            extra_pairs: Vec::new(),
            extra_over: Vec::new(),
            not_over: Vec::new(),
            suit_cycle: Vec::new(),
        }
    }
}

/// The suit or colour relation between a card and the card placed on it.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum BuildBy {
    /// Nothing may be built.
    None,
    /// Any suit.
    Any,
    /// Same suit.
    Suit,
    /// Alternate colours.
    Alternate,
    /// Same colour.
    SameColor,
    /// Any suit but the same one.
    OtherSuit,
    /// The same suit or the same rank (Accordion; pair with `dir: any`).
    SuitOrRank,
    /// Same rank of any suit, or same suit following `dir`.
    SuitOrSameRank,
    /// The suit that follows the one below in `Build::suit_cycle` (Following: spades, hearts,
    /// clubs, diamonds, and round again).
    SuitCycle,
    /// A card goes on another of the same suit that is one rank below it, on one of the same
    /// colour and another suit that is one rank above it, or on one of the same rank and the
    /// other colour; ranks wrap round the pack (Sticko). `dir` is ignored.
    RankSuitColor,
    /// A chain through every suit: a card goes on another of the same suit that is one rank
    /// below it, except that the first rank goes on the last rank of the suit before it in
    /// `Build::suit_cycle`. Needs `dir: up` and `wrap`.
    SuitChain,
}

/// Rank direction from a card to the card placed on it.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Dir {
    #[default]
    Down,
    Up,
    /// Up or down.
    Either,
    /// Same rank.
    Same,
    /// Any rank at all (a pile that takes anything, subject to `by`).
    Any,
    /// Any strictly higher rank in the pack's rank sequence (no wrap).
    UpAny,
    /// Any strictly lower rank in the pack's rank sequence (no wrap).
    DownAny,
    /// Same rank or one step down.
    DownOrSame,
    /// The card's position in the pack's ranks is double the one below it, plus one, modulo the
    /// number of ranks (Doublets: A 2 4 8 3 6 Q J 9 5 T 7 A).
    DoubleUp,
    /// The card's position in the pack's ranks mirrors the one below it: the first on the last,
    /// the second on the second last, and so on (Eiffel Tower: A on K, 2 on Q, 7 on 7).
    Mirror,
}

/// What an empty pile accepts.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum EmptyRule {
    /// Nothing.
    None,
    /// Any card (or any movable unit).
    Any,
    /// Only a card of this rank (13 for "kings only").
    Rank(u8),
    /// Only a card whose rank is in this list (e.g. `[1, 13]` for Ace or King).
    Ranks(Vec<u8>),
    /// Only a card of the rank turned up by the deal (Canfield). See [`DealStep::set_base`].
    DealtBase,
    /// Only the card this many places after the rank turned up by the deal, going round the
    /// pack's ranks: `-1` is the rank below the base (Penguin's columns, which take the card
    /// that would sit under the foundations' base). See [`DealStep::set_base`].
    DealtBaseOffset(i8),
    /// In a grid: a card that could be built (by this pile's build rule) on the top card of
    /// the pile to the left; in the first column, a card of rank `first` (Montana's gaps).
    AfterLeft { first: u8 },
    /// In a grid: like [`EmptyRule::AfterLeft`], or a card that the top card of the pile to the
    /// right (if any) could be built on. When `first == 0`, column 0 has no fixed base rank and
    /// only accepts a card matching its right neighbour.
    AfterNeighbor { first: u8 },
    /// A card whose rank is `offset` places after the top card of the pile at the same index in
    /// `group`, wrapping around the pack's rank sequence.
    AfterPile { group: String, offset: i8 },
    /// Any card if every pile in this group is empty; otherwise only a card matching the bottom
    /// card's rank of the first non-empty pile in this group.
    SameBase,
    /// In a ring of piles (the group's last pile is followed by its first): a card that could be
    /// built on the top card of the pile before it, or a card that the top card of the pile after
    /// it could be built on (Maze). `left_extra` lists `(under, over)` rank pairs, of any suit,
    /// that also let a card go after the pile before it (Maze: an ace after a queen).
    AfterRing {
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        left_extra: Vec<(u8, u8)>,
    },
    /// A card whose rank is `offset` places after the bottom card of `group[pile]`, wrapping
    /// around the pack's rank sequence (rejects if `group[pile]` is empty).
    AfterPileBottom {
        group: String,
        pile: u16,
        offset: i8,
    },
    /// Any card whose rank is not in this list.
    ExceptRanks(Vec<u8>),
}

/// Which cards may leave a pile together.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum MoveUnit {
    /// No card may leave.
    None,
    /// The top card only.
    Top,
    /// Any built sequence (by this group's build rule) from the top.
    Run,
    /// Any built sequence from the top whose cards are all one suit (Spider).
    SuitRun,
    /// Any number of face-up cards from the top, built or not (Yukon).
    AnyFaceUp,
    /// A built sequence, as long as free cells and empty piles would allow moving it one card at
    /// a time (FreeCell's "supermove"): (empty cells + 1) × 2^(empty piles).
    Supermove,
    /// Only the whole pile, all face up.
    Whole,
    /// Either the top card alone, or the whole pile when all face up and built in sequence.
    TopOrWhole,
    /// Any built sequence from the top whose cards alternate in colour.
    AltColorRun,
    /// Any built sequence from the top whose cards are all one colour.
    SameColorRun,
    /// Any built same-suit sequence or any equal-rank run from the top.
    SuitRunOrSameRank,
    /// Any run of one suit whose ranks are consecutive, from the top (for piles that build more
    /// loosely than they move).
    SuitSequence,
    /// Any single card of the pile, whatever its depth (a pile spread out so every card shows).
    /// Cards other than the top are moved by a pick step naming their position.
    AnySingle,
}

/// Overlapping piles: a pile is playable only once every pile covering it is empty.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Layout {
    /// A triangle with `rows` rows (row r has r + 1 piles); each pile is covered by the two
    /// below it. Group count must be rows × (rows + 1) / 2.
    Pyramid { rows: u16 },
    /// Three peaks of 3 rows each over a base row of 10 (28 piles).
    TriPeaks,
    /// Explicit: `covered_by[i]` lists the piles (indices within the group) covering pile i.
    Covers { covered_by: Vec<Vec<u16>> },
    /// Rows of `columns` piles, read left to right (gap games: Montana). Nothing covers
    /// anything; the layout gives each pile a left neighbour.
    Grid { columns: u16 },
    /// Grid of `columns` piles per row where pile `i` is blocked iff both its vertical neighbours
    /// (`i - columns` and `i + columns`) are non-empty.
    GridVertical { columns: u16 },
    /// Grid of `columns` piles per row where pile `i` is movable iff `i + columns` is out of
    /// bounds or empty, and accepts a card iff `i` is non-empty and vertically isolated.
    GridBottomOpen { columns: u16 },
}

/// How the stock deals.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct StockRules {
    /// Group the stock deals to. If it is a waste or foundation, `count` cards go onto its first
    /// pile. Otherwise (tableau, reserve, cell), `count` rounds of one card go to each pile in
    /// turn while cards remain.
    pub to: String,
    /// Cards per deal (or rounds per deal for multi-pile targets).
    #[serde(default = "one", skip_serializing_if = "is_one_u16")]
    pub count: u16,
    /// Times the waste may be turned back into the stock.
    #[serde(default, skip_serializing_if = "is_zero_u32")]
    pub redeals: u32,
    /// The waste may be turned back any number of times (overrides `redeals`).
    #[serde(default, skip_serializing_if = "is_false")]
    pub unlimited_redeals: bool,
    /// The stock may not deal while any pile of the target group is empty (Spider).
    #[serde(default, skip_serializing_if = "is_false")]
    pub require_no_empty: bool,
    /// Deal by itself whenever the waste is empty (and the stock isn't).
    #[serde(default, skip_serializing_if = "is_false")]
    pub auto: bool,
    /// For a multi-pile target: deal `count` cards into the first empty pile instead of one to
    /// every pile (Accordion).
    #[serde(default, skip_serializing_if = "is_false")]
    pub first_empty: bool,
    /// Deal only when the target pile is empty: each card must be played before the next is
    /// turned (Calculation, Sir Tommy).
    #[serde(default, skip_serializing_if = "is_false")]
    pub only_when_empty: bool,
    /// For a multi-pile target: deal only to non-empty piles (or to the first pile if all are
    /// empty).
    #[serde(default, skip_serializing_if = "is_false")]
    pub skip_empty: bool,
    /// Keep the top card of the stock turned face up so it may be played or removed directly.
    #[serde(default, skip_serializing_if = "is_false")]
    pub face_up: bool,
    /// Cards per deal on each round (0-indexed by redeals used). When non-empty, overrides `count`;
    /// rounds past the end reuse the last entry.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub count_per_round: Vec<u16>,
    /// For a multi-pile target: when the remaining stock has at most as many cards as this group
    /// has piles, deal one card to each pile of this group instead of `to`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub final_to: Option<String>,
    /// Specific piles of `to` to deal to (indices within the group). Default: all piles.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub piles: Option<Vec<u16>>,
    /// For a multi-pile target: when the remaining stock has at most `final_piles.len()` cards,
    /// deal one card to each of these piles of `to` (indices within the group) instead of `piles`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub final_piles: Option<Vec<u16>>,
    /// For a multi-pile target with `count > 1`: deal `count` cards to each pile in turn rather
    /// than `count` rounds of one card per pile.
    #[serde(default, skip_serializing_if = "is_false")]
    pub deal_per_pile: bool,
    /// Before dealing to a multi-pile target, move the top card of each non-empty target pile `i`
    /// onto pile `i` of the named group.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub drop_to_before_deal: Option<String>,
    /// For a multi-pile target with `count > 1`: deal the first round face down and the remaining
    /// rounds face up.
    #[serde(default, skip_serializing_if = "is_false")]
    pub deal_down_then_up: bool,
    /// When gathering a multi-pile target back into the stock on redeal, gather piles in reverse
    /// order.
    #[serde(default, skip_serializing_if = "is_false")]
    pub redeal_reverse: bool,
    /// When gathering a multi-pile target back into the stock on redeal, turn the gathered
    /// stock upside down, so the first card gathered is the first one dealt again.
    #[serde(default, skip_serializing_if = "is_false")]
    pub redeal_flip_stock: bool,
    /// On redeal only gather the target group back into the stock (nothing is dealt); the stock
    /// is played from its top (Puss in the Corner).
    #[serde(default, skip_serializing_if = "is_false")]
    pub redeal_gather_only: bool,
    /// When gathering a multi-pile target back into the stock on redeal, shuffle the gathered
    /// cards before dealing them out again.
    #[serde(default, skip_serializing_if = "is_false")]
    pub redeal_shuffle: bool,
    /// On a multi-pile stock redeal, deal all gathered cards back out in rows alternating face-up
    /// and face-down (ending face-up), honoring `divert_ranks`.
    #[serde(default, skip_serializing_if = "is_false")]
    pub redeal_deal_all_alternating: bool,
    /// For a multi-pile target: if any target piles are empty, deal only to the empty piles;
    /// otherwise deal to every target pile.
    #[serde(default, skip_serializing_if = "is_false")]
    pub deal_empty_first: bool,
    /// When dealing to a multi-pile target, divert cards of these ranks to the first accepting
    /// foundation and keep dealing until a non-diverted card lands on the current target pile.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub divert_ranks: Vec<u8>,
    /// Target pile indices within `to` for each round (0-indexed by redeals used). When non-empty,
    /// overrides `piles`; rounds past the end reuse the last entry.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub piles_per_round: Vec<Vec<u16>>,
    /// When set, dealing requires at least 2 cards in the stock. If dealing leaves (or starts
    /// with) exactly 2 cards in the stock, one card is dealt face up to this group's first pile
    /// and the last card remaining in the stock is turned face up.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub final_split_to: Option<String>,
    /// When exactly as many cards are left as the target and this group have piles together,
    /// the deal also puts one card on each pile of this group (Baroness's last seven cards).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub final_also_to: Option<String>,
    /// The stock may not deal while any pile of this named group is empty.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub require_no_empty_group: Option<String>,
    /// The stock may deal only while every pile of this named group is empty (The Lucky Number's
    /// reserves).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub require_group_empty: Option<String>,
    /// With `auto`: deal to the empty waste by itself only right after a move empties a pile of
    /// this named group, once, and let that pile (with a `refill_on_empty` refill from the waste)
    /// take the card if it stays (Q.C.: a card that fits a foundation goes there, and the row
    /// stays empty).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub auto_for_empty: Option<String>,
    /// A deal passes over every target pile that is a whole built run from this rank (1 = ace)
    /// down to its last card, face up (Churchill: finished king piles). Nothing deals when
    /// every pile is passed over.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub skip_built_from: Option<u8>,
    /// The most times the stock may deal (a limit on draws, not on turning a waste back).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_deals: Option<u32>,
    /// A deal passes over every target pile whose top built run (face up, as far as the pile's
    /// build rule goes) includes a card of this rank (Fechter's Game: a king run on top).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub skip_run_with_rank: Option<u8>,
    /// For a multi-pile target: deal one card at a time; if its rank equals this rank, deal it to
    /// the first empty target pile (falling back to the last non-empty pile, or the first pile if
    /// all are empty); otherwise deal it to the last non-empty target pile (or the first pile if
    /// all are empty).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub open_next_on_rank: Option<u8>,
    /// For a grid target group: deal either into a new row below when the grid is empty or all
    /// columns are full to the same height with a full top row, or run a two-phase hole fill
    /// within the occupied rows.
    #[serde(default, skip_serializing_if = "is_false")]
    pub fill_grid_holes_then_row: bool,
    /// With `fill_grid_holes_then_row`: both phases repeat, and the hole fill works within the
    /// first `n` rows, where `n` is the most cards in any one column (at least 1). The deal adds a
    /// new row instead when the top row is full and every column holds the same number of cards.
    /// Phase 1 repeats passes that put a card directly above each column's first card, until none
    /// can. Phase 2 repeats passes that put a card in each column's first remaining hole, until
    /// none can or the stock runs out.
    #[serde(default, skip_serializing_if = "is_false")]
    pub fill_grid_holes_repeat: bool,
    /// When the stock is empty and finite redeals remain, pick up `to[count - 1 - redeals_used]`
    /// face-down (top-to-bottom), deal its cards face-up rightward from that index wrapping
    /// around `to[0..count]`, and increment `redeals_used`.
    #[serde(default, skip_serializing_if = "is_false")]
    pub redeal_redistribute_reverse: bool,
    /// When dealing one card per pile to a multi-pile target, skip pile `i` if `other_group[i]`
    /// is at its `max_cards` capacity.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub skip_when_same_index_full: Option<String>,
    /// Additional groups whose piles are swept (in reverse index order, top-to-bottom face-down)
    /// back into the stock on redeal after `to`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub redeal_from_groups: Vec<String>,
    /// With `redeal_from_groups` and a waste target: on redeal, instead of turning the waste over
    /// as the bottom of the new stock, its top card is first put on the first pile of the first
    /// swept group, and the groups are then swept (last pile first, each pile from its top) into
    /// the stock. Any further waste cards stay where they are.
    #[serde(default, skip_serializing_if = "is_false")]
    pub redeal_waste_onto_group: bool,
    /// For a multi-pile target: bracket each deal with this group's first and last piles. A deal
    /// puts one card on the first pile, then one on each pile of `to`, then one on the last pile
    /// (cards permitting), except in the final round (after every redeal has been used), which
    /// deals to `to` alone. On redeal this group's piles are gathered (each from its top, in pile
    /// order) after the target's.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bookend: Option<String>,
    /// In round 1 (`redeals_used == 0`), dealing requires `to` to be empty; in later rounds,
    /// normal stock dealing is allowed even when `to` is non-empty.
    #[serde(default, skip_serializing_if = "is_false")]
    pub only_when_empty_first_round: bool,
    /// When dealing from a non-empty stock: if any pile in the named group has fewer than `n`
    /// cards, deal 1 face-up card at a time round-robin across short piles of that group until
    /// all have at least `n` cards or stock empties, instead of dealing to `to`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub top_up_group_to: Option<(String, u16)>,
    /// On the first redeal (`0 -> 1`), deal 1 face-up card to `to[0]` and 1 to each pile of the
    /// named group; thereafter manual deals are disabled and any emptied pile of `to[0]` or the
    /// named group automatically refills 1 face-up card from stock.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub redeal_switch_to_auto_refill: Option<String>,
    /// Round 1 sweeps `to` face-down onto the named single-pile discard group before dealing 1
    /// card to each pile of `to`; on redeal sweeps `to` to discard and turns discard back into
    /// stock; in round 2+ deals 1 card onto `to[0]` only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sweep_to_discard_round1: Option<String>,
    /// For a waste-dealing stock: if `to[0]` is empty and stock non-empty, deals 1 to `to[0]`;
    /// otherwise sweeps `grp` in reverse pile order face-down to the bottom of stock, refills
    /// `grp` from `to[0]` then stock, and deals 1 to `to[0]` if stock remains.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sweep_group_on_waste: Option<String>,
    /// For a waste-dealing stock: after a card goes from the waste onto a pile of this group,
    /// the stock acts by itself, as if the player had dealt (or turned the waste back, if that
    /// is all it can do). Does nothing if the stock can't act.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub deal_after_play_to: Option<String>,
    /// For a waste-dealing stock with redeals: an empty stock can only be redealt while the
    /// named group holds cards (and the waste holds at least as many). A redeal then moves that
    /// many of the waste's bottom-most cards back to the stock, face down, the waste's bottom
    /// card first (so the stock's top card is the one just above the bottom run), leaves the
    /// rest of the waste as it was, and deals one card as usual.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub redeal_bottom_count_from: Option<String>,
    /// For a multi-pile target: if the stock has cards and some target pile is empty, deal
    /// `count` cards face up to each empty pile in turn (the stock deals only to gaps);
    /// otherwise (no gap, or the stock is out) use up one of the `redeals`: gather every target
    /// pile back into the stock, face down, shuffle it, and deal `count` cards to each pile in
    /// turn (Forest Glade).
    #[serde(default, skip_serializing_if = "is_false")]
    pub fill_empty_or_reshuffle: bool,
    /// For a multi-pile target: when counter 0 of [`Rules::aux`] (required) has reached this
    /// value, the next deal first uses up one of the `redeals`: every target pile is gathered
    /// back into the stock, face down, and the stock is shuffled. Then it deals as usual. Once
    /// the redeals are gone no deal is possible at that point. The aux updates are expected to
    /// count deals, and to reset the counter on that deal.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reshuffle_at_counter: Option<i16>,
    /// Fan deal: `to` is a group of fan slots and this names a group of piles (one per rank,
    /// the ace's first). Counter 0 of [`Rules::aux`] (required, start it at -1) holds the open
    /// pile, or -1 for none. A deal first puts every fan card back on the open pile (slot by
    /// slot, each from its top). Then, with cards in the stock, it turns the stock's top card
    /// face up onto the first slot, opens the pile its rank names, and lays that pile's cards
    /// out on the other slots, bottom card on the second slot and so on up; a pile too tall for
    /// them sends its top cards to the last slot, the one before it and so on first. With the
    /// stock empty and redeals left, it instead gathers the piles of the named group face down
    /// into the stock (last pile first, each from its top) and deals them out again by the
    /// opening deal step that sets cards aside for that group, closing the open pile. Piles of
    /// the named group and the fan are not symmetric.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fan_rows: Option<String>,
    /// For a waste target: every deal moves `count` (or `count_per_round`) cards to the waste,
    /// turning the waste face down onto the stock whenever the stock runs out mid-deal and
    /// counting at most one redeal per deal. Dealing is legal while the stock holds at least that
    /// many cards or a redeal remains.
    #[serde(default, skip_serializing_if = "is_false")]
    pub wrap_mid_deal: bool,
    /// Extra redeals earned dynamically from card counts in paired piles across groups.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bonus_redeals: Option<BonusRedeals>,
}

/// Extra redeals earned dynamically from card counts in paired piles across `groups`.
///
/// Each group in `groups` must have the same even pile count `n`. For each index `i`, the pile
/// counts across `groups` are summed, and consecutive sums `(a, b)` are paired: if
/// `a + b >= 2 * threshold`, add 2 extra redeals; else if `a >= threshold || b >= threshold`, add
/// 1. The total redeals (`stock.redeals + bonus`) is capped at `max_redeals` if set.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct BonusRedeals {
    pub groups: Vec<String>,
    pub threshold: u16,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_redeals: Option<u32>,
}

impl BonusRedeals {
    pub fn new(groups: &[&str], threshold: u16) -> BonusRedeals {
        BonusRedeals {
            groups: groups.iter().map(|s| (*s).to_string()).collect(),
            threshold,
            max_redeals: None,
        }
    }

    pub fn max_redeals(mut self, cap: u32) -> Self {
        self.max_redeals = Some(cap);
        self
    }
}

impl StockRules {
    /// Deal one card at a time to `group`, with no redeals and no other conditions.
    pub fn to(group: &str) -> StockRules {
        StockRules {
            to: group.to_string(),
            count: 1,
            redeals: 0,
            unlimited_redeals: false,
            require_no_empty: false,
            auto: false,
            first_empty: false,
            only_when_empty: false,
            skip_empty: false,
            face_up: false,
            count_per_round: Vec::new(),
            final_to: None,
            piles: None,
            final_piles: None,
            deal_per_pile: false,
            drop_to_before_deal: None,
            deal_down_then_up: false,
            redeal_reverse: false,
            redeal_flip_stock: false,
            redeal_gather_only: false,
            redeal_shuffle: false,
            redeal_deal_all_alternating: false,
            deal_empty_first: false,
            divert_ranks: Vec::new(),
            piles_per_round: Vec::new(),
            final_split_to: None,
            final_also_to: None,
            require_no_empty_group: None,
            require_group_empty: None,
            auto_for_empty: None,
            skip_built_from: None,
            max_deals: None,
            skip_run_with_rank: None,
            open_next_on_rank: None,
            fill_grid_holes_then_row: false,
            fill_grid_holes_repeat: false,
            redeal_redistribute_reverse: false,
            skip_when_same_index_full: None,
            redeal_from_groups: Vec::new(),
            redeal_waste_onto_group: false,
            bookend: None,
            only_when_empty_first_round: false,
            top_up_group_to: None,
            redeal_switch_to_auto_refill: None,
            sweep_to_discard_round1: None,
            sweep_group_on_waste: None,
            deal_after_play_to: None,
            redeal_bottom_count_from: None,
            fill_empty_or_reshuffle: false,
            reshuffle_at_counter: None,
            fan_rows: None,
            wrap_mid_deal: false,
            bonus_redeals: None,
        }
    }

    pub fn wrap_mid_deal(mut self) -> Self {
        self.wrap_mid_deal = true;
        self
    }

    pub fn bonus_redeals(mut self, bonus: BonusRedeals) -> Self {
        self.bonus_redeals = Some(bonus);
        self
    }

    pub fn reshuffle_at_counter(mut self, value: i16) -> Self {
        self.reshuffle_at_counter = Some(value);
        self
    }

    pub fn fill_empty_or_reshuffle(mut self) -> Self {
        self.fill_empty_or_reshuffle = true;
        self
    }

    pub fn fan_rows(mut self, group: &str) -> Self {
        self.fan_rows = Some(group.to_string());
        self
    }

    pub fn redeal_bottom_count_from(mut self, group: &str) -> Self {
        self.redeal_bottom_count_from = Some(group.to_string());
        self
    }

    pub fn deal_after_play_to(mut self, group: &str) -> Self {
        self.deal_after_play_to = Some(group.to_string());
        self
    }

    pub fn open_next_on_rank(mut self, rank: u8) -> Self {
        self.open_next_on_rank = Some(rank);
        self
    }

    pub fn redeal_redistribute_reverse(mut self) -> Self {
        self.redeal_redistribute_reverse = true;
        self
    }

    pub fn skip_when_same_index_full(mut self, group: &str) -> Self {
        self.skip_when_same_index_full = Some(group.to_string());
        self
    }

    pub fn redeal_from_groups(mut self, groups: &[&str]) -> Self {
        self.redeal_from_groups = groups.iter().map(|s| s.to_string()).collect();
        self
    }

    pub fn bookend(mut self, group: &str) -> Self {
        self.bookend = Some(group.to_string());
        self
    }

    pub fn redeal_waste_onto_group(mut self) -> Self {
        self.redeal_waste_onto_group = true;
        self
    }

    pub fn only_when_empty_first_round(mut self) -> Self {
        self.only_when_empty_first_round = true;
        self
    }

    pub fn top_up_group_to(mut self, group: &str, len: u16) -> Self {
        self.top_up_group_to = Some((group.to_string(), len));
        self
    }

    pub fn redeal_switch_to_auto_refill(mut self, group: &str) -> Self {
        self.redeal_switch_to_auto_refill = Some(group.to_string());
        self
    }

    pub fn sweep_to_discard_round1(mut self, discard: &str) -> Self {
        self.sweep_to_discard_round1 = Some(discard.to_string());
        self
    }

    pub fn sweep_group_on_waste(mut self, group: &str) -> Self {
        self.sweep_group_on_waste = Some(group.to_string());
        self
    }
}

/// Gathering a group's cards and dealing them out again.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct RedealRules {
    /// The group gathered and redealt.
    pub group: String,
    /// How many redeals are allowed.
    #[serde(default, skip_serializing_if = "is_zero_u32")]
    pub times: u32,
    /// Any number of redeals (overrides `times`).
    #[serde(default, skip_serializing_if = "is_false")]
    pub unlimited: bool,
    pub how: RedealHow,
}

impl RedealRules {
    /// One redeal of `group`, dealt `how`. Set `times` or `unlimited` for more.
    pub fn new(group: &str, how: RedealHow) -> RedealRules {
        RedealRules {
            group: group.to_string(),
            times: 1,
            unlimited: false,
            how,
        }
    }
}

/// How a redeal deals the gathered cards.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum RedealHow {
    /// Keep the cards in order and deal them back `per_pile` at a time to each pile in turn,
    /// starting from the first pile's top cards (Cruel). Fewer piles may end up in use. If there
    /// are more cards than `per_pile` for every pile, the surplus is shared out: each pile gets
    /// an equal part and the first few one more.
    Regroup { per_pile: u16 },
    /// Shuffle the gathered cards, then deal `per_pile` to each pile in turn (La Belle Lucie),
    /// sharing out any surplus as for [`RedealHow::Regroup`].
    Shuffle { per_pile: u16 },
    /// Grid games: leave each row's built sequence in place, shuffle every other card, and
    /// deal them back leaving one gap straight after each sequence (Montana).
    GridShuffle,
    /// Close the gaps: slide the cards forward in reading order, then fill the empty places
    /// at the end from `refill_from`'s top card, turned face up (Monte Carlo).
    Compact {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        refill_from: Option<String>,
    },
    /// Grid games: leave each row's built sequence in place, shuffle every other card, and deal
    /// them back leaving the gaps at random positions among the non-sequence slots.
    GridShuffleRandomGaps,
    /// Move each pile's bottom card to its top (Crescent).
    RotateBottom,
    /// Gather piles left-to-right (reversing each pile) and deal all cards back row-by-row.
    DealRows,
    /// On redeal `k` (0-indexed), pick up pile `k` and deal its cards one-by-one across the group
    /// starting at pile `k` and wrapping around.
    RedistributePile,
    /// Gather all cards of the group, shuffle them, and replay the group's opening deal steps.
    ShuffleRedeal,
    /// As `shuffle`, but every card is dealt face down except the top card of a pile that gets at
    /// least two (Fascination Fan: the dealing goes round in three passes, the last face up).
    ShuffleTopUp { per_pile: u16 },
    /// Grid games: leave each row's built sequence in place, shuffle every other card, and deal
    /// them back leaving one gap at the last column of each row.
    GridShuffleEndGaps,
    /// Gather as `deal_rows`, then deal row by row where each row starts one pile further right
    /// than the last: the first row to every pile, the next to all but the first, and so on
    /// (Usk).
    DealStaircase,
    /// Grid games: slide cards in each column upward to the topmost empty cells (preserving
    /// relative order), then fill remaining empty cells in row-major order (one face-up card each)
    /// from `refill_from`.
    CompactColumns {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        refill_from: Option<String>,
    },
    /// Fill empty cells in row-major order (one face-up card each) from `refill_from` without
    /// shifting existing cards.
    FillEmpty { refill_from: String },
    /// Gather the group's piles and the `reserve` group into one stack, face down, and shuffle
    /// it. Then deal face up to each pile in turn until it holds `per_pile` cards, setting aside
    /// on a foundation (when one takes it) every card of the `divert_ranks` that comes up. What
    /// is left goes back to the reserve, face down (Intelligence).
    ShuffleFill {
        per_pile: u16,
        reserve: String,
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        divert_ranks: Vec<u8>,
    },
}

/// One step of the opening deal.
///
/// Cards come off the shuffled pack in order. With `count` or `counts`, they are dealt in rows:
/// one card to each selected pile, then the next row, as a person would deal them.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct DealStep {
    /// Target group.
    pub to: String,
    /// Piles of the group to deal to (indices). Default: all.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub piles: Option<Vec<u16>>,
    /// Cards to each selected pile.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub count: Option<u16>,
    /// Cards to each selected pile, per pile.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub counts: Option<Vec<u16>>,
    /// Deal every remaining card, round-robin over the selected piles.
    #[serde(default, skip_serializing_if = "is_false")]
    pub rest: bool,
    /// Take every card of these ranks out of the pack and put one on each selected pile in
    /// turn (Beleaguered Castle's aces).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ranks: Option<Vec<u8>>,
    /// With `ranks` (and no `count`): take at most this many matching cards in total instead of
    /// all of them.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<u16>,
    /// Face up (default) or face down.
    #[serde(default = "yes", skip_serializing_if = "is_true")]
    pub face_up: bool,
    /// Cards of these ranks met while dealing this step are passed over and put at the bottom of
    /// the pack instead (Doublets' kings).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub skip_ranks: Vec<u8>,
    /// After dealing, move each pile's kings to its bottom, keeping their order (Baker's Dozen).
    #[serde(default, skip_serializing_if = "is_false")]
    pub kings_to_bottom: bool,
    /// With `one_each`: each card taken must be of the colour opposite to the one before
    /// (Colours: a 2 and a 4 of one colour, a 3 and a 5 of the other).
    #[serde(default, skip_serializing_if = "is_false")]
    pub alternate_colors: bool,
    /// With `divert_ranks` or `auto_foundation`: a card sent to a foundation does not use up its
    /// turn; the same pile gets the next card instead (Dieppe: cards go to the foundations until
    /// one does not fit, and that one goes to the row).
    #[serde(default, skip_serializing_if = "is_false")]
    pub retry_after_divert: bool,
    /// With `ranks`: take only the first card of each listed rank, in the listed order
    /// (Calculation's A, 2, 3, 4).
    #[serde(default, skip_serializing_if = "is_false")]
    pub one_each: bool,
    /// After this step, take every card of these ranks off the table and put them on this
    /// step's group (Montana: deal all 52, then remove the aces to leave gaps).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub collect: Option<Vec<u8>>,
    /// The first card this step deals sets the base rank for [`EmptyRule::DealtBase`].
    #[serde(default, skip_serializing_if = "is_false")]
    pub set_base: bool,
    /// Take every remaining card of the dealt base rank out of the pack and put one on each
    /// selected pile in turn (requires an earlier step with `set_base`).
    #[serde(default, skip_serializing_if = "is_false")]
    pub of_base: bool,
    /// Pull one card of each suit (in pack suit order) from the deck per round (repeated `count`
    /// times, default 1), placing them on the selected piles in turn.
    #[serde(default, skip_serializing_if = "is_false")]
    pub one_per_suit: bool,
    /// With `rest`: deal sequentially into each selected pile, advancing to the next pile whenever
    /// a card of this rank is dealt to a non-empty pile.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub split_on_rank: Option<u8>,
    /// With `split_on_rank`: advance to the next pile after placing a card of that rank (on any
    /// pile) instead of before placing it on a non-empty pile.
    #[serde(default, skip_serializing_if = "is_false")]
    pub split_after: bool,
    /// During this step, place any dealt card directly on the first foundation that accepts it.
    #[serde(default, skip_serializing_if = "is_false")]
    pub auto_foundation: bool,
    /// During this step, divert dealt cards of these ranks to the first foundation that accepts
    /// them; with `drain_foundations`, restrict draining to these ranks.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub divert_ranks: Option<Vec<u8>>,
    /// After each dealt row, repeatedly move exposed top cards of the selected piles onto any
    /// accepting foundation (restricted to `divert_ranks` if set).
    #[serde(default, skip_serializing_if = "is_false")]
    pub drain_foundations: bool,
    /// The deal may run out of cards part-way through a round (the last round is short).
    #[serde(default, skip_serializing_if = "is_false")]
    pub stop_when_out: bool,
    /// With `rest`: send each card to the selected pile its rank or suit names instead of dealing
    /// round-robin (Lady of the Manor's reserves by rank, Four Colours' rows by suit).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub route: Option<DealRoute>,
    /// Deal `count` rounds of one card to each selected pile (face up), taking further cards
    /// off the pack and setting them aside, face down, as the rules say. The deal stops as soon
    /// as the pack runs out. The cards set aside go back on the pack's remaining cards, the
    /// last one set aside on top (the stock deals from there).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub set_aside: Option<SetAside>,
}

/// Cards a [`DealStep`] sets aside while dealing.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct SetAside {
    /// After each card dealt to a pile, every matching rule sets aside its `count`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub rules: Vec<AsideRule>,
    /// Cards set aside after each round.
    #[serde(default, skip_serializing_if = "is_zero_u16")]
    pub per_round: u16,
}

/// One set-aside rule: it fires for a dealt card of one of `ranks`, or (with
/// `rank_matches_pile`) whose rank is the position of the pile in the selection (the ace for
/// the first, the two for the second, and so on).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct AsideRule {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub ranks: Vec<u8>,
    #[serde(default, skip_serializing_if = "is_false")]
    pub rank_matches_pile: bool,
    pub count: u16,
}

impl SetAside {
    pub fn new(per_round: u16) -> SetAside {
        SetAside {
            rules: Vec::new(),
            per_round,
        }
    }

    pub fn rule(mut self, ranks: &[u8], rank_matches_pile: bool, count: u16) -> Self {
        self.rules.push(AsideRule {
            ranks: ranks.to_vec(),
            rank_matches_pile,
            count,
        });
        self
    }
}

/// How a `rest` deal step picks each card's pile.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum DealRoute {
    /// Pile `i` of the selection takes the cards of rank `first_rank + i` (ranks are 1 = ace).
    Rank { first_rank: u8 },
    /// Pile `i` of the selection takes the cards of the pack's `i`th suit.
    Suit,
    /// Each card of `rank` starts the next pile of group `to`; every other card goes on the
    /// selected pile with the index of the latest such start (Xerxes: the nines start the
    /// foundations and the cards after each one go on the matching row).
    Chain { rank: u8, to: String },
    /// Each card of `rank` starts the next pile of group `to`; every other card goes on the first
    /// selected pile, until `limit` of them are down (Frog: aces to the foundations, thirteen
    /// other cards to the reserve).
    Split { rank: u8, to: String },
}

impl DealStep {
    pub fn to(group: &str) -> DealStep {
        DealStep {
            to: group.to_string(),
            face_up: true,
            ..DealStep::default()
        }
    }

    pub fn each(mut self, n: u16) -> Self {
        self.count = Some(n);
        self
    }

    pub fn counts(mut self, c: &[u16]) -> Self {
        self.counts = Some(c.to_vec());
        self
    }

    pub fn rest(mut self) -> Self {
        self.rest = true;
        self
    }

    pub fn set_aside(mut self, sa: SetAside) -> Self {
        self.set_aside = Some(sa);
        self
    }

    pub fn piles(mut self, p: &[u16]) -> Self {
        self.piles = Some(p.to_vec());
        self
    }

    pub fn ranks(mut self, r: &[u8]) -> Self {
        self.ranks = Some(r.to_vec());
        self
    }

    pub fn down(mut self) -> Self {
        self.face_up = false;
        self
    }

    pub fn skip_ranks(mut self, ranks: &[u8]) -> Self {
        self.skip_ranks = ranks.to_vec();
        self
    }

    pub fn kings_to_bottom(mut self) -> Self {
        self.kings_to_bottom = true;
        self
    }

    pub fn collect(mut self, ranks: &[u8]) -> Self {
        self.collect = Some(ranks.to_vec());
        self
    }

    pub fn one_each(mut self) -> Self {
        self.one_each = true;
        self
    }

    pub fn set_base(mut self) -> Self {
        self.set_base = true;
        self
    }
}

/// Card-removal mechanics.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct RemovalRules {
    pub kind: RemovalKind,
    /// Groups whose playable top cards may be removed.
    pub from: Vec<String>,
    /// Group (its first pile) the removed cards go to.
    pub to: String,
    /// Cards must be neighbours in their grid (all from one grid group).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub adjacent: Option<Adjacency>,
    /// Cards of these ranks never take part in a removal (Aces Square's aces).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub exclude_ranks: Vec<u8>,
    /// The removal works only while the rules' latch is set.
    #[serde(default, skip_serializing_if = "is_false")]
    pub needs_latch: bool,
    /// Minimum number of consecutive piles for [`RemovalKind::ContiguousSumMultiple`] (default: 1).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min_len: Option<u8>,
    /// Maximum rank sum for [`RemovalKind::ContiguousSumMultiple`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_sum: Option<u8>,
    /// Count J/Q/K as 10 in [`RemovalKind::ContiguousSumMultiple`].
    #[serde(default, skip_serializing_if = "is_false")]
    pub face_ten: bool,
}

impl RemovalRules {
    /// Remove cards of `kind` from the playable tops of `from` to `to`'s first pile.
    pub fn new(kind: RemovalKind, from: &[&str], to: &str) -> RemovalRules {
        RemovalRules {
            kind,
            from: from.iter().map(|s| s.to_string()).collect(),
            to: to.to_string(),
            adjacent: None,
            exclude_ranks: Vec::new(),
            needs_latch: false,
            min_len: None,
            max_sum: None,
            face_ten: false,
        }
    }
}

/// Which grid positions count as neighbours.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Adjacency {
    /// Horizontally, vertically or diagonally next to each other (Monte Carlo).
    Eight,
    /// Horizontally or vertically next to each other.
    Four,
    /// Anywhere in the same row or the same column (Quatorze).
    SameLine,
}

/// Jokers are wild in removals: a joker pairs with any card (another joker too) and stands for
/// any one rank of a set. `lower_of_suit` ignores them.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum RemovalKind {
    /// Remove two playable cards whose ranks add up to `total` (Pyramid: 13), or one card
    /// whose rank is listed in `alone` (Pyramid: kings).
    PairsSum {
        total: u8,
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        alone: Vec<u8>,
    },
    /// Remove a playable card when another playable card is of the same suit and higher in the
    /// pack's rank order (Aces Up).
    LowerOfSuit,
    /// Remove two playable cards of the same rank (Nestor, Simple Pairs).
    SameRank,
    /// Remove playable cards whose ranks are exactly this set, together (Elevens' J-Q-K).
    RankSet { ranks: Vec<u8> },
    /// Remove two playable cards in the same group whose pile indices differ by one of
    /// `distances`, when they match in suit or rank.
    ReachSuitOrRank { distances: Vec<u16> },
    /// Remove `1..=max_len` consecutive non-empty piles in a group when the piles immediately
    /// before and after the run match in suit or rank.
    BetweenMatch { max_len: u8 },
    /// Remove `1..=max_len` (or `min_len..=max_len` when [`RemovalRules::min_len`] is set)
    /// consecutive non-empty piles in a group when the sum of their ranks (with J/Q/K counting as
    /// 10 if [`RemovalRules::face_ten`] is set) is a multiple of `divisor` (and at most
    /// [`RemovalRules::max_sum`], if set).
    ContiguousSumMultiple { divisor: u8, max_len: u8 },
    /// Remove two playable cards of the same rank when that rank is listed in `ranks`.
    SameRankIn { ranks: Vec<u8> },
    /// Remove two playable cards whose ranks differ by one of `distances` (Cheops: 0 or 1,
    /// Neptune: 1), counting ace as 1 and king as 13 with no wrap.
    RankDistance { distances: Vec<u8> },
    /// Remove two playable cards of different suits whose ranks add up to `total` (Exit's
    /// queen and king).
    PairsSumOtherSuit { total: u8 },
    /// Remove two playable cards of the same suit.
    SameSuit,
    /// Remove two playable cards of the same suit whose ranks add up to `total` (Suit Elevens).
    PairsSumSameSuit { total: u8 },
}

/// When the game is won.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum WinRule {
    /// Every card is on a foundation.
    #[default]
    AllOnFoundations,
    /// These groups are empty (Pyramid, Golf, TriPeaks: the tableau).
    Empty(Vec<String>),
    /// These piles (indices within `group`) are empty and every group in `empty` is empty
    /// (Camelot: the middle four cells and the stock).
    PilesEmpty {
        group: String,
        piles: Vec<u16>,
        empty: Vec<String>,
    },
    /// A group holds at least this many cards (Aces Up: 48 discarded).
    Count { group: String, cards: u16 },
    /// A group holds at least this many cards and every group in `empty` is empty.
    CountAndEmpty {
        group: String,
        cards: u16,
        empty: Vec<String>,
    },
    /// A group holds at least `cards` cards and every pile of `spread` holds at most one card.
    CountAndSpread {
        group: String,
        cards: u16,
        spread: String,
    },
    /// At most this many piles of a group hold cards (Accordion: 1).
    AtMostPiles { group: String, piles: u16 },
    /// Every row of a grid group holds a built sequence from its first column, `length` cards
    /// long (default: one less than the row), starting with the rank its first column takes
    /// (Montana).
    Rows {
        group: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        length: Option<u16>,
    },
    /// The position scores at least this many points (see [`Rules::score`]).
    Score { at_least: u32 },
    /// A round has been scored and the points of all rounds so far reach this many (see
    /// [`Rules::rounds`]).
    RoundScore { at_least: u32 },
    /// Every pile in `group` holds `max_cards` cards with a bottom card satisfying its `empty` rule.
    AllFull { group: String },
    /// The grid of the score rules is full and every row scores at least this many points, each
    /// on its own (Maverick: every row a straight or better).
    EachRowScore { at_least: u32 },
    /// The first `red` piles of `group` hold only red cards and the rest only black ones (Fire and
    /// Ice).
    ColorSplit { group: String, red: u16 },
    /// Like [`WinRule::Rows`], but checks each row's ordered prefix using `build` instead of the
    /// group's build rule.
    RowsBuilt {
        group: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        length: Option<u16>,
        build: Build,
    },
    /// Every pile of `group` holds exactly one card, the one the pack's order gives it: pile `i`
    /// takes suit `pack.suits[i / n]` and rank `pack.ranks[i % n]`, `n` being the number of ranks
    /// (the group must have one pile per card of a single copy of the pack).
    PackOrder { group: String },
    /// Every non-empty pile of `group` (or the single pile at `pile`) satisfies optional `length`
    /// and `build` sequence checks, and every group in `empty` is empty.
    PilesBuilt {
        group: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        length: Option<u16>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        build: Option<Build>,
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        empty: Vec<String>,
        /// Require at least one non-empty pile in `group`.
        #[serde(default, skip_serializing_if = "is_false")]
        non_empty: bool,
        /// Check only this 0-based pile index within `group` (it must be non-empty if `length` or
        /// `non_empty` is set).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pile: Option<u16>,
        /// Every non-empty pile must start (at its bottom) with a card of this rank.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        bottom: Option<u8>,
    },
    /// The cards of a ring of single-card piles form `runs` runs of `length` cards, each one suit
    /// from the first rank up, with no gap inside a run (Maze: four runs from ace to queen).
    /// Reading the cards round the ring, starting from the first ace, each run starts with an ace.
    RingRuns {
        group: String,
        runs: u16,
        length: u16,
    },
    /// Every group in `empty` is empty and every non-empty pile in `group` (a grid group) is
    /// vertically isolated (no non-empty pile directly above or below it in the grid).
    AllIsolated {
        group: String,
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        empty: Vec<String>,
    },
    /// `discard` holds at least `cards` cards and the first pile of `group` holds the target card
    /// chosen at deal time (stored as its face index in `aux[0]`, chosen from the pack excluding
    /// cards initially on the first `exclude_piles` piles of `group`).
    TargetCard {
        group: String,
        discard: String,
        cards: u16,
        #[serde(default, skip_serializing_if = "is_zero_u16")]
        exclude_piles: u16,
    },
}

/// Rounds of cribbage play, scored one round at a time.
///
/// A round starts when the stock deals: `crib_down` cards go face down on the first piles of
/// the crib, then one card on each of the first `hand_size` piles of the first hand. The player
/// moves cards from a hand into the crib (a card leaves the hand only while no later hand has
/// been dealt). When the crib is full and the first `keep` piles of every hand hold cards, the
/// round is scored by itself: the crib is turned face up, the top card of the stock becomes the
/// starter (on the `starter` pile), and the crib and each hand are scored as cribbage hands
/// with that starter. The points, and `heels` if the starter is a jack, are added to a running
/// total kept in counter 0. The stock deals again only once a round has been scored and the
/// stock holds enough for another; that deal first sweeps the previous round to the `discard`
/// pile (the last hand's piles last to first, then the first hand's, then the crib's, then the
/// starter) and starts the next. Counter 0 of [`Rules::aux`] is the running total, so the
/// position hashes it; don't combine with `aux` rules. Piles of these groups aren't symmetric.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct RoundRules {
    /// The crib: a group of single-card piles.
    pub crib: String,
    /// The hands (one or two groups of single-card piles), in the order they are dealt.
    pub hands: Vec<String>,
    /// A single-pile group for the starter.
    pub starter: String,
    /// A single-pile group the finished rounds are swept into.
    pub discard: String,
    /// Cards dealt face down to the crib at the start of a round (default 0).
    #[serde(default, skip_serializing_if = "is_zero_u16")]
    pub crib_down: u16,
    /// Cards dealt to each hand (default 6).
    #[serde(default = "six", skip_serializing_if = "is_six")]
    pub hand_size: u16,
    /// Piles of each hand that must hold a card for a round to be scored (default 4).
    #[serde(default = "four", skip_serializing_if = "is_four")]
    pub keep: u16,
    /// With two hands: the second is dealt as soon as exactly this many of the crib's first
    /// piles hold cards and the others are empty.
    #[serde(default, skip_serializing_if = "is_zero_u16")]
    pub next_hand_after: u16,
    #[serde(default, skip_serializing_if = "CribbagePoints::is_standard")]
    pub points: CribbagePoints,
}

fn six() -> u16 {
    6
}
fn is_six(n: &u16) -> bool {
    *n == 6
}
fn four() -> u16 {
    4
}
fn is_four(n: &u16) -> bool {
    *n == 4
}

impl RoundRules {
    /// Rounds with one hand of six cards, four kept, and no cards dealt to the crib.
    pub fn new(crib: &str, hand: &str, starter: &str, discard: &str) -> RoundRules {
        RoundRules {
            crib: crib.to_string(),
            hands: vec![hand.to_string()],
            starter: starter.to_string(),
            discard: discard.to_string(),
            crib_down: 0,
            hand_size: 6,
            keep: 4,
            next_hand_after: 0,
            points: CribbagePoints::default(),
        }
    }

    /// Add a second hand, dealt once `after` cards have gone into the crib.
    pub fn second_hand(mut self, hand: &str, after: u16) -> Self {
        self.hands.push(hand.to_string());
        self.next_hand_after = after;
        self
    }

    pub fn crib_down(mut self, n: u16) -> Self {
        self.crib_down = n;
        self
    }
}

/// How a position is scored.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct ScoreRules {
    /// A grid group. Each of its rows and each of its columns is scored as a hand.
    pub group: String,
    pub hands: Hands,
}

impl ScoreRules {
    /// Score each row and column of the grid group `group` as a hand.
    pub fn new(group: &str, hands: Hands) -> ScoreRules {
        ScoreRules {
            group: group.to_string(),
            hands,
        }
    }
}

/// How a hand (the cards in one row or column) scores.
///
/// A joker in a hand counts as whichever card scores that hand best. Each hand is valued on its
/// own, so a joker shared by a row and a column (or a joker starter) may stand for different
/// cards in each.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Hands {
    /// As a poker hand: its best five-card poker combination. Straights and flushes need five
    /// cards; pairs and sets count in a line of any length.
    Poker(PokerTable),
    /// As a cribbage hand, together with a shared starter card (Cribbage Squares).
    Cribbage(CribbageRules),
}

/// Cribbage scoring. Each line is a hand; once every pile of the grid holds a card, the
/// starter joins every hand as a fifth card. Fifteens, pairs and runs count in a line of any
/// length; a flush needs a full line of at least four cards.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct CribbageRules {
    /// Group whose first pile's top card is the starter, read when the grid is full. Usually
    /// the waste: the card turned after the grid is filled. No starter if left out or empty.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub starter: Option<String>,
    #[serde(default, skip_serializing_if = "CribbagePoints::is_standard")]
    pub points: CribbagePoints,
}

impl CribbageRules {
    /// Standard points, with the starter on top of `group`'s first pile.
    pub fn with_starter(group: &str) -> CribbageRules {
        CribbageRules {
            starter: Some(group.to_string()),
            points: CribbagePoints::default(),
        }
    }
}

impl Default for CribbageRules {
    /// Standard points, no starter.
    fn default() -> Self {
        CribbageRules {
            starter: None,
            points: CribbagePoints::default(),
        }
    }
}

/// Points for each cribbage combination. Defaults are the standard values.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields, default)]
#[non_exhaustive]
pub struct CribbagePoints {
    /// Each different set of cards adding up to 15 (court cards count 10, aces 1).
    pub fifteen: u32,
    /// Each pair of cards of the same rank.
    pub pair: u32,
    /// Each card of each run of three or more ranks in sequence (ace low), counted once per
    /// different set of cards making the run.
    pub run_card: u32,
    /// A full line all of one suit.
    pub flush: u32,
    /// More when the starter is that suit too.
    pub flush_starter: u32,
    /// For each hand holding the jack of the starter's suit ("one for his nob").
    pub nobs: u32,
    /// Once, if the starter is a jack ("two for his heels").
    pub heels: u32,
}

impl Default for CribbagePoints {
    fn default() -> Self {
        CribbagePoints {
            fifteen: 2,
            pair: 2,
            run_card: 1,
            flush: 4,
            flush_starter: 1,
            nobs: 1,
            heels: 2,
        }
    }
}

impl CribbagePoints {
    pub fn is_standard(&self) -> bool {
        *self == CribbagePoints::default()
    }
}

/// Points for each poker hand: a named table or explicit points.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(untagged)]
#[non_exhaustive]
pub enum PokerTable {
    Named(PokerScoring),
    Points(PokerPoints),
}

impl PokerTable {
    pub fn points(&self) -> PokerPoints {
        match self {
            PokerTable::Named(PokerScoring::American) => PokerPoints {
                pair: 2,
                two_pair: 5,
                three: 10,
                straight: 15,
                flush: 20,
                full_house: 25,
                four: 50,
                straight_flush: 75,
                royal_flush: 100,
            },
            PokerTable::Named(PokerScoring::English) => PokerPoints {
                pair: 1,
                two_pair: 3,
                three: 6,
                straight: 12,
                flush: 5,
                full_house: 10,
                four: 16,
                straight_flush: 30,
                royal_flush: 30,
            },
            PokerTable::Points(p) => p.clone(),
        }
    }
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum PokerScoring {
    /// Pair 2, two pair 5, three of a kind 10, straight 15, flush 20, full house 25, four of a
    /// kind 50, straight flush 75, royal flush 100.
    American,
    /// Pair 1, two pair 3, three of a kind 6, straight 12, flush 5, full house 10, four of a
    /// kind 16, straight or royal flush 30.
    English,
}

/// Points per poker hand. A hand counts as its highest-ranking combination (in the usual poker
/// order), whatever the points.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields, default)]
#[non_exhaustive]
pub struct PokerPoints {
    pub pair: u32,
    pub two_pair: u32,
    pub three: u32,
    pub straight: u32,
    pub flush: u32,
    pub full_house: u32,
    pub four: u32,
    pub straight_flush: u32,
    pub royal_flush: u32,
}

/// A move that draws out the second card of a pile, leaving the top card where it is.
///
/// A pile of group `from` with at least two cards may send its second card to the first pile
/// that accepts it, trying the groups of `to` in order (piles in order within a group, never
/// the pile itself). Limit how often with [`AuxEvent::Extract`] gates and updates. Piles are
/// not symmetric, since which pile is first matters.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct ExtractSecond {
    pub from: String,
    pub to: Vec<String>,
}

impl ExtractSecond {
    pub fn new(from: &str, to: &[&str]) -> ExtractSecond {
        ExtractSecond {
            from: from.to_string(),
            to: to.iter().map(|s| s.to_string()).collect(),
        }
    }
}

/// Counter rules: two small signed counters kept with the position.
///
/// `updates` change a counter when an event happens (a stock deal, a move between two groups);
/// `gates` forbid an event unless a condition holds. Conditions are tested on the position
/// before the event. Counters are part of the position (hashed, and saved in position data).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct AuxRules {
    /// Starting values of the two counters.
    #[serde(default, skip_serializing_if = "is_zero_pair")]
    pub initial: [i16; 2],
    /// Counter changes, applied in order for every matching event.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub updates: Vec<AuxUpdate>,
    /// An event is allowed only if every gate for it holds.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub gates: Vec<AuxGate>,
}

fn is_zero_pair(p: &[i16; 2]) -> bool {
    *p == [0, 0]
}

impl AuxRules {
    /// No counters changes or gates yet, counters starting at `initial`.
    pub fn new(initial: [i16; 2]) -> AuxRules {
        AuxRules {
            initial,
            updates: Vec::new(),
            gates: Vec::new(),
        }
    }

    /// Change counter `slot` with `op` when `on` happens (and `when` holds, if given).
    pub fn update(mut self, on: AuxEvent, when: Option<AuxCond>, slot: u8, op: AuxOp) -> Self {
        self.updates.push(AuxUpdate { on, when, slot, op });
        self
    }

    /// Allow `on` only while `require` holds.
    pub fn gate(mut self, on: AuxEvent, require: AuxCond) -> Self {
        self.gates.push(AuxGate { on, require });
        self
    }
}

/// A counter change.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct AuxUpdate {
    pub on: AuxEvent,
    /// Only when this holds (tested before the event). Default: always.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub when: Option<AuxCond>,
    /// Which counter: 0 or 1.
    pub slot: u8,
    pub op: AuxOp,
}

/// A condition on an event.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct AuxGate {
    pub on: AuxEvent,
    pub require: AuxCond,
}

/// Something that happens in play.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum AuxEvent {
    /// The stock deals, or the waste is turned back into it, or the tableau is redealt. Test
    /// whether the stock is empty with a condition to tell the cases apart.
    Deal,
    /// A card (or run) moves from a pile of group `from` to a pile of group `to`; a group left
    /// out matches any. Cards that go by themselves (refills, settling) are not moves.
    Transfer {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        from: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        to: Option<String>,
    },
    /// A pile of `group` (any group if left out) is about to be refilled automatically.
    /// Only usable in gates.
    Refill {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        group: Option<String>,
    },
    /// The second card of a pile is drawn out ([`Rules::extract_second`]).
    Extract,
}

/// How a counter changes.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum AuxOp {
    /// Set to a value.
    Set(i16),
    /// Raise to at least `floor` (if given), add `by`, then reduce modulo `modulo` (if given).
    Add {
        by: i16,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        modulo: Option<i16>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        floor: Option<i16>,
    },
    /// Set to the index, within its group, of the pile the moved cards came from. A
    /// [`AuxEvent::Transfer`] only. Makes pile numbering matter, so piles are not symmetric.
    SourcePile,
}

/// A test on the position (and, for moves, the cards moved).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum AuxCond {
    /// Counter `slot` compared with `value`.
    Counter {
        slot: u8,
        cmp: AuxCmp,
        value: i16,
    },
    /// Some pile of the group is empty.
    AnyEmpty {
        group: String,
    },
    /// Some pile of the group holds a card.
    AnyNonEmpty {
        group: String,
    },
    /// The first card moved has rank `counter + offset` (a [`AuxEvent::Transfer`] only).
    RankIsCounter {
        slot: u8,
        offset: i16,
    },
    /// The counter holds a pile index, and it and the pile the cards come from (an index in
    /// its own group) lie together in one of the `sets` (a [`AuxEvent::Transfer`] only).
    SharesSetWithSource {
        slot: u8,
        sets: Vec<Vec<u16>>,
    },
    Not(Box<AuxCond>),
    All(Vec<AuxCond>),
    Any(Vec<AuxCond>),
}

/// A comparison.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum AuxCmp {
    Eq,
    Ne,
    Lt,
    Le,
    Gt,
    Ge,
}

impl Rules {
    pub fn from_json(s: &str) -> Result<Rules, serde_json::Error> {
        serde_json::from_str(s)
    }

    pub fn to_json(&self) -> String {
        serde_json::to_string_pretty(self).expect("rules serialize")
    }

    /// Return a copy of these rules with `patch` applied using RFC 7396 JSON Merge Patch.
    ///
    /// Object fields are merged recursively; `null` removes a field (falling back to its default),
    /// and arrays or scalars replace the existing value.
    pub fn patch(&self, patch: &serde_json::Value) -> Result<Rules, serde_json::Error> {
        let mut base = serde_json::to_value(self)?;
        merge_json_value(&mut base, patch);
        serde_json::from_value(base)
    }

    /// Return a copy of these rules with a JSON Merge Patch string applied (e.g.
    /// `'{"stock":{"deal":3}}'`).
    pub fn patch_json(&self, patch_json: &str) -> Result<Rules, serde_json::Error> {
        let patch: serde_json::Value = serde_json::from_str(patch_json)?;
        self.patch(&patch)
    }
}

fn merge_json_value(base: &mut serde_json::Value, patch: &serde_json::Value) {
    match (base, patch) {
        (serde_json::Value::Object(base_map), serde_json::Value::Object(patch_map)) => {
            for (k, v) in patch_map {
                if v.is_null() {
                    base_map.remove(k);
                } else if let Some(existing) = base_map.get_mut(k) {
                    merge_json_value(existing, v);
                } else {
                    base_map.insert(k.clone(), v.clone());
                }
            }
        }
        (base_slot, patch_val) => {
            *base_slot = patch_val.clone();
        }
    }
}

#[cfg(test)]
mod patch_tests {
    #[test]
    fn patch_json_modifies_preset_fields() {
        let kl1 = crate::presets::klondike1();
        let patched = kl1
            .patch_json(r#"{"stock":{"count":3,"unlimited_redeals":false,"redeals":2}}"#)
            .expect("patch should succeed");
        let st = patched.stock.as_ref().unwrap();
        assert_eq!(st.count, 3);
        assert!(!st.unlimited_redeals);
        assert_eq!(st.redeals, 2);
        // Unpatched fields remain intact.
        assert_eq!(patched.name, kl1.name);
        assert_eq!(patched.groups.len(), kl1.groups.len());
        assert!(crate::Game::new(patched).is_ok());
    }
}