native-solver 0.2.0

Heads-up postflop No-Limit Hold'em solver: hand evaluator, ranges, betting trees, and combo-vectorized CFR / CFR+ / DCFR.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
//! Combo-vectorized CFR: instead of recursing per fixed hand pair (as the
//! Kuhn poker trainer does), each information set holds one regret/
//! strategy row **per combo** in the acting player's range
//! (`[action][combo]`), and terminal values are computed as a weighted
//! sum over the opponent's live (non-card-conflicting) combos. This is
//! the standard technique real postflop solvers use to solve a whole
//! range at once instead of one hand match-up at a time.
//!
//! `Chance` nodes (dealt community cards) are handled the same way: each
//! candidate card is equally likely conditional on a legal private deal.
//! Both players' hole cards are excluded: hero conflicts are masked while
//! aggregating branches and opponent conflicts are masked at terminals.
//! Every compatible private deal therefore has `N - 4` possible next
//! cards among the N cards not yet on the board, so raw counterfactual
//! values divide by `N - 4`, not by an own-hand-only conditional count.
//!
//! Sibling subtrees (a decision node's actions, a chance node's dealt
//! cards) are independent recursions given the strategy at this node, so
//! large ones are evaluated in parallel with `rayon`; small ones run
//! sequentially in one scratch buffer (see the `engine` module). Each
//! decision node's regret/strategy tables live behind a `Mutex` to make
//! that safe. It is never contended: one traversal reaches a node once.

use super::discount::{IterationUpdate, SolverAlgorithm, UpdateSchedule};
use super::terminal::{BoardOrder, TerminalIndex};
use super::tree::{validate_board, BoardError, Node, Player, Terminal};
#[cfg(test)]
use crate::card::CardSet;
use crate::card::{bit, mask_has, mask_of, Card};
use crate::eval::score_7;
use crate::range::Combo;
use rayon::prelude::*;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};

mod engine;
mod reach_scratch;

/// Per player: the groups of bucket indices one board's suit symmetries make
/// interchangeable.
type SuitGroups = [Vec<Vec<usize>>; 2];

struct NodeData {
    regret_sum: Vec<Vec<f64>>,
    strategy_sum: Vec<Vec<f64>>,
}

impl NodeData {
    fn empty() -> Self {
        Self {
            regret_sum: Vec::new(),
            strategy_sum: Vec::new(),
        }
    }

    fn sized(num_actions: usize, num_combos: usize) -> Self {
        Self {
            regret_sum: vec![vec![0.0; num_combos]; num_actions],
            strategy_sum: vec![vec![0.0; num_combos]; num_actions],
        }
    }
}

/// Which player learns, and which CFV vectors are needed by this traversal.
/// A missing vector stays empty; reaches remain available for own-reach
/// averaging and bucket weights even when only one player's CFV is returned.
#[derive(Clone, Copy)]
struct TrainingPass {
    update: IterationUpdate,
    updating: Option<usize>,
    values: u8,
}

impl TrainingPass {
    fn computes(self, player: usize) -> bool {
        self.values & (1 << player) != 0
    }
}

/// Trains a strategy for one game with counterfactual regret minimization.
///
/// A trainer owns the regret and strategy tables. The game itself
/// ([`SolverGame`]) is immutable and shared through [`Trainer::game`], so a
/// [`Policy`] snapshot can be read while training continues.
///
/// # Examples
///
/// ```
/// use native_solver::{build_tree, Card, CardSet, Chips, GameConfig, Player, Range, Trainer, TrainerOptions};
///
/// let board = ["Ks", "Th", "7s", "4d", "2s"]
///     .iter()
///     .map(|card| card.parse())
///     .collect::<Result<Vec<Card>, _>>()?;
/// let dead = CardSet::from_cards(&board);
/// let oop = "AA,KQs".parse::<Range>()?.combos(dead);
/// let ip = "QQ,JJ".parse::<Range>()?.combos(dead);
/// let config = GameConfig::new(board, Chips::whole(100), Chips::whole(100)).with_bet_sizes([1.0]);
///
/// let mut trainer = Trainer::new(build_tree(&config)?, [oop, ip], TrainerOptions::default())?;
/// trainer.train(200);
/// assert_eq!(trainer.iterations_completed(), 200);
///
/// // Node 0 is OOP's first decision: one row per action, one column per OOP combo.
/// let strategy = trainer.average_strategy(0);
/// assert_eq!(strategy[0].len(), trainer.game().combos(Player::Oop).len());
///
/// // How much a best response could still gain, in chips.
/// assert!(trainer.exploitability().total < 1.0);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub struct Trainer {
    game: Arc<SolverGame>,
    algorithm: SolverAlgorithm,
    update_schedule: UpdateSchedule,
    /// Full iterations completed across every call to `train`.
    iterations_completed: u64,
    node_data: Vec<Mutex<NodeData>>,
}

/// A snapshot of the average strategy at every decision node.
///
/// Take one with [`Trainer::policy`]; it does not change as training continues.
/// Pass it to [`SolverGame`]'s read methods. The probabilities are normalized,
/// suit-symmetrized, and stored per bucket as `[node][action][bucket]`
/// ([`Policy::rows`]), so a policy can be saved and later restored with
/// [`SolverGame::policy_from_rows`].
///
/// # Examples
///
/// ```
/// # use native_solver::*;
/// # let board = ["Ks", "Th", "7s", "4d", "2s"].iter().map(|c| c.parse()).collect::<Result<Vec<Card>, _>>()?;
/// # let dead = CardSet::from_cards(&board);
/// # let config = GameConfig::new(board, Chips::whole(100), Chips::whole(100)).with_bet_sizes([1.0]);
/// # let ranges = ["AA,KQs", "QQ,JJ"].map(|r| r.parse::<Range>().unwrap().combos(dead));
/// # let mut trainer = Trainer::new(build_tree(&config)?, ranges, TrainerOptions::default())?;
/// trainer.train(100);
/// let policy = trainer.policy();
/// let saved: Vec<Vec<Vec<f64>>> = policy.rows().to_vec();
///
/// // More training does not change the snapshot.
/// trainer.train(100);
/// let restored = trainer.game().policy_from_rows(saved)?;
/// assert_eq!(restored, policy);
/// let exploitability = trainer.game().exploitability(&restored).total;
/// assert!(exploitability.is_finite());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct Policy {
    rows: Vec<Vec<Vec<f64>>>,
}

impl Policy {
    /// `[node][action][bucket]` probabilities, e.g. for persisting a snapshot.
    pub fn rows(&self) -> &[Vec<Vec<f64>>] {
        &self.rows
    }
}

/// Why persisted policy rows do not fit a game (see [`SolverGame::policy_from_rows`]).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum PolicyError {
    /// The policy has a different number of decision nodes than the game.
    NodeCount {
        /// Decision nodes in the policy.
        policy: usize,
        /// Decision nodes in the game.
        game: usize,
    },
    /// A node's action or bucket count differs from the game's.
    Shape {
        /// The first mismatched decision node id.
        node: usize,
    },
    /// A bucket's probabilities are not finite, nonnegative, and summing to 1.
    NotDistribution {
        /// The first invalid decision node id.
        node: usize,
    },
    /// Suit-equivalent buckets have different probabilities.
    NotSymmetric {
        /// The first asymmetric decision node id.
        node: usize,
    },
}

impl std::fmt::Display for PolicyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NodeCount { policy, game } => {
                write!(f, "policy has {policy} nodes, game has {game}")
            }
            Self::Shape { node } => write!(f, "policy shape does not match node {node}"),
            Self::NotDistribution { node } => {
                write!(f, "policy at node {node} is not a probability distribution")
            }
            Self::NotSymmetric { node } => write!(f, "policy at node {node} is not suit-symmetric"),
        }
    }
}

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

/// Why [`Trainer::new`] rejected its inputs.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum TrainerError {
    /// The tree's board is not a legal flop, turn, or river.
    Board(BoardError),
    /// The tree's nodes do not continue from its board: they reach a
    /// showdown before the river, or deal a card past the river.
    TreeBoardMismatch,
    /// The tree is malformed: decision ids are not exactly
    /// `0..num_decision_nodes`, actions and children differ in length, a
    /// chance node does not deal every undealt card exactly once or groups
    /// cards that are not suit swaps of each other, or a terminal investment
    /// is negative or not finite.
    InvalidTree {
        /// What was wrong.
        reason: &'static str,
    },
    /// A player's range has no combo with positive weight.
    EmptyRange {
        /// The player whose range is empty.
        player: Player,
    },
    /// A combo holds the same card twice.
    InvalidCombo {
        /// The player whose range holds the combo.
        player: Player,
        /// The combo's index in that player's range.
        index: usize,
    },
    /// A combo appears more than once in the same range.
    DuplicateCombo {
        /// The player whose range holds the combo.
        player: Player,
        /// The index of the second occurrence.
        index: usize,
    },
    /// A combo uses a card that is already on the initial board.
    ///
    /// Pass the board as dead cards to [`Range::combos`](crate::Range::combos).
    ComboConflictsWithBoard {
        /// The player whose range holds the combo.
        player: Player,
        /// The combo's index in that player's range.
        index: usize,
    },
    /// A combo weight is negative or not finite.
    InvalidWeight {
        /// The player whose range holds the combo.
        player: Player,
        /// The combo's index in that player's range.
        index: usize,
    },
    /// Every pair of positive-weight combos shares a card, so no deal is
    /// possible and every value would be undefined.
    NoCompatibleDeals,
    /// A [`CardAbstraction`] street asks for zero buckets.
    ZeroBuckets,
    /// A range is not closed under the initial board's free-suit swaps.
    ///
    /// This is required when the tree groups chance cards by suit isomorphism
    /// (with equal weights for swapped combos) or when flop or turn buckets are
    /// on.
    AsymmetricRange {
        /// The player whose range is asymmetric.
        player: Player,
    },
}

impl std::fmt::Display for TrainerError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Board(error) => write!(f, "invalid initial board: {error}"),
            Self::TreeBoardMismatch => write!(f, "tree does not match the initial board"),
            Self::InvalidTree { reason } => write!(f, "invalid tree: {reason}"),
            Self::EmptyRange { player } => {
                write!(f, "{player:?} range has no combo with positive weight")
            }
            Self::InvalidCombo { player, index } => {
                write!(f, "{player:?} combo {index} must hold two distinct cards")
            }
            Self::DuplicateCombo { player, index } => {
                write!(f, "{player:?} combo {index} repeats an earlier combo")
            }
            Self::ComboConflictsWithBoard { player, index } => write!(
                f,
                "{player:?} combo {index} uses a card on the initial board"
            ),
            Self::InvalidWeight { player, index } => write!(
                f,
                "{player:?} combo {index} weight must be finite and nonnegative"
            ),
            Self::NoCompatibleDeals => {
                write!(f, "no pair of positive-weight combos can be dealt together")
            }
            Self::ZeroBuckets => write!(f, "card abstraction bucket counts must be positive"),
            Self::AsymmetricRange { player } => write!(
                f,
                "{player:?} range must be suit-symmetric for suit isomorphism or flop/turn buckets"
            ),
        }
    }
}

impl std::error::Error for TrainerError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Board(error) => Some(error),
            _ => None,
        }
    }
}

impl From<BoardError> for TrainerError {
    fn from(error: BoardError) -> Self {
        Self::Board(error)
    }
}

/// Rejects inputs that [`Trainer`] cannot solve as a legal game.
fn validate_trainer_inputs(
    tree: &super::tree::Tree,
    combos: &[Vec<Combo>; 2],
    abstraction: CardAbstraction,
) -> Result<(), TrainerError> {
    let initial_board = tree.board.as_slice();
    validate_board(initial_board)?;
    let mut seen_ids = vec![false; tree.num_decision_nodes];
    validate_tree(&tree.root, &mut initial_board.to_vec(), &mut seen_ids)?;
    if seen_ids.iter().any(|&seen| !seen) {
        return Err(TrainerError::InvalidTree {
            reason: "decision ids must cover 0..num_decision_nodes",
        });
    }

    let board = mask_of(initial_board);
    let mut masks = [Vec::new(), Vec::new()];
    for (p, player) in [Player::Oop, Player::Ip].into_iter().enumerate() {
        let mut seen = std::collections::HashSet::new();
        for (index, combo) in combos[p].iter().enumerate() {
            let [a, b] = combo.cards;
            if a == b {
                return Err(TrainerError::InvalidCombo { player, index });
            }
            if !combo.weight.is_finite() || combo.weight < 0.0 {
                return Err(TrainerError::InvalidWeight { player, index });
            }
            if !seen.insert(normalize_pair(a, b)) {
                return Err(TrainerError::DuplicateCombo { player, index });
            }
            if combo.bits() & board != 0 {
                return Err(TrainerError::ComboConflictsWithBoard { player, index });
            }
            if combo.weight > 0.0 {
                masks[p].push(combo.bits());
            }
        }
        if masks[p].is_empty() {
            return Err(TrainerError::EmptyRange { player });
        }
    }
    if !masks[0]
        .iter()
        .any(|&oop| masks[1].iter().any(|&ip| oop & ip == 0))
    {
        return Err(TrainerError::NoCompatibleDeals);
    }

    if [abstraction.flop, abstraction.turn, abstraction.river].contains(&Some(0)) {
        return Err(TrainerError::ZeroBuckets);
    }
    // Suit-reduced trees derive non-representative runouts by relabeling, so
    // swapped combos must exist with equal weights. Flop and turn buckets
    // average scores over suit-grouped runouts (`avg_score`), which only needs
    // the swapped combos to exist. Later boards only remove free suits, so
    // the initial board's free-suit swaps cover every reachable board.
    let reduced = has_suit_reduction(&tree.root);
    let averaged_buckets = (abstraction.flop.is_some() && initial_board.len() == 3)
        || (abstraction.turn.is_some() && initial_board.len() <= 4);
    if reduced || averaged_buckets {
        let free: Vec<u8> = (0..4)
            .filter(|&s| !initial_board.iter().any(|&c| c.suit() == s))
            .collect();
        for (p, player) in [Player::Oop, Player::Ip].into_iter().enumerate() {
            let weights: HashMap<(Card, Card), f64> = combos[p]
                .iter()
                .map(|combo| (normalize_pair(combo.cards[0], combo.cards[1]), combo.weight))
                .collect();
            for (i, &sa) in free.iter().enumerate() {
                for &sb in &free[i + 1..] {
                    for combo in &combos[p] {
                        let [a, b] = combo.cards;
                        let swapped = normalize_pair(swap_suit(a, sa, sb), swap_suit(b, sa, sb));
                        let symmetric = match weights.get(&swapped) {
                            Some(&weight) => !reduced || weight == combo.weight,
                            None => false,
                        };
                        if !symmetric {
                            return Err(TrainerError::AsymmetricRange { player });
                        }
                    }
                }
            }
        }
    }
    Ok(())
}

/// Checks the structure [`Trainer`] relies on while walking `node` from `board`.
fn validate_tree(
    node: &Node,
    board: &mut Vec<Card>,
    seen_ids: &mut [bool],
) -> Result<(), TrainerError> {
    let invalid = |reason| Err(TrainerError::InvalidTree { reason });
    match node {
        Node::Decision {
            id,
            actions,
            children,
            ..
        } => {
            match seen_ids.get_mut(*id) {
                Some(seen) if !*seen => *seen = true,
                Some(_) => return invalid("decision ids must be unique"),
                None => return invalid("decision ids must be below num_decision_nodes"),
            }
            if actions.is_empty() || actions.len() != children.len() {
                return invalid("decisions need matching nonempty actions and children");
            }
            for child in children {
                validate_tree(child, board, seen_ids)?;
            }
        }
        Node::Chance { children } => {
            if board.len() >= 5 {
                return Err(TrainerError::TreeBoardMismatch);
            }
            let mut dealt = mask_of(board);
            let mut count = 0;
            for (members, _) in children {
                if members.is_empty() {
                    return invalid("chance classes must not be empty");
                }
                for &card in members {
                    if mask_has(dealt, card) {
                        return invalid("chance nodes must deal each undealt card exactly once");
                    }
                    dealt |= bit(card);
                    count += 1;
                }
                // Grouped cards are derived from `members[0]` by swapping two
                // suits, which is only a symmetry when both suits are off the
                // board and the ranks match.
                if members.len() > 1
                    && members.iter().any(|&card| {
                        card.rank() != members[0].rank()
                            || board.iter().any(|&b| b.suit() == card.suit())
                    })
                {
                    return invalid(
                        "chance classes must group one rank in suits absent from the board",
                    );
                }
            }
            if count != 52 - board.len() {
                return invalid("chance nodes must deal each undealt card exactly once");
            }
            for (members, child) in children {
                board.push(members[0]);
                let result = validate_tree(child, board, seen_ids);
                board.pop();
                result?;
            }
        }
        Node::Terminal(terminal) => {
            let invested = match terminal {
                Terminal::Fold { invested, .. } => invested,
                Terminal::Showdown { invested } => {
                    if board.len() != 5 {
                        return Err(TrainerError::TreeBoardMismatch);
                    }
                    invested
                }
            };
            if invested.iter().any(|x| !x.is_finite() || *x < 0.0) {
                return invalid("terminal investments must be finite and nonnegative");
            }
        }
    }
    Ok(())
}

/// Everything about a solve that training does not change.
///
/// It holds the tree, the ranges, board caches, card abstraction, and
/// suit-symmetry groups. Its read methods (`evaluate`, `exploitability`,
/// `average_strategy`) take a [`Policy`], so they can run while a [`Trainer`]
/// keeps training. Get one from [`Trainer::game`].
pub struct SolverGame {
    tree: super::tree::Tree,
    initial_board: Vec<Card>,
    combos: [Vec<Combo>; 2],
    /// [`evaluate_7`](crate::evaluate_7) scores for every complete (5-card) board reachable via
    /// a `Chance` node, precomputed once so `train()` doesn't recompute
    /// hand strengths for the same board on every iteration.
    board_eval_cache: HashMap<Vec<Card>, Arc<[Vec<u32>; 2]>>,
    /// Per player: `(min(card1,card2), max(card1,card2))` -> index into
    /// `combos[player]`. Used by `chance_value`'s suit-isomorphism
    /// relabeling to look up which combo a suit-swapped combo corresponds
    /// to, without a linear scan.
    combo_index: [HashMap<(Card, Card), usize>; 2],
    /// Linear-time card-removal kernels and immutable per-board rank orders.
    terminal_index: TerminalIndex,
    board_order_cache: HashMap<Vec<Card>, Arc<BoardOrder>>,
    /// Per-street card abstraction setting this trainer was built with —
    /// see [`CardAbstraction`] and the module doc comment's "card
    /// abstraction" section. `CardAbstraction::default()` never buckets.
    abstraction: CardAbstraction,
    /// Per board (any length reachable by a Decision node — flop/turn use
    /// `avg_score`, river uses the real [`evaluate_7`](crate::evaluate_7) score), per player:
    /// combo index -> bucket index. Only populated for streets
    /// `abstraction` actually buckets.
    bucket_maps: HashMap<Vec<Card>, Arc<[Vec<usize>; 2]>>,
    /// Per player: `0..combos[player].len()`, the fallback "every combo is
    /// its own bucket" mapping used at any node not covered by
    /// `bucket_maps` (a street `abstraction` leaves unbucketed).
    identity_buckets: [Vec<usize>; 2],
    /// Exact board-stabilizing suit orbits in bucket coordinates. Only reduced
    /// trees need this: roundoff must not turn interchangeable hands into
    /// different policies and invalidate representative-only chance traversal.
    suit_groups: HashMap<Vec<Card>, Arc<SuitGroups>>,
    /// Per decision node id: `(acting player index, board at that node)`,
    /// recorded once during `init_node_data` — `average_strategy` needs
    /// this to look up the node's bucket map and expand bucket-level
    /// probabilities back out to the per-combo output the API contract
    /// promises.
    node_meta: Vec<(usize, Vec<Card>)>,
    /// The tree compiled for the training traversal.
    plan: engine::Plan,
    #[cfg(test)]
    use_pairwise_terminals: std::sync::atomic::AtomicBool,
    #[cfg(test)]
    terminal_calls: [std::sync::atomic::AtomicUsize; 2],
}

/// How a [`Trainer`] learns: the update rule, the update order, and card abstraction.
///
/// The default is DCFR with simultaneous updates and every street solved
/// exactly.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct TrainerOptions {
    /// The regret and strategy-averaging rule.
    pub algorithm: SolverAlgorithm,
    /// Whether both players update together or in alternation.
    pub schedule: UpdateSchedule,
    /// Which streets are bucketed, and into how many buckets.
    pub abstraction: CardAbstraction,
}

/// Which streets let hands of similar strength share one strategy (bucketing).
///
/// `Some(n)` groups each player's combos on that street into at most `n`
/// percentile buckets of hand strength that share a strategy. Tied strengths
/// stay in one bucket, so there can be fewer than `n`. `None` solves the street
/// exactly, and the default (all `None`) never buckets. Flop and turn buckets
/// use the mean river strength over the remaining runouts; river buckets use
/// the exact strength.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct CardAbstraction {
    /// Bucket count for decisions on a 3-card board.
    pub flop: Option<usize>,
    /// Bucket count for decisions on a 4-card board.
    pub turn: Option<usize>,
    /// Bucket count for decisions on a 5-card board.
    pub river: Option<usize>,
}

/// [`SolverGame::evaluate`]'s result: per-node values under a policy.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Evaluation {
    /// One entry per decision node, indexed by node id.
    pub nodes: Vec<NodeEvaluation>,
    /// Root `[OOP, IP]` raw range-weighted values, not EVs.
    ///
    /// They are zero-sum like [`Trainer::train`]'s return, but under the evaluated
    /// policy. See [the conventions](crate::conventions) for the
    /// normalization.
    pub root_values: [f64; 2],
}

/// Values at one decision node under a policy, per combo of the acting player.
///
/// Combos are in the acting player's range order. Equity is only reported on a
/// complete five-card board, where it is exact.
#[derive(Debug, Clone, PartialEq)]
pub struct NodeEvaluation {
    /// Each combo's EV from this node on, in input chips.
    ///
    /// It is the raw counterfactual value divided by the opponent's compatible
    /// reach (`0.0` when no opponent combo is compatible). Payoffs count half the
    /// initial pot as each player's own investment, as in [`Terminal`]. This is the
    /// value of the whole node under the policy, not of any single action.
    pub ev: Vec<f64>,
    /// Each combo's showdown win probability; `Some` only on a complete board.
    ///
    /// Ties count half. The probability is against the opponent's compatible,
    /// reach-weighted range at this node, or `0.5` when no opponent combo is
    /// compatible.
    pub equity: Option<Vec<f64>>,
}

/// How much a best response could gain against a policy, in chips.
///
/// `oop` and `ip` are each player's best-response value: the range-weighted EV
/// of deviating to a perfect best response while the other player keeps the
/// average strategy. In a zero-sum game they cancel at an exact Nash
/// equilibrium, so `total`, their average, is `0` there and grows with how much
/// either side can still gain. Values are in the same chips as the pot (not
/// mbb or a percentage of the pot), averaged over compatible initial deals
/// weighted by both ranges. Every field is NaN when that joint weight is zero
/// or not finite; treat such a result as invalid.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Exploitability {
    /// OOP's best-response value against IP's average strategy, in chips.
    pub oop: f64,
    /// IP's best-response value against OOP's average strategy, in chips.
    pub ip: f64,
    /// `(oop + ip) / 2`: the exploitability, in chips.
    pub total: f64,
}

impl std::fmt::Debug for Trainer {
    /// A summary: the update rule, progress, and the game, not the tables.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Trainer")
            .field("algorithm", &self.algorithm)
            .field("update_schedule", &self.update_schedule)
            .field("iterations_completed", &self.iterations_completed)
            .field("game", &self.game)
            .finish_non_exhaustive()
    }
}

impl std::fmt::Debug for SolverGame {
    /// A summary: board, tree size, range sizes, and abstraction.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SolverGame")
            .field("board", &self.tree.board)
            .field("num_decision_nodes", &self.tree.num_decision_nodes)
            .field("num_combos", &[self.combos[0].len(), self.combos[1].len()])
            .field("abstraction", &self.abstraction)
            .finish_non_exhaustive()
    }
}

impl Trainer {
    /// Builds a trainer for `tree` and both players' combos.
    ///
    /// The combo order is kept and is the combo axis of every per-combo result.
    /// `options` selects the update rule, the update order (fixed for this
    /// trainer's lifetime; an alternating iteration is an OOP pass followed by an
    /// IP pass), and per-street card abstraction.
    ///
    /// Trees with grouped chance cards (suit isomorphism) need ranges closed
    /// under every suit swap that fixes the board, with equal weights for
    /// swapped combos; flop and turn buckets need the swapped combos to exist.
    /// Ranges from [`Range::combos`](crate::Range::combos) satisfy both when
    /// `dead` is exactly the tree's board.
    ///
    /// # Errors
    /// Returns a [`TrainerError`] if the tree's board is illegal, the tree
    /// does not continue from it or is malformed, a range is empty or holds
    /// invalid, repeated, or board-blocked combos, no deal is possible, an
    /// abstraction asks for zero buckets, or a range is not suit-symmetric as
    /// required above.
    pub fn new(
        tree: super::tree::Tree,
        combos: [Vec<Combo>; 2],
        options: TrainerOptions,
    ) -> Result<Self, TrainerError> {
        validate_trainer_inputs(&tree, &combos, options.abstraction)?;
        Ok(Self::new_unchecked(tree, combos, options))
    }

    /// `new` without input validation, for tests that drive the terminal
    /// kernels with deliberately degenerate ranges.
    fn new_unchecked(
        tree: super::tree::Tree,
        combos: [Vec<Combo>; 2],
        options: TrainerOptions,
    ) -> Self {
        let initial_board = tree.board.clone();
        let TrainerOptions {
            algorithm,
            schedule: update_schedule,
            abstraction,
        } = options;
        let mut board_eval_cache = HashMap::new();
        precompute_board_eval(&tree.root, &initial_board, &combos, &mut board_eval_cache);
        // `precompute_board_eval` only inserts entries for boards reached
        // through a `Chance` node, so a solve that *starts* already at a
        // complete river board (no chance nodes in the tree at all — the
        // common "solve this exact river spot" case) would otherwise never
        // get an entry, silently disabling bucketing for it.
        if initial_board.len() == 5 {
            board_eval_cache
                .entry(initial_board.clone())
                .or_insert_with(|| Arc::new(eval_combos_if_complete(&combos, &initial_board)));
        }

        let combo_index = [build_combo_index(&combos[0]), build_combo_index(&combos[1])];
        let terminal_index = TerminalIndex::new(&combos);
        let board_order_cache = board_eval_cache
            .iter()
            .filter(|(board, _)| board.len() == 5)
            .map(|(board, scores)| {
                (
                    board.clone(),
                    Arc::new(BoardOrder::new(&combos, scores, mask_of(board))),
                )
            })
            .collect();

        let mut bucket_maps: HashMap<Vec<Card>, Arc<[Vec<usize>; 2]>> = HashMap::new();
        if let Some(n) = abstraction.river {
            // The cache also holds turn boards (with empty scores); bucketing
            // those would give turn decisions zero buckets.
            for (board, scores) in board_eval_cache.iter().filter(|(b, _)| b.len() == 5) {
                let scores_f64 = [
                    scores[0].iter().map(|&s| s as f64).collect::<Vec<f64>>(),
                    scores[1].iter().map(|&s| s as f64).collect::<Vec<f64>>(),
                ];
                bucket_maps.insert(
                    board.clone(),
                    Arc::new([
                        compute_percentile_buckets(&scores_f64[0], n),
                        compute_percentile_buckets(&scores_f64[1], n),
                    ]),
                );
            }
        }
        if abstraction.flop.is_some() || abstraction.turn.is_some() {
            // Every board a Decision node could actually be built at: the
            // initial board itself (same "starts already at this street"
            // reasoning as the river fix above), plus every board reached
            // by dealing a class representative — matching precisely what
            // `cfr()` ever recurses into (`chance_value` never visits a
            // non-representative member's own board; it derives those via
            // relabeling), so this can't miss or over-collect a board.
            let mut reachable_boards = std::collections::HashSet::new();
            reachable_boards.insert(initial_board.clone());
            collect_reachable_boards(&tree.root, &initial_board, &mut reachable_boards);
            let mut avg_score_cache = HashMap::new();
            for board in &reachable_boards {
                let n = match board.len() {
                    3 => abstraction.flop,
                    4 => abstraction.turn,
                    _ => None,
                };
                if let Some(n) = n {
                    let scores = avg_score(
                        board,
                        &combos,
                        &combo_index,
                        &board_eval_cache,
                        &mut avg_score_cache,
                    );
                    bucket_maps.insert(
                        board.clone(),
                        Arc::new([
                            compute_percentile_buckets(&scores[0], n),
                            compute_percentile_buckets(&scores[1], n),
                        ]),
                    );
                }
            }
        }
        let identity_buckets = [
            (0..combos[0].len()).collect(),
            (0..combos[1].len()).collect(),
        ];

        let mut node_data: Vec<NodeData> = (0..tree.num_decision_nodes)
            .map(|_| NodeData::empty())
            .collect();
        let mut node_meta: Vec<(usize, Vec<Card>)> = vec![(0, Vec::new()); tree.num_decision_nodes];
        init_node_data(
            &tree.root,
            &initial_board,
            &bucket_maps,
            &identity_buckets,
            &mut node_data,
            &mut node_meta,
        );
        let node_data: Vec<Mutex<NodeData>> = node_data.into_iter().map(Mutex::new).collect();
        let mut suit_groups = HashMap::new();
        if has_suit_reduction(&tree.root) {
            for (_, board) in &node_meta {
                suit_groups.entry(board.clone()).or_insert_with(|| {
                    let maps = bucket_maps
                        .get(board)
                        .map_or(&identity_buckets, |maps| &**maps);
                    Arc::new(suit_bucket_groups(board, &combos, &combo_index, maps))
                });
            }
        }

        let mut game = SolverGame {
            tree,
            initial_board,
            combos,
            board_eval_cache,
            combo_index,
            terminal_index,
            board_order_cache,
            abstraction,
            bucket_maps,
            identity_buckets,
            suit_groups,
            node_meta,
            plan: engine::Plan::empty(),
            #[cfg(test)]
            use_pairwise_terminals: std::sync::atomic::AtomicBool::new(false),
            #[cfg(test)]
            terminal_calls: std::array::from_fn(|_| std::sync::atomic::AtomicUsize::new(0)),
        };
        game.plan = engine::Plan::build(&game);
        Self {
            game: Arc::new(game),
            algorithm,
            update_schedule,
            iterations_completed: 0,
            node_data,
        }
    }

    /// The fixed update policy selected at construction.
    pub fn algorithm(&self) -> SolverAlgorithm {
        self.algorithm
    }

    /// The fixed player-update order selected at construction.
    pub fn update_schedule(&self) -> UpdateSchedule {
        self.update_schedule
    }

    /// Iterations completed across all calls to [`train`](Self::train).
    ///
    /// An alternating iteration counts once, though it makes two passes. DCFR uses
    /// this count as its discounting clock.
    pub fn iterations_completed(&self) -> u64 {
        self.iterations_completed
    }

    /// Runs `iterations` more training iterations.
    ///
    /// Returns the root `[OOP, IP]` raw range-weighted values under the last
    /// iteration's current strategy. They are a progress signal, not EVs, and say
    /// nothing about convergence; use [`exploitability`](Self::exploitability) for
    /// that and [`average_strategy`](Self::average_strategy) for the result. With
    /// alternating updates the values come from the final IP pass.
    ///
    /// # Panics
    /// Panics if the total iteration count would overflow `u64`.
    pub fn train(&mut self, iterations: u32) -> [f64; 2] {
        let mut last = [0.0, 0.0];
        for step in 0..iterations {
            let iteration = self
                .iterations_completed
                .checked_add(1)
                .expect("CFR iteration counter overflow");
            let update = self.algorithm.iteration(iteration);
            let pass = match self.update_schedule {
                UpdateSchedule::Simultaneous => TrainingPass {
                    update,
                    updating: None,
                    values: 3,
                },
                UpdateSchedule::Alternating => {
                    self.run_pass(TrainingPass {
                        update,
                        updating: Some(0),
                        values: 1,
                    });
                    // Preserve the exact public train() return on the final IP
                    // pass. Interior iterations need only the learning player's
                    // CFVs; no zero-sum reconstruction or extra traversal.
                    TrainingPass {
                        update,
                        updating: Some(1),
                        values: if step + 1 == iterations { 3 } else { 2 },
                    }
                }
            };
            let [cfv0, cfv1] = self.run_pass(pass);
            let ev0: f64 = cfv0
                .iter()
                .zip(&self.game.combos[0])
                .map(|(v, c)| v * c.weight)
                .sum();
            let ev1: f64 = cfv1
                .iter()
                .zip(&self.game.combos[1])
                .map(|(v, c)| v * c.weight)
                .sum();
            last = [ev0, ev1];
            self.iterations_completed = iteration;
        }
        last
    }

    /// The shared, immutable game definition.
    pub fn game(&self) -> &Arc<SolverGame> {
        &self.game
    }

    /// Snapshot of the average strategy at this iteration boundary.
    pub fn policy(&self) -> Policy {
        let nodes = self.node_data.len();
        let rows = if nodes < 1024 || rayon::current_num_threads() <= 1 {
            (0..nodes)
                .map(|id| self.average_bucket_strategy(id))
                .collect()
        } else {
            (0..nodes)
                .into_par_iter()
                .with_min_len(256)
                .map(|id| self.average_bucket_strategy(id))
                .collect()
        };
        Policy { rows }
    }

    /// [`SolverGame::evaluate`] under the current average strategy.
    pub fn evaluate(&self) -> Evaluation {
        self.game.evaluate(&self.policy())
    }

    /// [`SolverGame::exploitability`] under the current average strategy.
    pub fn exploitability(&self) -> Exploitability {
        self.game.exploitability(&self.policy())
    }

    /// The trained average strategy for one decision node, as
    /// `[action][combo]` (see [`SolverGame::average_strategy`]).
    ///
    /// # Panics
    /// Panics if `node_id` is not below [`SolverGame::num_decision_nodes`].
    pub fn average_strategy(&self, node_id: usize) -> Vec<Vec<f64>> {
        self.game
            .expand_strategy(node_id, &self.average_bucket_strategy(node_id))
    }

    /// Normalized strategy sums in bucket coordinates, suit-symmetrized.
    fn average_bucket_strategy(&self, node_id: usize) -> Vec<Vec<f64>> {
        let data = self.node_data[node_id].lock().unwrap();
        let num_actions = data.strategy_sum.len();
        let num_buckets = data.strategy_sum.first().map_or(0, Vec::len);
        // One total per bucket, added in action order.
        let mut totals = vec![0.0; num_buckets];
        for row in &data.strategy_sum {
            for (total, &sum) in totals.iter_mut().zip(row) {
                *total += sum;
            }
        }
        let uniform = 1.0 / num_actions as f64;
        let mut bucket_strategy: Vec<Vec<f64>> = data
            .strategy_sum
            .iter()
            .map(|row| {
                row.iter()
                    .zip(&totals)
                    .map(|(&sum, &total)| if total > 0.0 { sum / total } else { uniform })
                    .collect()
            })
            .collect();
        drop(data);
        self.game.symmetrize_strategy(node_id, &mut bucket_strategy);
        bucket_strategy
    }

    /// The regret-matching strategy the next traversal will play at node `id`.
    #[cfg(test)]
    fn current_strategy(&self, id: usize, num_actions: usize, num_combos: usize) -> Vec<Vec<f64>> {
        let (player, board) = &self.game.node_meta[id];
        let plan = &self.game.plan;
        let board = plan
            .boards
            .iter()
            .find(|candidate| candidate.cards == *board)
            .expect("every decision node's board is in the plan");
        let mut flat = vec![0.0; num_actions * num_combos];
        let mut totals = vec![0.0; num_combos];
        assert_eq!(num_combos, board.num_buckets[*player]);
        self.fill_strategy(id, board, *player, num_actions, &mut flat, &mut totals);
        (0..num_actions)
            .map(|a| flat[a * num_combos..(a + 1) * num_combos].to_vec())
            .collect()
    }
}

impl SolverGame {
    /// Number of regret/strategy rows (buckets, or plain combos if
    /// unabstracted) `player`'s combos collapse into at the given `board`.
    fn combo_buckets(&self, player: usize, board: &[Card]) -> (usize, &[usize]) {
        bucket_count_and_map(player, board, &self.bucket_maps, &self.identity_buckets)
    }

    /// Values at every decision node under `policy`.
    ///
    /// Reads only the game and `policy`, so it can run while training continues and
    /// always describes the iteration `policy` was taken at. One call walks the
    /// whole tree, so call it once and index the result rather than once per node.
    ///
    /// # Examples
    ///
    /// ```
    /// # use native_solver::*;
    /// # let board = ["Ks", "Th", "7s", "4d", "2s"].iter().map(|c| c.parse()).collect::<Result<Vec<Card>, _>>()?;
    /// # let dead = CardSet::from_cards(&board);
    /// # let config = GameConfig::new(board, Chips::whole(100), Chips::whole(100)).with_bet_sizes([1.0]);
    /// # let ranges = ["AA,KQs", "QQ,JJ"].map(|r| r.parse::<Range>().unwrap().combos(dead));
    /// # let mut trainer = Trainer::new(build_tree(&config)?, ranges, TrainerOptions::default())?;
    /// trainer.train(100);
    /// let evaluation = trainer.game().evaluate(&trainer.policy());
    /// assert_eq!(evaluation.nodes.len(), trainer.game().num_decision_nodes());
    ///
    /// // Root values are zero-sum.
    /// let [oop, ip] = evaluation.root_values;
    /// assert!((oop + ip).abs() < 1e-6);
    ///
    /// // EV of each OOP combo at the root, in chips.
    /// let root_ev = &evaluation.nodes[0].ev;
    /// assert_eq!(root_ev.len(), trainer.game().combos(Player::Oop).len());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn evaluate(&self, policy: &Policy) -> Evaluation {
        let out: Vec<std::sync::OnceLock<NodeEvaluation>> = (0..self.node_meta.len())
            .map(|_| std::sync::OnceLock::new())
            .collect();
        let reach0: Vec<f64> = self.combos[0].iter().map(|c| c.weight).collect();
        let reach1: Vec<f64> = self.combos[1].iter().map(|c| c.weight).collect();
        let [cfv0, cfv1] = self.evaluate_plan(policy, [&reach0, &reach1], &out);
        let ev0: f64 = cfv0
            .iter()
            .zip(&self.combos[0])
            .map(|(v, c)| v * c.weight)
            .sum();
        let ev1: f64 = cfv1
            .iter()
            .zip(&self.combos[1])
            .map(|(v, c)| v * c.weight)
            .sum();
        // `evaluate_node` visits every decision node exactly once.
        let nodes = out
            .into_iter()
            .map(|node| node.into_inner().expect("every decision node is evaluated"))
            .collect();
        Evaluation {
            nodes,
            root_values: [ev0, ev1],
        }
    }

    /// How much a best response could gain against `policy`, in chips.
    ///
    /// Runs one best-response pass for each player against the other's policy; see
    /// [`Exploitability`] for the definition.
    pub fn exploitability(&self, policy: &Policy) -> Exploitability {
        let board = &self.initial_board;
        let reach0: Vec<f64> = self.combos[0].iter().map(|c| c.weight).collect();
        let reach1: Vec<f64> = self.combos[1].iter().map(|c| c.weight).collect();

        // CFVs remain unnormalized throughout recursion. Only the public
        // metric is an expectation over legal initial deals, rather than a
        // sum that changes with the size or common scale of either range.
        let board_set = mask_of(board);
        let live = |c: &Combo| !mask_has(board_set, c.cards[0]) && !mask_has(board_set, c.cards[1]);
        let compatible_mass =
            self.terminal_index
                .compatible_mass(&self.combos, 0, &reach1, board_set);
        let joint_mass: f64 = self.combos[0]
            .iter()
            .zip(&compatible_mass)
            .filter(|(c, _)| live(c))
            .map(|(c, mass)| c.weight * mass)
            .sum();
        if !joint_mass.is_finite() || joint_mass <= 0.0 {
            return Exploitability {
                oop: f64::NAN,
                ip: f64::NAN,
                total: f64::NAN,
            };
        }

        let br0 = self.best_response(policy, 0, &reach1);
        let br1 = self.best_response(policy, 1, &reach0);
        let oop = br0
            .iter()
            .zip(&self.combos[0])
            .filter(|(_, c)| live(c))
            .map(|(v, c)| v * c.weight)
            .sum::<f64>()
            / joint_mass;
        let ip = br1
            .iter()
            .zip(&self.combos[1])
            .filter(|(_, c)| live(c))
            .map(|(v, c)| v * c.weight)
            .sum::<f64>()
            / joint_mass;
        Exploitability {
            oop,
            ip,
            total: (oop + ip) / 2.0,
        }
    }

    /// The betting tree this trainer is solving, e.g. to look up node ids
    /// by walking its structure.
    pub fn tree(&self) -> &Node {
        &self.tree.root
    }

    /// The board the tree starts from ([`Tree::board`](crate::Tree::board)).
    pub fn board(&self) -> &[Card] {
        &self.tree.board
    }

    /// The community cards dealt so far at decision node `node_id` (e.g.
    /// for display, or to label which card a `Chance` branch led through).
    ///
    /// # Panics
    /// Panics if `node_id` is not below [`num_decision_nodes`](Self::num_decision_nodes).
    pub fn node_board(&self, node_id: usize) -> &[Card] {
        &self.node_meta[node_id].1
    }

    /// `player`'s combos, in the order of every per-combo result (the combo
    /// axis of `average_strategy`, [`NodeEvaluation::ev`], and so on).
    pub fn combos(&self, player: Player) -> &[Combo] {
        &self.combos[player.index()]
    }

    /// The card abstraction this game was built with.
    pub fn abstraction(&self) -> CardAbstraction {
        self.abstraction
    }

    /// The strategy at `node_id` under `policy`, as `[action][combo]` probabilities.
    ///
    /// Combos follow the acting player's range order. With card abstraction, every
    /// combo in a bucket reports the bucket's shared probabilities.
    ///
    /// # Panics
    /// Panics if `node_id` is not below [`num_decision_nodes`](Self::num_decision_nodes)
    /// or `policy` was taken from a different game.
    pub fn average_strategy(&self, policy: &Policy, node_id: usize) -> Vec<Vec<f64>> {
        self.expand_strategy(node_id, &policy.rows[node_id])
    }

    /// Expands bucket rows to one probability per combo of the acting player.
    fn expand_strategy(&self, node_id: usize, bucket_strategy: &[Vec<f64>]) -> Vec<Vec<f64>> {
        let (player, board) = &self.node_meta[node_id];
        let (_, buckets) = self.combo_buckets(*player, board);
        bucket_strategy
            .iter()
            .map(|row| buckets.iter().map(|&b| row[b]).collect())
            .collect()
    }

    /// Restores a policy saved from [`Policy::rows`].
    ///
    /// The rows must fit this game: one row set per decision node, one row per
    /// action, one entry per bucket, each bucket a probability distribution, and
    /// suit-equivalent buckets identical. Rows are used as given, so reads match
    /// the saved policy bit for bit. See [`Policy`] for an example.
    ///
    /// # Errors
    /// Returns a [`PolicyError`] naming the first node whose rows have the
    /// wrong count or shape, are not distributions, or are not symmetric.
    pub fn policy_from_rows(&self, rows: Vec<Vec<Vec<f64>>>) -> Result<Policy, PolicyError> {
        fn action_counts(node: &Node, out: &mut [usize]) {
            match node {
                Node::Decision {
                    id,
                    actions,
                    children,
                    ..
                } => {
                    out[*id] = actions.len();
                    children.iter().for_each(|child| action_counts(child, out));
                }
                Node::Chance { children } => children
                    .iter()
                    .for_each(|(_, child)| action_counts(child, out)),
                Node::Terminal(_) => {}
            }
        }
        if rows.len() != self.num_decision_nodes() {
            return Err(PolicyError::NodeCount {
                policy: rows.len(),
                game: self.num_decision_nodes(),
            });
        }
        let mut actions = vec![0; rows.len()];
        action_counts(&self.tree.root, &mut actions);
        for (id, node_rows) in rows.iter().enumerate() {
            let (player, board) = &self.node_meta[id];
            let (num_buckets, _) = self.combo_buckets(*player, board);
            if node_rows.len() != actions[id]
                || node_rows.iter().any(|row| row.len() != num_buckets)
            {
                return Err(PolicyError::Shape { node: id });
            }
            for b in 0..num_buckets {
                let total: f64 = node_rows.iter().map(|row| row[b]).sum();
                if node_rows
                    .iter()
                    .any(|row| !row[b].is_finite() || row[b] < 0.0)
                    || (total - 1.0).abs() > 1e-9
                {
                    return Err(PolicyError::NotDistribution { node: id });
                }
            }
            if let Some(groups) = self.suit_groups.get(board) {
                let asymmetric = groups[*player].iter().any(|group| {
                    node_rows.iter().any(|row| {
                        group
                            .iter()
                            .any(|&b| row[b].to_bits() != row[group[0]].to_bits())
                    })
                });
                if asymmetric {
                    return Err(PolicyError::NotSymmetric { node: id });
                }
            }
        }
        Ok(Policy { rows })
    }

    /// Each combo's bucket, per board and player, sorted by board.
    ///
    /// Empty when no street is bucketed. A saved policy can use it to check that
    /// its rows still describe the same hands.
    pub fn bucket_assignments(&self) -> Vec<(&[Card], &[Vec<usize>; 2])> {
        let mut maps: Vec<_> = self
            .bucket_maps
            .iter()
            .map(|(board, maps)| (board.as_slice(), &**maps))
            .collect();
        maps.sort_unstable_by(|a, b| a.0.cmp(b.0));
        maps
    }

    /// Number of decision nodes (valid `node_id`s are `0..num_decision_nodes`).
    pub fn num_decision_nodes(&self) -> usize {
        self.node_meta.len()
    }

    fn symmetrize_strategy(&self, id: usize, strategy: &mut [Vec<f64>]) {
        let (player, board) = &self.node_meta[id];
        if let Some(groups) = self.suit_groups.get(board) {
            for group in &groups[*player] {
                for row in strategy.iter_mut() {
                    let probability =
                        group.iter().map(|&i| row[i]).sum::<f64>() / group.len() as f64;
                    for &i in group {
                        row[i] = probability;
                    }
                }
            }
        }
    }

    /// Re-expresses `rep_cfv` (computed with the class representative
    /// dealt, i.e. under a board whose newest card has suit `suit_a`) as
    /// the cfv for a board whose newest card is the same rank but suit
    /// `suit_b` instead: swapping `suit_a`/`suit_b` on both players' cards
    /// leaves the tree structure and every hand-strength comparison
    /// unchanged (both suits were free before this deal, so the swap fixes
    /// the rest of the board), so combo `j`'s cfv under the `suit_b`
    /// version equals the representative's cfv for whichever combo `j`
    /// becomes after swapping its two cards' suits.
    #[cfg(test)]
    fn relabel_cfv(&self, player: usize, rep_cfv: &[f64], suit_a: u8, suit_b: u8) -> Vec<f64> {
        self.combos[player]
            .iter()
            .map(
                |&Combo {
                     cards: [h1, h2], ..
                 }| {
                    let s1 = swap_suit(h1, suit_a, suit_b);
                    let s2 = swap_suit(h2, suit_a, suit_b);
                    let idx = self.combo_index[player][&normalize_pair(s1, s2)];
                    rep_cfv[idx]
                },
            )
            .collect()
    }

    #[cfg(test)]
    fn terminal_value(
        &self,
        t: &Terminal,
        reach: &[Vec<f64>; 2],
        board: &[Card],
        board_eval: &[Vec<u32>; 2],
    ) -> [Vec<f64>; 2] {
        [
            self.terminal_value_for_player(t, 0, &reach[1], board, board_eval),
            self.terminal_value_for_player(t, 1, &reach[0], board, board_eval),
        ]
    }

    #[cfg(test)]
    fn terminal_value_for_player(
        &self,
        t: &Terminal,
        player: usize,
        reach_opp: &[f64],
        board: &[Card],
        board_eval: &[Vec<u32>; 2],
    ) -> Vec<f64> {
        let mut out = vec![0.0; self.combos[player].len()];
        self.terminal_into(
            t,
            player,
            reach_opp,
            mask_of(board),
            board_eval,
            self.board_order_cache.get(board).map(|order| &**order),
            &mut out,
        );
        out
    }

    /// `player`'s raw terminal values written over `out`, one per combo.
    /// `order` is the board's rank order; every showdown board has one.
    #[allow(clippy::too_many_arguments)]
    fn terminal_into(
        &self,
        t: &Terminal,
        player: usize,
        reach_opp: &[f64],
        board_set: u64,
        board_eval: &[Vec<u32>; 2],
        order: Option<&BoardOrder>,
        out: &mut [f64],
    ) {
        #[cfg(test)]
        self.terminal_calls[player].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        #[cfg(test)]
        if self
            .use_pairwise_terminals
            .load(std::sync::atomic::Ordering::Relaxed)
        {
            for (i, out) in out.iter_mut().enumerate() {
                let [a, b] = self.combos[player][i].cards;
                *out = if mask_has(board_set, a) || mask_has(board_set, b) {
                    0.0
                } else {
                    match t {
                        Terminal::Fold { winner, invested } => {
                            let value = if winner.index() == player {
                                invested[1 - player]
                            } else {
                                -invested[player]
                            };
                            value * self.non_conflicting_reach_sum(player, i, reach_opp, board_set)
                        }
                        Terminal::Showdown { invested } => {
                            self.showdown_cfv(player, i, invested, reach_opp, board_eval, board_set)
                        }
                    }
                };
            }
            return;
        }
        match t {
            Terminal::Fold { winner, invested } => {
                let value = if winner.index() == player {
                    invested[1 - player]
                } else {
                    -invested[player]
                };
                self.terminal_index.compatible_mass_into(
                    &self.combos,
                    player,
                    reach_opp,
                    board_set,
                    out,
                );
                for mass in out.iter_mut() {
                    *mass *= value;
                }
            }
            Terminal::Showdown { invested } => self.terminal_index.showdown_into(
                &self.combos,
                player,
                reach_opp,
                board_eval,
                order.expect("every showdown board has a rank order"),
                board_set,
                invested,
                out,
            ),
        }
    }

    /// Sums `reach_opp` over the opponent's combos that are actually live
    /// against `player`'s own combo `combo_idx`: not blocked by `player`'s
    /// two hole cards, *and* not physically impossible given `board_set`
    /// (an opponent combo whose card was itself dealt onto the board this
    /// branch can never really be held here — see `chance_value`'s doc
    /// comment on the "N-4" private-deal normalization this complements. Without this
    /// check a board-conflicting opponent combo would still contribute its
    /// full reach weight to this terminal, breaking the zero-sum
    /// invariant).
    #[cfg(test)]
    fn non_conflicting_reach_sum(
        &self,
        player: usize,
        combo_idx: usize,
        reach_opp: &[f64],
        board_set: u64,
    ) -> f64 {
        let opp = 1 - player;
        let [h1, h2] = self.combos[player][combo_idx].cards;
        self.combos[opp]
            .iter()
            .zip(reach_opp)
            .filter(
                |(
                    Combo {
                        cards: [v1, v2], ..
                    },
                    _,
                )| {
                    *v1 != h1
                        && *v1 != h2
                        && *v2 != h1
                        && *v2 != h2
                        && !mask_has(board_set, *v1)
                        && !mask_has(board_set, *v2)
                },
            )
            .map(|(_, &r)| r)
            .sum()
    }

    /// Same board-conflict exclusion as `non_conflicting_reach_sum`,
    /// applied to the opponent combos aggregated over for a showdown value
    /// (see that function's doc comment).
    #[cfg(test)]
    fn showdown_cfv(
        &self,
        player: usize,
        combo_idx: usize,
        invested: &[f64; 2],
        reach_opp: &[f64],
        board_eval: &[Vec<u32>; 2],
        board_set: u64,
    ) -> f64 {
        let opp = 1 - player;
        let [h1, h2] = self.combos[player][combo_idx].cards;
        let hero_score = board_eval[player][combo_idx];
        let mut cfv = 0.0;
        for (
            j,
            &Combo {
                cards: [v1, v2], ..
            },
        ) in self.combos[opp].iter().enumerate()
        {
            if v1 == h1 || v1 == h2 || v2 == h1 || v2 == h2 {
                continue;
            }
            if mask_has(board_set, v1) || mask_has(board_set, v2) {
                continue;
            }
            let villain_score = board_eval[opp][j];
            let net = match hero_score.cmp(&villain_score) {
                std::cmp::Ordering::Greater => invested[opp],
                std::cmp::Ordering::Less => -invested[player],
                std::cmp::Ordering::Equal => (invested[opp] - invested[player]) / 2.0,
            };
            cfv += reach_opp[j] * net;
        }
        cfv
    }
}

/// `(min(c1,c2), max(c1,c2))`, the order-independent key `combo_index` and
/// `relabel_cfv` use to look up a combo regardless of the tuple order
/// `range::hand_combos` happened to store it in.
fn normalize_pair(c1: Card, c2: Card) -> (Card, Card) {
    if c1 <= c2 {
        (c1, c2)
    } else {
        (c2, c1)
    }
}

fn build_combo_index(combos: &[Combo]) -> HashMap<(Card, Card), usize> {
    combos
        .iter()
        .enumerate()
        .map(
            |(
                i,
                &Combo {
                    cards: [c1, c2], ..
                },
            )| (normalize_pair(c1, c2), i),
        )
        .collect()
}

/// `card` with its suit swapped to the other side of the `suit_a`/`suit_b`
/// transposition (identity if `card` uses neither suit).
fn swap_suit(card: Card, suit_a: u8, suit_b: u8) -> Card {
    let s = card.suit();
    let new_suit = if s == suit_a {
        suit_b
    } else if s == suit_b {
        suit_a
    } else {
        s
    };
    Card(card.rank() * 4 + new_suit)
}

/// [`evaluate_7`](crate::evaluate_7) scores for every combo, if `board` is a complete 5-card
/// board — otherwise empty (no [`Terminal::Showdown`] is ever reachable with
/// an incomplete board, so it's never read in that case).
///
/// A combo whose hole card was itself dealt as one of `board`'s later
/// (post-initial-deal) cards is physically impossible for this specific
/// board — `chance_value`'s per-node exclusion check always drops such a
/// combo from every aggregate sum before it reaches the root (that's the
/// whole point of the "N-4" private-deal normalization this module's doc comment
/// describes), so its score here is never actually read. Skipping
/// [`evaluate_7`](crate::evaluate_7) for it (sentinel `0`) avoids feeding it a 7-card hand that
/// can't occur in reality — e.g. a pocket-pair combo whose two ranks-match
/// a rank that also completes trips/quads on the board, which pushes one
/// rank to 5 "occurrences" among the 7 cards, a pattern `eval::evaluate_5`'s
/// lookup table correctly never populates (impossible with 4 suits/rank).
fn eval_combos_if_complete(combos: &[Vec<Combo>; 2], board: &[Card]) -> [Vec<u32>; 2] {
    if board.len() != 5 {
        return [Vec::new(), Vec::new()];
    }
    let board_set = mask_of(board);
    let score = |combo: &Combo| {
        if mask_has(board_set, combo.cards[0]) || mask_has(board_set, combo.cards[1]) {
            return 0;
        }
        score_7([
            combo.cards[0],
            combo.cards[1],
            board[0],
            board[1],
            board[2],
            board[3],
            board[4],
        ])
    };
    [
        combos[0].iter().map(score).collect(),
        combos[1].iter().map(score).collect(),
    ]
}

/// Walks every `Chance` branch once, filling `cache` with the
/// [`evaluate_7`](crate::evaluate_7) scores for each complete board reachable from `board`.
fn precompute_board_eval(
    node: &Node,
    board: &[Card],
    combos: &[Vec<Combo>; 2],
    cache: &mut HashMap<Vec<Card>, Arc<[Vec<u32>; 2]>>,
) {
    match node {
        Node::Decision { children, .. } => {
            for child in children {
                precompute_board_eval(child, board, combos, cache);
            }
        }
        Node::Chance { children } => {
            for (members, child) in children {
                // Only the class representative is actually recursed into
                // by `chance_value` — other members' values are derived by
                // relabeling, never by looking up their own board here.
                let rep = members[0];
                let mut child_board = board.to_vec();
                child_board.push(rep);
                cache
                    .entry(child_board.clone())
                    .or_insert_with(|| Arc::new(eval_combos_if_complete(combos, &child_board)));
                precompute_board_eval(child, &child_board, combos, cache);
            }
        }
        Node::Terminal(_) => {}
    }
}

/// Every board a `Decision` node is ever actually built at, below `board`
/// (not including `board` itself — callers that need the starting board
/// too, e.g. a solve beginning already at the target street, add it
/// separately). Mirrors `precompute_board_eval`'s representative-only
/// descent through `Chance` nodes for the same reason: those are the only
/// boards `cfr()` ever recurses into.
fn collect_reachable_boards(
    node: &Node,
    board: &[Card],
    acc: &mut std::collections::HashSet<Vec<Card>>,
) {
    match node {
        Node::Decision { children, .. } => {
            for child in children {
                collect_reachable_boards(child, board, acc);
            }
        }
        Node::Chance { children } => {
            for (members, child) in children {
                let rep = members[0];
                let mut child_board = board.to_vec();
                child_board.push(rep);
                acc.insert(child_board.clone());
                collect_reachable_boards(child, &child_board, acc);
            }
        }
        Node::Terminal(_) => {}
    }
}

/// Splits combos into `num_buckets` contiguous, roughly-equal-sized groups
/// by score percentile (river: real [`evaluate_7`](crate::evaluate_7) scores; flop/turn:
/// `avg_score`'s future-score expectation) — sorting by score and cutting
/// every `n / num_buckets`-th combo keeps the assignment monotonic (a
/// higher-scoring combo never lands in a lower bucket than a
/// lower-scoring one). When `num_buckets >= scores.len()` this reduces to
/// an exact bijection (every combo its own bucket, in score order) — the
/// baseline [`CardAbstraction`]'s per-street `Some(n)` for large `n` needs
/// to behave identically to `None`.
fn compute_percentile_buckets(scores: &[f64], num_buckets: usize) -> Vec<usize> {
    let n = scores.len();
    if n == 0 {
        return Vec::new();
    }
    let num_buckets = num_buckets.clamp(1, n);
    let mut order: Vec<usize> = (0..n).collect();
    order.sort_by(|&i, &j| scores[i].partial_cmp(&scores[j]).unwrap());
    let mut bucket_of = vec![0usize; n];
    for (rank, &i) in order.iter().enumerate() {
        bucket_of[i] = rank * num_buckets / n;
        // Never split a run of exactly-equal scores across a bucket
        // boundary: two combos this function scores identically are often
        // suit-swap-equivalent under `avg_score`'s isomorphism-class
        // averaging (or the river's raw `evaluate_7` tie), and
        // `chance_value`'s relabeling assumes such combos always share
        // the exact same strategy — a boundary landing mid-tie would
        // silently break that invariant.
        if rank > 0 && scores[i] == scores[order[rank - 1]] {
            bucket_of[i] = bucket_of[order[rank - 1]];
        }
    }
    bucket_of
}

/// Each combo's expected [`evaluate_7`](crate::evaluate_7) score from `board` through to the
/// river, averaged over future streets — the proxy [`CardAbstraction`]'s
/// flop/turn bucketing ranks combos by, since (unlike the river) their
/// hand isn't final yet. This is coarser than true equity: it's a plain
/// average of the eventual showdown *score*, not a win probability against
/// an opponent range, so it doesn't capture *how* a hand realizes its
/// value (e.g. a made hand with no more equity to gain and a drawing hand
/// with the same average score play very differently in reality) — but it
/// reuses the exact [`evaluate_7`](crate::evaluate_7) machinery already computed for real
/// showdowns, needs no separate equity engine, and preserves the right
/// ordering for the common case (stronger hands now tend to stay stronger).
///
/// Always groups future deals by suit-isomorphism class (`deal_classes`
/// with `suit_isomorphism: true`) regardless of whether the *tree* itself
/// was built with isomorphism — grouping same-rank free-suit cards is
/// always a valid equivalence, so this one-time precomputation is cheaper
/// this way, and when the tree *was* isomorphism-reduced this also means
/// every board it visits at the base case is already in `board_eval_cache`
/// (zero redundant [`evaluate_7`](crate::evaluate_7) calls beyond what training needs anyway).
fn avg_score(
    board: &[Card],
    combos: &[Vec<Combo>; 2],
    combo_index: &[HashMap<(Card, Card), usize>; 2],
    board_eval_cache: &HashMap<Vec<Card>, Arc<[Vec<u32>; 2]>>,
    cache: &mut HashMap<Vec<Card>, [Vec<f64>; 2]>,
) -> [Vec<f64>; 2] {
    if let Some(v) = cache.get(board) {
        return v.clone();
    }
    let result = if board.len() == 5 {
        let scores = match board_eval_cache.get(board) {
            Some(scores) => (**scores).clone(),
            None => eval_combos_if_complete(combos, board),
        };
        [
            scores[0].iter().map(|&s| s as f64).collect(),
            scores[1].iter().map(|&s| s as f64).collect(),
        ]
    } else {
        let mut sum = [vec![0.0; combos[0].len()], vec![0.0; combos[1].len()]];
        let mut weight = [vec![0.0; combos[0].len()], vec![0.0; combos[1].len()]];
        for members in super::tree::deal_classes(true, board) {
            let rep = members[0];
            let mut next_board = board.to_vec();
            next_board.push(rep);
            // `child[p][i]` is the real (or further-averaged) score for
            // combo `i` under board+`rep` specifically. For any *other*
            // class member `m`, a fixed combo's score under board+`m`
            // isn't `child[p][i]` (the two boards aren't the same!) — it's
            // `child`'s value for whichever combo `i` becomes after
            // swapping `rep`'s suit with `m`'s (the same relabeling
            // `chance_value`/`relabel_cfv` uses, for the same reason: that
            // suit swap is the symmetry that maps board+`m` to board+`rep`).
            let child = avg_score(&next_board, combos, combo_index, board_eval_cache, cache);
            for &m in &members {
                let (suit_a, suit_b) = (rep.suit(), m.suit());
                for p in 0..2 {
                    for (
                        i,
                        &Combo {
                            cards: [h1, h2], ..
                        },
                    ) in combos[p].iter().enumerate()
                    {
                        if h1 == m || h2 == m {
                            continue; // this combo can't coexist with m being dealt
                        }
                        let idx = if m == rep {
                            i
                        } else {
                            let s1 = swap_suit(h1, suit_a, suit_b);
                            let s2 = swap_suit(h2, suit_a, suit_b);
                            combo_index[p][&normalize_pair(s1, s2)]
                        };
                        sum[p][i] += child[p][idx];
                        weight[p][i] += 1.0;
                    }
                }
            }
        }
        [
            sum[0]
                .iter()
                .zip(&weight[0])
                .map(|(&s, &w)| if w > 0.0 { s / w } else { 0.0 })
                .collect(),
            sum[1]
                .iter()
                .zip(&weight[1])
                .map(|(&s, &w)| if w > 0.0 { s / w } else { 0.0 })
                .collect(),
        ]
    };
    cache.insert(board.to_vec(), result.clone());
    result
}

/// `player`'s bucket count and combo->bucket map at `board`: the
/// precomputed river map if one exists there, else the identity fallback
/// (every combo its own bucket — non-river nodes, or `river_buckets: None`).
fn bucket_count_and_map<'a>(
    player: usize,
    board: &[Card],
    bucket_maps: &'a HashMap<Vec<Card>, Arc<[Vec<usize>; 2]>>,
    identity_buckets: &'a [Vec<usize>; 2],
) -> (usize, &'a [usize]) {
    match bucket_maps.get(board) {
        Some(maps) => {
            let map = &maps[player];
            let num_buckets = map.iter().copied().max().map_or(0, |m| m + 1);
            (num_buckets, map)
        }
        None => (identity_buckets[player].len(), &identity_buckets[player]),
    }
}

/// Walks the tree threading `board` (mirroring `precompute_board_eval`'s
/// representative-only descent through `Chance` nodes) to size each
/// decision node's regret/strategy tables by its actual bucket count and
/// record `(player, board)` in `node_meta` for `average_strategy` to use.
fn init_node_data(
    node: &Node,
    board: &[Card],
    bucket_maps: &HashMap<Vec<Card>, Arc<[Vec<usize>; 2]>>,
    identity_buckets: &[Vec<usize>; 2],
    out: &mut [NodeData],
    node_meta: &mut [(usize, Vec<Card>)],
) {
    match node {
        Node::Decision {
            id,
            player,
            actions,
            children,
        } => {
            let p = player.index();
            let (num_buckets, _) = bucket_count_and_map(p, board, bucket_maps, identity_buckets);
            out[*id] = NodeData::sized(actions.len(), num_buckets);
            node_meta[*id] = (p, board.to_vec());
            for child in children {
                init_node_data(child, board, bucket_maps, identity_buckets, out, node_meta);
            }
        }
        Node::Chance { children } => {
            for (members, child) in children {
                let rep = members[0];
                let mut child_board = board.to_vec();
                child_board.push(rep);
                init_node_data(
                    child,
                    &child_board,
                    bucket_maps,
                    identity_buckets,
                    out,
                    node_meta,
                );
            }
        }
        Node::Terminal(_) => {}
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::card::Card;
    use crate::range::Range;
    use crate::solver::tree::{build_tree, GameConfig};
    use crate::solver::Chips;

    #[test]
    fn dcfr_discounts_once_per_bucket_after_adding_the_full_iteration() {
        use crate::solver::tree::{Action, Player, Tree};
        let c = |s: &str| s.parse::<Card>().unwrap();
        let board = ["2c", "3d", "7h", "8s", "9c"].map(c).to_vec();
        // Both AA combos have the same strength and merge into one bucket.
        // Unequal reaches expose mistakenly discounting after each combo.
        let combos = [
            vec![
                Combo::new(c("Ac"), c("Ad"), 1.0),
                Combo::new(c("Ah"), c("As"), 3.0),
            ],
            vec![Combo::new(c("Kh"), c("Kd"), 1.0)],
        ];
        let tree = Tree {
            board: board.clone(),
            root: Node::Decision {
                id: 0,
                player: Player::Oop,
                actions: vec![Action::Check, Action::Bet(Chips::whole(8))],
                children: vec![
                    Node::Terminal(Terminal::Fold {
                        winner: Player::Oop,
                        invested: [8.0, 8.0],
                    }),
                    Node::Terminal(Terminal::Fold {
                        winner: Player::Ip,
                        invested: [8.0, 8.0],
                    }),
                ],
            },
            num_decision_nodes: 1,
        };
        let mut trainer = Trainer::new(
            tree,
            combos,
            TrainerOptions {
                algorithm: SolverAlgorithm::Dcfr,
                abstraction: CardAbstraction {
                    river: Some(1),
                    ..CardAbstraction::default()
                },
                ..TrainerOptions::default()
            },
        )
        .unwrap();
        assert_eq!(trainer.train(1), [0.0, 0.0]);
        {
            let data = trainer.node_data[0].lock().unwrap();
            // Uniform strategy gives instantaneous regret +/-8. At t=1
            // both signs discount by 1/2, and total strategy mass 4 by 1/4.
            assert_eq!(data.regret_sum, vec![vec![4.0], vec![-4.0]]);
            assert_eq!(data.strategy_sum, vec![vec![0.5], vec![0.5]]);
        }
        assert_eq!(trainer.train(1), [32.0, -32.0]);
        {
            let data = trainer.node_data[0].lock().unwrap();
            let positive = 2.0_f64.powf(1.5);
            assert_eq!(data.regret_sum[0][0], 4.0 * positive / (positive + 1.0));
            // The action now always loses 16 relative to the current action;
            // both the old -4 and new -16 are discounted together.
            assert_eq!(data.regret_sum[1][0], -10.0);
            assert_eq!(data.strategy_sum[0][0], 2.0);
            assert_eq!(data.strategy_sum[1][0], 2.0 / 9.0);
        }
        // Iteration weights are 1^2:2^2, so (.5+4)/5 = .9.
        for probability in &trainer.average_strategy(0)[0] {
            assert!((probability - 0.9).abs() < 1e-15);
        }
    }

    #[test]
    fn chunking_preserves_all_update_state_through_chance_nodes() {
        let pool = rayon::ThreadPoolBuilder::new()
            .num_threads(1)
            .build()
            .unwrap();
        pool.install(|| {
            let c = |s: &str| s.parse::<Card>().unwrap();
            let cfg = GameConfig {
                board: ["2c", "7d", "9h", "Js"].map(c).to_vec(),
                pot: Chips::whole(2),
                effective_stack: Chips::whole(1),
                bet_sizes: vec![0.5],
                max_raises: 0,
                suit_isomorphism: false,
            };
            let combos = [
                vec![
                    Combo::new(c("Jh"), c("Jd"), 0.7),
                    Combo::new(c("Ac"), c("Kd"), 1.0),
                ],
                vec![Combo::new(c("7h"), c("6s"), 1.0)],
            ];
            for (algorithm, schedule) in [
                SolverAlgorithm::Cfr,
                SolverAlgorithm::CfrPlus,
                SolverAlgorithm::Dcfr,
            ]
            .into_iter()
            .flat_map(|a| {
                [UpdateSchedule::Simultaneous, UpdateSchedule::Alternating].map(|s| (a, s))
            }) {
                let make = || {
                    Trainer::new(
                        build_tree(&cfg).unwrap(),
                        combos.clone(),
                        TrainerOptions {
                            algorithm,
                            schedule,
                            abstraction: CardAbstraction {
                                river: Some(2),
                                ..CardAbstraction::default()
                            },
                        },
                    )
                    .unwrap()
                };
                let mut whole = make();
                let mut chunks = make();
                let expected = whole.train(11);
                chunks.train(3);
                chunks.train(0);
                assert_eq!(chunks.train(8), expected, "{algorithm:?}");
                assert_eq!(whole.iterations_completed(), 11);
                assert_eq!(chunks.iterations_completed(), 11);
                for (a, b) in whole.node_data.iter().zip(&chunks.node_data) {
                    let a = a.lock().unwrap();
                    let b = b.lock().unwrap();
                    assert_eq!(a.regret_sum, b.regret_sum, "{algorithm:?}");
                    assert_eq!(a.strategy_sum, b.strategy_sum, "{algorithm:?}");
                }
            }
        });
    }

    fn river_board() -> Vec<Card> {
        ["2h", "7c", "9d", "Jc", "4s"]
            .iter()
            .map(|s| s.parse::<Card>().unwrap())
            .collect()
    }

    struct Scenario {
        tree: super::super::tree::Tree,
        trainer_combos: [Vec<Combo>; 2],
        pot: f64,
        bet: f64,
    }

    fn build_scenario() -> Scenario {
        let board = river_board();
        let dead = CardSet::from_cards(&board);
        // OOP: JJ (value, always beats IP's 99) + KQo (air, always loses to IP's 99).
        let oop_range = Range::parse("JJ,KQo").unwrap();
        // IP: 99 (bluffcatcher — beats KQo, loses to JJ).
        let ip_range = Range::parse("99").unwrap();
        let oop_combos = oop_range.combos(dead);
        let ip_combos = ip_range.combos(dead);

        let pot = 100.0;
        let bet = 100.0; // pot-size bet
        let cfg = GameConfig {
            board: board.clone(),
            pot: Chips::from_f64(pot).unwrap(),
            effective_stack: Chips::whole(200),
            bet_sizes: vec![bet / pot],
            max_raises: 0,
            suit_isomorphism: false,
        };
        let tree = build_tree(&cfg).unwrap();
        Scenario {
            tree,
            trainer_combos: [oop_combos, ip_combos],
            pot,
            bet,
        }
    }

    fn is_jj(c1: Card, c2: Card) -> bool {
        c1.rank() == 9 && c2.rank() == 9 // J = rank index 9
    }

    #[test]
    fn zero_sum_at_root() {
        let scenario = build_scenario();
        let mut trainer = Trainer::new(
            scenario.tree,
            scenario.trainer_combos,
            TrainerOptions {
                algorithm: SolverAlgorithm::CfrPlus,
                ..TrainerOptions::default()
            },
        )
        .unwrap();
        let [ev0, ev1] = trainer.train(20_000);
        assert!(
            (ev0 + ev1).abs() < 1.0,
            "expected zero-sum root EV, got ev0={ev0}, ev1={ev1}"
        );
    }

    #[test]
    fn converges_to_known_bet_and_call_frequencies() {
        let scenario = build_scenario();
        let value_combo_count = scenario.trainer_combos[0]
            .iter()
            .filter(
                |&&Combo {
                     cards: [c1, c2], ..
                 }| is_jj(c1, c2),
            )
            .count();
        let bluff_combo_count = scenario.trainer_combos[0].len() - value_combo_count;
        let wv = value_combo_count as f64;
        let wb = bluff_combo_count as f64;
        let pot = scenario.pot;
        let bet = scenario.bet;

        let root_id = match &scenario.tree.root {
            Node::Decision { id, .. } => *id,
            _ => panic!("expected decision"),
        };
        let ip_facing_bet_id = match &scenario.tree.root {
            Node::Decision { children, .. } => match &children[1] {
                Node::Decision { id, .. } => *id,
                _ => panic!("expected IP decision facing the bet"),
            },
            _ => panic!("expected decision"),
        };

        let combos0 = scenario.trainer_combos[0].clone();
        let mut trainer = Trainer::new(
            scenario.tree,
            scenario.trainer_combos,
            TrainerOptions {
                algorithm: SolverAlgorithm::CfrPlus,
                ..TrainerOptions::default()
            },
        )
        .unwrap();
        trainer.train(60_000);

        let root_strategy = trainer.average_strategy(root_id); // [action][combo], action 1 = Bet
        let combos0 = &combos0;
        let bet_freq_value: Vec<f64> = combos0
            .iter()
            .enumerate()
            .filter(
                |(
                    _,
                    &Combo {
                        cards: [c1, c2], ..
                    },
                )| is_jj(c1, c2),
            )
            .map(|(i, _)| root_strategy[1][i])
            .collect();
        let bet_freq_bluff: Vec<f64> = combos0
            .iter()
            .enumerate()
            .filter(
                |(
                    _,
                    &Combo {
                        cards: [c1, c2], ..
                    },
                )| !is_jj(c1, c2),
            )
            .map(|(i, _)| root_strategy[1][i])
            .collect();

        let tol = 0.05;
        for f in &bet_freq_value {
            assert!(
                (f - 1.0).abs() < tol,
                "value combo should always bet, got {f}"
            );
        }
        let expected_beta = (bet / (pot + bet)) * (wv / wb);
        for f in &bet_freq_bluff {
            assert!(
                (f - expected_beta).abs() < tol,
                "expected bluff bet freq {expected_beta}, got {f}"
            );
        }

        let ip_strategy = trainer.average_strategy(ip_facing_bet_id); // action 1 = Call
        let expected_call = pot / (pot + bet); // MDF
        for &f in &ip_strategy[1] {
            assert!(
                (f - expected_call).abs() < tol,
                "expected call freq (MDF) {expected_call}, got {f}"
            );
        }
    }

    // --- Multi-street (turn -> chance node deals the river -> river betting) ---
    //
    // Board starts on the turn (4 cards); a single chance node deals all 48
    // possible river cards. The hands below were checked to keep the same win/lose
    // ordering across *every* possible river card.
    //
    // Unlike the single-street scenario, reaching the river here still
    // leaves a full betting round before showdown, so the single-street closed-form
    // bluff-frequency formula (which assumed an immediate showdown) no
    // longer applies exactly — a genuine multi-street equilibrium can bluff
    // at a different rate once the value of retaining bluffs into a further
    // street of betting is accounted for. Empirically, two of the three
    // single-street relationships still hold almost
    // exactly even with a full river betting round: value bets ~100% of the
    // time, and IP's calling frequency still matches the pot-odds MDF
    // formula. Only the bluffing frequency itself shifts. So this test
    // checks those two robust relationships precisely, and checks the
    // bluffing frequency only qualitatively (genuine interior mixing, and
    // identical across combos of the same hand type).
    fn turn_board() -> Vec<Card> {
        ["2c", "7d", "9h", "Js"]
            .iter()
            .map(|s| s.parse::<Card>().unwrap())
            .collect()
    }

    struct MultiStreetScenario {
        tree: super::super::tree::Tree,
        trainer_combos: [Vec<Combo>; 2],
        pot: f64,
        bet: f64,
    }

    /// `Range::combos()` iterates a `HashMap<String, f64>` internally, whose
    /// element order isn't guaranteed to match between two independently
    /// parsed `Range`s (see the suit-isomorphism equivalence test's doc
    /// comment for the same pitfall) — build these once and share/clone
    /// them across trainers being compared, rather than calling
    /// `build_multi_street_scenario()` (which re-parses fresh) more than once.
    fn multi_street_scenario_combos() -> [Vec<Combo>; 2] {
        let dead = CardSet::from_cards(&turn_board());
        // OOP: JJ (value, always beats IP's 76o on any river) + 54o (air, always loses).
        let oop_combos = Range::parse("JJ,54o").unwrap().combos(dead);
        // IP: 76o (bluffcatcher — always beats 54o, always loses to JJ, on any river).
        let ip_combos = Range::parse("76o").unwrap().combos(dead);
        [oop_combos, ip_combos]
    }

    fn build_multi_street_scenario() -> MultiStreetScenario {
        build_multi_street_scenario_with_combos(multi_street_scenario_combos())
    }

    fn build_multi_street_scenario_with_combos(
        trainer_combos: [Vec<Combo>; 2],
    ) -> MultiStreetScenario {
        let board = turn_board();
        let pot = 100.0;
        let bet = 100.0;
        let cfg = GameConfig {
            board: board.clone(),
            pot: Chips::from_f64(pot).unwrap(),
            effective_stack: Chips::whole(200),
            bet_sizes: vec![bet / pot],
            max_raises: 0,
            suit_isomorphism: false,
        };
        let tree = build_tree(&cfg).unwrap();
        MultiStreetScenario {
            tree,
            trainer_combos,
            pot,
            bet,
        }
    }

    fn is_pocket_jacks(c1: Card, c2: Card) -> bool {
        c1.rank() == 9 && c2.rank() == 9
    }

    #[test]
    fn multi_street_zero_sum_at_root() {
        let scenario = build_multi_street_scenario();
        let mut trainer = Trainer::new(
            scenario.tree,
            scenario.trainer_combos,
            TrainerOptions {
                algorithm: SolverAlgorithm::CfrPlus,
                ..TrainerOptions::default()
            },
        )
        .unwrap();
        let [ev0, ev1] = trainer.train(500);
        assert!(
            (ev0 + ev1).abs() < 1.0,
            "expected zero-sum root EV, got ev0={ev0}, ev1={ev1}"
        );
    }

    #[test]
    fn multi_street_value_bets_and_ip_defends_at_mdf() {
        let scenario = build_multi_street_scenario();
        let pot = scenario.pot;
        let bet = scenario.bet;

        let root_id = match &scenario.tree.root {
            Node::Decision { id, .. } => *id,
            _ => panic!("expected decision"),
        };
        let ip_facing_bet_id = match &scenario.tree.root {
            Node::Decision { children, .. } => match &children[1] {
                Node::Decision { id, .. } => *id,
                _ => panic!("expected IP decision facing the bet"),
            },
            _ => panic!("expected decision"),
        };

        let combos0 = scenario.trainer_combos[0].clone();
        let mut trainer = Trainer::new(
            scenario.tree,
            scenario.trainer_combos,
            TrainerOptions {
                algorithm: SolverAlgorithm::CfrPlus,
                ..TrainerOptions::default()
            },
        )
        .unwrap();
        trainer.train(4_000);

        let root_strategy = trainer.average_strategy(root_id); // [action][combo], action 1 = Bet
        let bet_freq_value: Vec<f64> = combos0
            .iter()
            .enumerate()
            .filter(
                |(
                    _,
                    &Combo {
                        cards: [c1, c2], ..
                    },
                )| is_pocket_jacks(c1, c2),
            )
            .map(|(i, _)| root_strategy[1][i])
            .collect();
        let bet_freq_bluff: Vec<f64> = combos0
            .iter()
            .enumerate()
            .filter(
                |(
                    _,
                    &Combo {
                        cards: [c1, c2], ..
                    },
                )| !is_pocket_jacks(c1, c2),
            )
            .map(|(i, _)| root_strategy[1][i])
            .collect();

        let tol = 0.08;
        // Slightly looser: pure-value combos should approach betting 100%
        // of the time, but CFR+'s average strategy converges at O(1/sqrt(T))
        // and this scenario's tree got noticeably bigger once the
        // board-conflict exclusion fix (see the cfr.rs module doc)
        // stopped a phantom-combo bug from artificially accelerating early
        // convergence, so this specific check needs a bit more slack at a
        // fixed, debug-build-friendly iteration count.
        let value_bet_tol = 0.1;
        for f in &bet_freq_value {
            assert!(
                (f - 1.0).abs() < value_bet_tol,
                "value combo should always bet, got {f}"
            );
        }

        // Bluffing frequency: checked only qualitatively (see comment above)
        // — genuine interior mixing, not degenerate, and identical across
        // combos of the same hand type (verifies symmetric combos are
        // treated symmetrically by the chance-node averaging).
        let bluff_avg = bet_freq_bluff.iter().sum::<f64>() / bet_freq_bluff.len() as f64;
        assert!(
            (0.01..0.9).contains(&bluff_avg),
            "expected genuine interior bluff mixing, got {bluff_avg}"
        );
        for f in &bet_freq_bluff {
            assert!((f - bluff_avg).abs() < 0.02, "combos of the same hand type should bet at the same frequency, got {f} vs avg {bluff_avg}");
        }
        assert!(
            bluff_avg < bet_freq_value[0],
            "bluffs should bet less often than value, got bluff={bluff_avg}, value={}",
            bet_freq_value[0]
        );

        let ip_strategy = trainer.average_strategy(ip_facing_bet_id); // action 1 = Call
        let expected_call = pot / (pot + bet); // MDF
        for &f in &ip_strategy[1] {
            assert!(
                (f - expected_call).abs() < tol,
                "expected call freq (MDF) {expected_call}, got {f}"
            );
        }
    }

    // --- Suit isomorphism: reduced (chance-node classes + relabeling)
    // must converge to the same equilibrium as unreduced (one child per
    // card), since it's purely a computational grouping and shouldn't
    // change the underlying extensive-form game at all.

    fn two_suit_turn_board() -> Vec<Card> {
        // Only clubs and diamonds on board -> hearts and spades are both
        // free, so river deals actually get grouped into classes of size
        // up to 2 (unlike `turn_board()`, which is rainbow and gets no
        // isomorphism reduction at all).
        ["2c", "7d", "9c", "Jd"]
            .iter()
            .map(|s| s.parse::<Card>().unwrap())
            .collect()
    }

    /// `Range::combos()` iterates a `HashMap<String, f64>` internally, whose
    /// element order isn't guaranteed to match between two independently
    /// parsed `Range`s (std `HashMap`'s per-instance hasher keys differ) —
    /// so building the reduced/unreduced scenarios from two separate
    /// `Range::parse` calls would silently compare unrelated combos
    /// position-wise. Build the combo lists once and share them so "combo
    /// index i" means the same physical combo in both trainers.
    fn build_two_suit_scenario(
        suit_isomorphism: bool,
        trainer_combos: [Vec<Combo>; 2],
    ) -> MultiStreetScenario {
        let board = two_suit_turn_board();
        let pot = 100.0;
        let bet = 100.0;
        let cfg = GameConfig {
            board: board.clone(),
            pot: Chips::from_f64(pot).unwrap(),
            effective_stack: Chips::whole(200),
            bet_sizes: vec![bet / pot],
            max_raises: 0,
            suit_isomorphism,
        };
        let tree = build_tree(&cfg).unwrap();
        MultiStreetScenario {
            tree,
            trainer_combos,
            pot,
            bet,
        }
    }

    fn two_suit_scenario_combos() -> [Vec<Combo>; 2] {
        let dead = CardSet::from_cards(&two_suit_turn_board());
        let oop_combos = Range::parse("JJ,54o").unwrap().combos(dead);
        let ip_combos = Range::parse("76o").unwrap().combos(dead);
        [oop_combos, ip_combos]
    }

    #[test]
    fn suit_isomorphism_actually_reduces_the_tree() {
        let combos = two_suit_scenario_combos();
        let reduced = build_two_suit_scenario(true, combos.clone());
        let unreduced = build_two_suit_scenario(false, combos);
        assert!(
            reduced.tree.num_decision_nodes < unreduced.tree.num_decision_nodes,
            "expected fewer decision nodes with isomorphism enabled, got {} (reduced) vs {} (unreduced)",
            reduced.tree.num_decision_nodes,
            unreduced.tree.num_decision_nodes
        );
    }

    /// Node ids are allocated in preorder during `build()`, so the "check"
    /// branch (built before the "bet" branch) consumes a different number
    /// of ids depending on how much the chance node inside it is reduced —
    /// the same numeric id can point at unrelated nodes in the reduced vs.
    /// unreduced trees. So ids must be looked up per-tree, not shared.
    fn root_and_ip_facing_bet_ids(root: &Node) -> (usize, usize) {
        let Node::Decision {
            id: root_id,
            children,
            ..
        } = root
        else {
            panic!("expected decision")
        };
        let Node::Decision {
            id: ip_facing_bet_id,
            ..
        } = &children[1]
        else {
            panic!("expected IP decision facing the bet")
        };
        (*root_id, *ip_facing_bet_id)
    }

    #[test]
    fn suit_isomorphism_reduced_and_unreduced_converge_to_the_same_equilibrium() {
        let combos = two_suit_scenario_combos();
        let reduced = build_two_suit_scenario(true, combos.clone());
        let unreduced = build_two_suit_scenario(false, combos);

        let (reduced_root_id, reduced_ip_facing_bet_id) =
            root_and_ip_facing_bet_ids(&reduced.tree.root);
        let (unreduced_root_id, unreduced_ip_facing_bet_id) =
            root_and_ip_facing_bet_ids(&unreduced.tree.root);

        let iterations = 3_000;
        let mut reduced_trainer = Trainer::new(
            reduced.tree,
            reduced.trainer_combos,
            TrainerOptions {
                algorithm: SolverAlgorithm::CfrPlus,
                ..TrainerOptions::default()
            },
        )
        .unwrap();
        reduced_trainer.train(iterations);
        let mut unreduced_trainer = Trainer::new(
            unreduced.tree,
            unreduced.trainer_combos,
            TrainerOptions {
                algorithm: SolverAlgorithm::CfrPlus,
                ..TrainerOptions::default()
            },
        )
        .unwrap();
        unreduced_trainer.train(iterations);

        let tol = 0.05;
        for (row_r, row_u) in reduced_trainer
            .average_strategy(reduced_root_id)
            .iter()
            .zip(unreduced_trainer.average_strategy(unreduced_root_id).iter())
        {
            for (&fr, &fu) in row_r.iter().zip(row_u.iter()) {
                assert!(
                    (fr - fu).abs() < tol,
                    "root strategy mismatch: reduced={fr}, unreduced={fu}"
                );
            }
        }
        for (row_r, row_u) in reduced_trainer
            .average_strategy(reduced_ip_facing_bet_id)
            .iter()
            .zip(
                unreduced_trainer
                    .average_strategy(unreduced_ip_facing_bet_id)
                    .iter(),
            )
        {
            for (&fr, &fu) in row_r.iter().zip(row_u.iter()) {
                assert!(
                    (fr - fu).abs() < tol,
                    "IP-facing-bet strategy mismatch: reduced={fr}, unreduced={fu}"
                );
            }
        }
    }

    // --- River card abstraction (bucketing) ---

    #[test]
    fn compute_percentile_buckets_is_monotonic_and_bijective_when_large_enough() {
        let scores = [30.0, 10.0, 20.0, 10.0, 40.0];
        let n = scores.len();

        // A bucket count >= the combo count must be an exact bijection
        // *over distinct scores*: every combo its own bucket, in score
        // order, except that combos 1 and 3 (tied at 10.0) must always
        // share a bucket (see `compute_percentile_buckets_never_splits_a_tie`)
        // — so 4 distinct buckets for 5 combos here, not 5.
        let bijective = compute_percentile_buckets(&scores, 100);
        assert_eq!(
            bijective[1], bijective[3],
            "tied scores must share a bucket, got {bijective:?}"
        );
        let mut seen = std::collections::HashSet::new();
        for (i, &b) in bijective.iter().enumerate() {
            if i == 3 {
                continue; // shares combo 1's bucket, already recorded
            }
            assert!(
                seen.insert(b),
                "expected every distinct-score combo to get a distinct bucket, got {bijective:?}"
            );
        }
        // Monotonic: a strictly higher score never lands in a lower bucket.
        for i in 0..n {
            for j in 0..n {
                if scores[i] < scores[j] {
                    assert!(
                        bijective[i] <= bijective[j],
                        "score {} (bucket {}) should not outrank score {} (bucket {})",
                        scores[i],
                        bijective[i],
                        scores[j],
                        bijective[j]
                    );
                }
            }
        }

        // A small bucket count must actually merge combos (fewer distinct
        // buckets used than combos) while staying monotonic and in range.
        let reduced = compute_percentile_buckets(&scores, 2);
        let distinct: std::collections::HashSet<usize> = reduced.iter().copied().collect();
        assert!(
            distinct.len() <= 2,
            "expected at most 2 distinct buckets, got {distinct:?}"
        );
        assert!(reduced.iter().all(|&b| b < 2));
        for i in 0..n {
            for j in 0..n {
                if scores[i] < scores[j] {
                    assert!(reduced[i] <= reduced[j]);
                }
            }
        }
    }

    /// `river_buckets: Some(n)` with `n` at least as large as either
    /// player's combo count must be a bijection (see
    /// `compute_percentile_buckets_is_monotonic_and_bijective_when_large_enough`),
    /// so it must converge to the same equilibrium as `None` — this is the
    /// same kind of equivalence check as suit isomorphism's, and also
    /// exercises the board_eval_cache fix for a solve that starts already
    /// at a complete river board (no `Chance` node at all, so
    /// `precompute_board_eval` alone would never seed a bucket map for it).
    #[test]
    fn river_buckets_bijective_matches_unbucketed() {
        let board = river_board();
        let dead = CardSet::from_cards(&board);
        let oop_combos = Range::parse("JJ,KQo").unwrap().combos(dead);
        let ip_combos = Range::parse("99").unwrap().combos(dead);
        let pot = 100.0;
        let bet = 100.0;
        let cfg = GameConfig {
            board: board.clone(),
            pot: Chips::from_f64(pot).unwrap(),
            effective_stack: Chips::whole(200),
            bet_sizes: vec![bet / pot],
            max_raises: 0,
            suit_isomorphism: false,
        };

        let tree_none = build_tree(&cfg).unwrap();
        let tree_bucketed = build_tree(&cfg).unwrap();
        let (root_id, ip_facing_bet_id) = root_and_ip_facing_bet_ids(&tree_none.root);

        let iterations = 3_000;
        let mut trainer_none = Trainer::new(
            tree_none,
            [oop_combos.clone(), ip_combos.clone()],
            TrainerOptions {
                algorithm: SolverAlgorithm::CfrPlus,
                ..TrainerOptions::default()
            },
        )
        .unwrap();
        trainer_none.train(iterations);
        // 100 exceeds both players' combo counts here, so this is a bijection on both sides.
        let mut trainer_bucketed = Trainer::new(
            tree_bucketed,
            [oop_combos, ip_combos],
            TrainerOptions {
                algorithm: SolverAlgorithm::CfrPlus,
                abstraction: CardAbstraction {
                    river: Some(100),
                    ..Default::default()
                },
                ..TrainerOptions::default()
            },
        )
        .unwrap();
        trainer_bucketed.train(iterations);

        let tol = 0.05;
        for (row_n, row_b) in trainer_none
            .average_strategy(root_id)
            .iter()
            .zip(trainer_bucketed.average_strategy(root_id).iter())
        {
            for (&fn_, &fb) in row_n.iter().zip(row_b.iter()) {
                assert!(
                    (fn_ - fb).abs() < tol,
                    "root strategy mismatch: none={fn_}, bucketed(bijective)={fb}"
                );
            }
        }
        for (row_n, row_b) in trainer_none
            .average_strategy(ip_facing_bet_id)
            .iter()
            .zip(trainer_bucketed.average_strategy(ip_facing_bet_id).iter())
        {
            for (&fn_, &fb) in row_n.iter().zip(row_b.iter()) {
                assert!(
                    (fn_ - fb).abs() < tol,
                    "IP-facing-bet strategy mismatch: none={fn_}, bucketed(bijective)={fb}"
                );
            }
        }
    }

    /// With a genuinely small bucket count, exact per-combo behavior isn't
    /// expected (that's the whole point of abstraction), but the trained
    /// strategy should still be sane: zero-sum at the root, and betting
    /// frequency should respect real hand-strength ordering across three
    /// clearly-separated tiers (trips > overpair > air) sharing only 3
    /// buckets between them.
    #[test]
    fn river_buckets_reduced_stays_zero_sum_and_respects_hand_strength_order() {
        let board = river_board(); // 2h 7c 9d Jc 4s
        let dead = CardSet::from_cards(&board);
        // OOP: JJ (trips jacks - top tier), QQ (overpair - middle tier),
        // KQo+72o (air, kicker-only - bottom tier).
        let oop_range = Range::parse("JJ,QQ,KQo,72o").unwrap();
        // IP: 99 (trips nines, beats everything but JJ) + 55 (a small
        // pocket pair unconnected to the board, beaten by QQ but ahead of
        // pure air). Giving IP a *range* instead of a single fixed hand
        // matters here: with IP holding only 99, QQ and air would both
        // simply always lose to IP's one possible hand, making them
        // strategically interchangeable "always-losing" bluff candidates
        // with no real reason for one to bet more than the other — 55
        // gives QQ genuine partial equity (it beats 55, loses to 99) so it
        // actually is a distinct middle tier.
        let ip_range = Range::parse("99,55").unwrap();
        let oop_combos = oop_range.combos(dead);
        let ip_combos = ip_range.combos(dead);

        let pot = 100.0;
        let bet = 100.0;
        let cfg = GameConfig {
            board: board.clone(),
            pot: Chips::from_f64(pot).unwrap(),
            effective_stack: Chips::whole(200),
            bet_sizes: vec![bet / pot],
            max_raises: 0,
            suit_isomorphism: false,
        };
        let tree = build_tree(&cfg).unwrap();
        let (root_id, _) = root_and_ip_facing_bet_ids(&tree.root);

        let combos0 = oop_combos.clone();
        let mut trainer = Trainer::new(
            tree,
            [oop_combos, ip_combos],
            TrainerOptions {
                algorithm: SolverAlgorithm::CfrPlus,
                abstraction: CardAbstraction {
                    river: Some(3),
                    ..Default::default()
                },
                ..TrainerOptions::default()
            },
        )
        .unwrap();
        let [ev0, ev1] = trainer.train(4_000);
        assert!(
            (ev0 + ev1).abs() < 1.0,
            "expected zero-sum root EV even under abstraction, got ev0={ev0}, ev1={ev1}"
        );

        let is_jj = |c1: Card, c2: Card| c1.rank() == 9 && c2.rank() == 9;
        let is_qq = |c1: Card, c2: Card| c1.rank() == 10 && c2.rank() == 10;
        let avg = |pred: &dyn Fn(Card, Card) -> bool, strategy: &[Vec<f64>]| -> f64 {
            let matching: Vec<f64> = combos0
                .iter()
                .enumerate()
                .filter(
                    |(
                        _,
                        &Combo {
                            cards: [c1, c2], ..
                        },
                    )| pred(c1, c2),
                )
                .map(|(i, _)| strategy[1][i]) // action 1 = Bet
                .collect();
            matching.iter().sum::<f64>() / matching.len() as f64
        };

        let root_strategy = trainer.average_strategy(root_id);
        let bet_freq_jj = avg(&is_jj, &root_strategy);
        let bet_freq_qq = avg(&is_qq, &root_strategy);
        let bet_freq_air = avg(&|c1, c2| !is_jj(c1, c2) && !is_qq(c1, c2), &root_strategy);

        // With only 3 buckets shared across 4 hand types, the top bucket
        // will typically end up merging JJ (only 3 combos, the very top of
        // the score range) with some of the next-highest-scoring QQ
        // combos — so an unbucketed-style ">90% bet" floor for JJ alone
        // isn't a fair expectation here; what abstraction should still
        // guarantee is that hand-strength order isn't inverted, and that
        // trips clearly bets more than pure air (not diluted down to it).
        let tol = 0.05;
        assert!(
            bet_freq_jj >= bet_freq_qq - tol,
            "trips should bet at least as often as the overpair tier, got jj={bet_freq_jj}, qq={bet_freq_qq}"
        );
        assert!(
            bet_freq_qq >= bet_freq_air - tol,
            "overpair should bet at least as often as pure air, got qq={bet_freq_qq}, air={bet_freq_air}"
        );
        assert!(
            bet_freq_jj > bet_freq_air + 0.1,
            "trips should still clearly out-bet pure air despite bucketing, got jj={bet_freq_jj}, air={bet_freq_air}"
        );
    }

    // --- Flop/turn card abstraction ---

    /// Cross-checks `avg_score`'s suit-isomorphism-class-weighted
    /// averaging against a naive full 1-card-at-a-time enumeration (no
    /// classes at all) — the same "fast path vs. reference" pattern
    /// `eval::evaluate_5` is validated with elsewhere in this codebase.
    /// Uses a two-suit board (like `two_suit_turn_board`) specifically so
    /// classes of size > 1 actually get exercised, not just trivial
    /// singletons.
    #[test]
    fn avg_score_matches_naive_full_enumeration_average() {
        let board = two_suit_turn_board(); // 2c 7d 9c Jd -- h/s free
        let dead = CardSet::from_cards(&board);
        let combos = Range::parse("JJ,54o").unwrap().combos(dead);
        let used = CardSet::from_cards(&board);

        let naive: Vec<f64> = combos
            .iter()
            .map(
                |&Combo {
                     cards: [h1, h2], ..
                 }| {
                    let mut sum = 0.0;
                    let mut count = 0.0;
                    for c in Card::all() {
                        if used.contains(c) || c == h1 || c == h2 {
                            continue;
                        }
                        let mut river = board.clone();
                        river.push(c);
                        let score =
                            score_7([h1, h2, river[0], river[1], river[2], river[3], river[4]]);
                        sum += score as f64;
                        count += 1.0;
                    }
                    sum / count
                },
            )
            .collect();

        let board_eval_cache = HashMap::new();
        let mut memo = HashMap::new();
        let combo_index = [build_combo_index(&combos), HashMap::new()];
        let via_classes = avg_score(
            &board,
            &[combos.clone(), Vec::new()],
            &combo_index,
            &board_eval_cache,
            &mut memo,
        );

        for (i, (&n, &c)) in naive.iter().zip(via_classes[0].iter()).enumerate() {
            assert!((n - c).abs() < 1e-9, "combo {i}: naive={n}, avg_score={c}");
        }
    }

    fn flop_board() -> Vec<Card> {
        // Monotone (all clubs) -> maximal isomorphism benefit (3 free
        // suits), keeping the two-chance-node tree small enough to train
        // quickly even without bucketing, for the equivalence check below.
        ["2c", "7c", "9c"]
            .iter()
            .map(|s| s.parse::<Card>().unwrap())
            .collect()
    }

    struct FlopScenario {
        tree: super::super::tree::Tree,
        trainer_combos: [Vec<Combo>; 2],
    }

    fn flop_scenario_combos() -> [Vec<Combo>; 2] {
        let dead = CardSet::from_cards(&flop_board());
        let oop_combos = Range::parse("JJ,54o").unwrap().combos(dead);
        let ip_combos = Range::parse("76o").unwrap().combos(dead);
        [oop_combos, ip_combos]
    }

    fn build_flop_scenario(trainer_combos: [Vec<Combo>; 2]) -> FlopScenario {
        let board = flop_board();
        let cfg = GameConfig {
            board: board.clone(),
            pot: Chips::whole(100),
            effective_stack: Chips::whole(200),
            bet_sizes: vec![1.0],
            max_raises: 0,
            suit_isomorphism: true,
        };
        let tree = build_tree(&cfg).unwrap();
        FlopScenario {
            tree,
            trainer_combos,
        }
    }

    /// `CardAbstraction { turn: Some(n), .. }` with `n` at least as large
    /// as either player's combo count must be a bijection on the turn
    /// street (same reasoning as `compute_percentile_buckets_...`), so it
    /// must converge to the same equilibrium as no abstraction at all.
    /// Uses `turn_board()`'s scenario directly (a solve that *starts*
    /// already at the turn — no chance node deals into it), which also
    /// exercises the "initial board" inclusion in `collect_reachable_boards`
    /// usage for turn/flop, mirroring the river case.
    #[test]
    fn turn_buckets_bijective_matches_unbucketed() {
        let combos = multi_street_scenario_combos();
        let scenario_none = build_multi_street_scenario_with_combos(combos.clone());
        let scenario_bucketed = build_multi_street_scenario_with_combos(combos);
        let (root_id, ip_facing_bet_id) = root_and_ip_facing_bet_ids(&scenario_none.tree.root);

        let iterations = 1_500;
        let mut trainer_none = Trainer::new(
            scenario_none.tree,
            scenario_none.trainer_combos,
            TrainerOptions {
                algorithm: SolverAlgorithm::CfrPlus,
                ..TrainerOptions::default()
            },
        )
        .unwrap();
        trainer_none.train(iterations);
        let mut trainer_bucketed = Trainer::new(
            scenario_bucketed.tree,
            scenario_bucketed.trainer_combos,
            TrainerOptions {
                algorithm: SolverAlgorithm::CfrPlus,
                abstraction: CardAbstraction {
                    turn: Some(100),
                    ..Default::default()
                },
                ..TrainerOptions::default()
            },
        )
        .unwrap();
        trainer_bucketed.train(iterations);

        let tol = 0.05;
        for (row_n, row_b) in trainer_none
            .average_strategy(root_id)
            .iter()
            .zip(trainer_bucketed.average_strategy(root_id).iter())
        {
            for (&fn_, &fb) in row_n.iter().zip(row_b.iter()) {
                assert!(
                    (fn_ - fb).abs() < tol,
                    "root strategy mismatch: none={fn_}, bucketed(bijective)={fb}"
                );
            }
        }
        for (row_n, row_b) in trainer_none
            .average_strategy(ip_facing_bet_id)
            .iter()
            .zip(trainer_bucketed.average_strategy(ip_facing_bet_id).iter())
        {
            for (&fn_, &fb) in row_n.iter().zip(row_b.iter()) {
                assert!(
                    (fn_ - fb).abs() < tol,
                    "IP-facing-bet strategy mismatch: none={fn_}, bucketed(bijective)={fb}"
                );
            }
        }
    }

    /// Same equivalence check, but on the flop: `CardAbstraction { flop:
    /// Some(n), .. }` bijective must match unabstracted, exercising a tree
    /// with *two* chance nodes (flop deals the turn, which deals the
    /// river) and `avg_score`'s two-level recursion.
    #[test]
    fn flop_buckets_bijective_matches_unbucketed() {
        let combos = flop_scenario_combos();
        let scenario_none = build_flop_scenario(combos.clone());
        let scenario_bucketed = build_flop_scenario(combos);
        let (root_id, ip_facing_bet_id) = root_and_ip_facing_bet_ids(&scenario_none.tree.root);

        let iterations = 300;
        let mut trainer_none = Trainer::new(
            scenario_none.tree,
            scenario_none.trainer_combos,
            TrainerOptions {
                algorithm: SolverAlgorithm::CfrPlus,
                ..TrainerOptions::default()
            },
        )
        .unwrap();
        trainer_none.train(iterations);
        let mut trainer_bucketed = Trainer::new(
            scenario_bucketed.tree,
            scenario_bucketed.trainer_combos,
            TrainerOptions {
                algorithm: SolverAlgorithm::CfrPlus,
                abstraction: CardAbstraction {
                    flop: Some(100),
                    ..Default::default()
                },
                ..TrainerOptions::default()
            },
        )
        .unwrap();
        trainer_bucketed.train(iterations);

        let tol = 0.08;
        for (row_n, row_b) in trainer_none
            .average_strategy(root_id)
            .iter()
            .zip(trainer_bucketed.average_strategy(root_id).iter())
        {
            for (&fn_, &fb) in row_n.iter().zip(row_b.iter()) {
                assert!(
                    (fn_ - fb).abs() < tol,
                    "root strategy mismatch: none={fn_}, bucketed(bijective)={fb}"
                );
            }
        }
        for (row_n, row_b) in trainer_none
            .average_strategy(ip_facing_bet_id)
            .iter()
            .zip(trainer_bucketed.average_strategy(ip_facing_bet_id).iter())
        {
            for (&fn_, &fb) in row_n.iter().zip(row_b.iter()) {
                assert!(
                    (fn_ - fb).abs() < tol,
                    "IP-facing-bet strategy mismatch: none={fn_}, bucketed(bijective)={fb}"
                );
            }
        }
    }

    /// With a small turn bucket count, exact per-combo behavior isn't
    /// expected, but zero-sum should still hold and JJ (the only real
    /// value hand, always beating IP's fixed 76o) should still bet
    /// noticeably more than pure air (54o, which always loses) — the same
    /// kind of sanity check as the river's reduced-bucket test, adapted to
    /// a street where the strength proxy is `avg_score`, not a final
    /// `evaluate_7` score.
    #[test]
    fn turn_buckets_reduced_stays_zero_sum_and_respects_hand_strength_order() {
        let scenario = build_multi_street_scenario();
        let (root_id, _) = root_and_ip_facing_bet_ids(&scenario.tree.root);
        let combos0 = scenario.trainer_combos[0].clone();

        let mut trainer = Trainer::new(
            scenario.tree,
            scenario.trainer_combos,
            TrainerOptions {
                algorithm: SolverAlgorithm::CfrPlus,
                abstraction: CardAbstraction {
                    turn: Some(2),
                    ..Default::default()
                },
                ..TrainerOptions::default()
            },
        )
        .unwrap();
        let [ev0, ev1] = trainer.train(1_500);
        assert!(
            (ev0 + ev1).abs() < 1.0,
            "expected zero-sum root EV even under turn abstraction, got ev0={ev0}, ev1={ev1}"
        );

        let is_jj = |c1: Card, c2: Card| c1.rank() == 9 && c2.rank() == 9;
        let root_strategy = trainer.average_strategy(root_id);
        let bet_freq_jj: Vec<f64> = combos0
            .iter()
            .enumerate()
            .filter(
                |(
                    _,
                    &Combo {
                        cards: [c1, c2], ..
                    },
                )| is_jj(c1, c2),
            )
            .map(|(i, _)| root_strategy[1][i])
            .collect();
        let bet_freq_air: Vec<f64> = combos0
            .iter()
            .enumerate()
            .filter(
                |(
                    _,
                    &Combo {
                        cards: [c1, c2], ..
                    },
                )| !is_jj(c1, c2),
            )
            .map(|(i, _)| root_strategy[1][i])
            .collect();
        let avg_jj = bet_freq_jj.iter().sum::<f64>() / bet_freq_jj.len() as f64;
        let avg_air = bet_freq_air.iter().sum::<f64>() / bet_freq_air.len() as f64;
        assert!(avg_jj > avg_air + 0.1, "value should still clearly out-bet air despite turn bucketing, got jj={avg_jj}, air={avg_air}");
    }

    /// A naive rank-based percentile split can place two *exactly tied*
    /// scores into different buckets purely because their sort positions
    /// straddle a cut point. That's specifically dangerous under suit
    /// isomorphism: two combos related by a free-suit swap always get the
    /// identical `avg_score` (a provable symmetry — the whole future
    /// board/outcome distribution is suit-blind), and `chance_value`'s
    /// relabeling assumes such combos always share one strategy, so
    /// splitting their tie across a bucket boundary would silently break
    /// that invariant. Regression test for exactly that bug, found via
    /// `flop_and_isomorphism_interaction_stays_zero_sum` below.
    #[test]
    fn compute_percentile_buckets_never_splits_a_tie() {
        let scores = [10.0, 10.0, 10.0, 20.0, 20.0, 30.0, 40.0, 40.0];
        for num_buckets in 1..=scores.len() {
            let buckets = compute_percentile_buckets(&scores, num_buckets);
            for (a, b) in [(0, 1), (1, 2), (3, 4), (6, 7)] {
                assert_eq!(
                    buckets[a], buckets[b],
                    "num_buckets={num_buckets}: tied scores {}/{} got different buckets {:?}",
                    scores[a], scores[b], buckets
                );
            }
        }
    }

    /// Regression test for a real bug found while building flop/turn
    /// abstraction: with isomorphism enabled, `chance_value`'s relabeling
    /// requires every ancestor decision node (bucketed or not) to treat
    /// suit-swap-equivalent combos identically. A flop decision node
    /// bucketed by `avg_score` broke that when tied scores landed in
    /// different buckets (fixed by `compute_percentile_buckets_never_splits_a_tie`'s
    /// fix) — the visible symptom was the root EV silently losing its
    /// zero-sum property at some iteration counts (but not others,
    /// depending on when the bucket-shared regret happened to matter),
    /// entirely deterministically (not a floating-point/thread-ordering
    /// issue — reproduced bit-for-bit across repeated runs), which is why
    /// this checks several iteration counts, not just one.
    #[test]
    fn flop_and_isomorphism_interaction_stays_zero_sum() {
        for iters in [1u32, 5, 20, 100] {
            let combos = flop_scenario_combos();
            let scenario = build_flop_scenario(combos);
            let mut trainer = Trainer::new(
                scenario.tree,
                scenario.trainer_combos,
                TrainerOptions {
                    algorithm: SolverAlgorithm::CfrPlus,
                    abstraction: CardAbstraction {
                        flop: Some(2),
                        ..Default::default()
                    },
                    ..TrainerOptions::default()
                },
            )
            .unwrap();
            let [ev0, ev1] = trainer.train(iters);
            assert!(
                (ev0 + ev1).abs() < 1e-6,
                "iters={iters}: expected exact zero-sum, got ev0={ev0}, ev1={ev1}, sum={}",
                ev0 + ev1
            );
        }
    }

    // --- EV / equity (Trainer::evaluate) ---

    #[test]
    fn evaluate_average_strategy_root_ev_is_zero_sum() {
        let scenario = build_scenario();
        let mut trainer = Trainer::new(
            scenario.tree,
            scenario.trainer_combos,
            TrainerOptions {
                algorithm: SolverAlgorithm::CfrPlus,
                ..TrainerOptions::default()
            },
        )
        .unwrap();
        trainer.train(20_000);
        let [ev0, ev1] = trainer.evaluate().root_values;
        assert!(
            (ev0 + ev1).abs() < 1.0,
            "expected zero-sum root EV under the average strategy, got ev0={ev0}, ev1={ev1}"
        );
    }

    /// `river_board()`'s scenario (`build_scenario`) has a known winner at
    /// showdown: OOP's JJ always beats IP's fixed 99, OOP's KQo always
    /// loses to it. Equity is exact and cheap at a river (complete-board)
    /// node, so this checks it directly against hand-derived values,
    /// unlike EV (which folds in betting and is only checked qualitatively
    /// elsewhere).
    #[test]
    fn river_equity_matches_known_showdown_outcomes() {
        let scenario = build_scenario();
        let root_id = match &scenario.tree.root {
            Node::Decision { id, .. } => *id,
            _ => panic!("expected decision"),
        };
        let combos0 = scenario.trainer_combos[0].clone();
        let mut trainer = Trainer::new(
            scenario.tree,
            scenario.trainer_combos,
            TrainerOptions {
                algorithm: SolverAlgorithm::CfrPlus,
                ..TrainerOptions::default()
            },
        )
        .unwrap();
        trainer.train(5_000);

        let eval = trainer.evaluate().nodes;
        let root_eval = eval.get(root_id).expect("root should have an evaluation");
        let equity = root_eval
            .equity
            .as_ref()
            .expect("river (complete board) node should have equity");

        for (
            i,
            &Combo {
                cards: [c1, c2], ..
            },
        ) in combos0.iter().enumerate()
        {
            if is_jj(c1, c2) {
                assert!(
                    (equity[i] - 1.0).abs() < 1e-9,
                    "JJ should have 100% equity vs IP's fixed 99, got {}",
                    equity[i]
                );
            } else {
                assert!(
                    equity[i].abs() < 1e-9,
                    "KQo should have 0% equity vs IP's fixed 99, got {}",
                    equity[i]
                );
            }
        }
    }

    /// Equity is only computed where it's cheap and exact (a complete
    /// board) — see `NodeEvaluation`'s doc comment for why flop/turn
    /// equity isn't implemented yet. A pre-river node's evaluation should
    /// still have a sensible EV, just no equity figure.
    #[test]
    fn equity_is_none_before_the_river() {
        let scenario = build_multi_street_scenario(); // starts at the turn, one chance node to the river
        let root_id = match &scenario.tree.root {
            Node::Decision { id, .. } => *id,
            _ => panic!("expected decision"),
        };
        let mut trainer = Trainer::new(
            scenario.tree,
            scenario.trainer_combos,
            TrainerOptions {
                algorithm: SolverAlgorithm::CfrPlus,
                ..TrainerOptions::default()
            },
        )
        .unwrap();
        trainer.train(500);

        let eval = trainer.evaluate().nodes;
        let root_eval = eval.get(root_id).expect("root should have an evaluation");
        assert!(
            root_eval.equity.is_none(),
            "expected no equity figure at a pre-river (incomplete board) node"
        );
        assert_eq!(
            root_eval.ev.len(),
            trainer.game.combos(Player::Oop).len(),
            "EV should still be reported per combo"
        );
    }

    /// Regression test for a normalization bug: the per-node `NodeEvaluation.ev`
    /// stored for display must be a true per-combo expected value, not the
    /// raw counterfactual value `v(I) = sum_j reach_opp[j] * payoff_j` used
    /// internally elsewhere in this module (a sum over the opponent's whole
    /// live range, which scales with the *number* of opponent combos and can
    /// be many times larger than any real outcome). In `build_scenario`, the
    /// most any combo can win is `pot + bet` (called and won) and the most it
    /// can lose is `bet` (called and lost), so every displayed EV must stay
    /// within that range — the un-normalized bug produced values in the
    /// hundreds to thousands, far outside it.
    #[test]
    fn evaluate_ev_is_normalized_per_combo_not_raw_counterfactual_value() {
        let scenario = build_scenario();
        let pot = scenario.pot;
        let bet = scenario.bet;
        let root_id = match &scenario.tree.root {
            Node::Decision { id, .. } => *id,
            _ => panic!("expected decision"),
        };
        let ip_facing_bet_id = match &scenario.tree.root {
            Node::Decision { children, .. } => match &children[1] {
                Node::Decision { id, .. } => *id,
                _ => panic!("expected IP decision facing the bet"),
            },
            _ => panic!("expected decision"),
        };

        let mut trainer = Trainer::new(
            scenario.tree,
            scenario.trainer_combos,
            TrainerOptions {
                algorithm: SolverAlgorithm::CfrPlus,
                ..TrainerOptions::default()
            },
        )
        .unwrap();
        trainer.train(20_000);
        let eval = trainer.evaluate().nodes;

        let bound = pot + bet;
        let root_eval = eval.get(root_id).expect("root should have an evaluation");
        for &ev in &root_eval.ev {
            assert!(
                ev.abs() <= bound + 1e-6,
                "root EV {ev} exceeds the game's stake bound of {bound}"
            );
        }
        let ip_eval = eval
            .get(ip_facing_bet_id)
            .expect("IP-facing-bet node should have an evaluation");
        for &ev in &ip_eval.ev {
            assert!(
                ev.abs() <= bound + 1e-6,
                "IP-facing-bet EV {ev} exceeds the game's stake bound of {bound}"
            );
        }

        // JJ always bets and always beats IP's fixed 99, so under the
        // converged average strategy its root EV should be close to
        // winning the pot every time it isn't check-through — strictly
        // positive, not just "in bounds".
        let combos0 = trainer.game.combos(Player::Oop);
        for (
            i,
            &Combo {
                cards: [c1, c2], ..
            },
        ) in combos0.iter().enumerate()
        {
            if is_jj(c1, c2) {
                assert!(
                    root_eval.ev[i] > 0.0,
                    "JJ should have positive EV, got {}",
                    root_eval.ev[i]
                );
            }
        }
    }

    // --- Exploitability (Trainer::exploitability) ---

    /// `Exploitability::total` is the standard `(BR0 + BR1) / 2` figure — it
    /// can never be meaningfully negative (best-responding to a fixed
    /// opponent strategy can never do worse than the strategy actually
    /// played) and shrinks toward 0 as training converges. Check the
    /// monotonic trend rather than an iteration-specific value; separate
    /// analytical tests below pin the units and normalization.
    #[test]
    fn policy_snapshot_is_frozen_and_matches_trainer_reads() {
        let board: Vec<Card> = ["2c", "7c", "9d", "Jd"]
            .iter()
            .map(|s| s.parse::<Card>().unwrap())
            .collect();
        let dead = CardSet::from_cards(&board);
        let combos = [
            Range::parse("AA:0.5,KK,QQ").unwrap().combos(dead),
            Range::parse("JJ,TT").unwrap().combos(dead),
        ];
        let cfg = GameConfig {
            board: board.clone(),
            pot: Chips::whole(100),
            effective_stack: Chips::whole(150),
            bet_sizes: vec![0.5, 1.0],
            max_raises: 1,
            suit_isomorphism: true,
        };
        let abstraction = CardAbstraction {
            river: Some(2),
            ..CardAbstraction::default()
        };
        let make = || {
            Trainer::new(
                build_tree(&cfg).unwrap(),
                combos.clone(),
                TrainerOptions {
                    algorithm: SolverAlgorithm::Dcfr,
                    abstraction,
                    ..TrainerOptions::default()
                },
            )
            .unwrap()
        };
        let bits = |evaluation: Evaluation| {
            let nodes: Vec<Vec<u64>> = evaluation
                .nodes
                .iter()
                .map(|e| e.ev.iter().map(|v| v.to_bits()).collect())
                .collect();
            (nodes, evaluation.root_values.map(f64::to_bits))
        };

        let mut trainer = make();
        trainer.train(30);
        let policy = trainer.policy();
        let game = Arc::clone(trainer.game());
        let evaluation = bits(game.evaluate(&policy));
        let exploitability = game.exploitability(&policy).total.to_bits();
        assert_eq!(evaluation, bits(trainer.evaluate()));
        assert_eq!(exploitability, trainer.exploitability().total.to_bits());
        for id in 0..game.num_decision_nodes() {
            assert_eq!(
                trainer.average_strategy(id),
                game.average_strategy(&policy, id)
            );
        }

        // Training on does not disturb the snapshot, which still equals a
        // fresh trainer stopped at the same iteration.
        trainer.train(30);
        assert_ne!(evaluation, bits(trainer.evaluate()));
        assert_eq!(evaluation, bits(game.evaluate(&policy)));
        assert_eq!(exploitability, game.exploitability(&policy).total.to_bits());
        let mut fresh = make();
        fresh.train(30);
        assert_eq!(evaluation, bits(fresh.evaluate()));

        // A policy rebuilt from its rows (as a save does) reads identically,
        // and rows that do not fit the game are rejected.
        let restored = game.policy_from_rows(policy.rows().to_vec()).unwrap();
        assert_eq!(evaluation, bits(game.evaluate(&restored)));
        let mut short = policy.rows().to_vec();
        short.pop();
        assert!(game.policy_from_rows(short).is_err());
        let mut skewed = policy.rows().to_vec();
        skewed[0][0][0] += 0.5;
        assert!(game.policy_from_rows(skewed).is_err());

        // A distribution that breaks suit symmetry is rejected: chance nodes
        // derive non-representative cards from the representative's values.
        let (id, b, partner) = game
            .node_meta
            .iter()
            .enumerate()
            .find_map(|(id, (player, board))| {
                let group = game.suit_groups.get(board)?[*player]
                    .iter()
                    .find(|g| g.len() > 1)?;
                Some((id, group[0], group[1]))
            })
            .expect("suit-reduced fixture has a nontrivial suit group");
        let mut asymmetric = policy.rows().to_vec();
        let rows = &mut asymmetric[id];
        rows.iter_mut().for_each(|row| row[b] = 0.0);
        rows[0][b] = 1.0;
        rows.iter_mut().for_each(|row| row[partner] = 0.0);
        let last = rows.len() - 1;
        rows[last][partner] = 1.0;
        assert!(last > 0);
        assert!(
            matches!(game.policy_from_rows(asymmetric).unwrap_err(), PolicyError::NotSymmetric { node } if node == id)
        );
    }

    #[test]
    fn exploitability_decreases_with_more_training() {
        let few = build_scenario();
        let mut few_trainer = Trainer::new(
            few.tree,
            few.trainer_combos,
            TrainerOptions {
                algorithm: SolverAlgorithm::CfrPlus,
                ..TrainerOptions::default()
            },
        )
        .unwrap();
        few_trainer.train(100);
        let few_expl = few_trainer.exploitability();

        let many = build_scenario();
        let mut many_trainer = Trainer::new(
            many.tree,
            many.trainer_combos,
            TrainerOptions {
                algorithm: SolverAlgorithm::CfrPlus,
                ..TrainerOptions::default()
            },
        )
        .unwrap();
        many_trainer.train(20_000);
        let many_expl = many_trainer.exploitability();

        assert!(
            few_expl.total > -1e-6,
            "exploitability should never be meaningfully negative, got {}",
            few_expl.total
        );
        assert!(
            many_expl.total > -1e-6,
            "exploitability should never be meaningfully negative, got {}",
            many_expl.total
        );
        assert!(
            many_expl.total < few_expl.total,
            "expected exploitability to shrink with more training: 100 iters -> {}, 20,000 iters -> {}",
            few_expl.total,
            many_expl.total
        );
    }

    #[test]
    fn exploitability_is_near_zero_after_convergence() {
        let scenario = build_scenario();
        let pot = scenario.pot;
        let mut trainer = Trainer::new(
            scenario.tree,
            scenario.trainer_combos,
            TrainerOptions {
                algorithm: SolverAlgorithm::CfrPlus,
                ..TrainerOptions::default()
            },
        )
        .unwrap();
        trainer.train(20_000);
        let expl = trainer.exploitability();
        assert!(
            expl.total < pot * 0.001,
            "expected exploitability below 0.1% of pot after 20,000 iterations, got {}",
            expl.total
        );
    }

    // A tiny, independently solvable river game. OOP always wins showdown:
    // check wins 5; bet wins 10 when IP calls and 5 when IP folds. With the
    // untrained uniform strategy, BR(OOP) = 7.5, BR(IP) = -5, so exploitability
    // is 1.25 chips. This pins a NONZERO metric, unlike an equilibrium-only
    // assertion that would pass with any (or no) normalization.
    fn analytical_exploitability_trainer(combos: [Vec<Combo>; 2]) -> Trainer {
        use crate::solver::tree::{Action, Player, Tree};
        let board: Vec<Card> = ["2c", "7d", "9h", "Js", "Qd"]
            .iter()
            .map(|s| s.parse::<Card>().unwrap())
            .collect();
        let scores = eval_combos_if_complete(&combos, &board);
        let dead = mask_of(&board);
        // Assert the fixture's actual hand ordering, including every legal
        // pair; otherwise the analytical payoff argument would be invalid.
        for (
            i,
            &Combo {
                cards: [h1, h2], ..
            },
        ) in combos[0].iter().enumerate()
        {
            for (
                j,
                &Combo {
                    cards: [v1, v2], ..
                },
            ) in combos[1].iter().enumerate()
            {
                if [h1, h2, v1, v2].iter().any(|&c| mask_has(dead, c))
                    || h1 == v1
                    || h1 == v2
                    || h2 == v1
                    || h2 == v2
                {
                    continue;
                }
                assert!(
                    scores[0][i] > scores[1][j],
                    "fixture requires OOP to win every legal showdown"
                );
            }
        }
        let tree = Tree {
            board: board.clone(),
            root: Node::Decision {
                id: 0,
                player: Player::Oop,
                actions: vec![Action::Check, Action::Bet(Chips::whole(5))],
                children: vec![
                    Node::Terminal(Terminal::Showdown {
                        invested: [5.0, 5.0],
                    }),
                    Node::Decision {
                        id: 1,
                        player: Player::Ip,
                        actions: vec![Action::Call, Action::Fold],
                        children: vec![
                            Node::Terminal(Terminal::Showdown {
                                invested: [10.0, 10.0],
                            }),
                            Node::Terminal(Terminal::Fold {
                                winner: Player::Oop,
                                invested: [10.0, 5.0],
                            }),
                        ],
                    },
                ],
            },
            num_decision_nodes: 2,
        };
        // Unchecked: the fixtures deliberately include board-blocked combos
        // and impossible deals, which the kernels must still ignore.
        Trainer::new_unchecked(
            tree,
            combos,
            TrainerOptions {
                algorithm: SolverAlgorithm::CfrPlus,
                ..TrainerOptions::default()
            },
        )
    }

    fn weighted_combo(a: &str, b: &str, weight: f64) -> Combo {
        Combo::new(
            a.parse::<Card>().unwrap(),
            b.parse::<Card>().unwrap(),
            weight,
        )
    }

    fn assert_analytical_exploitability(expl: Exploitability) {
        assert!(
            (expl.oop - 7.5).abs() < 1e-10,
            "OOP BR must be 7.5 chips, got {}",
            expl.oop
        );
        assert!(
            (expl.ip + 5.0).abs() < 1e-10,
            "IP BR must be -5 chips, got {}",
            expl.ip
        );
        assert!(
            (expl.total - 1.25).abs() < 1e-10,
            "exploitability must be 1.25 chips, got {}",
            expl.total
        );
    }

    #[test]
    fn exploitability_matches_analytical_best_responses_with_blockers() {
        // Three legal deals, not the four pairs in the Cartesian product:
        // AcAd cannot be dealt against AcKs. Board-blocked entries on BOTH
        // sides must affect neither numerator nor denominator.
        let combos = [
            vec![
                weighted_combo("Ac", "Ad", 1.0),
                weighted_combo("Ah", "As", 1.0),
                weighted_combo("Qd", "Qc", 1.0),
            ],
            vec![
                weighted_combo("Kc", "Kd", 1.0),
                weighted_combo("Ac", "Ks", 1.0),
                weighted_combo("2c", "3d", 1.0),
            ],
        ];
        assert_analytical_exploitability(
            analytical_exploitability_trainer(combos).exploitability(),
        );
    }

    #[test]
    fn exploitability_chip_units_ignore_range_weight_scale() {
        for (oop_scale, ip_scale) in [(1.0, 1.0), (0.25, 1.0), (1.0, 0.7), (0.25, 0.7)] {
            let combos = [
                vec![
                    weighted_combo("Ac", "Ad", oop_scale),
                    weighted_combo("Ah", "As", 0.3 * oop_scale),
                ],
                vec![
                    weighted_combo("Kc", "Kd", ip_scale),
                    weighted_combo("Ac", "Ks", 0.6 * ip_scale),
                ],
            ];
            assert_analytical_exploitability(
                analytical_exploitability_trainer(combos).exploitability(),
            );
        }
    }

    #[test]
    fn exploitability_rejects_zero_or_nonfinite_joint_mass() {
        for combos in [
            [
                vec![weighted_combo("Ac", "Ad", 1.0)],
                vec![weighted_combo("Ac", "Ks", 1.0)],
            ],
            [
                vec![weighted_combo("Ac", "Ad", 0.0)],
                vec![weighted_combo("Kc", "Kd", 1.0)],
            ],
            [
                vec![weighted_combo("Qd", "Qc", 1.0)],
                vec![weighted_combo("Kc", "Kd", 1.0)],
            ],
            [
                vec![weighted_combo("Ac", "Ad", f64::INFINITY)],
                vec![weighted_combo("Kc", "Kd", 1.0)],
            ],
            [
                vec![weighted_combo("Ac", "Ad", f64::NAN)],
                vec![weighted_combo("Kc", "Kd", 1.0)],
            ],
        ] {
            let expl = analytical_exploitability_trainer(combos).exploitability();
            assert!(
                expl.oop.is_nan() && expl.ip.is_nan() && expl.total.is_nan(),
                "undefined metric must not appear converged: {expl:?}"
            );
        }
    }

    /// `best_response_chance_value` (the counterpart to `chance_value`'s
    /// suit-isomorphism relabeling) is only exercised by a scenario with an
    /// actual `Chance` node whose classes have more than one member — this
    /// codebase has repeatedly found relabeling bugs that only manifest
    /// with isomorphism enabled, so mirror
    /// `suit_isomorphism_reduced_and_unreduced_converge_to_the_same_equilibrium`
    /// and check that isomorphism-reduced and unreduced trees converge to
    /// the same exploitability rather than merely not-crashing.
    #[test]
    fn exploitability_isomorphism_reduced_and_unreduced_match() {
        let combos = two_suit_scenario_combos();
        let reduced = build_two_suit_scenario(true, combos.clone());
        let unreduced = build_two_suit_scenario(false, combos);

        let iterations = 3_000;
        let mut reduced_trainer = Trainer::new(
            reduced.tree,
            reduced.trainer_combos,
            TrainerOptions {
                algorithm: SolverAlgorithm::CfrPlus,
                ..TrainerOptions::default()
            },
        )
        .unwrap();
        reduced_trainer.train(iterations);
        let mut unreduced_trainer = Trainer::new(
            unreduced.tree,
            unreduced.trainer_combos,
            TrainerOptions {
                algorithm: SolverAlgorithm::CfrPlus,
                ..TrainerOptions::default()
            },
        )
        .unwrap();
        unreduced_trainer.train(iterations);

        let reduced_expl = reduced_trainer.exploitability();
        let unreduced_expl = unreduced_trainer.exploitability();
        // Reduced/unreduced training takes different floating-point paths
        // (different iteration order over the tree) to the same underlying
        // equilibrium, so — unlike the average-strategy comparison this test
        // mirrors, whose *probabilities* are naturally bounded to [0, 1] and
        // so can use a tight absolute tolerance — exploitability's chip
        // magnitude calls for a relative tolerance instead.
        let rel_diff =
            (reduced_expl.total - unreduced_expl.total).abs() / unreduced_expl.total.abs().max(1.0);
        assert!(
            rel_diff < 0.1,
            "expected matching exploitability with isomorphism enabled/disabled: reduced={}, unreduced={}",
            reduced_expl.total,
            unreduced_expl.total
        );
    }
}

#[cfg(test)]
mod terminal_regression_tests {
    use super::*;
    use crate::card::Card;
    use crate::solver::tree::{Player, Tree};
    use crate::solver::Chips;

    fn close(actual: f64, expected: f64) {
        let tolerance = 2e-10 + expected.abs() * 2e-12;
        assert!(
            (actual - expected).abs() <= tolerance,
            "actual={actual}, expected={expected}, tolerance={tolerance}"
        );
    }

    #[test]
    fn linear_terminals_match_pairwise_oracle() {
        // Entire deck includes initial-board conflicts, overlaps, equal-rank
        // groups, empty support and every valid two-card blocker pattern.
        let full: Vec<_> = (0..52)
            .flat_map(|a| (a + 1..52).map(move |b| Combo::new(Card(a), Card(b), 1.0)))
            .collect();
        let mut asymmetric = full.iter().step_by(7).copied().collect::<Vec<_>>();
        asymmetric.reverse();
        let Combo {
            cards: [a, b],
            weight,
        } = asymmetric[3];
        asymmetric.push(Combo::new(b, a, weight)); // repeated, reversed exact pair
        for board in [
            ["2c", "7d", "9h", "Js", "Qd"],
            ["Tc", "Jc", "Qc", "Kc", "Ac"],
            ["Jh", "Js", "2c", "2d", "3h"],
        ] {
            let board: Vec<_> = board.iter().map(|s| s.parse::<Card>().unwrap()).collect();
            for combos in [
                [full.clone(), full.clone()],
                [asymmetric.clone(), full.clone()],
                [full.clone(), Vec::new()],
            ] {
                let tree = Tree {
                    board: board.clone(),
                    root: Node::Terminal(Terminal::Showdown {
                        invested: [37.0, 121.0],
                    }),
                    num_decision_nodes: 0,
                };
                // Unchecked: blocked, repeated, and empty ranges exercise the
                // kernels' degenerate paths.
                let trainer = Trainer::new_unchecked(
                    tree,
                    combos,
                    TrainerOptions {
                        algorithm: SolverAlgorithm::CfrPlus,
                        ..TrainerOptions::default()
                    },
                );
                for phase in 0..3 {
                    let reach: [Vec<f64>; 2] = std::array::from_fn(|p| {
                        (0..trainer.game.combos[p].len())
                            .map(|i| {
                                if phase == 2 || (i + phase) % 5 == 0 {
                                    0.0
                                } else {
                                    ((i * 37 + p * 19 + phase) % 103) as f64 / 103.0
                                }
                            })
                            .collect()
                    });
                    for terminal in [
                        Terminal::Showdown {
                            invested: [37.0, 121.0],
                        },
                        Terminal::Showdown {
                            invested: [50.0, 50.0],
                        },
                        Terminal::Fold {
                            winner: Player::Oop,
                            invested: [37.0, 121.0],
                        },
                        Terminal::Fold {
                            winner: Player::Ip,
                            invested: [37.0, 121.0],
                        },
                    ] {
                        let scores = eval_combos_if_complete(&trainer.game.combos, &board);
                        trainer
                            .game
                            .use_pairwise_terminals
                            .store(false, std::sync::atomic::Ordering::Relaxed);
                        let actual = trainer
                            .game
                            .terminal_value(&terminal, &reach, &board, &scores);
                        if let Terminal::Showdown { invested } = &terminal {
                            for p in 0..2 {
                                let before =
                                    trainer.game.terminal_index.showdown_before_rank_cache(
                                        &trainer.game.combos,
                                        p,
                                        &reach[1 - p],
                                        &scores,
                                        &trainer.game.board_order_cache[&board],
                                        mask_of(&board),
                                        invested,
                                    );
                                assert_eq!(
                                    actual[p].iter().map(|x| x.to_bits()).collect::<Vec<_>>(),
                                    before.iter().map(|x| x.to_bits()).collect::<Vec<_>>()
                                );
                            }
                        }
                        trainer
                            .game
                            .use_pairwise_terminals
                            .store(true, std::sync::atomic::Ordering::Relaxed);
                        let reference = trainer
                            .game
                            .terminal_value(&terminal, &reach, &board, &scores);
                        for p in 0..2 {
                            for (a, b) in actual[p].iter().zip(&reference[p]) {
                                close(*a, *b);
                            }
                        }
                    }
                }
            }
        }
    }

    #[test]
    fn linear_terminals_preserve_training_and_best_response() {
        use crate::range::Range;
        use crate::solver::tree::{build_tree, GameConfig};
        for board in [
            vec!["2c", "7d", "9h", "Js", "Qd"],
            vec!["Jh", "Js", "2c", "2d"],
        ] {
            let board: Vec<_> = board.iter().map(|s| s.parse::<Card>().unwrap()).collect();
            let combos: [Vec<_>; 2] = ["AA,KK,JJ,54s:0.3", "QQ,TT,88,65s:0.7"].map(|s| {
                let mut v = Range::parse(s).unwrap().combos(CardSet::from_cards(&board));
                v.sort_by_key(|c| (c.cards[0], c.cards[1]));
                v
            });
            let cfg = GameConfig {
                board: board.clone(),
                pot: Chips::whole(100),
                effective_stack: Chips::whole(100),
                bet_sizes: vec![0.5],
                max_raises: 0,
                suit_isomorphism: false,
            };
            let mut actual = Trainer::new(
                build_tree(&cfg).unwrap(),
                combos.clone(),
                TrainerOptions {
                    algorithm: SolverAlgorithm::CfrPlus,
                    ..TrainerOptions::default()
                },
            )
            .unwrap();
            let mut reference = Trainer::new(
                build_tree(&cfg).unwrap(),
                combos,
                TrainerOptions {
                    algorithm: SolverAlgorithm::CfrPlus,
                    ..TrainerOptions::default()
                },
            )
            .unwrap();
            reference
                .game
                .use_pairwise_terminals
                .store(true, std::sync::atomic::Ordering::Relaxed);
            let ev_a = actual.train(60);
            let ev_b = reference.train(60);
            for p in 0..2 {
                close(ev_a[p], ev_b[p]);
            }
            for id in 0..actual.game.tree.num_decision_nodes {
                for (a, b) in actual
                    .average_strategy(id)
                    .iter()
                    .flatten()
                    .zip(reference.average_strategy(id).iter().flatten())
                {
                    close(*a, *b);
                }
            }
            let a = actual.exploitability();
            let b = reference.exploitability();
            close(a.oop, b.oop);
            close(a.ip, b.ip);
            close(a.total, b.total);
            let a = actual.evaluate().nodes;
            let b = reference.evaluate().nodes;
            for (eval, other) in a.iter().zip(&b) {
                for (x, y) in eval.ev.iter().zip(&other.ev) {
                    close(*x, *y);
                }
            }
        }
    }
}

#[cfg(test)]
#[path = "cfr/target_values_tests.rs"]
mod target_values_tests;

#[cfg(test)]
#[path = "suit_reduction_tests.rs"]
mod suit_reduction_tests;

fn has_suit_reduction(node: &Node) -> bool {
    match node {
        Node::Chance { children } => children
            .iter()
            .any(|(members, child)| members.len() > 1 || has_suit_reduction(child)),
        Node::Decision { children, .. } => children.iter().any(has_suit_reduction),
        Node::Terminal(_) => false,
    }
}

/// The free-suit transpositions generate the board's full stabilizer. Union
/// bucket indices so overlapping abstraction buckets still form a partition.
fn suit_bucket_groups(
    board: &[Card],
    combos: &[Vec<Combo>; 2],
    index: &[HashMap<(Card, Card), usize>; 2],
    maps: &[Vec<usize>; 2],
) -> [Vec<Vec<usize>>; 2] {
    let free: Vec<u8> = (0..4)
        .filter(|s| !board.iter().any(|&c| c.suit() == *s))
        .collect();
    std::array::from_fn(|p| {
        if free.len() < 2 {
            return Vec::new();
        }
        let n = maps[p].iter().max().map_or(0, |b| b + 1);
        let mut parent: Vec<usize> = (0..n).collect();
        fn root(parent: &[usize], mut i: usize) -> usize {
            while parent[i] != i {
                i = parent[i];
            }
            i
        }
        for (a, &sa) in free.iter().enumerate() {
            for &sb in &free[a + 1..] {
                for (
                    i,
                    &Combo {
                        cards: [h1, h2],
                        weight: w,
                    },
                ) in combos[p].iter().enumerate()
                {
                    let pair = normalize_pair(swap_suit(h1, sa, sb), swap_suit(h2, sa, sb));
                    let &j = index[p]
                        .get(&pair)
                        .expect("suit reduction requires suit-closed ranges");
                    assert_eq!(
                        w, combos[p][j].weight,
                        "suit reduction requires suit-symmetric range weights"
                    );
                    let (x, y) = (root(&parent, maps[p][i]), root(&parent, maps[p][j]));
                    parent[x.max(y)] = x.min(y);
                }
            }
        }
        let mut groups = vec![Vec::new(); n];
        for i in 0..n {
            groups[root(&parent, i)].push(i);
        }
        groups.into_iter().filter(|group| group.len() > 1).collect()
    })
}