rs_poker 5.0.0

A library to help with any Rust code dealing with poker. This includes card values, suits, hands, hand ranks, 5 card hand strength calculation, 7 card hand strength calulcation, and monte carlo game simulation helpers.
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
use std::collections::{HashMap, HashSet, VecDeque};

use approx::abs_diff_eq;

use crate::core::Card;

use super::{Action, ActionObj, HandHistory, PlayerObj, PotObj, RoundObj};

/// Assert that an Open Hand History object is internally consistent.
///
/// This performs structural validation of betting flow, chip accounting,
/// card uniqueness, forced blinds correspondence, and general data-model sanity.
pub fn assert_valid_open_hand_history(hand_history: &HandHistory) {
    let mut validator = HandHistoryValidator::new(hand_history);
    validator.validate();
}

/// Assert that the Open Hand History mirrors the final arena `GameState`.
///
/// This runs the base validation and additionally checks chips, board cards,
/// player counts, and winnings against the provided `GameState`.
#[cfg(feature = "arena")]
pub fn assert_open_hand_history_matches_game_state(
    hand_history: &HandHistory,
    game_state: &crate::arena::GameState,
) {
    assert_valid_open_hand_history(hand_history);
    HandHistoryArenaComparator::new(hand_history, game_state).assert_consistent();
}

struct HandHistoryValidator<'a> {
    hh: &'a HandHistory,
    players: HashMap<u64, PlayerState>,
    active_order: Vec<u64>,
    dealer_player_id: u64,
    small_blind_player: Option<u64>,
    big_blind_player: Option<u64>,
    board_cards: Vec<Card>,
    seen_cards: HashSet<Card>,
    total_contribution: f32,
    table_contribution: f32,
    ante_posted: HashSet<u64>,
    small_blind_posted: bool,
    big_blind_posted: bool,
    betting_state: BettingRoundState,
    rotation: BettingRotation,
}

impl<'a> HandHistoryValidator<'a> {
    fn new(hh: &'a HandHistory) -> Self {
        assert!(
            !hh.players.is_empty(),
            "Hand {game} must include at least one player",
            game = hh.game_number
        );
        assert_eq!(
            hh.players.len() as u64,
            hh.table_size,
            "Hand {game} has mismatched table size",
            game = hh.game_number
        );
        assert!(
            hh.big_blind_amount + f32::EPSILON >= hh.small_blind_amount,
            "Hand {game} big blind must be >= small blind",
            game = hh.game_number
        );

        let mut players: HashMap<u64, PlayerState> = HashMap::new();
        let mut seat_entries = Vec::with_capacity(hh.players.len());
        for player in &hh.players {
            assert!(
                players
                    .insert(player.id, PlayerState::new(player))
                    .is_none(),
                "Hand {game} contains duplicate player id {id}",
                game = hh.game_number,
                id = player.id
            );
            seat_entries.push((player.seat, player.id));
        }
        seat_entries.sort_by_key(|(seat, _)| *seat);

        let dealer_player_id = seat_entries
            .iter()
            .find(|(seat, _)| *seat == hh.dealer_seat)
            .map(|(_, id)| *id)
            .expect("Dealer seat must correspond to a player");

        let active_order: Vec<u64> = seat_entries
            .iter()
            .map(|(_, id)| *id)
            .filter(|id| !players.get(id).unwrap().sitting_out)
            .collect();
        assert!(
            active_order.len() >= 2,
            "Hand {game} must have at least two active players",
            game = hh.game_number
        );
        assert!(
            active_order.contains(&dealer_player_id),
            "Dealer must be seated at the table"
        );

        let small_blind_player = determine_small_blind(&active_order, dealer_player_id);
        let big_blind_player =
            determine_big_blind(&active_order, dealer_player_id, small_blind_player);

        let rotation = BettingRotation::new(active_order.clone());

        Self {
            hh,
            players,
            active_order,
            dealer_player_id,
            small_blind_player,
            big_blind_player,
            board_cards: Vec::new(),
            seen_cards: HashSet::new(),
            total_contribution: 0.0,
            table_contribution: 0.0,
            ante_posted: HashSet::new(),
            small_blind_posted: false,
            big_blind_posted: false,
            betting_state: BettingRoundState::default(),
            rotation,
        }
    }

    fn validate(&mut self) {
        assert!(
            !self.hh.rounds.is_empty(),
            "Hand {game} must contain at least one round",
            game = self.hh.game_number
        );

        for round in &self.hh.rounds {
            self.process_round(round);
        }

        self.finish_validation();
    }

    fn process_round(&mut self, round: &RoundObj) {
        let street = Street::from(round.street.as_str());
        if street.is_betting_round() {
            self.start_betting_round(street);
        }

        if let Some(cards) = &round.cards {
            self.record_board_cards(street, cards);
        }

        for action in &round.actions {
            self.process_action(street, action);
        }
    }

    fn start_betting_round(&mut self, street: Street) {
        // In No-Limit Texas Hold'em, the minimum raise starts at the big blind
        self.betting_state.reset(self.hh.big_blind_amount);
        self.rotation.start_round(
            street,
            self.dealer_player_id,
            self.big_blind_player,
            &self.players,
        );
    }

    fn record_board_cards(&mut self, street: Street, cards: &[Card]) {
        match street {
            Street::Flop => assert_eq!(cards.len(), 3, "Flop must contain exactly 3 cards"),
            Street::Turn | Street::River => {
                assert_eq!(cards.len(), 1, "Turn and river must contain exactly 1 card")
            }
            _ => {
                assert!(cards.is_empty(), "Only community streets may specify cards");
                return;
            }
        }

        for &card in cards {
            self.assert_new_card(card, "board");
            self.board_cards.push(card);
        }

        assert!(
            self.board_cards.len() <= 5,
            "A holdem board cannot contain more than 5 cards"
        );
    }

    fn process_action(&mut self, street: Street, action: &ActionObj) {
        let player_id = action.player_id;
        self.players
            .get(&player_id)
            .unwrap_or_else(|| panic!("Unknown player {player_id} referenced"));

        assert!(action.amount.is_finite(), "Action amounts must be finite");
        assert!(
            action.amount >= 0.0 || matches!(action.action, Action::Fold | Action::Check),
            "Negative chip movements are invalid"
        );

        let requires_turn = matches!(
            action.action,
            Action::Fold | Action::Check | Action::Call | Action::Bet | Action::Raise
        ) && street.is_betting_round();
        if requires_turn {
            self.rotation.expect_actor(player_id, &self.players);
        }

        match action.action {
            Action::DealtCards => self.handle_dealt_cards(player_id, action),
            Action::PostAnte => self.handle_post_ante(player_id, action.amount),
            Action::PostSmallBlind => self.handle_small_blind(player_id, action.amount),
            Action::PostBigBlind => self.handle_big_blind(player_id, action.amount),
            Action::PostDead | Action::PostExtraBlind | Action::Straddle => {
                self.handle_optional_force(player_id, action.amount)
            }
            Action::Bet => self.handle_bet(player_id, action.amount, street, action.is_allin),
            Action::Raise => self.handle_raise(player_id, action.amount, action.is_allin),
            Action::Call => self.handle_call(player_id, action.amount, action.is_allin),
            Action::Check => self.handle_check(player_id, action.is_allin),
            Action::Fold => self.handle_fold(player_id),
            Action::AddedChips => self.handle_added_chips(player_id, action.amount),
            Action::AddedToPot => self.handle_table_addition(action.amount),
            Action::ShowsCards => self.handle_show_cards(player_id, action),
            Action::MucksCards => self.handle_muck(player_id),
            Action::SitsDown | Action::StandsUp => {}
        }

        if requires_turn {
            self.rotation.trim_inactive(&self.players);
        }
    }

    fn handle_dealt_cards(&mut self, player_id: u64, action: &ActionObj) {
        let cards = action
            .cards
            .as_ref()
            .expect("DealtCards entries must include card payloads");
        assert_eq!(
            cards.len(),
            2,
            "Holdem players must receive exactly 2 cards"
        );
        {
            let state = self
                .players
                .get(&player_id)
                .expect("Player must exist for DealtCards action");
            assert!(
                state.cards.is_empty(),
                "Player {player_id} already has hole cards assigned"
            );
        }

        for &card in cards {
            self.assert_new_card(card, "player");
        }

        let state = self
            .players
            .get_mut(&player_id)
            .expect("Player must exist for DealtCards action");
        state.cards.extend(cards.iter().copied());
    }

    fn handle_post_ante(&mut self, player_id: u64, amount: f32) {
        assert!(amount >= 0.0, "Ante amount must be non-negative");
        // Validate the same way as the blinds. `validate_forced_amount` tolerates
        // an amount within `f32::EPSILON` of the expected ante, which covers
        // extreme (subnormal) antes: when `ante_amount` is below the chip-math
        // precision floor, no chips actually move and the posted amount is
        // recorded as 0.
        self.validate_forced_amount(player_id, amount, self.hh.ante_amount);
        self.ante_posted.insert(player_id);
        self.apply_contribution(player_id, amount, "ante");
    }

    fn handle_small_blind(&mut self, player_id: u64, amount: f32) {
        if let Some(expected) = self.small_blind_player {
            assert_eq!(
                player_id, expected,
                "Small blind must be posted by expected player"
            );
        }
        self.small_blind_posted = true;
        self.validate_forced_amount(player_id, amount, self.hh.small_blind_amount);
        self.apply_contribution(player_id, amount, "small blind");
    }

    fn handle_big_blind(&mut self, player_id: u64, amount: f32) {
        if let Some(expected) = self.big_blind_player {
            assert_eq!(
                player_id, expected,
                "Big blind must be posted by expected player"
            );
        }
        self.big_blind_posted = true;
        self.validate_forced_amount(player_id, amount, self.hh.big_blind_amount);
        self.apply_contribution(player_id, amount, "big blind");
    }

    fn handle_optional_force(&mut self, player_id: u64, amount: f32) {
        assert!(amount >= 0.0, "Forced bets must be non-negative");
        self.apply_contribution(player_id, amount, "forced bet");
    }

    fn ensure_effective_wager_amount(
        &self,
        player_id: u64,
        amount: f32,
        is_allin: bool,
        label: &str,
    ) {
        if amount > f32::EPSILON {
            return;
        }

        assert!(
            amount > 0.0,
            "{label} amount must be positive",
            label = label
        );
        let state = self.players.get(&player_id).unwrap();
        let short_stack_threshold = f32::EPSILON + f32::EPSILON;
        assert!(
            is_allin && state.stack_remaining <= short_stack_threshold,
            "Player {player_id} {label} amount {amount} below minimum ({min_amount}) without being all-in (stack {stack})",
            player_id = player_id,
            label = label,
            amount = amount,
            min_amount = f32::EPSILON,
            stack = state.stack_remaining,
        );
    }

    fn handle_bet(&mut self, player_id: u64, amount: f32, street: Street, is_allin: bool) {
        assert!(
            street.is_betting_round(),
            "Bets only allowed on betting streets"
        );
        self.ensure_effective_wager_amount(player_id, amount, is_allin, "bet");
        assert!(
            self.betting_state.current_max <= f32::EPSILON,
            "Cannot bet when a live bet exists"
        );
        self.ensure_player_can_act(player_id, "bet");

        // Validate minimum bet sizing (Texas Hold'em No-Limit rule):
        // An opening bet must be at least the big blind, unless it's an all-in.
        // Tiny "bets" (below the arena's scaled bet-epsilon) are accepted by
        // the arena but represent no real chip movement; the converter should
        // have classified them as Check, but as defense-in-depth we tolerate
        // them here too.
        if !is_allin && self.hh.big_blind_amount > 0.0 {
            let min_bet = self.hh.big_blind_amount;
            let scaled_epsilon = amount.abs().max(min_bet.abs()).max(1.0) * f32::EPSILON * 1000.0;
            if amount.abs() > scaled_epsilon {
                let tolerance = (min_bet * 0.001 + f32::EPSILON).max(scaled_epsilon);
                assert!(
                    amount >= min_bet - tolerance,
                    "Player {} bet of {} does not meet minimum bet requirement of {}",
                    player_id,
                    amount,
                    min_bet
                );
            }
        }

        self.apply_contribution(player_id, amount, "bet");
        self.rotation.rebuild_after_raise(player_id, &self.players);
    }

    fn handle_raise(&mut self, player_id: u64, amount: f32, is_allin: bool) {
        self.ensure_effective_wager_amount(player_id, amount, is_allin, "raise");
        assert!(
            self.betting_state.current_max > 0.0,
            "Cannot raise without a live bet"
        );
        self.ensure_player_can_act(player_id, "raise");
        let previous_max = self.betting_state.current_max;
        let already_committed = self.betting_state.committed(player_id);
        let new_total = self.apply_contribution(player_id, amount, "raise");

        // The raise amount is how much this raises the current bet
        let raise_amount = new_total - previous_max;

        // For a raise to be valid:
        // - Normal raise: must exceed current bet by at least f32::EPSILON
        // - All-in raise: just needs to exceed current bet (with floating point tolerance
        //   in the player's favor to handle cases where remaining chips are tiny)
        let raise_is_valid = new_total > previous_max + f32::EPSILON
            || (is_allin && new_total + f32::EPSILON > previous_max);
        assert!(raise_is_valid, "Raise must exceed the current bet");

        // Validate minimum raise sizing (Texas Hold'em No-Limit rule):
        // A raise must be at least the size of the previous raise (or big blind for first raise)
        // All-in raises are exempt from minimum raise requirements.
        //
        // A "raise" whose increment is below the arena's scaled bet-epsilon
        // (`magnitude * EPSILON * 1000`) is one the arena classified as a
        // call, not a raise -- it just falls inside its precision tolerance.
        // The converter still classifies it as Raise because `new_total >
        // previous_max` is strictly true, so we must mirror the arena's view
        // here and skip the min-raise check for these float-edge cases.
        let raise_scaled_epsilon =
            new_total.abs().max(previous_max.abs()).max(1.0) * f32::EPSILON * 1000.0;
        if !is_allin && raise_amount > raise_scaled_epsilon {
            let min_raise = self.betting_state.min_raise;
            // Allow small tolerance for floating point arithmetic
            let tolerance = (min_raise * 0.001 + f32::EPSILON).max(raise_scaled_epsilon);
            assert!(
                raise_amount >= min_raise - tolerance,
                "Player {} raise of {} does not meet minimum raise requirement of {} (committed: {}, previous max: {}, new total: {})",
                player_id,
                raise_amount,
                min_raise,
                already_committed,
                previous_max,
                new_total
            );
        }

        self.rotation.rebuild_after_raise(player_id, &self.players);
    }

    fn handle_call(&mut self, player_id: u64, amount: f32, is_allin: bool) {
        assert!(amount >= 0.0, "Call amount must be non-negative");
        // A "call" with no chips added is a no-op: the player already matches
        // the current bet (e.g., big-blind option, or they were already
        // committed). The arena emits these at all-in / float-edge boundaries;
        // there's no per-action invariant left to check.
        if amount <= 0.0 {
            return;
        }
        let current_max = self.betting_state.current_max;
        self.ensure_player_can_act(player_id, "call");
        let available = self
            .players
            .get(&player_id)
            .map(|state| state.stack_remaining)
            .unwrap_or(0.0);
        let committing_stack = is_allin || amount + f32::EPSILON >= available;
        let already = self.betting_state.committed(player_id);
        let required = (current_max - already).max(0.0);
        let has_live_bet =
            current_max > f32::EPSILON || required > 0.0 || (committing_stack && current_max > 0.0);
        assert!(has_live_bet, "Cannot call when no bet is pending");
        // Mirror the arena's `validate_bet_amount` scaled-epsilon tolerance
        // (`magnitude * EPSILON * 1000`). At large chip magnitudes a single
        // f32 ULP grows much bigger than `f32::EPSILON`, so a call the arena
        // accepted (because the shortfall fell inside its tolerance) can
        // still look noticeably short to a strict comparison here.
        let chip_magnitude = amount
            .abs()
            .max(current_max.abs())
            .max(required.abs())
            .max(1.0);
        let scaled_epsilon = chip_magnitude * f32::EPSILON * 1000.0;
        assert!(
            approx_eq(required, amount) || amount >= required - scaled_epsilon || committing_stack,
            "Player {player_id} attempted to call incorrect amount (required: {required}, amount: {amount}, tolerance: {scaled_epsilon})"
        );
        let new_total = self.apply_contribution(player_id, amount, "call");
        if !committing_stack {
            assert!(
                approx_eq(new_total, current_max) || new_total >= current_max - scaled_epsilon,
                "Call did not match outstanding bet (new_total: {new_total}, current_max: {current_max}, tolerance: {scaled_epsilon})"
            );
        }
    }

    fn handle_check(&mut self, player_id: u64, is_allin: bool) {
        let committed = self.betting_state.committed(player_id);
        assert!(
            approx_eq(committed, self.betting_state.current_max),
            "Player {player_id} checked while facing a bet"
        );
        // If player is marked as all-in on a check, they've depleted their stack.
        // Mark them all-in and remove from rotation so they don't act on future streets.
        if is_allin {
            if let Some(state) = self.players.get_mut(&player_id) {
                state.all_in = true;
                state.stack_remaining = 0.0;
            }
            self.rotation.remove_player(player_id);
        }
    }

    fn handle_fold(&mut self, player_id: u64) {
        let state = self
            .players
            .get_mut(&player_id)
            .expect("Fold action player must exist");
        assert!(!state.folded, "Player {player_id} cannot fold twice");
        assert!(!state.all_in, "All-in players cannot fold");
        state.folded = true;
        self.rotation.remove_player(player_id);
    }

    fn handle_added_chips(&mut self, player_id: u64, amount: f32) {
        assert!(amount >= 0.0, "Added chips must be non-negative");
        let state = self
            .players
            .get_mut(&player_id)
            .expect("Added chips player must exist");
        state.stack_remaining += amount;
        state.total_added_chips += amount;
        if amount > 0.0 {
            state.all_in = false;
        }
    }

    fn handle_table_addition(&mut self, amount: f32) {
        assert!(amount >= 0.0, "Added pot chips must be non-negative");
        self.table_contribution += amount;
    }

    fn handle_show_cards(&self, player_id: u64, action: &ActionObj) {
        if let Some(cards) = &action.cards {
            let state = self
                .players
                .get(&player_id)
                .expect("Show cards requires valid player");
            if !state.cards.is_empty() {
                assert_eq!(
                    state.cards.len(),
                    cards.len(),
                    "Player {player_id} revealed mismatched card count"
                );
                for card in cards {
                    assert!(
                        state.cards.contains(card),
                        "Player {player_id} revealed unexpected card"
                    );
                }
            }
        }
    }

    fn handle_muck(&self, _player_id: u64) {}

    fn finish_validation(&self) {
        if self.hh.ante_amount > 0.0 {
            for player_id in &self.active_order {
                assert!(
                    self.ante_posted.contains(player_id),
                    "Active player {player_id} failed to post ante"
                );
            }
        }

        if self.hh.small_blind_amount > 0.0 {
            assert!(self.small_blind_posted, "Small blind was not posted");
        }
        if self.hh.big_blind_amount > 0.0 {
            assert!(self.big_blind_posted, "Big blind was not posted");
        }

        // Validate Texas Hold'em specific rules
        self.validate_board_progression();
        self.validate_dealer_positioning();
        self.validate_betting_round_sequence();
        self.validate_raise_sizing();
        self.validate_player_hole_cards();

        let mut payouts: HashMap<u64, f32> = HashMap::new();
        let mut pot_total = 0.0;
        let mut total_rake = 0.0;
        let mut total_jackpot = 0.0;
        for pot in &self.hh.pots {
            pot_total += pot.amount;
            total_rake += pot.rake.unwrap_or(0.0);
            total_jackpot += pot.jackpot.unwrap_or(0.0);
            self.validate_pot(pot, &mut payouts);
        }

        let all_contributions = self.total_contribution + self.table_contribution;
        assert!(
            approx_eq(all_contributions, pot_total),
            "Total contributions {all_contrib} do not equal pot total {pot_total}",
            all_contrib = all_contributions
        );

        let payout_sum: f32 = payouts.values().copied().sum();
        let expected_payout = pot_total - total_rake - total_jackpot;
        assert!(
            approx_eq(payout_sum, expected_payout),
            "Winnings {payout_sum} must equal pot total minus rake and jackpot {expected}",
            expected = expected_payout
        );

        for (player_id, state) in &self.players {
            assert!(
                state.stack_remaining + f32::EPSILON >= 0.0,
                "Player {player_id} ended with negative chips"
            );
        }
    }

    fn validate_pot(&self, pot: &PotObj, payouts: &mut HashMap<u64, f32>) {
        let mut sum = 0.0;
        for win in &pot.player_wins {
            assert!(win.win_amount >= 0.0, "Pot wins must be non-negative");
            let player = self
                .players
                .get(&win.player_id)
                .expect("Pot winner must be a known player");
            assert!(
                !player.folded,
                "Folded player {} cannot win a pot",
                win.player_id
            );
            *payouts.entry(win.player_id).or_default() += win.win_amount;
            sum += win.win_amount;
        }

        let rake = pot.rake.unwrap_or(0.0);
        let jackpot = pot.jackpot.unwrap_or(0.0);
        assert!(
            approx_eq(sum + rake + jackpot, pot.amount),
            "Pot {} does not balance",
            pot.number
        );
    }

    fn validate_forced_amount(&self, player_id: u64, amount: f32, expected: f32) {
        if expected <= 0.0 {
            return;
        }
        let state = self.players.get(&player_id).unwrap();
        if state.starting_stack + state.total_added_chips + f32::EPSILON >= expected {
            assert!(
                approx_eq(amount, expected) || amount >= expected - f32::EPSILON,
                "Player {player_id} forced bet should match expected amount"
            );
        }
    }

    fn ensure_player_can_act(&self, player_id: u64, label: &str) {
        let state = self.players.get(&player_id).unwrap();
        assert!(
            !state.sitting_out,
            "Sitting out player {player_id} cannot {label}"
        );
        assert!(
            !state.folded,
            "Player {player_id} cannot {label} after folding"
        );
        assert!(!state.all_in, "All-in player {player_id} cannot {label}");
    }

    fn apply_contribution(&mut self, player_id: u64, amount: f32, label: &str) -> f32 {
        assert!(amount >= 0.0, "{label} amount must be non-negative");
        let state = self
            .players
            .get_mut(&player_id)
            .expect("Contribution player must exist");
        assert!(
            state.stack_remaining + f32::EPSILON >= amount,
            "Player {player_id} attempted to {label} more chips than available (amount {amount}, stack {stack}, contributed {contrib}, starting {starting})",
            amount = amount,
            stack = state.stack_remaining,
            contrib = state.total_contribution,
            starting = state.starting_stack
        );
        state.stack_remaining -= amount;
        state.total_contribution += amount;
        if state.stack_remaining <= f32::EPSILON {
            state.stack_remaining = 0.0;
            state.all_in = true;
        }
        self.total_contribution += amount;
        self.betting_state.record(player_id, amount)
    }

    fn assert_new_card(&mut self, card: Card, location: &str) {
        assert!(
            self.seen_cards.insert(card),
            "Duplicate card {:?} observed on {}",
            card,
            location
        );
    }

    /// Validate that board cards follow Texas Hold'em progression (0->3->4->5)
    fn validate_board_progression(&self) {
        let board_count = self.board_cards.len();
        assert!(
            matches!(board_count, 0 | 3 | 4 | 5),
            "Board must have 0, 3, 4, or 5 cards in Texas Hold'em, found {}",
            board_count
        );
    }

    /// Validate dealer positioning follows clockwise rotation rules
    fn validate_dealer_positioning(&self) {
        // Dealer must be at a valid position
        assert!(
            self.active_order.contains(&self.dealer_player_id),
            "Dealer player {} must be active in the hand",
            self.dealer_player_id
        );

        // For heads-up, dealer is small blind
        if self.active_order.len() == 2 {
            assert_eq!(
                self.small_blind_player,
                Some(self.dealer_player_id),
                "In heads-up play, dealer must be small blind"
            );
        }
    }

    /// Validate betting rounds follow proper sequence (preflop -> flop -> turn -> river -> showdown)
    fn validate_betting_round_sequence(&self) {
        let mut seen_streets = HashSet::new();
        let mut last_street = None;

        for round in &self.hh.rounds {
            let street = Street::from(round.street.as_str());
            seen_streets.insert(street);

            if let Some(prev_street) = last_street {
                assert!(
                    street.comes_after(prev_street) || street == prev_street,
                    "Street sequence violation: {:?} cannot follow {:?}",
                    street,
                    prev_street
                );
            }
            last_street = Some(street);
        }

        // If we have community cards, we must have seen the appropriate streets
        if matches!(self.board_cards.len(), 3..=5) {
            assert!(
                seen_streets.contains(&Street::Flop),
                "Flop street required for community cards"
            );
        }
    }

    /// Validate minimum raise sizing and blind structure
    fn validate_raise_sizing(&self) {
        if self.hh.big_blind_amount > 0.0 && self.hh.small_blind_amount > 0.0 {
            assert!(
                self.hh.big_blind_amount >= self.hh.small_blind_amount,
                "Big blind {} must be at least as large as small blind {}",
                self.hh.big_blind_amount,
                self.hh.small_blind_amount
            );
        }
    }

    /// Validate player hole cards (each active player should have exactly 2 cards)
    fn validate_player_hole_cards(&self) {
        for (player_id, state) in &self.players {
            if !state.sitting_out {
                // In a completed hand, each player should have been dealt exactly 2 cards
                // unless they were sitting out from the beginning
                assert!(
                    state.cards.len() <= 2,
                    "Player {} has {} hole cards, maximum is 2",
                    player_id,
                    state.cards.len()
                );

                // If the hand proceeded past dealing, all active players should have cards
                if !self.hh.rounds.is_empty() && state.cards.is_empty() && !state.folded {
                    // This is suspicious - player was active but never got cards
                    eprintln!("Warning: Active player {} has no hole cards", player_id);
                }
            }
        }
    }
}

fn determine_small_blind(active_order: &[u64], dealer_id: u64) -> Option<u64> {
    if active_order.len() < 2 {
        return None;
    }
    if active_order.len() == 2 {
        return Some(dealer_id);
    }
    next_after(active_order, dealer_id)
}

fn determine_big_blind(
    active_order: &[u64],
    dealer_id: u64,
    small_blind: Option<u64>,
) -> Option<u64> {
    if active_order.len() < 2 {
        return None;
    }
    if active_order.len() == 2 {
        return active_order.iter().copied().find(|id| *id != dealer_id);
    }
    let sb = small_blind?;
    next_after(active_order, sb)
}

fn next_after(active_order: &[u64], start: u64) -> Option<u64> {
    if active_order.is_empty() {
        return None;
    }
    let start_index = active_order.iter().position(|id| *id == start)?;
    for offset in 1..=active_order.len() {
        let idx = (start_index + offset) % active_order.len();
        let candidate = active_order[idx];
        if candidate != start {
            return Some(candidate);
        }
    }
    None
}

#[derive(Clone)]
struct PlayerState {
    starting_stack: f32,
    stack_remaining: f32,
    total_added_chips: f32,
    total_contribution: f32,
    cards: Vec<Card>,
    folded: bool,
    all_in: bool,
    sitting_out: bool,
}

impl PlayerState {
    fn new(player: &PlayerObj) -> Self {
        assert!(player.starting_stack.is_finite(), "Stacks must be finite");
        assert!(player.starting_stack >= 0.0, "Stacks cannot be negative");
        Self {
            starting_stack: player.starting_stack,
            stack_remaining: player.starting_stack,
            total_added_chips: 0.0,
            total_contribution: 0.0,
            cards: Vec::new(),
            folded: false,
            all_in: false,
            sitting_out: player.is_sitting_out.unwrap_or(false),
        }
    }

    fn is_available_for_action(&self) -> bool {
        !self.folded && !self.all_in && !self.sitting_out
    }
}

#[derive(Default)]
struct BettingRoundState {
    contributions: HashMap<u64, f32>,
    current_max: f32,
    /// The minimum raise amount (starts at big blind, increases with raises)
    min_raise: f32,
    /// The amount of the last raise (used to calculate min_raise)
    last_raise_amount: f32,
}

impl BettingRoundState {
    fn reset(&mut self, min_raise: f32) {
        self.contributions.clear();
        self.current_max = 0.0;
        self.min_raise = min_raise;
        self.last_raise_amount = min_raise;
    }

    fn record(&mut self, player_id: u64, amount: f32) -> f32 {
        let entry = self.contributions.entry(player_id).or_insert(0.0);
        *entry += amount;
        let previous_max = self.current_max;
        if *entry > self.current_max {
            self.current_max = *entry;
            // Update the minimum raise based on the raise amount
            let raise_amount = self.current_max - previous_max;
            if raise_amount > 0.0 {
                self.last_raise_amount = raise_amount;
                // In No-Limit, min_raise is at least the previous raise amount
                self.min_raise = self.min_raise.max(raise_amount);
            }
        }
        *entry
    }

    fn committed(&self, player_id: u64) -> f32 {
        *self.contributions.get(&player_id).unwrap_or(&0.0)
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
enum Street {
    Preflop,
    Flop,
    Turn,
    River,
    Showdown,
    Unknown,
}

impl Street {
    fn from(value: &str) -> Self {
        match value.to_lowercase().as_str() {
            "preflop" => Street::Preflop,
            "flop" => Street::Flop,
            "turn" => Street::Turn,
            "river" => Street::River,
            "showdown" => Street::Showdown,
            _ => Street::Unknown,
        }
    }

    fn is_betting_round(self) -> bool {
        matches!(
            self,
            Street::Preflop | Street::Flop | Street::Turn | Street::River
        )
    }

    fn comes_after(self, other: Street) -> bool {
        matches!(
            (self, other),
            (Street::Flop, Street::Preflop)
                | (Street::Turn, Street::Preflop | Street::Flop)
                | (Street::River, Street::Preflop | Street::Flop | Street::Turn)
                | (
                    Street::Showdown,
                    Street::Preflop | Street::Flop | Street::Turn | Street::River
                )
        )
    }
}

struct BettingRotation {
    order: Vec<u64>,
    queue: VecDeque<u64>,
}

impl BettingRotation {
    fn new(order: Vec<u64>) -> Self {
        Self {
            order,
            queue: VecDeque::new(),
        }
    }

    fn start_round(
        &mut self,
        street: Street,
        dealer_id: u64,
        big_blind: Option<u64>,
        players: &HashMap<u64, PlayerState>,
    ) {
        if !street.is_betting_round() {
            self.queue.clear();
            return;
        }
        let start_player = match street {
            Street::Preflop => {
                if self.order.len() == 2 {
                    Some(dealer_id)
                } else {
                    big_blind.and_then(|bb| self.next_active_after(bb, players))
                }
            }
            Street::Flop | Street::Turn | Street::River => {
                self.next_active_after(dealer_id, players)
            }
            _ => None,
        };

        if let Some(start) = start_player {
            self.queue = self.build_queue_from(start, players);
        } else {
            self.queue.clear();
        }
    }

    fn expect_actor(&mut self, player_id: u64, players: &HashMap<u64, PlayerState>) {
        self.trim_inactive(players);
        let expected = self
            .queue
            .front()
            .copied()
            .expect("No players left to act in betting round");
        assert_eq!(
            expected, player_id,
            "Action out of turn: expected player {expected}, saw {player_id}"
        );
        self.queue.rotate_left(1);
        self.trim_inactive(players);
    }

    fn rebuild_after_raise(&mut self, raiser: u64, players: &HashMap<u64, PlayerState>) {
        if let Some(next) = self.next_active_after(raiser, players) {
            self.queue = self.build_queue_from(next, players);
        } else {
            self.queue.clear();
        }
    }

    fn remove_player(&mut self, player_id: u64) {
        self.queue.retain(|id| *id != player_id);
    }

    fn trim_inactive(&mut self, players: &HashMap<u64, PlayerState>) {
        while let Some(front) = self.queue.front() {
            if players
                .get(front)
                .map(|s| s.is_available_for_action())
                .unwrap_or(false)
            {
                break;
            }
            self.queue.pop_front();
        }
    }

    fn build_queue_from(&self, start: u64, players: &HashMap<u64, PlayerState>) -> VecDeque<u64> {
        let mut queue = VecDeque::new();
        if self.order.is_empty() {
            return queue;
        }
        let start_index = self.order.iter().position(|id| *id == start).unwrap_or(0);
        for offset in 0..self.order.len() {
            let idx = (start_index + offset) % self.order.len();
            let candidate = self.order[idx];
            if players
                .get(&candidate)
                .map(|s| s.is_available_for_action())
                .unwrap_or(false)
            {
                queue.push_back(candidate);
            }
        }
        queue
    }

    fn next_active_after(
        &self,
        player_id: u64,
        players: &HashMap<u64, PlayerState>,
    ) -> Option<u64> {
        if self.order.is_empty() {
            return None;
        }
        let start_index = self.order.iter().position(|id| *id == player_id)?;
        for offset in 1..=self.order.len() {
            let idx = (start_index + offset) % self.order.len();
            let candidate = self.order[idx];
            if players
                .get(&candidate)
                .map(|s| s.is_available_for_action())
                .unwrap_or(false)
            {
                return Some(candidate);
            }
        }
        None
    }
}

fn approx_eq(lhs: f32, rhs: f32) -> bool {
    // Use abs_diff_eq with appropriate tolerance:
    // Allow 0.001% relative error to account for accumulated floating point
    // errors in chip calculations, with a floor at the arena's scaled
    // bet-epsilon (`magnitude * f32::EPSILON * 1000`). The arena accepts
    // individual bet/raise/call amounts within that scaled epsilon, so a sum
    // over N actions can drift by up to that much per action; the floor
    // keeps the cumulative pot/contribution checks from tripping on fuzz
    // inputs the arena itself considered legal.
    let max_val = lhs.abs().max(rhs.abs());
    let epsilon = if max_val == 0.0 {
        f32::EPSILON
    } else {
        (max_val / 100_000.0).max(max_val * f32::EPSILON * 1000.0)
    };
    abs_diff_eq!(lhs, rhs, epsilon = epsilon)
}

#[cfg(feature = "arena")]
struct HandHistoryArenaComparator<'a> {
    hh: &'a HandHistory,
    game_state: &'a crate::arena::GameState,
}

#[cfg(feature = "arena")]
impl<'a> HandHistoryArenaComparator<'a> {
    fn new(hh: &'a HandHistory, game_state: &'a crate::arena::GameState) -> Self {
        Self { hh, game_state }
    }

    fn assert_consistent(&self) {
        assert_eq!(
            self.hh.players.len(),
            self.game_state.num_players,
            "Hand history player count must match game state"
        );
        assert_eq!(
            self.hh.table_size as usize, self.game_state.num_players,
            "Hand history table size must match game state"
        );
        assert!(
            approx_eq(self.hh.small_blind_amount, self.game_state.small_blind),
            "Small blind mismatch"
        );
        assert!(
            approx_eq(self.hh.big_blind_amount, self.game_state.big_blind),
            "Big blind mismatch"
        );
        assert!(
            approx_eq(self.hh.ante_amount, self.game_state.ante),
            "Ante mismatch"
        );

        let board = collect_board_cards(self.hh);
        assert_eq!(
            board.as_slice(),
            self.game_state.board.as_slice(),
            "Board cards must align"
        );

        for (idx, player) in self.hh.players.iter().enumerate() {
            let expected_stack = *self
                .game_state
                .starting_stacks
                .get(idx)
                .expect("Game state must include starting stack");
            assert!(
                approx_eq(player.starting_stack, expected_stack),
                "Starting stack mismatch for player {idx}"
            );
            let was_active = self.game_state.player_active.get(idx);
            if player.is_sitting_out.unwrap_or(false) {
                assert!(
                    !was_active,
                    "Player {idx} marked sitting out but active in game state"
                );
            }
        }

        let total_pot_hh: f32 = self.hh.pots.iter().map(|pot| pot.amount).sum();
        assert!(
            approx_eq(total_pot_hh, self.game_state.total_pot),
            "Total pot mismatch"
        );

        let mut hh_winnings = vec![0.0f32; self.game_state.num_players];
        for pot in &self.hh.pots {
            for win in &pot.player_wins {
                let idx = win.player_id as usize;
                hh_winnings[idx] += win.win_amount;
            }
        }
        for (idx, &amount) in self.game_state.player_winnings.iter().enumerate() {
            assert!(
                approx_eq(amount, hh_winnings[idx]),
                "Player {idx} winnings mismatch"
            );
        }
    }
}

fn collect_board_cards(hand_history: &HandHistory) -> Vec<Card> {
    let mut cards = Vec::new();
    for round in &hand_history.rounds {
        if let Some(round_cards) = &round.cards {
            cards.extend(round_cards.iter().copied());
        }
    }
    cards
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::{Card, Suit, Value};
    use crate::open_hand_history::{BetLimitObj, BetType, GameType, PlayerWinsObj};

    fn sample_hand_history() -> HandHistory {
        let players = vec![
            PlayerObj {
                id: 0,
                seat: 1,
                name: "P1".into(),
                display: None,
                starting_stack: 100.0,
                player_bounty: None,
                is_sitting_out: Some(false),
            },
            PlayerObj {
                id: 1,
                seat: 2,
                name: "P2".into(),
                display: None,
                starting_stack: 100.0,
                player_bounty: None,
                is_sitting_out: Some(false),
            },
        ];

        let deal_p1 = ActionObj {
            action_number: 1,
            player_id: 0,
            action: Action::DealtCards,
            amount: 0.0,
            is_allin: false,
            cards: Some(vec![
                Card::new(Value::Ace, Suit::Spade),
                Card::new(Value::King, Suit::Heart),
            ]),
        };
        let deal_p2 = ActionObj {
            action_number: 2,
            player_id: 1,
            action: Action::DealtCards,
            amount: 0.0,
            is_allin: false,
            cards: Some(vec![
                Card::new(Value::Queen, Suit::Club),
                Card::new(Value::Queen, Suit::Diamond),
            ]),
        };
        let post_sb = ActionObj {
            action_number: 3,
            player_id: 0,
            action: Action::PostSmallBlind,
            amount: 1.0,
            is_allin: false,
            cards: None,
        };
        let post_bb = ActionObj {
            action_number: 4,
            player_id: 1,
            action: Action::PostBigBlind,
            amount: 2.0,
            is_allin: false,
            cards: None,
        };
        let fold = ActionObj {
            action_number: 5,
            player_id: 0,
            action: Action::Fold,
            amount: 0.0,
            is_allin: false,
            cards: None,
        };

        let rounds = vec![RoundObj {
            id: 1,
            street: "Preflop".into(),
            cards: None,
            actions: vec![deal_p1, deal_p2, post_sb, post_bb, fold],
        }];

        let pots = vec![PotObj {
            number: 1,
            amount: 3.0,
            rake: None,
            jackpot: None,
            player_wins: vec![PlayerWinsObj {
                player_id: 1,
                win_amount: 3.0,
                cashout_amount: None,
                cashout_fee: None,
                bonus_amount: None,
                contributed_rake: None,
            }],
        }];

        HandHistory {
            spec_version: "1.4.7".into(),
            site_name: "rs_poker".into(),
            network_name: "rs_poker".into(),
            internal_version: "test".into(),
            tournament: false,
            tournament_info: None,
            game_number: "1".into(),
            start_date_utc: None,
            table_name: "table".into(),
            table_handle: None,
            table_skin: None,
            game_type: GameType::Holdem,
            bet_limit: Some(BetLimitObj {
                bet_type: BetType::NoLimit,
                bet_cap: 0.0,
            }),
            table_size: 2,
            currency: "USD".into(),
            dealer_seat: 1,
            small_blind_amount: 1.0,
            big_blind_amount: 2.0,
            ante_amount: 0.0,
            hero_player_id: None,
            players,
            rounds,
            pots,
            tournament_bounties: None,
        }
    }

    #[test]
    fn valid_history_passes() {
        let history = sample_hand_history();
        assert_valid_open_hand_history(&history);
    }

    #[test]
    #[should_panic]
    fn duplicate_card_panics() {
        let mut history = sample_hand_history();
        if let Some(round) = history.rounds.first_mut()
            && let Some(action) = round
                .actions
                .iter_mut()
                .find(|a| a.player_id == 1 && matches!(a.action, Action::DealtCards))
        {
            action.cards = Some(vec![
                Card::new(Value::Ace, Suit::Spade),
                Card::new(Value::Two, Suit::Club),
            ]);
        }
        assert_valid_open_hand_history(&history);
    }

    #[test]
    fn allows_call_of_tiny_all_in_bet() {
        let players = vec![
            PlayerObj {
                id: 0,
                seat: 1,
                name: "Caller".into(),
                display: None,
                starting_stack: 100.0,
                player_bounty: None,
                is_sitting_out: Some(false),
            },
            PlayerObj {
                id: 1,
                seat: 2,
                name: "Shorty".into(),
                display: None,
                starting_stack: 1.0005,
                player_bounty: None,
                is_sitting_out: Some(false),
            },
        ];

        let preflop_actions = vec![
            ActionObj {
                action_number: 1,
                player_id: 0,
                action: Action::DealtCards,
                amount: 0.0,
                is_allin: false,
                cards: Some(vec![
                    Card::new(Value::Ten, Suit::Spade),
                    Card::new(Value::Nine, Suit::Heart),
                ]),
            },
            ActionObj {
                action_number: 2,
                player_id: 1,
                action: Action::DealtCards,
                amount: 0.0,
                is_allin: false,
                cards: Some(vec![
                    Card::new(Value::Eight, Suit::Club),
                    Card::new(Value::Seven, Suit::Diamond),
                ]),
            },
            ActionObj {
                action_number: 3,
                player_id: 0,
                action: Action::PostSmallBlind,
                amount: 1.0,
                is_allin: false,
                cards: None,
            },
            ActionObj {
                action_number: 4,
                player_id: 1,
                action: Action::PostBigBlind,
                amount: 1.0,
                is_allin: false,
                cards: None,
            },
            ActionObj {
                action_number: 5,
                player_id: 0,
                action: Action::Check,
                amount: 0.0,
                is_allin: false,
                cards: None,
            },
            ActionObj {
                action_number: 6,
                player_id: 1,
                action: Action::Check,
                amount: 0.0,
                is_allin: false,
                cards: None,
            },
        ];

        let flop_actions = vec![
            ActionObj {
                action_number: 1,
                player_id: 1,
                action: Action::Bet,
                amount: 0.0005,
                is_allin: true,
                cards: None,
            },
            ActionObj {
                action_number: 2,
                player_id: 0,
                action: Action::Call,
                amount: 0.0005,
                is_allin: false,
                cards: None,
            },
        ];

        let showdown_actions = vec![ActionObj {
            action_number: 1,
            player_id: 0,
            action: Action::ShowsCards,
            amount: 0.0,
            is_allin: false,
            cards: Some(vec![
                Card::new(Value::Ten, Suit::Spade),
                Card::new(Value::Nine, Suit::Heart),
            ]),
        }];

        let rounds = vec![
            RoundObj {
                id: 1,
                street: "Preflop".into(),
                cards: None,
                actions: preflop_actions,
            },
            RoundObj {
                id: 2,
                street: "Flop".into(),
                cards: Some(vec![
                    Card::new(Value::Two, Suit::Club),
                    Card::new(Value::Five, Suit::Heart),
                    Card::new(Value::Jack, Suit::Diamond),
                ]),
                actions: flop_actions,
            },
            RoundObj {
                id: 3,
                street: "Showdown".into(),
                cards: None,
                actions: showdown_actions,
            },
        ];

        let pots = vec![PotObj {
            number: 1,
            amount: 2.001,
            rake: None,
            jackpot: None,
            player_wins: vec![PlayerWinsObj {
                player_id: 0,
                win_amount: 2.001,
                cashout_amount: None,
                cashout_fee: None,
                bonus_amount: None,
                contributed_rake: None,
            }],
        }];

        let history = HandHistory {
            spec_version: "1.4.7".into(),
            site_name: "rs_poker".into(),
            network_name: "rs_poker".into(),
            internal_version: "test".into(),
            tournament: false,
            tournament_info: None,
            game_number: "micro-call".into(),
            start_date_utc: None,
            table_name: "tiny-pot".into(),
            table_handle: None,
            table_skin: None,
            game_type: GameType::Holdem,
            bet_limit: Some(BetLimitObj {
                bet_type: BetType::NoLimit,
                bet_cap: 0.0,
            }),
            table_size: 2,
            currency: "USD".into(),
            dealer_seat: 1,
            small_blind_amount: 1.0,
            big_blind_amount: 1.0,
            ante_amount: 0.0,
            hero_player_id: None,
            players,
            rounds,
            pots,
            tournament_bounties: None,
        };

        assert_valid_open_hand_history(&history);
    }

    #[test]
    fn allows_short_stack_all_in_bet() {
        let history = HandHistory {
            spec_version: "1.4.7".into(),
            site_name: "rs_poker".into(),
            network_name: "rs_poker_arena".into(),
            internal_version: "test".into(),
            tournament: false,
            tournament_info: None,
            game_number: "short_stack".into(),
            start_date_utc: None,
            table_name: "table".into(),
            table_handle: None,
            table_skin: None,
            game_type: GameType::Holdem,
            bet_limit: Some(BetLimitObj {
                bet_type: BetType::NoLimit,
                bet_cap: 0.0,
            }),
            table_size: 2,
            currency: "USD".into(),
            dealer_seat: 1,
            small_blind_amount: 1.0,
            big_blind_amount: 1.0,
            ante_amount: 0.0,
            hero_player_id: None,
            players: vec![
                PlayerObj {
                    id: 0,
                    seat: 1,
                    name: "Deep".into(),
                    display: None,
                    starting_stack: 10.0,
                    player_bounty: None,
                    is_sitting_out: Some(false),
                },
                PlayerObj {
                    id: 1,
                    seat: 2,
                    name: "Shorty".into(),
                    display: None,
                    starting_stack: 1.0005,
                    player_bounty: None,
                    is_sitting_out: Some(false),
                },
            ],
            rounds: vec![
                RoundObj {
                    id: 1,
                    street: "Preflop".into(),
                    cards: None,
                    actions: vec![
                        ActionObj {
                            action_number: 1,
                            player_id: 0,
                            action: Action::DealtCards,
                            amount: 0.0,
                            is_allin: false,
                            cards: Some(vec![
                                Card::new(Value::Ace, Suit::Spade),
                                Card::new(Value::King, Suit::Heart),
                            ]),
                        },
                        ActionObj {
                            action_number: 2,
                            player_id: 1,
                            action: Action::DealtCards,
                            amount: 0.0,
                            is_allin: false,
                            cards: Some(vec![
                                Card::new(Value::Queen, Suit::Club),
                                Card::new(Value::Jack, Suit::Diamond),
                            ]),
                        },
                        ActionObj {
                            action_number: 3,
                            player_id: 0,
                            action: Action::PostSmallBlind,
                            amount: 1.0,
                            is_allin: false,
                            cards: None,
                        },
                        ActionObj {
                            action_number: 4,
                            player_id: 1,
                            action: Action::PostBigBlind,
                            amount: 1.0,
                            is_allin: false,
                            cards: None,
                        },
                        ActionObj {
                            action_number: 5,
                            player_id: 0,
                            action: Action::Check,
                            amount: 0.0,
                            is_allin: false,
                            cards: None,
                        },
                        ActionObj {
                            action_number: 6,
                            player_id: 1,
                            action: Action::Check,
                            amount: 0.0,
                            is_allin: false,
                            cards: None,
                        },
                    ],
                },
                RoundObj {
                    id: 2,
                    street: "Flop".into(),
                    cards: Some(vec![
                        Card::new(Value::Two, Suit::Club),
                        Card::new(Value::Five, Suit::Diamond),
                        Card::new(Value::Seven, Suit::Heart),
                    ]),
                    actions: vec![
                        ActionObj {
                            action_number: 1,
                            player_id: 1,
                            action: Action::Check,
                            amount: 0.0,
                            is_allin: false,
                            cards: None,
                        },
                        ActionObj {
                            action_number: 2,
                            player_id: 0,
                            action: Action::Check,
                            amount: 0.0,
                            is_allin: false,
                            cards: None,
                        },
                    ],
                },
                RoundObj {
                    id: 3,
                    street: "Turn".into(),
                    cards: Some(vec![Card::new(Value::Nine, Suit::Spade)]),
                    actions: vec![
                        ActionObj {
                            action_number: 1,
                            player_id: 1,
                            action: Action::Bet,
                            amount: 0.0005,
                            is_allin: true,
                            cards: None,
                        },
                        ActionObj {
                            action_number: 2,
                            player_id: 0,
                            action: Action::Raise,
                            amount: 9.0,
                            is_allin: true,
                            cards: None,
                        },
                    ],
                },
            ],
            pots: vec![PotObj {
                number: 1,
                amount: 11.0005,
                rake: None,
                jackpot: None,
                player_wins: vec![PlayerWinsObj {
                    player_id: 0,
                    win_amount: 11.0005,
                    cashout_amount: None,
                    cashout_fee: None,
                    bonus_amount: None,
                    contributed_rake: None,
                }],
            }],
            tournament_bounties: None,
        };

        assert_valid_open_hand_history(&history);
    }

    #[test]
    fn allows_tiny_all_in_raise_after_call() {
        // Regression test for fuzzer crash: when a player has posted a large blind
        // and only has a tiny amount remaining, going all-in with that tiny amount
        // should be accepted as a valid raise even though the increase is smaller
        // than f32::EPSILON. This tests floating point precision with large bet sizes.
        let players = vec![
            PlayerObj {
                id: 0,
                seat: 1,
                name: "SB".into(),
                display: None,
                starting_stack: 195.26274,
                player_bounty: None,
                is_sitting_out: Some(false),
            },
            PlayerObj {
                id: 1,
                seat: 2,
                name: "BB".into(),
                display: None,
                starting_stack: 195.26282,
                player_bounty: None,
                is_sitting_out: Some(false),
            },
        ];

        let preflop_actions = vec![
            ActionObj {
                action_number: 1,
                player_id: 0,
                action: Action::DealtCards,
                amount: 0.0,
                is_allin: false,
                cards: Some(vec![
                    Card::new(Value::Three, Suit::Diamond),
                    Card::new(Value::Five, Suit::Heart),
                ]),
            },
            ActionObj {
                action_number: 2,
                player_id: 1,
                action: Action::DealtCards,
                amount: 0.0,
                is_allin: false,
                cards: Some(vec![
                    Card::new(Value::Five, Suit::Diamond),
                    Card::new(Value::Ace, Suit::Heart),
                ]),
            },
            ActionObj {
                action_number: 3,
                player_id: 0,
                action: Action::PostSmallBlind,
                amount: 195.24321,
                is_allin: false,
                cards: None,
            },
            ActionObj {
                action_number: 4,
                player_id: 1,
                action: Action::PostBigBlind,
                amount: 195.26271,
                is_allin: false,
                cards: None,
            },
            // SB calls to match BB
            ActionObj {
                action_number: 5,
                player_id: 0,
                action: Action::Call,
                amount: 0.019500732,
                is_allin: false,
                cards: None,
            },
            // BB goes all-in with tiny remaining amount - this is the key action
            // The raise amount (0.00010681152) is smaller than f32::EPSILON
            // but should be accepted because it's an all-in
            ActionObj {
                action_number: 6,
                player_id: 1,
                action: Action::Raise,
                amount: 0.00010681152,
                is_allin: true,
                cards: None,
            },
        ];

        let showdown_actions = vec![
            ActionObj {
                action_number: 1,
                player_id: 0,
                action: Action::ShowsCards,
                amount: 0.0,
                is_allin: false,
                cards: Some(vec![
                    Card::new(Value::Three, Suit::Diamond),
                    Card::new(Value::Five, Suit::Heart),
                ]),
            },
            ActionObj {
                action_number: 2,
                player_id: 1,
                action: Action::ShowsCards,
                amount: 0.0,
                is_allin: false,
                cards: Some(vec![
                    Card::new(Value::Five, Suit::Diamond),
                    Card::new(Value::Ace, Suit::Heart),
                ]),
            },
        ];

        let rounds = vec![
            RoundObj {
                id: 1,
                street: "Preflop".into(),
                cards: None,
                actions: preflop_actions,
            },
            RoundObj {
                id: 2,
                street: "Flop".into(),
                cards: Some(vec![
                    Card::new(Value::Three, Suit::Spade),
                    Card::new(Value::Six, Suit::Heart),
                    Card::new(Value::Jack, Suit::Heart),
                ]),
                actions: vec![],
            },
            RoundObj {
                id: 3,
                street: "Turn".into(),
                cards: Some(vec![Card::new(Value::Nine, Suit::Diamond)]),
                actions: vec![],
            },
            RoundObj {
                id: 4,
                street: "River".into(),
                cards: Some(vec![Card::new(Value::Two, Suit::Club)]),
                actions: vec![],
            },
            RoundObj {
                id: 5,
                street: "Showdown".into(),
                cards: None,
                actions: showdown_actions,
            },
        ];

        // Total pot: SB contributed 195.26271 + BB contributed 195.26282 = 390.52553
        let total_pot = 195.26271 + 0.00010681152 + 195.24321 + 0.019500732;
        let pots = vec![PotObj {
            number: 1,
            amount: total_pot,
            rake: None,
            jackpot: None,
            player_wins: vec![PlayerWinsObj {
                player_id: 1,
                win_amount: total_pot,
                cashout_amount: None,
                cashout_fee: None,
                bonus_amount: None,
                contributed_rake: None,
            }],
        }];

        let history = HandHistory {
            spec_version: "1.4.7".into(),
            site_name: "rs_poker".into(),
            network_name: "rs_poker_arena".into(),
            internal_version: "test".into(),
            tournament: false,
            tournament_info: None,
            game_number: "tiny_raise".into(),
            start_date_utc: None,
            table_name: "table".into(),
            table_handle: None,
            table_skin: None,
            game_type: GameType::Holdem,
            bet_limit: Some(BetLimitObj {
                bet_type: BetType::NoLimit,
                bet_cap: 0.0,
            }),
            table_size: 2,
            currency: "USD".into(),
            dealer_seat: 1,
            small_blind_amount: 195.24321,
            big_blind_amount: 195.26271,
            ante_amount: 0.0,
            hero_player_id: None,
            players,
            rounds,
            pots,
            tournament_bounties: None,
        };

        assert_valid_open_hand_history(&history);
    }

    #[test]
    fn allows_subnormal_ante_recorded_as_zero() {
        // Regression test for a config_agent fuzzer crash. With an extreme
        // (subnormal) ante like 9.2e-44 -- far below f32::EPSILON and below the
        // ULP of a normal stack -- the arena's chip math cannot move any chips
        // (`stack - ante == stack`), so the converter records a posted ante of
        // 0.0 while the OHH header keeps the configured `ante_amount`.
        //
        // Blind validation already tolerates this via `validate_forced_amount`
        // (`amount >= expected - f32::EPSILON`), but ante validation used to
        // reimplement the check without that tolerance and panicked.
        let subnormal_ante = 9.2e-44_f32;
        assert!(subnormal_ante > 0.0, "ante must stay positive");
        assert!(
            subnormal_ante < f32::EPSILON,
            "ante must be below the precision floor to exercise the bug"
        );

        let players = vec![
            PlayerObj {
                id: 0,
                seat: 1,
                name: "SB".into(),
                display: None,
                starting_stack: 120.0,
                player_bounty: None,
                is_sitting_out: Some(false),
            },
            PlayerObj {
                id: 1,
                seat: 2,
                name: "BB".into(),
                display: None,
                starting_stack: 120.0,
                player_bounty: None,
                is_sitting_out: Some(false),
            },
        ];

        let preflop_actions = vec![
            ActionObj {
                action_number: 1,
                player_id: 0,
                action: Action::DealtCards,
                amount: 0.0,
                is_allin: false,
                cards: Some(vec![
                    Card::new(Value::Ace, Suit::Spade),
                    Card::new(Value::King, Suit::Heart),
                ]),
            },
            ActionObj {
                action_number: 2,
                player_id: 1,
                action: Action::DealtCards,
                amount: 0.0,
                is_allin: false,
                cards: Some(vec![
                    Card::new(Value::Queen, Suit::Club),
                    Card::new(Value::Queen, Suit::Diamond),
                ]),
            },
            // Both players "post" the subnormal ante, but no chips actually move.
            ActionObj {
                action_number: 3,
                player_id: 0,
                action: Action::PostAnte,
                amount: 0.0,
                is_allin: false,
                cards: None,
            },
            ActionObj {
                action_number: 4,
                player_id: 1,
                action: Action::PostAnte,
                amount: 0.0,
                is_allin: false,
                cards: None,
            },
            ActionObj {
                action_number: 5,
                player_id: 0,
                action: Action::PostSmallBlind,
                amount: 1.0,
                is_allin: false,
                cards: None,
            },
            ActionObj {
                action_number: 6,
                player_id: 1,
                action: Action::PostBigBlind,
                amount: 2.0,
                is_allin: false,
                cards: None,
            },
            // Heads-up: dealer/SB acts first preflop and folds.
            ActionObj {
                action_number: 7,
                player_id: 0,
                action: Action::Fold,
                amount: 0.0,
                is_allin: false,
                cards: None,
            },
        ];

        let rounds = vec![RoundObj {
            id: 1,
            street: "Preflop".into(),
            cards: None,
            actions: preflop_actions,
        }];

        let pots = vec![PotObj {
            number: 1,
            amount: 3.0,
            rake: None,
            jackpot: None,
            player_wins: vec![PlayerWinsObj {
                player_id: 1,
                win_amount: 3.0,
                cashout_amount: None,
                cashout_fee: None,
                bonus_amount: None,
                contributed_rake: None,
            }],
        }];

        let history = HandHistory {
            spec_version: "1.4.7".into(),
            site_name: "rs_poker".into(),
            network_name: "rs_poker_arena".into(),
            internal_version: "test".into(),
            tournament: false,
            tournament_info: None,
            game_number: "subnormal_ante".into(),
            start_date_utc: None,
            table_name: "table".into(),
            table_handle: None,
            table_skin: None,
            game_type: GameType::Holdem,
            bet_limit: Some(BetLimitObj {
                bet_type: BetType::NoLimit,
                bet_cap: 0.0,
            }),
            table_size: 2,
            currency: "USD".into(),
            dealer_seat: 1,
            small_blind_amount: 1.0,
            big_blind_amount: 2.0,
            ante_amount: subnormal_ante,
            hero_player_id: None,
            players,
            rounds,
            pots,
            tournament_bounties: None,
        };

        assert_valid_open_hand_history(&history);
    }
}