ogdoad 1.0.0

Clifford algebras (with nilpotents) over the field-like subclasses of combinatorial games: nimbers, surreals, surcomplex.
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
//! Python bindings for combinatorial game theory: partizan games, the exterior
//! algebra and checked integer Clifford deformation of the game group generators,
//! and nim-mult via the Turning-Corners game recurrence.

use super::engine::{IntegerAlgebra, IntegerMV};
use super::forms::{wrap_binary_code, wrap_quadric_fit, PyBinaryCode, PyQuadricFit};
use super::scalars::{
    parse_rational, parse_surreal, wrap_rational, PyOrdinal, PyRational, PySurreal,
};
use crate::clifford::CliffordAlgebra;
use crate::games::{
    thermography, AbstractGame, Color, Game, GameClifford, GameExterior, GameRelation, Hackenbush,
    LoopyGraph, LoopyNimCertificate, LoopyNimber, LoopyPartizanGraph, LoopyPartizanOutcome,
    LoopyValue, LoopyWinner, NimLexicode, NimberGame, NumberGame, Outcome, PartizanOutcome,
    Quotient,
};
use crate::scalar::{Integer, Rational, SignExpansion, Surreal};
use pyo3::basic::CompareOp;
use pyo3::exceptions::{PyTypeError, PyValueError};
use pyo3::prelude::*;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Arc;

/// Validate an adjacency list: every successor index must be `< n = succ.len()`.
/// Returns `PyValueError` with the offending position and index on failure.
/// This is the shared bounds-check for all list-input Python entry points that
/// forward directly to Rust kernels (which would otherwise panic on out-of-range
/// indices in the predecessor/successor arrays).
fn check_succ_bounds(succ: &[Vec<usize>]) -> PyResult<()> {
    let n = succ.len();
    for (v, neighbors) in succ.iter().enumerate() {
        for &w in neighbors {
            if w >= n {
                return Err(PyValueError::new_err(format!(
                    "adjacency list out of range: succ[{v}] contains index {w}, \
                     but the graph has only {n} positions (0..{n})"
                )));
            }
        }
    }
    Ok(())
}

fn check_partizan_succ_bounds(left: &[Vec<usize>], right: &[Vec<usize>]) -> PyResult<()> {
    if left.len() != right.len() {
        return Err(PyValueError::new_err(format!(
            "left/right move tables must have the same number of positions: left has {}, right has {}",
            left.len(),
            right.len()
        )));
    }
    check_succ_bounds(left)?;
    check_succ_bounds(right)
}

/// Wrap a dyadic `Rational` (a thermograph coordinate) as a `Surreal` for Python.
fn rat_to_py(r: Rational) -> PySurreal {
    PySurreal::from_inner(Surreal::from_rational(r))
}

fn wrap_pl(inner: thermography::Pl) -> PyPl {
    PyPl { inner }
}

fn wrap_thermograph(inner: thermography::Thermograph) -> PyThermograph {
    PyThermograph { inner }
}

#[pyclass(name = "GameRelation", module = "ogdoad", from_py_object)]
#[derive(Clone)]
struct PyGameRelation {
    inner: GameRelation,
}

#[pymethods]
impl PyGameRelation {
    #[new]
    fn new(coeffs: Vec<i128>) -> Self {
        PyGameRelation {
            inner: GameRelation::new(coeffs),
        }
    }
    #[getter]
    fn coeffs(&self) -> Vec<i128> {
        self.inner.coeffs.clone()
    }
    fn __richcmp__(&self, other: &Bound<'_, PyAny>, op: CompareOp) -> PyResult<bool> {
        let Ok(rel) = other.extract::<PyRef<'_, PyGameRelation>>() else {
            return Ok(matches!(op, CompareOp::Ne));
        };
        match op {
            CompareOp::Eq => Ok(self.inner.coeffs == rel.inner.coeffs),
            CompareOp::Ne => Ok(self.inner.coeffs != rel.inner.coeffs),
            CompareOp::Lt | CompareOp::Le | CompareOp::Gt | CompareOp::Ge => Err(
                PyValueError::new_err("GameRelation only supports equality comparisons"),
            ),
        }
    }
    fn __repr__(&self) -> String {
        format!("GameRelation(coeffs={:?})", self.inner.coeffs)
    }
}

fn wrap_game_relation(inner: GameRelation) -> PyGameRelation {
    PyGameRelation { inner }
}

#[pyclass(name = "GameRelationCertificate", module = "ogdoad")]
struct PyGameRelationCertificate {
    inner: crate::games::GameRelationCertificate,
}

#[pymethods]
impl PyGameRelationCertificate {
    #[getter]
    fn coeffs(&self) -> Vec<i128> {
        self.inner.coeffs.clone()
    }
    #[getter]
    fn value_key(&self) -> String {
        self.inner.value_key.clone()
    }
    #[getter]
    fn independent(&self) -> bool {
        self.inner.independent
    }
    fn display(&self) -> String {
        self.inner.display()
    }
    fn __repr__(&self) -> String {
        self.inner.display()
    }
}

fn wrap_game_relation_certificate(
    inner: crate::games::GameRelationCertificate,
) -> PyGameRelationCertificate {
    PyGameRelationCertificate { inner }
}

#[pyclass(name = "RelationSearchCertificate", module = "ogdoad")]
struct PyRelationSearchCertificate {
    inner: crate::games::RelationSearchCertificate,
}

#[pymethods]
impl PyRelationSearchCertificate {
    #[getter]
    fn bound(&self) -> i128 {
        self.inner.bound
    }
    #[getter]
    fn exhaustive(&self) -> bool {
        self.inner.exhaustive
    }
    #[getter]
    fn candidate_count(&self) -> Option<usize> {
        self.inner.candidate_count
    }
    #[getter]
    fn relations(&self) -> Vec<PyGameRelationCertificate> {
        self.inner
            .relations
            .iter()
            .cloned()
            .map(wrap_game_relation_certificate)
            .collect()
    }
    fn display(&self) -> String {
        self.inner.display()
    }
    fn __repr__(&self) -> String {
        self.inner.display()
    }
}

fn wrap_relation_search_certificate(
    inner: crate::games::RelationSearchCertificate,
) -> PyRelationSearchCertificate {
    PyRelationSearchCertificate { inner }
}

#[pyclass(name = "Pl", module = "ogdoad", from_py_object)]
#[derive(Clone)]
struct PyPl {
    inner: thermography::Pl,
}

#[pymethods]
impl PyPl {
    #[staticmethod]
    fn constant(value: &Bound<'_, PyAny>) -> PyResult<Self> {
        Ok(wrap_pl(thermography::Pl::constant(parse_rational(value)?)))
    }
    fn points(&self) -> Vec<(PyRational, PyRational)> {
        self.inner
            .points()
            .iter()
            .map(|(t, v)| (wrap_rational(t.clone()), wrap_rational(v.clone())))
            .collect()
    }
    fn value_at(&self, t: &Bound<'_, PyAny>) -> PyResult<PyRational> {
        Ok(wrap_rational(self.inner.value_at(&parse_rational(t)?)))
    }
    fn oplus_max(&self, other: &PyPl) -> PyPl {
        wrap_pl(self.inner.oplus_max(&other.inner))
    }
    fn oplus_min(&self, other: &PyPl) -> PyPl {
        wrap_pl(self.inner.oplus_min(&other.inner))
    }
    fn otimes(&self, other: &PyPl) -> PyPl {
        wrap_pl(self.inner.otimes(&other.inner))
    }
    fn __repr__(&self) -> String {
        format!("Pl({:?})", self.inner.points())
    }
}

#[pyclass(name = "Thermograph", module = "ogdoad", from_py_object)]
#[derive(Clone)]
struct PyThermograph {
    inner: thermography::Thermograph,
}

#[pymethods]
impl PyThermograph {
    #[getter]
    fn mean(&self) -> PyRational {
        wrap_rational(self.inner.mean())
    }
    #[getter]
    fn temperature(&self) -> PyRational {
        wrap_rational(self.inner.temperature.clone())
    }
    #[getter]
    fn left_wall(&self) -> PyPl {
        wrap_pl(self.inner.left_wall.clone())
    }
    #[getter]
    fn right_wall(&self) -> PyPl {
        wrap_pl(self.inner.right_wall.clone())
    }
    fn left_stop(&self) -> PyRational {
        wrap_rational(self.inner.left_stop())
    }
    fn right_stop(&self) -> PyRational {
        wrap_rational(self.inner.right_stop())
    }
    fn cooled_stops(&self, t: &Bound<'_, PyAny>) -> PyResult<(PyRational, PyRational)> {
        let (l, r) = self.inner.cooled_stops(&parse_rational(t)?);
        Ok((wrap_rational(l), wrap_rational(r)))
    }
    fn __repr__(&self) -> String {
        format!(
            "Thermograph(mean={:?}, temperature={:?})",
            self.inner.mast, self.inner.temperature
        )
    }
}

/// Nim-multiplication via Conway's Turning-Corners game recurrence (the
/// game-theoretic definition; equals the algebraic nim-product).
#[pyfunction]
fn nim_mul_mex(x: u128, y: u128) -> u128 {
    crate::games::nim_mul_mex(x, y)
}

#[derive(Clone, Copy)]
enum CoinFamily {
    Singleton,
    Turtles,
}

type CompanionFn = fn(u128) -> Vec<u128>;

impl CoinFamily {
    fn companions(self) -> CompanionFn {
        match self {
            CoinFamily::Singleton => crate::games::singleton_companions,
            CoinFamily::Turtles => crate::games::turtles_companions,
        }
    }
}

fn parse_coin_family(name: &str) -> PyResult<CoinFamily> {
    match name.trim().to_ascii_lowercase().as_str() {
        "singleton" | "singletons" | "turning-corners" | "turning_corners" | "corners" => {
            Ok(CoinFamily::Singleton)
        }
        "turtles" | "turning-turtles" | "turning_turtles" => Ok(CoinFamily::Turtles),
        other => Err(PyValueError::new_err(format!(
            "unknown coin-turning family {other:?}; expected 'singleton' or 'turtles'"
        ))),
    }
}

fn check_coin_index(n: u128, label: &str) -> PyResult<()> {
    if n >= 128 {
        Err(PyValueError::new_err(format!(
            "{label} must be < 128 because companion sets are u128 bitmasks"
        )))
    } else {
        Ok(())
    }
}

fn lower_coin_mask(n: u128, label: &str) -> PyResult<u128> {
    check_coin_index(n, label)?;
    Ok(if n == 0 { 0 } else { (1u128 << n) - 1 })
}

fn call_u128_moves(callback: &Bound<'_, PyAny>, pos: u128) -> PyResult<Vec<u128>> {
    callback.call1((pos,))?.extract()
}

fn call_usize_moves(callback: &Bound<'_, PyAny>, pos: usize) -> PyResult<Vec<usize>> {
    callback.call1((pos,))?.extract()
}

fn grundy_u128_inner(
    pos: u128,
    moves: &Bound<'_, PyAny>,
    memo: &mut HashMap<u128, u128>,
) -> PyResult<u128> {
    if let Some(&v) = memo.get(&pos) {
        return Ok(v);
    }
    let nexts = call_u128_moves(moves, pos)?;
    let mut values = Vec::with_capacity(nexts.len());
    for next in nexts {
        values.push(grundy_u128_inner(next, moves, memo)?);
    }
    let g = crate::games::mex(values);
    memo.insert(pos, g);
    Ok(g)
}

fn misere_is_n_u128_inner(
    pos: u128,
    moves: &Bound<'_, PyAny>,
    memo: &mut HashMap<u128, bool>,
    visiting: &mut HashSet<u128>,
) -> PyResult<Option<bool>> {
    if let Some(&v) = memo.get(&pos) {
        return Ok(Some(v));
    }
    if !visiting.insert(pos) {
        return Ok(None);
    }
    let nexts = call_u128_moves(moves, pos)?;
    let mut result = nexts.is_empty();
    if !result {
        for next in nexts {
            match misere_is_n_u128_inner(next, moves, memo, visiting)? {
                Some(false) => {
                    result = true;
                    break;
                }
                Some(true) => {}
                None => {
                    visiting.remove(&pos);
                    return Ok(None);
                }
            }
        }
    }
    visiting.remove(&pos);
    memo.insert(pos, result);
    Ok(Some(result))
}

fn loopy_succ_from_callback(n: usize, moves: &Bound<'_, PyAny>) -> PyResult<Vec<Vec<usize>>> {
    let mut succ = Vec::with_capacity(n);
    for v in 0..n {
        let nexts = call_usize_moves(moves, v)?;
        if nexts.iter().any(|&w| w >= n) {
            return Err(PyValueError::new_err(format!(
                "move callback for position {v} returned an out-of-range target"
            )));
        }
        succ.push(nexts);
    }
    Ok(succ)
}

/// Legal companion masks for the named 1-D coin-turning family at coin `n`.
/// Families: `"singleton"` (turn exactly one lower coin) and `"turtles"`
/// (turn optionally one lower coin).
#[pyfunction]
fn coin_companions(kind: &str, n: u128) -> PyResult<Vec<u128>> {
    check_coin_index(n, "n")?;
    Ok((parse_coin_family(kind)?.companions())(n))
}

#[pyfunction]
fn singleton_companions(n: u128) -> PyResult<Vec<u128>> {
    check_coin_index(n, "n")?;
    Ok(crate::games::singleton_companions(n))
}

#[pyfunction]
fn turtles_companions(n: u128) -> PyResult<Vec<u128>> {
    check_coin_index(n, "n")?;
    Ok(crate::games::turtles_companions(n))
}

/// Single-coin Grundy value for a Python companion-mask callback.
/// `companions(n)` must return legal bitmasks over lower coins `{0, …, n-1}`.
#[pyfunction]
fn grundy_1d(companions: Bound<'_, PyAny>, n: u128) -> PyResult<u128> {
    fn inner(
        companions: &Bound<'_, PyAny>,
        n: u128,
        memo: &mut HashMap<u128, u128>,
    ) -> PyResult<u128> {
        let allowed = lower_coin_mask(n, "n")?;
        if let Some(&v) = memo.get(&n) {
            return Ok(v);
        }
        let mut seen = HashSet::new();
        for s in call_u128_moves(companions, n)? {
            if s & !allowed != 0 {
                return Err(PyValueError::new_err(
                    "companion mask contains a coin that is not strictly lower than n",
                ));
            }
            let mut acc = 0u128;
            let mut ss = s;
            while ss != 0 {
                let i = ss.trailing_zeros() as u128;
                ss &= ss - 1;
                acc ^= inner(companions, i, memo)?;
            }
            seen.insert(acc);
        }
        let g = crate::games::mex(seen);
        memo.insert(n, g);
        Ok(g)
    }

    check_coin_index(n, "n")?;
    inner(&companions, n, &mut HashMap::new())
}

/// Single-coin Grundy value of a named 1-D coin-turning family.
#[pyfunction]
fn coin_turning_grundy(kind: &str, n: u128) -> PyResult<u128> {
    check_coin_index(n, "n")?;
    let mut memo = HashMap::new();
    let companions = parse_coin_family(kind)?.companions();
    Ok(crate::games::grundy_1d(&companions, n, &mut memo))
}

/// Single-cell Grundy value of the Tartan product of two named 1-D coin-turning
/// families, computed directly from the 2-D excludant.
#[pyfunction]
fn coin_turning_tartan_grundy(kind_a: &str, kind_b: &str, x: u128, y: u128) -> PyResult<u128> {
    check_coin_index(x, "x")?;
    check_coin_index(y, "y")?;
    let comp_a = parse_coin_family(kind_a)?.companions();
    let comp_b = parse_coin_family(kind_b)?.companions();
    let mut memo = HashMap::new();
    Ok(crate::games::tartan_grundy(
        &comp_a, &comp_b, x, y, &mut memo,
    ))
}

/// Single-cell Grundy value of the Tartan product for two Python companion-mask
/// callbacks.
#[pyfunction]
fn tartan_grundy(
    comp_a: Bound<'_, PyAny>,
    comp_b: Bound<'_, PyAny>,
    x: u128,
    y: u128,
) -> PyResult<u128> {
    fn inner(
        comp_a: &Bound<'_, PyAny>,
        comp_b: &Bound<'_, PyAny>,
        x: u128,
        y: u128,
        memo: &mut HashMap<(u128, u128), u128>,
    ) -> PyResult<u128> {
        let allowed_x = lower_coin_mask(x, "x")?;
        let allowed_y = lower_coin_mask(y, "y")?;
        if let Some(&v) = memo.get(&(x, y)) {
            return Ok(v);
        }
        let mut seen = HashSet::new();
        for ta in call_u128_moves(comp_a, x)? {
            if ta & !allowed_x != 0 {
                return Err(PyValueError::new_err(
                    "row companion mask contains a coin that is not strictly lower than x",
                ));
            }
            let acells = ta | (1u128 << x);
            for tb in call_u128_moves(comp_b, y)? {
                if tb & !allowed_y != 0 {
                    return Err(PyValueError::new_err(
                        "column companion mask contains a coin that is not strictly lower than y",
                    ));
                }
                let bcells = tb | (1u128 << y);
                let mut acc = 0u128;
                let mut aa = acells;
                while aa != 0 {
                    let a = aa.trailing_zeros() as u128;
                    aa &= aa - 1;
                    let mut bb = bcells;
                    while bb != 0 {
                        let b = bb.trailing_zeros() as u128;
                        bb &= bb - 1;
                        if a != x || b != y {
                            acc ^= inner(comp_a, comp_b, a, b, memo)?;
                        }
                    }
                }
                seen.insert(acc);
            }
        }
        let g = crate::games::mex(seen);
        memo.insert((x, y), g);
        Ok(g)
    }

    check_coin_index(x, "x")?;
    check_coin_index(y, "y")?;
    inner(&comp_a, &comp_b, x, y, &mut HashMap::new())
}

/// Grundy value of an acyclic impartial game with `u128` positions and a Python
/// move callback `moves(pos) -> list[u128]`.
#[pyfunction]
fn grundy(pos: u128, moves: Bound<'_, PyAny>) -> PyResult<u128> {
    grundy_u128_inner(pos, &moves, &mut HashMap::new())
}

/// Sprague–Grundy values of a finite **acyclic** impartial game graph given as
/// adjacency lists (`succ[v]` = positions reachable from `v`). Errors on a cycle
/// (Grundy values are undefined on loopy games). A position is a P-position iff
/// its value is 0.
#[pyfunction]
fn grundy_graph(succ: Vec<Vec<usize>>) -> PyResult<Vec<u128>> {
    check_succ_bounds(&succ)?;
    crate::games::grundy_graph(&succ)
        .ok_or_else(|| PyValueError::new_err("graph has a cycle — Grundy value is undefined"))
}

/// The minimal excludant `mex(S)` — the least non-negative integer not in the
/// multiset `values`. The core of the Sprague–Grundy recurrence.
#[pyfunction]
fn mex(values: Vec<u128>) -> u128 {
    crate::games::mex(values)
}

// ---------------------------------------------------------------------------
// Outcomes of a finite game graph (kernel): Win / Loss / Draw + scoring
// ---------------------------------------------------------------------------

fn outcome_name(o: Outcome) -> String {
    match o {
        Outcome::Loss => "Loss",
        Outcome::Win => "Win",
        Outcome::Draw => "Draw",
    }
    .to_string()
}

#[pyclass(name = "Outcome", module = "ogdoad", from_py_object)]
#[derive(Clone)]
struct PyOutcome {
    inner: Outcome,
}

fn wrap_outcome(inner: Outcome) -> PyOutcome {
    PyOutcome { inner }
}

fn parse_outcome(obj: &Bound<'_, PyAny>) -> PyResult<Outcome> {
    if let Ok(outcome) = obj.cast::<PyOutcome>() {
        return Ok(outcome.borrow().inner);
    }
    Err(PyTypeError::new_err("expected Outcome"))
}

#[pymethods]
impl PyOutcome {
    #[staticmethod]
    fn loss() -> Self {
        wrap_outcome(Outcome::Loss)
    }
    #[staticmethod]
    fn win() -> Self {
        wrap_outcome(Outcome::Win)
    }
    #[staticmethod]
    fn draw() -> Self {
        wrap_outcome(Outcome::Draw)
    }
    fn name(&self) -> String {
        outcome_name(self.inner)
    }
    fn is_loss(&self) -> bool {
        self.inner == Outcome::Loss
    }
    fn is_win(&self) -> bool {
        self.inner == Outcome::Win
    }
    fn is_draw(&self) -> bool {
        self.inner == Outcome::Draw
    }
    fn __richcmp__(&self, other: &Bound<'_, PyAny>, op: CompareOp) -> PyResult<bool> {
        match op {
            CompareOp::Eq => Ok(parse_outcome(other).is_ok_and(|o| o == self.inner)),
            CompareOp::Ne => Ok(parse_outcome(other).is_ok_and(|o| o != self.inner)),
            CompareOp::Lt | CompareOp::Le | CompareOp::Gt | CompareOp::Ge => Err(
                PyValueError::new_err("Outcome only supports equality comparisons"),
            ),
        }
    }
    fn __str__(&self) -> String {
        self.name()
    }
    fn __repr__(&self) -> String {
        format!("Outcome.{}", outcome_name(self.inner))
    }
}

fn partizan_outcome_name(o: PartizanOutcome) -> String {
    match o {
        PartizanOutcome::P => "P",
        PartizanOutcome::N => "N",
        PartizanOutcome::L => "L",
        PartizanOutcome::R => "R",
        PartizanOutcome::Draw => "Draw",
    }
    .to_string()
}

#[pyclass(name = "PartizanOutcome", module = "ogdoad", from_py_object)]
#[derive(Clone)]
struct PyPartizanOutcome {
    inner: PartizanOutcome,
}

fn wrap_partizan_outcome(inner: PartizanOutcome) -> PyPartizanOutcome {
    PyPartizanOutcome { inner }
}

fn parse_partizan_outcome(obj: &Bound<'_, PyAny>) -> PyResult<PartizanOutcome> {
    if let Ok(outcome) = obj.cast::<PyPartizanOutcome>() {
        return Ok(outcome.borrow().inner);
    }
    Err(PyTypeError::new_err("expected PartizanOutcome"))
}

#[pymethods]
impl PyPartizanOutcome {
    #[staticmethod]
    fn p() -> Self {
        wrap_partizan_outcome(PartizanOutcome::P)
    }
    #[staticmethod]
    fn n() -> Self {
        wrap_partizan_outcome(PartizanOutcome::N)
    }
    #[staticmethod]
    fn l() -> Self {
        wrap_partizan_outcome(PartizanOutcome::L)
    }
    #[staticmethod]
    fn r() -> Self {
        wrap_partizan_outcome(PartizanOutcome::R)
    }
    #[staticmethod]
    fn draw() -> Self {
        wrap_partizan_outcome(PartizanOutcome::Draw)
    }
    fn name(&self) -> String {
        partizan_outcome_name(self.inner)
    }
    fn __richcmp__(&self, other: &Bound<'_, PyAny>, op: CompareOp) -> PyResult<bool> {
        match op {
            CompareOp::Eq => Ok(parse_partizan_outcome(other).is_ok_and(|o| o == self.inner)),
            CompareOp::Ne => Ok(parse_partizan_outcome(other).is_ok_and(|o| o != self.inner)),
            CompareOp::Lt | CompareOp::Le | CompareOp::Gt | CompareOp::Ge => Err(
                PyValueError::new_err("PartizanOutcome only supports equality comparisons"),
            ),
        }
    }
    fn __str__(&self) -> String {
        self.name()
    }
    fn __repr__(&self) -> String {
        format!("PartizanOutcome.{}", partizan_outcome_name(self.inner))
    }
}

fn loopy_winner_name(w: LoopyWinner) -> String {
    match w {
        LoopyWinner::Left => "Left",
        LoopyWinner::Right => "Right",
        LoopyWinner::Draw => "Draw",
    }
    .to_string()
}

#[pyclass(name = "LoopyWinner", module = "ogdoad", from_py_object)]
#[derive(Clone)]
struct PyLoopyWinner {
    inner: LoopyWinner,
}

fn wrap_loopy_winner(inner: LoopyWinner) -> PyLoopyWinner {
    PyLoopyWinner { inner }
}

fn parse_loopy_winner(obj: &Bound<'_, PyAny>) -> PyResult<LoopyWinner> {
    if let Ok(winner) = obj.cast::<PyLoopyWinner>() {
        return Ok(winner.borrow().inner);
    }
    Err(PyTypeError::new_err("expected LoopyWinner"))
}

#[pymethods]
impl PyLoopyWinner {
    #[staticmethod]
    fn left() -> Self {
        wrap_loopy_winner(LoopyWinner::Left)
    }
    #[staticmethod]
    fn right() -> Self {
        wrap_loopy_winner(LoopyWinner::Right)
    }
    #[staticmethod]
    fn draw() -> Self {
        wrap_loopy_winner(LoopyWinner::Draw)
    }
    fn name(&self) -> String {
        loopy_winner_name(self.inner)
    }
    fn is_left(&self) -> bool {
        self.inner == LoopyWinner::Left
    }
    fn is_right(&self) -> bool {
        self.inner == LoopyWinner::Right
    }
    fn is_draw(&self) -> bool {
        self.inner == LoopyWinner::Draw
    }
    fn __richcmp__(&self, other: &Bound<'_, PyAny>, op: CompareOp) -> PyResult<bool> {
        match op {
            CompareOp::Eq => Ok(parse_loopy_winner(other).is_ok_and(|w| w == self.inner)),
            CompareOp::Ne => Ok(parse_loopy_winner(other).is_ok_and(|w| w != self.inner)),
            CompareOp::Lt | CompareOp::Le | CompareOp::Gt | CompareOp::Ge => Err(
                PyValueError::new_err("LoopyWinner only supports equality comparisons"),
            ),
        }
    }
    fn __str__(&self) -> String {
        self.name()
    }
    fn __repr__(&self) -> String {
        format!("LoopyWinner.{}", loopy_winner_name(self.inner))
    }
}

#[pyclass(name = "LoopyPartizanOutcome", module = "ogdoad", from_py_object)]
#[derive(Clone)]
struct PyLoopyPartizanOutcome {
    inner: LoopyPartizanOutcome,
}

fn wrap_loopy_partizan_outcome(inner: LoopyPartizanOutcome) -> PyLoopyPartizanOutcome {
    PyLoopyPartizanOutcome { inner }
}

fn parse_loopy_partizan_outcome(obj: &Bound<'_, PyAny>) -> PyResult<LoopyPartizanOutcome> {
    if let Ok(outcome) = obj.cast::<PyLoopyPartizanOutcome>() {
        return Ok(outcome.borrow().inner);
    }
    Err(PyTypeError::new_err("expected LoopyPartizanOutcome"))
}

#[pymethods]
impl PyLoopyPartizanOutcome {
    #[new]
    fn new(left_to_move: &Bound<'_, PyAny>, right_to_move: &Bound<'_, PyAny>) -> PyResult<Self> {
        Ok(wrap_loopy_partizan_outcome(LoopyPartizanOutcome::new(
            parse_loopy_winner(left_to_move)?,
            parse_loopy_winner(right_to_move)?,
        )))
    }
    #[getter]
    fn left_to_move(&self) -> PyLoopyWinner {
        wrap_loopy_winner(self.inner.left_to_move)
    }
    #[getter]
    fn right_to_move(&self) -> PyLoopyWinner {
        wrap_loopy_winner(self.inner.right_to_move)
    }
    fn partizan_class(&self) -> Option<PyPartizanOutcome> {
        self.inner.partizan_class().map(wrap_partizan_outcome)
    }
    fn has_draw(&self) -> bool {
        self.inner.has_draw()
    }
    fn __richcmp__(&self, other: &Bound<'_, PyAny>, op: CompareOp) -> PyResult<bool> {
        match op {
            CompareOp::Eq => Ok(parse_loopy_partizan_outcome(other).is_ok_and(|o| o == self.inner)),
            CompareOp::Ne => Ok(parse_loopy_partizan_outcome(other).is_ok_and(|o| o != self.inner)),
            CompareOp::Lt | CompareOp::Le | CompareOp::Gt | CompareOp::Ge => Err(
                PyValueError::new_err("LoopyPartizanOutcome only supports equality comparisons"),
            ),
        }
    }
    fn __repr__(&self) -> String {
        format!(
            "LoopyPartizanOutcome(left_to_move={}, right_to_move={})",
            loopy_winner_name(self.inner.left_to_move),
            loopy_winner_name(self.inner.right_to_move)
        )
    }
}

#[pyclass(name = "LoopyNimber", module = "ogdoad", from_py_object)]
#[derive(Clone)]
struct PyLoopyNimber {
    inner: LoopyNimber,
}

fn wrap_loopy_nimber(inner: LoopyNimber) -> PyLoopyNimber {
    PyLoopyNimber { inner }
}

fn parse_loopy_nimber(obj: &Bound<'_, PyAny>) -> PyResult<LoopyNimber> {
    if let Ok(value) = obj.cast::<PyLoopyNimber>() {
        return Ok(value.borrow().inner);
    }
    Err(PyTypeError::new_err("expected LoopyNimber"))
}

#[pymethods]
impl PyLoopyNimber {
    #[staticmethod]
    fn value(n: u128) -> Self {
        wrap_loopy_nimber(LoopyNimber::Value(n))
    }
    #[staticmethod]
    fn side() -> Self {
        wrap_loopy_nimber(LoopyNimber::Side)
    }
    fn to_u128(&self) -> PyResult<u128> {
        match self.inner {
            LoopyNimber::Value(n) => Ok(n),
            LoopyNimber::Side => Err(PyValueError::new_err("LoopyNimber.Side has no u128 value")),
        }
    }
    fn is_side(&self) -> bool {
        self.inner == LoopyNimber::Side
    }
    fn is_value(&self) -> bool {
        matches!(self.inner, LoopyNimber::Value(_))
    }
    fn __richcmp__(&self, other: &Bound<'_, PyAny>, op: CompareOp) -> PyResult<bool> {
        match op {
            CompareOp::Eq => Ok(parse_loopy_nimber(other).is_ok_and(|x| x == self.inner)),
            CompareOp::Ne => Ok(parse_loopy_nimber(other).is_ok_and(|x| x != self.inner)),
            CompareOp::Lt | CompareOp::Le | CompareOp::Gt | CompareOp::Ge => Err(
                PyValueError::new_err("LoopyNimber only supports equality comparisons"),
            ),
        }
    }
    fn __repr__(&self) -> String {
        match self.inner {
            LoopyNimber::Value(n) => format!("LoopyNimber.Value({n})"),
            LoopyNimber::Side => "LoopyNimber.Side".to_string(),
        }
    }
}

/// Normal-play typed [`Outcome`] of every position of a finite
/// game graph given as adjacency lists (`succ[v]` = positions reachable from `v`).
/// Retrograde analysis; `Loss` = P-position. Cyclic graphs are fine (→ `Draw`).
/// Raises `ValueError` if any successor index is out of range.
#[pyfunction]
fn outcomes(succ: Vec<Vec<usize>>) -> PyResult<Vec<PyOutcome>> {
    check_succ_bounds(&succ)?;
    Ok(crate::games::outcomes(&succ)
        .into_iter()
        .map(wrap_outcome)
        .collect())
}

/// The P-positions (Loss positions) of a finite game graph, as node indices.
/// Raises `ValueError` if any successor index is out of range.
#[pyfunction]
fn p_positions(succ: Vec<Vec<usize>>) -> PyResult<Vec<usize>> {
    check_succ_bounds(&succ)?;
    Ok(crate::games::p_positions(&succ))
}

#[pyclass(name = "ScoreInterval", module = "ogdoad")]
struct PyScoreInterval {
    inner: crate::games::ScoreInterval,
}

#[pymethods]
impl PyScoreInterval {
    #[getter]
    fn left(&self) -> i128 {
        self.inner.left
    }
    #[getter]
    fn right(&self) -> i128 {
        self.inner.right
    }
    fn __repr__(&self) -> String {
        format!(
            "ScoreInterval(left={}, right={})",
            self.inner.left, self.inner.right
        )
    }
}

fn wrap_score_interval(inner: crate::games::ScoreInterval) -> PyScoreInterval {
    PyScoreInterval { inner }
}

/// Milnor scoring-game minimax on a finite **acyclic** graph: the `(left, right)`
/// value interval of every position (`left` = optimal score with Left/maximizer
/// to move, `right` with Right/minimizer), where `terminal_score[v]` scores each
/// move-less position. Errors on a cycle (loopy scoring is out of scope) or if any
/// successor index is out of range.
#[pyfunction]
fn scoring_values(
    succ: Vec<Vec<usize>>,
    terminal_score: Vec<i128>,
) -> PyResult<Vec<PyScoreInterval>> {
    check_succ_bounds(&succ)?;
    crate::games::scoring_values(&succ, &terminal_score)
        .map(|v| v.into_iter().map(wrap_score_interval).collect())
        .ok_or_else(|| PyValueError::new_err("graph has a cycle — scoring value is undefined"))
}

// ---------------------------------------------------------------------------
// Misère play: Nim witnesses, octal moves, and the indistinguishability quotient
// ---------------------------------------------------------------------------

/// Normalize a Nim heap-multiset: drop empty heaps and sort ascending.
#[pyfunction]
fn nim_canonical(heaps: Vec<u128>) -> Vec<u128> {
    crate::games::nim_canonical(heaps)
}

/// The closed-form misère-Nim P-position rule: with every nonzero heap equal to
/// `1`, a P iff an odd number of nonzero heaps; otherwise (some heap `≥ 2`) a P
/// iff the XOR is `0`.
#[pyfunction]
fn misere_nim_p_predicted(heaps: Vec<u128>) -> bool {
    crate::games::misere_nim_p_predicted(&heaps)
}

/// Misère outcome of a finite acyclic impartial game with `u128` positions and a
/// Python move callback. Returns `None` if the callback-defined graph has a cycle.
#[pyfunction]
fn try_misere_is_n(pos: u128, moves: Bound<'_, PyAny>) -> PyResult<Option<bool>> {
    misere_is_n_u128_inner(pos, &moves, &mut HashMap::new(), &mut HashSet::new())
}

/// Misère N/P outcome for an acyclic Python callback game; errors on cycles.
#[pyfunction]
fn misere_is_n(pos: u128, moves: Bound<'_, PyAny>) -> PyResult<bool> {
    try_misere_is_n(pos, moves)?
        .ok_or_else(|| PyValueError::new_err("misere_is_n requires an acyclic move graph"))
}

/// `True` iff a callback-defined acyclic game is a misère P-position.
#[pyfunction]
fn misere_is_p(pos: u128, moves: Bound<'_, PyAny>) -> PyResult<bool> {
    Ok(!misere_is_n(pos, moves)?)
}

/// The moves of Nim: reduce any one heap to any strictly smaller size.
#[pyfunction]
fn nim_moves(pos: Vec<u128>) -> Vec<Vec<u128>> {
    crate::games::nim_moves(&pos)
}

/// The moves of an octal game `0.d₁d₂…` (`code[k-1] = dₖ`) on a heap-multiset:
/// remove `k` tokens leaving the heap empty (`dₖ & 1`), one nonempty heap
/// (`dₖ & 2`), or two nonempty heaps (`dₖ & 4`). Nim is `0.333…`.
#[pyfunction]
fn octal_moves(code: Vec<u128>, pos: Vec<u128>) -> Vec<Vec<u128>> {
    crate::games::octal_moves(&code, &pos)
}

/// The bounded misère indistinguishability quotient of an octal game, over single
/// heaps `1..=max_heap` as atoms (elements are sums up to `elem_bound`, separated
/// by tests up to `test_bound`). Raises `ValueError` if the bounded search reaches
/// a cyclic position (not reachable through `octal_moves` in practice, but the
/// binding stays honest about the partial primitive underneath).
#[pyfunction]
fn octal_misere_quotient(
    code: Vec<u128>,
    max_heap: usize,
    elem_bound: usize,
    test_bound: usize,
) -> PyResult<PyQuotient> {
    crate::games::octal_misere_quotient(&code, max_heap, elem_bound, test_bound)
        .map(|inner| PyQuotient { inner })
        .ok_or_else(|| {
            PyValueError::new_err("octal_misere_quotient requires an acyclic bounded move graph")
        })
}

/// Loopy impartial nim-values of a (possibly cyclic) game graph: each position is
/// a typed `LoopyNimber.Value(n)`, or `LoopyNimber.Side` for a Draw position.
/// Errors when a cyclic non-Draw subgraph has no unique bounded sidling solution,
/// or when any successor index is out of range.
#[pyfunction]
fn loopy_nim_values(succ: Vec<Vec<usize>>) -> PyResult<Vec<PyLoopyNimber>> {
    check_succ_bounds(&succ)?;
    crate::games::loopy_nim_values(&succ)
        .map(|vs| vs.into_iter().map(wrap_loopy_nimber).collect())
        .ok_or_else(|| {
            PyValueError::new_err("cyclic non-Draw subgraph has no unique bounded sidling solution")
        })
}

/// `(loss_set, draw_set)` for a cyclic Python move rule on positions `0..n`.
#[pyfunction]
fn loopy_decision_sets(n: usize, moves: Bound<'_, PyAny>) -> PyResult<(Vec<usize>, Vec<usize>)> {
    let succ = loopy_succ_from_callback(n, &moves)?;
    let g = LoopyGraph::new(succ);
    Ok((g.loss_set(), g.draw_set()))
}

/// Fit F₂ quadrics to the loss and draw sets of a callback-defined loopy rule on
/// `F_2^k` (`positions = 0..2^k`).
#[pyfunction]
fn loopy_quadric_probe(
    k: usize,
    moves: Bound<'_, PyAny>,
) -> PyResult<(Option<PyQuadricFit>, Option<PyQuadricFit>)> {
    const MAX_ANF_DIM: usize = 20;
    if k > MAX_ANF_DIM {
        return Err(PyValueError::new_err(format!(
            "loopy_quadric_probe is exponential in k; max supported k is {MAX_ANF_DIM}"
        )));
    }
    let n = 1usize << k;
    let (loss, draw) = loopy_decision_sets(n, moves)?;
    let loss_u: Vec<u128> = loss.into_iter().map(|v| v as u128).collect();
    let draw_u: Vec<u128> = draw.into_iter().map(|v| v as u128).collect();
    Ok((
        crate::forms::fit_f2_quadratic(&loss_u, k).map(wrap_quadric_fit),
        crate::forms::fit_f2_quadratic(&draw_u, k).map(wrap_quadric_fit),
    ))
}

#[pyclass(name = "LoopyNimCertificate", module = "ogdoad")]
struct PyLoopyNimCertificate {
    inner: LoopyNimCertificate,
}

#[pymethods]
impl PyLoopyNimCertificate {
    #[getter]
    fn outcomes(&self) -> Vec<PyOutcome> {
        self.inner
            .outcomes
            .iter()
            .copied()
            .map(wrap_outcome)
            .collect()
    }
    #[getter]
    fn side_positions(&self) -> Vec<usize> {
        self.inner.side_positions.clone()
    }
    #[getter]
    fn used_sidling_solver(&self) -> bool {
        self.inner.used_sidling_solver
    }
    #[getter]
    fn sidling_assignments_examined(&self) -> usize {
        self.inner.sidling_assignments_examined
    }
    #[getter]
    fn recovery_condition_holds(&self) -> bool {
        self.inner.recovery_condition_holds
    }
    #[getter]
    fn recovery_blockers(&self) -> Vec<usize> {
        self.inner.recovery_blockers.clone()
    }
    fn display(&self) -> String {
        self.inner.display()
    }
    fn __repr__(&self) -> String {
        self.inner.display()
    }
}

/// Loopy nim-values plus a certificate explaining Draw/Side promotion and
/// whether the bounded sidling solver and finite recovery condition were needed.
/// Raises `ValueError` if any successor index is out of range.
#[pyfunction]
fn loopy_nim_values_certified(
    succ: Vec<Vec<usize>>,
) -> PyResult<(Vec<PyLoopyNimber>, PyLoopyNimCertificate)> {
    check_succ_bounds(&succ)?;
    crate::games::loopy_nim_values_certified(&succ)
        .map(|(vs, inner)| {
            let values = vs.into_iter().map(wrap_loopy_nimber).collect();
            (values, PyLoopyNimCertificate { inner })
        })
        .ok_or_else(|| {
            PyValueError::new_err("cyclic non-Draw subgraph has no unique bounded sidling solution")
        })
}

/// Exact thermograph object for a short game, with `Rational` wall coordinates.
#[pyfunction]
fn thermograph(game: &PyGame) -> Option<PyThermograph> {
    thermography::thermograph(&game.inner).map(wrap_thermograph)
}

/// The same exact thermograph, computed through the named tropical wall folds.
#[pyfunction]
fn thermograph_via_tropical(game: &PyGame) -> Option<PyThermograph> {
    crate::games::tropical_thermography::thermograph_via_tropical(&game.inner).map(wrap_thermograph)
}

#[pyfunction]
fn temperature(game: &PyGame) -> Option<PySurreal> {
    crate::games::temperature(&game.inner).map(rat_to_py)
}

#[pyfunction]
fn mean_value(game: &PyGame) -> Option<PySurreal> {
    crate::games::mean_value(&game.inner).map(rat_to_py)
}

#[pyfunction]
#[pyo3(signature = (game, num, den=1))]
fn heat(game: &PyGame, num: i128, den: i128) -> PyResult<Option<PyGame>> {
    let t = Rational::try_new(num, den)
        .ok_or_else(|| PyValueError::new_err("zero denominator or bounded i128 overflow"))?;
    Ok(crate::games::heat(&game.inner, &t).map(|inner| PyGame { inner }))
}

#[pyfunction]
fn norton_multiply(game: &PyGame, unit: &PyGame) -> Option<PyGame> {
    crate::games::norton_multiply(&game.inner, &unit.inner).map(|inner| PyGame { inner })
}

#[pyfunction]
fn overheat(game: &PyGame, s: &PyGame, t: &PyGame) -> Option<PyGame> {
    crate::games::overheat(&game.inner, &s.inner, &t.inner).map(|inner| PyGame { inner })
}

#[pyfunction]
fn left_stop(game: &PyGame) -> Option<PySurreal> {
    crate::games::left_stop(&game.inner).map(rat_to_py)
}

#[pyfunction]
fn right_stop(game: &PyGame) -> Option<PySurreal> {
    crate::games::right_stop(&game.inner).map(rat_to_py)
}

/// The atomic weight as a `Game` (`None` if the input is not all-small).
#[pyfunction]
fn atomic_weight(game: &PyGame) -> Option<PyGame> {
    crate::games::atomic_weight(&game.inner).map(|inner| PyGame { inner })
}

/// The atomic weight as an integer (`None` if undefined or genuinely non-integer).
#[pyfunction]
fn atomic_weight_int(game: &PyGame) -> Option<i128> {
    crate::games::atomic_weight_int(&game.inner)
}

// ---------------------------------------------------------------------------
// Partizan games + the exterior algebra of the game group
// ---------------------------------------------------------------------------

#[pyclass(name = "Game", module = "ogdoad", from_py_object)]
#[derive(Clone)]
struct PyGame {
    inner: Game,
}

#[pymethods]
impl PyGame {
    #[staticmethod]
    fn zero() -> PyGame {
        PyGame {
            inner: Game::zero(),
        }
    }
    #[staticmethod]
    fn star() -> PyGame {
        PyGame {
            inner: Game::star(),
        }
    }
    #[staticmethod]
    fn up() -> PyGame {
        PyGame { inner: Game::up() }
    }
    #[staticmethod]
    fn integer(n: i128) -> PyGame {
        PyGame {
            inner: Game::integer(n),
        }
    }
    #[staticmethod]
    fn switch(a: i128, b: i128) -> PyGame {
        PyGame {
            inner: Game::switch(a, b),
        }
    }
    /// A general game `{ left | right }` from explicit option lists.
    #[staticmethod]
    fn of(left: Vec<PyGame>, right: Vec<PyGame>) -> PyGame {
        PyGame {
            inner: Game::new(
                left.into_iter().map(|g| g.inner).collect(),
                right.into_iter().map(|g| g.inner).collect(),
            ),
        }
    }
    /// The Left options.
    fn left(&self) -> Vec<PyGame> {
        self.inner
            .left()
            .iter()
            .map(|g| PyGame { inner: g.clone() })
            .collect()
    }
    /// The Right options.
    fn right(&self) -> Vec<PyGame> {
        self.inner
            .right()
            .iter()
            .map(|g| PyGame { inner: g.clone() })
            .collect()
    }
    fn __add__(&self, other: &PyGame) -> PyGame {
        PyGame {
            inner: self.inner.add(&other.inner),
        }
    }
    fn __neg__(&self) -> PyGame {
        PyGame {
            inner: self.inner.neg(),
        }
    }
    fn __sub__(&self, other: &PyGame) -> PyGame {
        PyGame {
            inner: self.inner.add(&other.inner.neg()),
        }
    }
    fn le(&self, other: &PyGame) -> bool {
        self.inner.le(&other.inner)
    }
    fn __eq__(&self, other: &PyGame) -> bool {
        self.inner.eq(&other.inner)
    }
    fn fuzzy(&self, other: &PyGame) -> bool {
        self.inner.fuzzy(&other.inner)
    }
    fn birthday(&self) -> u128 {
        self.inner.birthday()
    }
    fn is_number(&self) -> bool {
        self.inner.is_number()
    }
    /// The Nim-heap `⋆n` (the remote/far star of the atomic-weight calculus).
    #[staticmethod]
    fn star_n(n: u128) -> PyGame {
        PyGame {
            inner: Game::nim_heap(n),
        }
    }
    /// The Nim-heap `⋆n`, matching Rust's `Game::nim_heap` name.
    #[staticmethod]
    fn nim_heap(n: u128) -> PyGame {
        PyGame {
            inner: Game::nim_heap(n),
        }
    }
    /// Whether this game is **all-small** (a Left move iff a Right move at every
    /// position) — the domain of the atomic weight.
    fn is_all_small(&self) -> bool {
        self.inner.is_all_small()
    }
    /// The **atomic weight** as a `Game` (`None` if not all-small).
    fn atomic_weight(&self) -> Option<PyGame> {
        crate::games::atomic_weight(&self.inner).map(|inner| PyGame { inner })
    }
    /// The **atomic weight as an integer** (`None` if not all-small or its atomic
    /// weight is a genuine non-integer game). `aw(↑)=1`, `aw(⋆)=0`, `aw(⇑)=2`.
    fn atomic_weight_int(&self) -> Option<i128> {
        crate::games::atomic_weight_int(&self.inner)
    }
    fn times_int(&self, n: i128) -> PyGame {
        PyGame {
            inner: self.inner.times_int(n),
        }
    }
    /// The canonical form: the unique simplest game equal in value (dominated
    /// options removed, reversible options bypassed).
    fn canonical(&self) -> PyGame {
        PyGame {
            inner: self.inner.canonical(),
        }
    }
    /// Whether this game is already in canonical form.
    fn is_canonical(&self) -> bool {
        self.inner.is_canonical()
    }
    /// An order-independent canonical string `{L|R}` — equal iff the games are
    /// equal in value.
    fn canonical_string(&self) -> String {
        self.inner.canonical_string()
    }
    /// An order-independent structural string of the game tree as given; no
    /// canonicalization.
    fn structural_string(&self) -> String {
        self.inner.structural_string()
    }
    /// Structural equality of the game trees as given, without canonicalization.
    fn structural_eq(&self, other: &PyGame) -> bool {
        self.inner.structural_eq(&other.inner)
    }
    /// A readable structural form: `0` for `{|}`, else `{L|R}` recursively.
    fn display(&self) -> String {
        self.inner.display()
    }
    /// The surreal value of a number-valued game (`None` for non-numbers like
    /// `⋆`, `↑`, switches).
    fn number_value(&self) -> Option<PySurreal> {
        self.inner.number_value().map(PySurreal::from_inner)
    }
    /// The canonical game of a dyadic surreal (or int); errors for non-dyadics.
    #[staticmethod]
    fn from_surreal(s: &Bound<'_, PyAny>) -> PyResult<PyGame> {
        let s = parse_surreal(s)?;
        Game::from_surreal(&s)
            .map(|inner| PyGame { inner })
            .ok_or_else(|| PyValueError::new_err("surreal is not a dyadic rational"))
    }
    /// The ordinal sum `G : H` (play in `H`; a move in the base `G` discards `H`).
    fn ordinal_sum(&self, h: &PyGame) -> PyGame {
        PyGame {
            inner: self.inner.ordinal_sum(&h.inner),
        }
    }
    /// Temperature `t(G)` as a surreal (`−1` for a number); `None` for the rare
    /// degenerate positions outside temperature theory.
    fn temperature(&self) -> Option<PySurreal> {
        thermography::temperature(&self.inner).map(rat_to_py)
    }
    /// Mean (mast) value as a surreal.
    fn mean_value(&self) -> Option<PySurreal> {
        thermography::mean_value(&self.inner).map(rat_to_py)
    }
    /// Heat this game by the dyadic rational `num/den`; `None` if non-dyadic.
    #[pyo3(signature = (num, den=1))]
    fn heat(&self, num: i128, den: i128) -> PyResult<Option<PyGame>> {
        let t = Rational::try_new(num, den)
            .ok_or_else(|| PyValueError::new_err("zero denominator or bounded i128 overflow"))?;
        Ok(crate::games::heat(&self.inner, &t).map(|inner| PyGame { inner }))
    }
    /// Norton multiplication by a positive unit game; `None` if the unit is not
    /// strictly positive.
    fn norton_multiply(&self, unit: &PyGame) -> Option<PyGame> {
        crate::games::norton_multiply(&self.inner, &unit.inner).map(|inner| PyGame { inner })
    }
    /// Berlekamp overheating `int_s^t G`; `None` if `s` is not positive.
    fn overheat(&self, s: &PyGame, t: &PyGame) -> Option<PyGame> {
        crate::games::overheat(&self.inner, &s.inner, &t.inner).map(|inner| PyGame { inner })
    }
    /// Left stop `LS(G)` (left wall at temperature 0).
    fn left_stop(&self) -> Option<PySurreal> {
        thermography::left_stop(&self.inner).map(rat_to_py)
    }
    /// Right stop `RS(G)` (right wall at temperature 0).
    fn right_stop(&self) -> Option<PySurreal> {
        thermography::right_stop(&self.inner).map(rat_to_py)
    }
    /// The thermograph as a first-class exact object with `Pl` walls.
    fn thermograph(&self) -> Option<PyThermograph> {
        thermography::thermograph(&self.inner).map(wrap_thermograph)
    }
    /// The same thermograph, routed through the named tropical max-plus/min-plus
    /// wall folds and pinned equal to `thermograph` in the Rust tests.
    fn thermograph_via_tropical(&self) -> Option<PyThermograph> {
        crate::games::tropical_thermography::thermograph_via_tropical(&self.inner)
            .map(wrap_thermograph)
    }
    /// Cooled stops `(LS(G_t), RS(G_t))` at the rational temperature `num/den`.
    #[pyo3(signature = (num, den=1))]
    fn cooled_stops(&self, num: i128, den: i128) -> PyResult<Option<(PySurreal, PySurreal)>> {
        let t = Rational::try_new(num, den)
            .ok_or_else(|| PyValueError::new_err("zero denominator or bounded i128 overflow"))?;
        Ok(thermography::thermograph(&self.inner).map(|th| {
            let (l, r) = th.cooled_stops(&t);
            (rat_to_py(l), rat_to_py(r))
        }))
    }
    fn __repr__(&self) -> String {
        self.inner.display()
    }
}

fn color_name(c: Color) -> String {
    match c {
        Color::Blue => "blue",
        Color::Red => "red",
        Color::Green => "green",
    }
    .to_string()
}

#[pyclass(name = "Color", module = "ogdoad", from_py_object)]
#[derive(Clone)]
struct PyColor {
    inner: Color,
}

fn wrap_color(inner: Color) -> PyColor {
    PyColor { inner }
}

fn parse_color_obj(obj: &Bound<'_, PyAny>) -> PyResult<Color> {
    if let Ok(color) = obj.cast::<PyColor>() {
        return Ok(color.borrow().inner);
    }
    Err(PyTypeError::new_err("expected Color"))
}

#[pymethods]
impl PyColor {
    #[staticmethod]
    fn blue() -> Self {
        wrap_color(Color::Blue)
    }
    #[staticmethod]
    fn red() -> Self {
        wrap_color(Color::Red)
    }
    #[staticmethod]
    fn green() -> Self {
        wrap_color(Color::Green)
    }
    fn name(&self) -> String {
        color_name(self.inner)
    }
    fn __richcmp__(&self, other: &Bound<'_, PyAny>, op: CompareOp) -> PyResult<bool> {
        match op {
            CompareOp::Eq => Ok(parse_color_obj(other).is_ok_and(|c| c == self.inner)),
            CompareOp::Ne => Ok(parse_color_obj(other).is_ok_and(|c| c != self.inner)),
            CompareOp::Lt | CompareOp::Le | CompareOp::Gt | CompareOp::Ge => Err(
                PyValueError::new_err("Color only supports equality comparisons"),
            ),
        }
    }
    fn __str__(&self) -> String {
        self.name()
    }
    fn __repr__(&self) -> String {
        match self.inner {
            Color::Blue => "Color.Blue".to_string(),
            Color::Red => "Color.Red".to_string(),
            Color::Green => "Color.Green".to_string(),
        }
    }
}

#[pyclass(name = "Hackenbush", module = "ogdoad")]
struct PyHackenbush {
    inner: Hackenbush,
}

#[pymethods]
impl PyHackenbush {
    /// A position from `(u, v, Color)` edges; vertex `0` is the ground.
    #[new]
    fn new(edges: Vec<(usize, usize, PyColor)>) -> Self {
        let edges = edges.into_iter().map(|(u, v, c)| (u, v, c.inner)).collect();
        PyHackenbush {
            inner: Hackenbush::new(edges),
        }
    }
    /// A stalk `0—1—2—…` from the ground, edge `i` coloured `colors[i]`.
    #[staticmethod]
    fn string(colors: Vec<PyColor>) -> Self {
        let cs = colors.into_iter().map(|c| c.inner).collect::<Vec<_>>();
        PyHackenbush {
            inner: Hackenbush::string(&cs),
        }
    }
    /// The edges `(u, v, Color)` as typed Python `Color` values.
    fn edges(&self) -> Vec<(usize, usize, PyColor)> {
        self.inner
            .edges()
            .iter()
            .map(|&(u, v, c)| (u, v, wrap_color(c)))
            .collect()
    }
    /// The partizan game value (the universal evaluator).
    fn to_game(&self) -> PyGame {
        PyGame {
            inner: self.inner.to_game(),
        }
    }
    /// The surreal number value (`None` if the value is not a number).
    fn value(&self) -> Option<PySurreal> {
        self.inner.value().map(PySurreal::from_inner)
    }
    /// The Sprague–Grundy / nim value (`Some` only for all-green positions).
    fn grundy(&self) -> Option<u128> {
        self.inner.grundy()
    }
}

#[pyclass(name = "GameExterior", module = "ogdoad")]
struct PyGameExterior {
    inner: GameExterior,
    alg: Arc<CliffordAlgebra<Integer>>,
}

#[pymethods]
impl PyGameExterior {
    #[new]
    fn new(gens: Vec<PyGame>) -> Self {
        let games: Vec<Game> = gens.iter().map(|g| g.inner.clone()).collect();
        PyGameExterior::from_inner(GameExterior::new(games))
    }
    #[staticmethod]
    fn free(gens: Vec<PyGame>) -> Self {
        let games: Vec<Game> = gens.iter().map(|g| g.inner.clone()).collect();
        PyGameExterior::from_inner(GameExterior::free(games))
    }
    #[staticmethod]
    fn with_relation_bound(gens: Vec<PyGame>, bound: i128) -> Self {
        let games: Vec<Game> = gens.iter().map(|g| g.inner.clone()).collect();
        PyGameExterior::from_inner(GameExterior::with_relation_search(games, bound))
    }
    #[staticmethod]
    fn with_relation_search(gens: Vec<PyGame>, bound: i128) -> Self {
        Self::with_relation_bound(gens, bound)
    }
    #[staticmethod]
    fn with_relations(gens: Vec<PyGame>, relations: Vec<PyGameRelation>) -> Self {
        let games: Vec<Game> = gens.iter().map(|g| g.inner.clone()).collect();
        let relations = relations.into_iter().map(|rel| rel.inner).collect();
        PyGameExterior::from_inner(GameExterior::with_relations(games, relations))
    }
    #[getter]
    fn dim(&self) -> usize {
        self.inner.algebra().dim()
    }
    /// The underlying free Grassmann algebra before quotienting by game-group
    /// relations. Use `reduce`/`wedge`/`add` on `GameExterior` for quotient-aware
    /// operations.
    fn algebra(&self) -> IntegerAlgebra {
        IntegerAlgebra {
            inner: self.alg.clone(),
        }
    }
    fn relations(&self) -> Vec<PyGameRelation> {
        self.inner
            .relations()
            .iter()
            .cloned()
            .map(wrap_game_relation)
            .collect()
    }
    /// Whether the automatic bounded relation search exhausted its coefficient
    /// box. Explicit relations always report true.
    fn relation_search_complete(&self) -> bool {
        self.inner.relation_search_complete()
    }
    /// Full relation-search certificate as a named record.
    fn relation_search_certificate(&self) -> PyRelationSearchCertificate {
        wrap_relation_search_certificate(self.inner.relation_search_certificate().clone())
    }
    /// The grade-1 generator e_i (an `IntegerMV`) standing for game g_i.
    fn generator(&self, i: usize) -> IntegerMV {
        IntegerMV {
            alg: self.alg.clone(),
            mv: self.inner.generator(i),
        }
    }
    /// The game g_i a generator stands for.
    fn game(&self, i: usize) -> PyGame {
        PyGame {
            inner: self.inner.game(i).clone(),
        }
    }
    fn reduce(&self, mv: &IntegerMV) -> PyResult<IntegerMV> {
        self.ensure_mv(mv)?;
        Ok(IntegerMV {
            alg: self.alg.clone(),
            mv: self.inner.reduce(&mv.mv),
        })
    }
    fn add(&self, a: &IntegerMV, b: &IntegerMV) -> PyResult<IntegerMV> {
        self.ensure_mv(a)?;
        self.ensure_mv(b)?;
        Ok(IntegerMV {
            alg: self.alg.clone(),
            mv: self.inner.add(&a.mv, &b.mv),
        })
    }
    fn scalar_mul(&self, s: i128, mv: &IntegerMV) -> PyResult<IntegerMV> {
        self.ensure_mv(mv)?;
        Ok(IntegerMV {
            alg: self.alg.clone(),
            mv: self.inner.scalar_mul(s, &mv.mv),
        })
    }
    fn wedge(&self, a: &IntegerMV, b: &IntegerMV) -> PyResult<IntegerMV> {
        self.ensure_mv(a)?;
        self.ensure_mv(b)?;
        Ok(IntegerMV {
            alg: self.alg.clone(),
            mv: self.inner.wedge(&a.mv, &b.mv),
        })
    }
    fn is_zero(&self, mv: &IntegerMV) -> PyResult<bool> {
        self.ensure_mv(mv)?;
        Ok(self.inner.is_zero(&mv.mv))
    }
    /// Map a grade-1 element Σ c_i e_i back to the game Σ c_i·g_i (the module map
    /// Λ¹ → game group). Errors if the multivector is not purely grade 1.
    fn value_of_grade1(&self, mv: &IntegerMV) -> PyResult<PyGame> {
        self.ensure_mv(mv)?;
        let reduced = self.inner.reduce(&mv.mv);
        if reduced.terms.keys().any(|blade| blade.count_ones() != 1) {
            return Err(PyValueError::new_err("expected a grade-1 element"));
        }
        Ok(PyGame {
            inner: self.inner.value_of_grade1(&reduced),
        })
    }
}

impl PyGameExterior {
    fn from_inner(inner: GameExterior) -> Self {
        let alg = Arc::new(inner.algebra().clone());
        PyGameExterior { inner, alg }
    }

    fn ensure_mv(&self, mv: &IntegerMV) -> PyResult<()> {
        if self.alg.as_ref() == mv.alg.as_ref() {
            Ok(())
        } else {
            Err(PyValueError::new_err(
                "multivector belongs to a different GameExterior algebra",
            ))
        }
    }
}

#[pyclass(name = "GameClifford", module = "ogdoad")]
struct PyGameClifford {
    inner: GameClifford,
    alg: Arc<CliffordAlgebra<Integer>>,
}

#[pymethods]
impl PyGameClifford {
    #[new]
    #[pyo3(signature = (gens, q, b=None))]
    fn new(
        gens: Vec<PyGame>,
        q: Vec<i128>,
        b: Option<Vec<(usize, usize, i128)>>,
    ) -> PyResult<Self> {
        let games: Vec<Game> = gens.iter().map(|g| g.inner.clone()).collect();
        let b = parse_game_clifford_bilinear(b);
        GameClifford::new(games, q, b)
            .map(PyGameClifford::from_inner)
            .map_err(game_clifford_error)
    }
    #[staticmethod]
    #[pyo3(signature = (gens, q, b=None))]
    fn free(
        gens: Vec<PyGame>,
        q: Vec<i128>,
        b: Option<Vec<(usize, usize, i128)>>,
    ) -> PyResult<Self> {
        let games: Vec<Game> = gens.iter().map(|g| g.inner.clone()).collect();
        let b = parse_game_clifford_bilinear(b);
        GameClifford::free(games, q, b)
            .map(PyGameClifford::from_inner)
            .map_err(game_clifford_error)
    }
    #[staticmethod]
    #[pyo3(signature = (gens, bound, q, b=None))]
    fn with_relation_bound(
        gens: Vec<PyGame>,
        bound: i128,
        q: Vec<i128>,
        b: Option<Vec<(usize, usize, i128)>>,
    ) -> PyResult<Self> {
        let games: Vec<Game> = gens.iter().map(|g| g.inner.clone()).collect();
        let b = parse_game_clifford_bilinear(b);
        GameClifford::with_relation_search(games, bound, q, b)
            .map(PyGameClifford::from_inner)
            .map_err(game_clifford_error)
    }
    #[staticmethod]
    #[pyo3(signature = (gens, bound, q, b=None))]
    fn with_relation_search(
        gens: Vec<PyGame>,
        bound: i128,
        q: Vec<i128>,
        b: Option<Vec<(usize, usize, i128)>>,
    ) -> PyResult<Self> {
        Self::with_relation_bound(gens, bound, q, b)
    }
    #[staticmethod]
    #[pyo3(signature = (gens, relations, q, b=None))]
    fn with_quadratic_data(
        gens: Vec<PyGame>,
        relations: Vec<PyGameRelation>,
        q: Vec<i128>,
        b: Option<Vec<(usize, usize, i128)>>,
    ) -> PyResult<Self> {
        let games: Vec<Game> = gens.iter().map(|g| g.inner.clone()).collect();
        let relations = relations.into_iter().map(|rel| rel.inner).collect();
        let b = parse_game_clifford_bilinear(b);
        GameClifford::with_quadratic_data(games, relations, q, b)
            .map(PyGameClifford::from_inner)
            .map_err(game_clifford_error)
    }
    #[getter]
    fn dim(&self) -> usize {
        self.inner.algebra().dim()
    }
    /// The underlying free integer Clifford algebra before quotienting by
    /// checked game-group relations.
    fn algebra(&self) -> IntegerAlgebra {
        IntegerAlgebra {
            inner: self.alg.clone(),
        }
    }
    fn relations(&self) -> Vec<PyGameRelation> {
        self.inner
            .relations()
            .iter()
            .cloned()
            .map(wrap_game_relation)
            .collect()
    }
    /// Whether the automatic bounded relation search exhausted its coefficient
    /// box. Explicit relations always report true.
    fn relation_search_complete(&self) -> bool {
        self.inner.relation_search_complete()
    }
    /// Full relation-search certificate as a named record.
    fn relation_search_certificate(&self) -> PyRelationSearchCertificate {
        wrap_relation_search_certificate(self.inner.relation_search_certificate().clone())
    }
    /// The grade-1 generator e_i (an `IntegerMV`) standing for game g_i.
    fn generator(&self, i: usize) -> IntegerMV {
        IntegerMV {
            alg: self.alg.clone(),
            mv: self.inner.generator(i),
        }
    }
    /// The game g_i a generator stands for.
    fn game(&self, i: usize) -> PyGame {
        PyGame {
            inner: self.inner.game(i).clone(),
        }
    }
    fn reduce(&self, mv: &IntegerMV) -> PyResult<IntegerMV> {
        self.ensure_mv(mv)?;
        Ok(IntegerMV {
            alg: self.alg.clone(),
            mv: self.inner.reduce(&mv.mv),
        })
    }
    fn add(&self, a: &IntegerMV, b: &IntegerMV) -> PyResult<IntegerMV> {
        self.ensure_mv(a)?;
        self.ensure_mv(b)?;
        Ok(IntegerMV {
            alg: self.alg.clone(),
            mv: self.inner.add(&a.mv, &b.mv),
        })
    }
    fn scalar_mul(&self, s: i128, mv: &IntegerMV) -> PyResult<IntegerMV> {
        self.ensure_mv(mv)?;
        Ok(IntegerMV {
            alg: self.alg.clone(),
            mv: self.inner.scalar_mul(s, &mv.mv),
        })
    }
    fn mul(&self, a: &IntegerMV, b: &IntegerMV) -> PyResult<IntegerMV> {
        self.ensure_mv(a)?;
        self.ensure_mv(b)?;
        Ok(IntegerMV {
            alg: self.alg.clone(),
            mv: self.inner.mul(&a.mv, &b.mv),
        })
    }
    fn wedge(&self, a: &IntegerMV, b: &IntegerMV) -> PyResult<IntegerMV> {
        self.ensure_mv(a)?;
        self.ensure_mv(b)?;
        Ok(IntegerMV {
            alg: self.alg.clone(),
            mv: self.inner.wedge(&a.mv, &b.mv),
        })
    }
    fn is_zero(&self, mv: &IntegerMV) -> PyResult<bool> {
        self.ensure_mv(mv)?;
        Ok(self.inner.is_zero(&mv.mv))
    }
    /// Map a grade-1 element Σ c_i e_i back to the game Σ c_i·g_i. Errors if
    /// the reduced multivector is not purely grade 1.
    fn value_of_grade1(&self, mv: &IntegerMV) -> PyResult<PyGame> {
        self.ensure_mv(mv)?;
        let reduced = self.inner.reduce(&mv.mv);
        if reduced.terms.keys().any(|blade| blade.count_ones() != 1) {
            return Err(PyValueError::new_err("expected a grade-1 element"));
        }
        Ok(PyGame {
            inner: self.inner.value_of_grade1(&reduced),
        })
    }
}

impl PyGameClifford {
    fn from_inner(inner: GameClifford) -> Self {
        let alg = Arc::new(inner.algebra().clone());
        PyGameClifford { inner, alg }
    }

    fn ensure_mv(&self, mv: &IntegerMV) -> PyResult<()> {
        if self.alg.as_ref() == mv.alg.as_ref() {
            Ok(())
        } else {
            Err(PyValueError::new_err(
                "multivector belongs to a different GameClifford algebra",
            ))
        }
    }
}

fn parse_game_clifford_bilinear(
    b: Option<Vec<(usize, usize, i128)>>,
) -> BTreeMap<(usize, usize), i128> {
    b.unwrap_or_default()
        .into_iter()
        .map(|(i, j, value)| ((i, j), value))
        .collect()
}

fn game_clifford_error(err: crate::games::GameCliffordError) -> PyErr {
    PyValueError::new_err(err.to_string())
}

/// A transfinite **number-valued** game, carried by its surreal value (e.g. the
/// game `ω = {0,1,2,…|}`). The numbers-only honoring of transfinite birthdays —
/// value/birthday/sum/order all delegate to the surreal.
#[pyclass(name = "NumberGame", module = "ogdoad", from_py_object)]
#[derive(Clone)]
struct PyNumberGame {
    inner: NumberGame,
}

#[pymethods]
impl PyNumberGame {
    #[staticmethod]
    fn from_surreal(s: &Bound<'_, PyAny>) -> PyResult<PyNumberGame> {
        Ok(PyNumberGame {
            inner: NumberGame::from_surreal(&parse_surreal(s)?),
        })
    }
    /// The exact surreal value.
    fn value(&self) -> PySurreal {
        PySurreal::from_inner(self.inner.value().clone())
    }
    /// The birthday as a finite ordinal value, if finite.
    fn birthday_finite(&self) -> Option<u128> {
        self.inner.birthday().and_then(|o| o.as_finite())
    }
    /// The birthday as an `Ordinal`, matching Rust's `NumberGame::birthday` name.
    fn birthday(&self) -> Option<PyOrdinal> {
        self.inner.birthday().map(PyOrdinal::from_inner)
    }
    /// The birthday as an `Ordinal`, when the value is in the representable
    /// sign-expansion subclass.
    fn birthday_ordinal(&self) -> Option<PyOrdinal> {
        self.inner.birthday().map(PyOrdinal::from_inner)
    }
    /// The birthday as an ordinal string (`None` outside the representable
    /// subclass, e.g. `√ω`).
    fn birthday_repr(&self) -> Option<String> {
        self.inner.birthday().map(|o| format!("{o:?}"))
    }
    /// The transfinite sign expansion as runs `(sign, length)` (`True = +`,
    /// length an `Ordinal`), the finite encoding of the number-game tree.
    fn sign_expansion(&self) -> Option<Vec<(bool, PyOrdinal)>> {
        self.inner.sign_expansion().map(|se| {
            se.runs()
                .iter()
                .map(|(s, l)| (*s, PyOrdinal::from_inner(l.clone())))
                .collect()
        })
    }
    /// Reconstruct a number game from transfinite sign-expansion runs
    /// `(sign, length)`.
    #[staticmethod]
    fn from_sign_expansion(runs: Vec<(bool, PyOrdinal)>) -> Option<PyNumberGame> {
        let se = SignExpansion::from_runs(
            runs.into_iter()
                .map(|(sign, len)| (sign, len.as_ordinal().clone()))
                .collect(),
        );
        NumberGame::from_sign_expansion(&se).map(|inner| PyNumberGame { inner })
    }
    /// The short `Game`, if the value is dyadic; `None` for transfinite numbers.
    fn to_finite_game(&self) -> Option<PyGame> {
        self.inner.to_finite_game().map(|inner| PyGame { inner })
    }
    fn __add__(&self, other: &PyNumberGame) -> PyNumberGame {
        PyNumberGame {
            inner: self.inner.add(&other.inner),
        }
    }
    fn __neg__(&self) -> PyNumberGame {
        PyNumberGame {
            inner: self.inner.neg(),
        }
    }
    fn __richcmp__(&self, other: &PyNumberGame, op: CompareOp) -> bool {
        op.matches(self.inner.cmp(&other.inner))
    }
    fn __repr__(&self) -> String {
        format!("NumberGame({:?})", self.inner.value())
    }
}

/// A transfinite **nimber-valued** (impartial) game — the Nim heap `⋆α` (e.g.
/// `⋆ω`) — carried by its ordinal Grundy value. The char-2 mirror of `NumberGame`:
/// Grundy value / disjunctive sum (XOR) / Turning-Corners product all delegate to
/// the `Ordinal` (`On₂`) backend, completing the `No ↔ On₂` symmetry at the games
/// layer.
#[pyclass(name = "NimberGame", module = "ogdoad", from_py_object)]
#[derive(Clone)]
struct PyNimberGame {
    inner: NimberGame,
}

#[pymethods]
impl PyNimberGame {
    /// The transfinite Nim heap `⋆α` of a given ordinal Grundy value.
    #[staticmethod]
    fn from_ordinal(o: &PyOrdinal) -> PyNimberGame {
        PyNimberGame {
            inner: NimberGame::from_ordinal(o.as_ordinal()),
        }
    }
    /// The finite Nim heap `⋆n`.
    #[staticmethod]
    fn nim_heap(n: u128) -> PyNimberGame {
        PyNimberGame {
            inner: NimberGame::nim_heap(n),
        }
    }
    /// The exact Grundy value (a transfinite nimber). P-position ⟺ this is `0`.
    fn grundy(&self) -> PyOrdinal {
        PyOrdinal::from_inner(self.inner.grundy().clone())
    }
    /// The Grundy value as a finite nimber, if the heap is finite (`< ω`).
    fn grundy_finite(&self) -> Option<u128> {
        self.inner.grundy().as_finite()
    }
    /// The short `Game`, if the heap is finite; `None` for transfinite heaps.
    fn to_finite_game(&self) -> Option<PyGame> {
        self.inner.to_finite_game().map(|inner| PyGame { inner })
    }
    /// The **Turning-Corners product** (nim-multiplication); `None` only past the
    /// verified Kummer table or at `≥ ω^(ω^ω)`.
    fn turning_corners(&self, other: &PyNimberGame) -> Option<PyNimberGame> {
        self.inner
            .turning_corners(&other.inner)
            .map(|inner| PyNimberGame { inner })
    }
    fn __add__(&self, other: &PyNimberGame) -> PyNimberGame {
        PyNimberGame {
            inner: self.inner.add(&other.inner),
        }
    }
    fn __neg__(&self) -> PyNimberGame {
        PyNimberGame {
            inner: self.inner.neg(),
        }
    }
    fn __richcmp__(&self, other: &PyNimberGame, op: CompareOp) -> bool {
        op.matches(self.inner.cmp(&other.inner))
    }
    fn __repr__(&self) -> String {
        format!("NimberGame(⋆{:?})", self.inner.grundy())
    }
}

/// A bounded misère indistinguishability quotient: the elements (atom-multisets),
/// their class ids, the per-class representatives, and which classes are P.
#[pyclass(name = "Quotient", module = "ogdoad")]
struct PyQuotient {
    inner: Quotient,
}

#[pymethods]
impl PyQuotient {
    /// The enumerated elements (sorted atom-multisets, up to `elem_bound`).
    #[getter]
    fn elements(&self) -> Vec<Vec<usize>> {
        self.inner.elements.clone()
    }
    /// The test positions used to distinguish bounded quotient classes.
    #[getter]
    fn test_positions(&self) -> Vec<Vec<usize>> {
        self.inner.test_positions.clone()
    }
    /// Outcome signatures parallel to `elements`: True means N-position.
    #[getter]
    fn signatures(&self) -> Vec<Vec<bool>> {
        self.inner.signatures.clone()
    }
    /// The class id of each element (parallel to `elements`).
    #[getter]
    fn class_of(&self) -> Vec<usize> {
        self.inner.class_of.clone()
    }
    /// The number of distinct classes (the order of the bounded quotient monoid).
    #[getter]
    fn num_classes(&self) -> usize {
        self.inner.num_classes()
    }
    /// A representative multiset for each class.
    #[getter]
    fn class_rep(&self) -> Vec<Vec<usize>> {
        self.inner.class_rep.clone()
    }
    /// P-status of each class (`True` = a misère P-position / second-player win).
    #[getter]
    fn class_is_p(&self) -> Vec<bool> {
        self.inner.class_is_p.clone()
    }
    /// Class multiplication table, if represented at the current bounds.
    #[getter]
    fn multiplication(&self) -> Option<Vec<Vec<usize>>> {
        self.inner.multiplication.clone()
    }
    /// Whether every represented product agrees with the multiplication table.
    #[getter]
    fn multiplication_consistent(&self) -> bool {
        self.inner.multiplication_consistent
    }
    /// Whether the bounded element set is closed under disjunctive sum.
    #[getter]
    fn elements_closed_under_sum(&self) -> bool {
        self.inner.elements_closed_under_sum
    }
    /// Whether represented classes carry a complete sampled monoid table.
    #[getter]
    fn has_complete_bounded_monoid(&self) -> bool {
        self.inner.has_complete_bounded_monoid()
    }
    /// Product of quotient classes, if represented at the current bounds.
    fn class_product(&self, a: usize, b: usize) -> Option<usize> {
        self.inner.class_product(a, b)
    }
    /// Exact outcome signature for an enumerated element.
    fn signature_of_element(&self, element_index: usize) -> Option<Vec<bool>> {
        self.inner
            .signature_of_element(element_index)
            .map(<[bool]>::to_vec)
    }
    fn display(&self) -> String {
        self.inner.display()
    }
    fn __repr__(&self) -> String {
        self.inner.display()
    }
}

/// An abstract finite impartial game for misère analysis: position `0` is the
/// empty game (no moves); position `p` carries the option list `moves[p]` (each
/// option is a position index; `0` = move to empty).
#[pyclass(name = "AbstractGame", module = "ogdoad")]
struct PyAbstractGame {
    inner: AbstractGame,
}

#[pymethods]
impl PyAbstractGame {
    #[new]
    fn new(moves: Vec<Vec<usize>>) -> Self {
        PyAbstractGame {
            inner: AbstractGame { moves },
        }
    }
    /// Misère outcome of a disjunctive sum (a multiset of component positions):
    /// `True` = N (next player / first-player win), `False` = P.
    /// Raises `ValueError` if the move graph has a cycle (e.g. a position whose
    /// option list references itself or forms an indirect cycle).
    fn misere_outcome(&self, pos: Vec<usize>) -> PyResult<bool> {
        let mut memo = std::collections::HashMap::new();
        self.inner.misere_outcome(&pos, &mut memo).ok_or_else(|| {
            PyValueError::new_err("misere_outcome: move graph has a cycle — outcome is undefined")
        })
    }
    /// The bounded misère indistinguishability quotient over the generating
    /// `atoms` (elements are sums up to `elem_bound`, tests up to `test_bound`).
    /// Raises `ValueError` if the bounded search reaches a position whose move
    /// graph has a directed cycle.
    fn misere_quotient(
        &self,
        atoms: Vec<usize>,
        elem_bound: usize,
        test_bound: usize,
    ) -> PyResult<PyQuotient> {
        crate::games::misere_quotient(&self.inner, &atoms, elem_bound, test_bound)
            .map(|inner| PyQuotient { inner })
            .ok_or_else(|| {
                PyValueError::new_err("misere_quotient requires an acyclic bounded move graph")
            })
    }
}

/// Rust-name module-level wrapper for `games::misere_quotient`; Python passes
/// the `AbstractGame` value explicitly. Raises `ValueError` if the bounded
/// search reaches a position whose move graph has a directed cycle.
#[pyfunction]
fn misere_quotient(
    game: &PyAbstractGame,
    atoms: Vec<usize>,
    elem_bound: usize,
    test_bound: usize,
) -> PyResult<PyQuotient> {
    crate::games::misere_quotient(&game.inner, &atoms, elem_bound, test_bound)
        .map(|inner| PyQuotient { inner })
        .ok_or_else(|| {
            PyValueError::new_err("misere_quotient requires an acyclic bounded move graph")
        })
}

/// A named loopy value tag (`on`, `off`, `over`, `under`, `dud`, `tis`, `tisn`,
/// `±`, or an integer `s&t` onside/offside pair).
#[pyclass(name = "LoopyValue", module = "ogdoad", from_py_object)]
#[derive(Clone)]
struct PyLoopyValue {
    inner: LoopyValue,
}

#[pymethods]
impl PyLoopyValue {
    #[staticmethod]
    fn zero() -> Self {
        PyLoopyValue {
            inner: LoopyValue::Zero,
        }
    }
    #[staticmethod]
    fn star() -> Self {
        PyLoopyValue {
            inner: LoopyValue::Star,
        }
    }
    #[staticmethod]
    fn on() -> Self {
        PyLoopyValue {
            inner: LoopyValue::On,
        }
    }
    #[staticmethod]
    fn off() -> Self {
        PyLoopyValue {
            inner: LoopyValue::Off,
        }
    }
    #[staticmethod]
    fn over() -> Self {
        PyLoopyValue {
            inner: LoopyValue::Over,
        }
    }
    #[staticmethod]
    fn under() -> Self {
        PyLoopyValue {
            inner: LoopyValue::Under,
        }
    }
    #[staticmethod]
    fn plus_minus() -> Self {
        PyLoopyValue {
            inner: LoopyValue::PlusMinus,
        }
    }
    #[staticmethod]
    fn tis() -> Self {
        PyLoopyValue {
            inner: LoopyValue::Tis,
        }
    }
    #[staticmethod]
    fn tisn() -> Self {
        PyLoopyValue {
            inner: LoopyValue::Tisn,
        }
    }
    #[staticmethod]
    fn onside_offside(onside: i128, offside: i128) -> Self {
        PyLoopyValue {
            inner: LoopyValue::onside_offside(onside, offside),
        }
    }
    #[staticmethod]
    fn dud() -> Self {
        PyLoopyValue {
            inner: LoopyValue::Dud,
        }
    }
    fn name(&self) -> String {
        self.inner.name()
    }
    fn form(&self) -> String {
        self.inner.form()
    }
    fn outcome(&self) -> PyLoopyPartizanOutcome {
        wrap_loopy_partizan_outcome(self.inner.outcome())
    }
    fn partizan_outcome(&self) -> Option<PyPartizanOutcome> {
        self.inner.partizan_outcome().map(wrap_partizan_outcome)
    }
    fn sides(&self) -> Option<(i128, i128)> {
        self.inner.sides()
    }
    fn __neg__(&self) -> PyLoopyValue {
        PyLoopyValue {
            inner: self.inner.neg(),
        }
    }
    fn is_stopper(&self) -> bool {
        self.inner.is_stopper()
    }
    fn __add__(&self, other: &PyLoopyValue) -> Option<PyLoopyValue> {
        self.inner
            .add(&other.inner)
            .map(|inner| PyLoopyValue { inner })
    }
    fn __richcmp__(&self, other: &PyLoopyValue, op: CompareOp) -> bool {
        match op {
            CompareOp::Eq => self.inner == other.inner,
            CompareOp::Ne => self.inner != other.inner,
            CompareOp::Lt | CompareOp::Le | CompareOp::Gt | CompareOp::Ge => self
                .inner
                .partial_cmp(&other.inner)
                .is_some_and(|ordering| op.matches(ordering)),
        }
    }
    fn __repr__(&self) -> String {
        format!("LoopyValue({:?})", self.inner)
    }
}

#[pyclass(name = "LoopyGraph", module = "ogdoad")]
struct PyLoopyGraph {
    inner: LoopyGraph,
}

#[pymethods]
impl PyLoopyGraph {
    #[new]
    fn new(succ: Vec<Vec<usize>>) -> PyResult<Self> {
        check_succ_bounds(&succ)?;
        Ok(PyLoopyGraph {
            inner: LoopyGraph::new(succ),
        })
    }
    #[staticmethod]
    fn from_rule(n: usize, moves: Bound<'_, PyAny>) -> PyResult<Self> {
        Ok(PyLoopyGraph {
            inner: LoopyGraph::new(loopy_succ_from_callback(n, &moves)?),
        })
    }
    /// The adjacency lists.
    fn succ(&self) -> Vec<Vec<usize>> {
        self.inner.succ().to_vec()
    }
    /// Typed `Outcome` of every position.
    fn outcomes(&self) -> Vec<PyOutcome> {
        self.inner
            .outcomes()
            .into_iter()
            .map(wrap_outcome)
            .collect()
    }
    /// The Loss positions = P-positions (the player to move loses).
    fn loss_set(&self) -> Vec<usize> {
        self.inner.loss_set()
    }
    /// The Win positions = N-positions (the player to move wins).
    fn win_set(&self) -> Vec<usize> {
        self.inner.win_set()
    }
    /// The Draw positions — the loopy degree of freedom.
    fn draw_set(&self) -> Vec<usize> {
        self.inner.draw_set()
    }
    /// A coarse catalogue reading of position `v` via its impartial outcome:
    /// `LoopyValue.Zero` for a Loss, `LoopyValue.Dud` for a Draw, `None` for a Win (a nonzero loopy
    /// nimber — use `loopy_nim_values`).
    fn classify(&self, v: usize) -> Option<PyLoopyValue> {
        self.inner.classify(v).map(|inner| PyLoopyValue { inner })
    }
}

#[pyclass(name = "LoopyPartizanGraph", module = "ogdoad")]
struct PyLoopyPartizanGraph {
    inner: LoopyPartizanGraph,
}

#[pymethods]
impl PyLoopyPartizanGraph {
    #[new]
    fn new(left: Vec<Vec<usize>>, right: Vec<Vec<usize>>) -> PyResult<Self> {
        check_partizan_succ_bounds(&left, &right)?;
        Ok(PyLoopyPartizanGraph {
            inner: LoopyPartizanGraph::new(left, right)
                .expect("Python adjacency was checked immediately above"),
        })
    }
    #[staticmethod]
    fn from_rules(
        n: usize,
        left_moves: Bound<'_, PyAny>,
        right_moves: Bound<'_, PyAny>,
    ) -> PyResult<Self> {
        let left = loopy_succ_from_callback(n, &left_moves)?;
        let right = loopy_succ_from_callback(n, &right_moves)?;
        Ok(PyLoopyPartizanGraph {
            inner: LoopyPartizanGraph::new(left, right)
                .expect("callback adjacency uses the declared node range"),
        })
    }
    /// Left's adjacency lists.
    fn left(&self) -> Vec<Vec<usize>> {
        self.inner.left().to_vec()
    }
    /// Right's adjacency lists.
    fn right(&self) -> Vec<Vec<usize>> {
        self.inner.right().to_vec()
    }
    /// Exact two-sided outcomes of every position.
    fn outcomes(&self) -> Vec<PyLoopyPartizanOutcome> {
        self.inner
            .outcomes()
            .into_iter()
            .map(wrap_loopy_partizan_outcome)
            .collect()
    }
    /// Classical partizan classes where available; mixed draw/win cases are `None`.
    fn partizan_outcomes(&self) -> Vec<Option<PyPartizanOutcome>> {
        self.inner
            .partizan_outcomes()
            .into_iter()
            .map(|o| o.map(wrap_partizan_outcome))
            .collect()
    }
    /// The classical class of position `v`, if it has one.
    fn classify(&self, v: usize) -> Option<PyPartizanOutcome> {
        self.inner.classify(v).map(wrap_partizan_outcome)
    }
    /// Positions whose exact starter pair contains a draw.
    fn draw_set(&self) -> Vec<usize> {
        self.inner.draw_set()
    }
    /// Positions outside the classical five outcome classes.
    fn nonclassical_set(&self) -> Vec<usize> {
        self.inner.nonclassical_set()
    }
}

#[pyclass(name = "NimLexicode", module = "ogdoad", from_py_object)]
#[derive(Clone)]
struct PyNimLexicode {
    inner: NimLexicode,
}

#[pymethods]
impl PyNimLexicode {
    #[getter]
    fn base_exp(&self) -> usize {
        self.inner.base_exp()
    }
    #[getter]
    fn base(&self) -> u128 {
        self.inner.base()
    }
    fn len(&self) -> usize {
        self.inner.len()
    }
    fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }
    #[getter]
    fn min_distance(&self) -> usize {
        self.inner.min_distance()
    }
    fn word_count(&self) -> usize {
        self.inner.word_count()
    }
    fn packed_words(&self) -> Vec<u128> {
        self.inner.packed_words().to_vec()
    }
    fn words(&self) -> Vec<Vec<u128>> {
        self.inner.words()
    }
    fn f2_dimension(&self) -> Option<usize> {
        self.inner.f2_dimension()
    }
    fn is_closed_under_nim_add(&self) -> bool {
        self.inner.is_closed_under_nim_add()
    }
    fn is_closed_under_nim_scalars(&self) -> bool {
        self.inner.is_closed_under_nim_scalars()
    }
    fn has_nim_field_base(&self) -> bool {
        self.inner.has_nim_field_base()
    }
    fn __repr__(&self) -> String {
        format!(
            "NimLexicode(base_exp={}, len={}, min_distance={}, word_count={})",
            self.inner.base_exp(),
            self.inner.len(),
            self.inner.min_distance(),
            self.inner.word_count()
        )
    }
}

#[pyfunction]
fn lexicode(n: usize, d: usize) -> Option<PyBinaryCode> {
    crate::games::lexicode(n, d).map(wrap_binary_code)
}

#[pyfunction]
fn lexicode_naive(n: usize, d: usize) -> Option<PyBinaryCode> {
    crate::games::lexicode_naive(n, d).map(wrap_binary_code)
}

#[pyfunction]
fn lexicode_bounded(n: usize, d: usize, node_budget: u128) -> Option<PyBinaryCode> {
    crate::games::lexicode_bounded(n, d, node_budget).map(wrap_binary_code)
}

#[pyfunction]
fn nim_lexicode_naive(base_exp: usize, n: usize, d: usize) -> Option<PyNimLexicode> {
    crate::games::nim_lexicode_naive(base_exp, n, d).map(|inner| PyNimLexicode { inner })
}

#[pyfunction]
fn nim_lexicode_naive_bounded(
    base_exp: usize,
    n: usize,
    d: usize,
    node_budget: u128,
) -> Option<PyNimLexicode> {
    crate::games::nim_lexicode_naive_bounded(base_exp, n, d, node_budget)
        .map(|inner| PyNimLexicode { inner })
}

pub(crate) fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_class::<PyGame>()?;
    m.add_class::<PyOutcome>()?;
    m.add_class::<PyPartizanOutcome>()?;
    m.add_class::<PyLoopyWinner>()?;
    m.add_class::<PyLoopyPartizanOutcome>()?;
    m.add_class::<PyLoopyNimber>()?;
    m.add_class::<PyColor>()?;
    m.add_class::<PyPl>()?;
    m.add_class::<PyThermograph>()?;
    m.add_class::<PyNumberGame>()?;
    m.add_class::<PyNimberGame>()?;
    m.add_class::<PyGameExterior>()?;
    m.add_class::<PyGameClifford>()?;
    m.add_class::<PyGameRelation>()?;
    m.add_class::<PyGameRelationCertificate>()?;
    m.add_class::<PyRelationSearchCertificate>()?;
    m.add_class::<PyScoreInterval>()?;
    m.add_class::<PyHackenbush>()?;
    m.add_class::<PyQuotient>()?;
    m.add_class::<PyAbstractGame>()?;
    m.add_class::<PyLoopyValue>()?;
    m.add_class::<PyLoopyGraph>()?;
    m.add_class::<PyLoopyPartizanGraph>()?;
    m.add_class::<PyLoopyNimCertificate>()?;
    m.add_class::<PyNimLexicode>()?;
    m.add("LEXICODE_NODE_BUDGET", crate::games::LEXICODE_NODE_BUDGET)?;
    m.add(
        "NIM_LEXICODE_NODE_BUDGET",
        crate::games::NIM_LEXICODE_NODE_BUDGET,
    )?;
    m.add_function(wrap_pyfunction!(nim_mul_mex, m)?)?;
    m.add_function(wrap_pyfunction!(lexicode, m)?)?;
    m.add_function(wrap_pyfunction!(lexicode_naive, m)?)?;
    m.add_function(wrap_pyfunction!(lexicode_bounded, m)?)?;
    m.add_function(wrap_pyfunction!(nim_lexicode_naive, m)?)?;
    m.add_function(wrap_pyfunction!(nim_lexicode_naive_bounded, m)?)?;
    m.add_function(wrap_pyfunction!(coin_companions, m)?)?;
    m.add_function(wrap_pyfunction!(singleton_companions, m)?)?;
    m.add_function(wrap_pyfunction!(turtles_companions, m)?)?;
    m.add_function(wrap_pyfunction!(grundy_1d, m)?)?;
    m.add_function(wrap_pyfunction!(coin_turning_grundy, m)?)?;
    m.add_function(wrap_pyfunction!(coin_turning_tartan_grundy, m)?)?;
    m.add_function(wrap_pyfunction!(tartan_grundy, m)?)?;
    m.add_function(wrap_pyfunction!(grundy, m)?)?;
    m.add_function(wrap_pyfunction!(grundy_graph, m)?)?;
    m.add_function(wrap_pyfunction!(mex, m)?)?;
    m.add_function(wrap_pyfunction!(outcomes, m)?)?;
    m.add_function(wrap_pyfunction!(p_positions, m)?)?;
    m.add_function(wrap_pyfunction!(scoring_values, m)?)?;
    m.add_function(wrap_pyfunction!(nim_canonical, m)?)?;
    m.add_function(wrap_pyfunction!(misere_nim_p_predicted, m)?)?;
    m.add_function(wrap_pyfunction!(try_misere_is_n, m)?)?;
    m.add_function(wrap_pyfunction!(misere_is_n, m)?)?;
    m.add_function(wrap_pyfunction!(misere_is_p, m)?)?;
    m.add_function(wrap_pyfunction!(nim_moves, m)?)?;
    m.add_function(wrap_pyfunction!(octal_moves, m)?)?;
    m.add_function(wrap_pyfunction!(octal_misere_quotient, m)?)?;
    m.add_function(wrap_pyfunction!(misere_quotient, m)?)?;
    m.add_function(wrap_pyfunction!(loopy_nim_values, m)?)?;
    m.add_function(wrap_pyfunction!(loopy_decision_sets, m)?)?;
    m.add_function(wrap_pyfunction!(loopy_quadric_probe, m)?)?;
    m.add_function(wrap_pyfunction!(loopy_nim_values_certified, m)?)?;
    m.add_function(wrap_pyfunction!(thermograph, m)?)?;
    m.add_function(wrap_pyfunction!(thermograph_via_tropical, m)?)?;
    m.add_function(wrap_pyfunction!(temperature, m)?)?;
    m.add_function(wrap_pyfunction!(mean_value, m)?)?;
    m.add_function(wrap_pyfunction!(heat, m)?)?;
    m.add_function(wrap_pyfunction!(norton_multiply, m)?)?;
    m.add_function(wrap_pyfunction!(overheat, m)?)?;
    m.add_function(wrap_pyfunction!(left_stop, m)?)?;
    m.add_function(wrap_pyfunction!(right_stop, m)?)?;
    m.add_function(wrap_pyfunction!(atomic_weight, m)?)?;
    m.add_function(wrap_pyfunction!(atomic_weight_int, m)?)?;
    Ok(())
}