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
use std::{
    collections::{BTreeSet, HashMap, HashSet},
    fmt,
    time::{Duration, Instant},
};

use rs_poker::arena::historian::StatsStorage;
use rs_poker::open_hand_history::{Action, HandHistory};

use crate::tui::event::SimError;
use crate::tui::widgets::stats_table::SortColumn;

/// Threshold for classifying profits as win/loss/breakeven.
pub const PROFIT_EPSILON: f32 = 0.01;

/// Compute per-player profits from an OHH `HandHistory`.
///
/// Returns `(id_to_idx, profits)` where `id_to_idx` maps player IDs to seat
/// indices and `profits[i]` is the net profit for the player at seat `i`.
pub fn compute_hand_profits(hand: &HandHistory) -> (HashMap<u64, usize>, Vec<f32>) {
    let num_players = hand.players.len();

    let id_to_idx: HashMap<u64, usize> = hand
        .players
        .iter()
        .enumerate()
        .map(|(i, p)| (p.id, i))
        .collect();

    let mut wins = vec![0.0_f32; num_players];
    for pot in &hand.pots {
        for pw in &pot.player_wins {
            if let Some(&idx) = id_to_idx.get(&pw.player_id) {
                wins[idx] += pw.win_amount;
            }
        }
    }

    let mut invested = vec![0.0_f32; num_players];
    for round in &hand.rounds {
        for action in &round.actions {
            if let Some(&idx) = id_to_idx.get(&action.player_id)
                && matches!(
                    action.action,
                    Action::Bet
                        | Action::Raise
                        | Action::Call
                        | Action::PostSmallBlind
                        | Action::PostBigBlind
                        | Action::PostAnte
                        | Action::Straddle
                        | Action::PostDead
                        | Action::PostExtraBlind
                        | Action::AddedToPot
                )
            {
                invested[idx] += action.amount;
            }
        }
    }

    let mut profits = vec![0.0_f32; num_players];
    for i in 0..num_players {
        profits[i] = wins[i] - invested[i];
    }

    (id_to_idx, profits)
}

/// Determine the ending round from a completed game's stats snapshot.
///
/// After `sim.run()`, `game_state.round` is always `Complete`, so we infer
/// the last street from which street-completion counters are non-zero.
/// The deepest street any player reached is the ending round.
pub fn ending_round_from_stats(stats: &StatsStorage, num_players: usize) -> RoundLabel {
    let any = |counts: &[usize]| counts.iter().take(num_players).any(|&c| c > 0);

    if any(&stats.showdown_count) {
        return RoundLabel::Showdown;
    }
    if any(&stats.river_completes) {
        return RoundLabel::River;
    }
    if any(&stats.turn_completes) {
        return RoundLabel::Turn;
    }
    if any(&stats.flop_completes) {
        return RoundLabel::Flop;
    }
    RoundLabel::Preflop
}

/// Flat per-seat stats extracted from a `StatsStorage` snapshot.
///
/// All fields are scalars — no heap allocations. This is `Copy` so it can be
/// sent across threads without triggering cross-thread malloc fragmentation
/// that caused OOM in the old `StatsStorage`-in-`GameResult` design.
#[derive(Debug, Clone, Copy, Default)]
pub struct SeatStats {
    pub actions_count: usize,
    pub vpip_count: usize,
    pub vpip_total: f32,
    pub raise_count: usize,
    pub hands_played: usize,
    pub hands_vpip: usize,
    pub hands_pfr: usize,
    pub preflop_raise_count: usize,
    pub preflop_actions: usize,
    pub three_bet_count: usize,
    pub three_bet_opportunities: usize,
    pub call_count: usize,
    pub bet_count: usize,
    pub total_profit: f32,
    pub total_invested: f32,
    pub games_won: usize,
    pub games_lost: usize,
    pub games_breakeven: usize,
    pub preflop_wins: usize,
    pub flop_wins: usize,
    pub turn_wins: usize,
    pub river_wins: usize,
    pub preflop_completes: usize,
    pub flop_completes: usize,
    pub turn_completes: usize,
    pub river_completes: usize,
    pub cbet_opportunities: usize,
    pub cbet_count: usize,
    pub wtsd_opportunities: usize,
    pub wtsd_count: usize,
    pub showdown_count: usize,
    pub showdown_wins: usize,
    pub fold_count: usize,
    pub flop_bets: usize,
    pub flop_raises: usize,
    pub flop_calls: usize,
    pub turn_bets: usize,
    pub turn_raises: usize,
    pub turn_calls: usize,
    pub river_bets: usize,
    pub river_raises: usize,
    pub river_calls: usize,
    pub steal_opportunities: usize,
    pub steal_count: usize,
}

impl SeatStats {
    /// Extract one seat's stats from a multi-player `StatsStorage`.
    pub fn from_storage(storage: &StatsStorage, seat: usize) -> Self {
        Self {
            actions_count: storage.actions_count[seat],
            vpip_count: storage.vpip_count[seat],
            vpip_total: storage.vpip_total[seat],
            raise_count: storage.raise_count[seat],
            hands_played: storage.hands_played[seat],
            hands_vpip: storage.hands_vpip[seat],
            hands_pfr: storage.hands_pfr[seat],
            preflop_raise_count: storage.preflop_raise_count[seat],
            preflop_actions: storage.preflop_actions[seat],
            three_bet_count: storage.three_bet_count[seat],
            three_bet_opportunities: storage.three_bet_opportunities[seat],
            call_count: storage.call_count[seat],
            bet_count: storage.bet_count[seat],
            total_profit: storage.total_profit[seat],
            total_invested: storage.total_invested[seat],
            games_won: storage.games_won[seat],
            games_lost: storage.games_lost[seat],
            games_breakeven: storage.games_breakeven[seat],
            preflop_wins: storage.preflop_wins[seat],
            flop_wins: storage.flop_wins[seat],
            turn_wins: storage.turn_wins[seat],
            river_wins: storage.river_wins[seat],
            preflop_completes: storage.preflop_completes[seat],
            flop_completes: storage.flop_completes[seat],
            turn_completes: storage.turn_completes[seat],
            river_completes: storage.river_completes[seat],
            cbet_opportunities: storage.cbet_opportunities[seat],
            cbet_count: storage.cbet_count[seat],
            wtsd_opportunities: storage.wtsd_opportunities[seat],
            wtsd_count: storage.wtsd_count[seat],
            showdown_count: storage.showdown_count[seat],
            showdown_wins: storage.showdown_wins[seat],
            fold_count: storage.fold_count[seat],
            flop_bets: storage.flop_bets[seat],
            flop_raises: storage.flop_raises[seat],
            flop_calls: storage.flop_calls[seat],
            turn_bets: storage.turn_bets[seat],
            turn_raises: storage.turn_raises[seat],
            turn_calls: storage.turn_calls[seat],
            river_bets: storage.river_bets[seat],
            river_raises: storage.river_raises[seat],
            river_calls: storage.river_calls[seat],
            steal_opportunities: storage.steal_opportunities[seat],
            steal_count: storage.steal_count[seat],
        }
    }

    /// Merge this seat's stats into a single-player accumulator at index 0.
    pub fn merge_into(&self, dest: &mut StatsStorage) {
        let d = 0;
        dest.actions_count[d] += self.actions_count;
        dest.vpip_count[d] += self.vpip_count;
        dest.vpip_total[d] += self.vpip_total;
        dest.raise_count[d] += self.raise_count;
        dest.hands_played[d] += self.hands_played;
        dest.hands_vpip[d] += self.hands_vpip;
        dest.hands_pfr[d] += self.hands_pfr;
        dest.preflop_raise_count[d] += self.preflop_raise_count;
        dest.preflop_actions[d] += self.preflop_actions;
        dest.three_bet_count[d] += self.three_bet_count;
        dest.three_bet_opportunities[d] += self.three_bet_opportunities;
        dest.call_count[d] += self.call_count;
        dest.bet_count[d] += self.bet_count;
        dest.total_profit[d] += self.total_profit;
        dest.total_invested[d] += self.total_invested;
        dest.games_won[d] += self.games_won;
        dest.games_lost[d] += self.games_lost;
        dest.games_breakeven[d] += self.games_breakeven;
        dest.preflop_wins[d] += self.preflop_wins;
        dest.flop_wins[d] += self.flop_wins;
        dest.turn_wins[d] += self.turn_wins;
        dest.river_wins[d] += self.river_wins;
        dest.preflop_completes[d] += self.preflop_completes;
        dest.flop_completes[d] += self.flop_completes;
        dest.turn_completes[d] += self.turn_completes;
        dest.river_completes[d] += self.river_completes;
        dest.cbet_opportunities[d] += self.cbet_opportunities;
        dest.cbet_count[d] += self.cbet_count;
        dest.wtsd_opportunities[d] += self.wtsd_opportunities;
        dest.wtsd_count[d] += self.wtsd_count;
        dest.showdown_count[d] += self.showdown_count;
        dest.showdown_wins[d] += self.showdown_wins;
        dest.fold_count[d] += self.fold_count;
        dest.flop_bets[d] += self.flop_bets;
        dest.flop_raises[d] += self.flop_raises;
        dest.flop_calls[d] += self.flop_calls;
        dest.turn_bets[d] += self.turn_bets;
        dest.turn_raises[d] += self.turn_raises;
        dest.turn_calls[d] += self.turn_calls;
        dest.river_bets[d] += self.river_bets;
        dest.river_raises[d] += self.river_raises;
        dest.river_calls[d] += self.river_calls;
        dest.steal_opportunities[d] += self.steal_opportunities;
        dest.steal_count[d] += self.steal_count;
    }
}

/// Result from a single completed game, sent from the simulation thread.
#[derive(Debug, Clone)]
pub struct GameResult {
    pub agent_names: Vec<String>,
    pub profits: Vec<f32>,
    pub ending_round: RoundLabel,
    pub seat_stats: Vec<SeatStats>,
    pub big_blind: f32,
}

/// Simplified round label for display.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RoundLabel {
    Preflop,
    Flop,
    Turn,
    River,
    Showdown,
}

impl RoundLabel {
    /// Parse an OHH street name into a `RoundLabel`.
    pub fn from_street_name(s: &str) -> Self {
        match s.to_lowercase().as_str() {
            "preflop" => Self::Preflop,
            "flop" => Self::Flop,
            "turn" => Self::Turn,
            "river" => Self::River,
            "showdown" => Self::Showdown,
            _ => Self::Showdown,
        }
    }
}

impl fmt::Display for RoundLabel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Preflop => write!(f, "preflop"),
            Self::Flop => write!(f, "flop"),
            Self::Turn => write!(f, "turn"),
            Self::River => write!(f, "river"),
            Self::Showdown => write!(f, "showdown"),
        }
    }
}

/// Pre-computed display data for one agent.
#[derive(Debug, Clone)]
pub struct AgentDisplayData {
    pub name: String,
    pub total_profit: f32,
    /// Cumulative profit in big blinds, accumulated per-game using each game's BB.
    pub profit_bb: f32,
    pub games_played: usize,
    pub wins: usize,
    pub vpip_percent: f32,
    pub pfr_percent: f32,
    pub three_bet_percent: f32,
    pub aggression_factor: f32,
    pub cbet_percent: f32,
    pub wtsd_percent: f32,
    pub wsd_percent: f32,
    pub roi_percent: f32,
}

/// Tracks how games ended across streets.
#[derive(Debug, Clone, Default)]
pub struct StreetDistribution {
    pub preflop: usize,
    pub flop: usize,
    pub turn: usize,
    pub river: usize,
    pub showdown: usize,
}

impl StreetDistribution {
    pub fn total(&self) -> usize {
        self.preflop + self.flop + self.turn + self.river + self.showdown
    }

    pub(crate) fn record(&mut self, round: RoundLabel) {
        match round {
            RoundLabel::Preflop => self.preflop += 1,
            RoundLabel::Flop => self.flop += 1,
            RoundLabel::Turn => self.turn += 1,
            RoundLabel::River => self.river += 1,
            RoundLabel::Showdown => self.showdown += 1,
        }
    }
}

fn toggle_in<T: Eq + std::hash::Hash>(set: &mut HashSet<T>, item: T) {
    if !set.remove(&item) {
        set.insert(item);
    }
}

fn toggle_in_str(set: &mut HashSet<String>, name: &str) {
    if !set.remove(name) {
        set.insert(name.to_string());
    }
}

/// Filter state for narrowing the game log and stats table.
#[derive(Debug, Clone, Default)]
pub struct FilterState {
    pub winners: HashSet<String>,
    pub losers: HashSet<String>,
    pub participants: HashSet<String>,
    pub streets: HashSet<RoundLabel>,
    pub win_sizes: HashSet<ProfitBucket>,
    pub loss_sizes: HashSet<ProfitBucket>,
    pub player_counts: HashSet<usize>,
    /// Index of the selected item in the filter panel list.
    pub selected: usize,
}

impl FilterState {
    pub fn is_active(&self) -> bool {
        !self.winners.is_empty()
            || !self.losers.is_empty()
            || !self.participants.is_empty()
            || !self.streets.is_empty()
            || !self.win_sizes.is_empty()
            || !self.loss_sizes.is_empty()
            || !self.player_counts.is_empty()
    }

    pub fn clear(&mut self) {
        self.winners.clear();
        self.losers.clear();
        self.participants.clear();
        self.streets.clear();
        self.win_sizes.clear();
        self.loss_sizes.clear();
        self.player_counts.clear();
    }

    pub fn toggle_winner(&mut self, name: &str) {
        toggle_in_str(&mut self.winners, name);
    }

    pub fn toggle_loser(&mut self, name: &str) {
        toggle_in_str(&mut self.losers, name);
    }

    pub fn toggle_participant(&mut self, name: &str) {
        toggle_in_str(&mut self.participants, name);
    }

    pub fn toggle_street(&mut self, street: RoundLabel) {
        toggle_in(&mut self.streets, street);
    }

    pub fn toggle_win_size(&mut self, bucket: ProfitBucket) {
        toggle_in(&mut self.win_sizes, bucket);
    }

    pub fn toggle_loss_size(&mut self, bucket: ProfitBucket) {
        toggle_in(&mut self.loss_sizes, bucket);
    }

    pub fn toggle_player_count(&mut self, count: usize) {
        toggle_in(&mut self.player_counts, count);
    }

    /// Returns true if the given game log entry passes all active filters.
    /// Filters combine with AND across types: winner AND participant AND street.
    pub fn matches_entry(&self, entry: &GameLogEntry) -> bool {
        // Winner filter: entry's biggest winner matches
        if !self.winners.is_empty() && !self.winners.contains(&entry.winner_name) {
            return false;
        }

        // Loser filter: entry's biggest loser matches
        if !self.losers.is_empty() && !self.losers.contains(&entry.loser_name) {
            return false;
        }

        // Participant filter: at least one participant in the entry matches
        if !self.participants.is_empty() {
            let has_participant = entry
                .agent_names
                .iter()
                .any(|name| self.participants.contains(name));
            if !has_participant {
                return false;
            }
        }

        // Street filter: entry's ending round matches one of the selected streets
        if !self.streets.is_empty() && !self.streets.contains(&entry.ending_round) {
            return false;
        }

        // Win size filter: bucket of winner's profit (already in BB; a zero-bb
        // entry buckets as Small, so no big-blind guard is needed here).
        if !self.win_sizes.is_empty() {
            let bucket = ProfitBucket::from_bb(entry.winner_profit);
            if !self.win_sizes.contains(&bucket) {
                return false;
            }
        }

        // Loss size filter: bucket of loser's loss in BB
        if !self.loss_sizes.is_empty() {
            let bucket = ProfitBucket::from_bb(entry.loser_loss.abs());
            if !self.loss_sizes.contains(&bucket) {
                return false;
            }
        }

        // Player count filter: entry's player count matches one of the selected counts
        if !self.player_counts.is_empty() && !self.player_counts.contains(&entry.agent_names.len())
        {
            return false;
        }

        true
    }
}

/// Bucket for categorizing profit/loss sizes in big blinds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ProfitBucket {
    /// 0-5 big blinds.
    Small,
    /// 5-20 big blinds.
    Medium,
    /// 20-100 big blinds.
    Large,
    /// 100+ big blinds.
    Huge,
}

impl ProfitBucket {
    /// Classify an amount (in big blinds) into a bucket.
    pub fn from_bb(amount_bb: f32) -> Self {
        if amount_bb < 5.0 {
            Self::Small
        } else if amount_bb < 20.0 {
            Self::Medium
        } else if amount_bb < 100.0 {
            Self::Large
        } else {
            Self::Huge
        }
    }

    /// Human-readable label for this bucket.
    pub fn label(self) -> &'static str {
        match self {
            Self::Small => "0-5bb",
            Self::Medium => "5-20bb",
            Self::Large => "20-100bb",
            Self::Huge => "100+bb",
        }
    }
}

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

/// All profit buckets in order.
pub const ALL_PROFIT_BUCKETS: [ProfitBucket; 4] = [
    ProfitBucket::Small,
    ProfitBucket::Medium,
    ProfitBucket::Large,
    ProfitBucket::Huge,
];

/// A single entry in the game log.
///
/// All chip amounts are normalized to big blinds using the game's big blind,
/// matching the rest of the arena stats output.
#[derive(Debug, Clone)]
pub struct GameLogEntry {
    pub game_number: usize,
    pub agent_names: Vec<String>,
    pub ending_round: RoundLabel,
    pub winner_name: String,
    /// Winner's profit in big blinds.
    pub winner_profit: f32,
    pub loser_name: String,
    /// Loser's loss (negative) in big blinds.
    pub loser_loss: f32,
    /// Pot size in big blinds.
    pub pot_size: f32,
}

impl GameLogEntry {
    /// Create a new game log entry, computing derived fields from the raw data.
    pub fn new(
        game_number: usize,
        agent_names: Vec<String>,
        profits: Vec<f32>,
        ending_round: RoundLabel,
        big_blind: f32,
    ) -> Self {
        // Normalize chip amounts to big blinds. A non-positive big blind never
        // occurs in a real game; we treat it as 0 bb so the value still buckets
        // as `ProfitBucket::Small` rather than producing inf/NaN from a divide.
        let to_bb = |chips: f32| {
            if big_blind > 0.0 {
                chips / big_blind
            } else {
                0.0
            }
        };

        let (winner_name, winner_profit) = agent_names
            .iter()
            .zip(profits.iter())
            .max_by(|a, b| a.1.partial_cmp(b.1).unwrap_or(std::cmp::Ordering::Equal))
            .map(|(n, &p)| (n.clone(), to_bb(p)))
            .unwrap_or_default();

        let (loser_name, loser_loss) = agent_names
            .iter()
            .zip(profits.iter())
            .min_by(|a, b| a.1.partial_cmp(b.1).unwrap_or(std::cmp::Ordering::Equal))
            .map(|(n, &p)| (n.clone(), to_bb(p)))
            .unwrap_or_default();

        let pot_size: f32 = to_bb(profits.iter().filter(|&&p| p > 0.0).sum());

        Self {
            game_number,
            agent_names,
            ending_round,
            winner_name,
            winner_profit,
            loser_name,
            loser_loss,
            pot_size,
        }
    }

    /// Create a `GameLogEntry` from an OHH `HandHistory`.
    pub fn from_hand(game_number: usize, hand: &HandHistory) -> Self {
        let agent_names: Vec<String> = hand.players.iter().map(|p| p.name.clone()).collect();
        let (_id_to_idx, profits) = compute_hand_profits(hand);

        let ending_round = hand
            .rounds
            .last()
            .map(|r| RoundLabel::from_street_name(&r.street))
            .unwrap_or(RoundLabel::Preflop);

        Self::new(
            game_number,
            agent_names,
            profits,
            ending_round,
            hand.big_blind_amount,
        )
    }
}

/// Running profit history for a single agent.
///
/// Stored as a ring buffer capped at [`MAX_PROFIT_HISTORY`] entries.
/// `first_game_index` is the absolute game number (1-based) of the
/// oldest sample still retained in `values`, so that after the front
/// has been evicted the chart can still label games by their true
/// absolute index (e.g. `[N - 10_000, N]`) instead of restarting
/// labels at zero.
#[derive(Debug, Default, Clone)]
pub struct ProfitHistory {
    pub first_game_index: usize,
    pub values: Vec<f32>,
}

impl ProfitHistory {
    /// x-axis index of the sample at position `i` within `values`.
    pub fn x_at(&self, i: usize) -> usize {
        self.first_game_index + i
    }
}

/// The complete TUI state, updated as game results arrive.
pub struct TuiState {
    pub games_target: Option<usize>,
    pub start_time: Instant,
    pub completed: bool,
    /// Whether this is a live simulation (true) or a static viewer (false).
    pub live: bool,
    /// Error from the simulation thread, if any.
    pub error: Option<SimError>,

    /// Projection over ALL games (maintained incrementally on each `update`).
    base: crate::tui::projection::Projection,
    /// Projection over only the filter-matching games, or `None` when no
    /// filter is active. Rebuilt from disk on filter change (Phase 3).
    filtered: Option<crate::tui::projection::Projection>,

    /// Distinct player counts observed across games.
    pub distinct_player_counts: BTreeSet<usize>,

    // Cached derived data
    cached_agent_names: Option<Vec<String>>,

    // UI state
    pub table_selected: Option<usize>,
    pub log_selected: Option<usize>,
    pub log_scroll: usize,
    pub sort_col: SortColumn,
    pub active_panel: Panel,
    pub filter: FilterState,
}

/// Which panel is currently focused for keyboard navigation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Panel {
    Table,
    GameLog,
    Filter,
}

impl Panel {
    pub fn next(self) -> Self {
        match self {
            Self::Table => Self::GameLog,
            Self::GameLog => Self::Filter,
            Self::Filter => Self::Table,
        }
    }

    pub fn prev(self) -> Self {
        match self {
            Self::Table => Self::Filter,
            Self::GameLog => Self::Table,
            Self::Filter => Self::GameLog,
        }
    }
}

impl TuiState {
    pub fn new(games_target: Option<usize>) -> Self {
        Self {
            games_target,
            start_time: Instant::now(),
            completed: false,
            live: true,
            error: None,
            base: crate::tui::projection::Projection::new(),
            filtered: None,
            distinct_player_counts: BTreeSet::new(),
            cached_agent_names: None,
            table_selected: None,
            log_selected: None,
            log_scroll: 0,
            sort_col: SortColumn::Profit,
            active_panel: Panel::Table,
            filter: FilterState::default(),
        }
    }

    /// Incorporate a game result into the base projection.
    pub fn update(&mut self, result: &GameResult) {
        self.base.fold(result);
        self.distinct_player_counts.insert(result.agent_names.len());
        self.cached_agent_names = None;
    }

    /// Total games seen (the base projection's count).
    pub fn games_completed(&self) -> usize {
        self.base.game_count()
    }

    /// Number of games matching the active filter, or the total when no filter
    /// is active.
    pub fn matching_games(&self) -> usize {
        self.filtered
            .as_ref()
            .map(|f| f.game_count())
            .unwrap_or_else(|| self.base.game_count())
    }

    /// The projection the views should read: filtered if active, else base.
    fn active_projection(&self) -> &crate::tui::projection::Projection {
        self.filtered.as_ref().unwrap_or(&self.base)
    }

    fn active_projection_mut(&mut self) -> &mut crate::tui::projection::Projection {
        self.filtered.as_mut().unwrap_or(&mut self.base)
    }

    /// Replace (or clear) the filtered projection. Called on filter change.
    pub fn set_filter_projection(&mut self, proj: Option<crate::tui::projection::Projection>) {
        self.filtered = proj;
    }

    /// Fold a newly-arrived game into the filtered projection if one is active.
    pub fn fold_filtered(&mut self, result: &GameResult) {
        if let Some(f) = self.filtered.as_mut() {
            f.fold(result);
        }
    }

    /// Per-agent display data over the ACTIVE projection, sorted by `sort_col`.
    pub fn agent_display_data(&mut self) -> Vec<AgentDisplayData> {
        let sort = self.sort_col;
        self.active_projection_mut().agent_display_data(sort)
    }

    /// All agent names seen across ALL games (for the filter panel options).
    pub fn all_agent_names(&mut self) -> Vec<String> {
        if let Some(cached) = &self.cached_agent_names {
            return cached.clone();
        }
        let names = self.base.agent_names();
        self.cached_agent_names = Some(names.clone());
        names
    }

    /// Invalidate the active projection's display cache (e.g. on sort change).
    pub fn invalidate_display_cache(&mut self) {
        self.active_projection_mut().invalidate_display_cache();
    }

    /// Profit histories over the ACTIVE projection (for the graph).
    pub fn profit_histories(&self) -> &HashMap<String, ProfitHistory> {
        self.active_projection().profit_histories()
    }

    /// Street distribution over the ACTIVE projection (for the street bars).
    pub fn street_dist(&self) -> &StreetDistribution {
        self.active_projection().street_dist()
    }

    pub fn elapsed(&self) -> Duration {
        self.start_time.elapsed()
    }

    pub fn games_per_second(&self) -> f64 {
        let secs = self.elapsed().as_secs_f64();
        if secs > 0.0 {
            self.games_completed() as f64 / secs
        } else {
            0.0
        }
    }

    pub fn eta(&self) -> Option<Duration> {
        let gps = self.games_per_second();
        let target = self.games_target?;
        if gps <= 0.0 || self.games_completed() >= target {
            return None;
        }
        let remaining = target - self.games_completed();
        Some(Duration::from_secs_f64(remaining as f64 / gps))
    }

    #[cfg(test)]
    pub fn set_games_completed(&mut self, n: usize) {
        self.base.set_game_count(n);
    }
}

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

    fn make_stats(num_players: usize) -> StatsStorage {
        StatsStorage::new_with_num_players(num_players)
    }

    fn make_game_result(names: &[&str], profits: &[f32], round: RoundLabel) -> GameResult {
        let num_players = names.len();
        let mut stats = make_stats(num_players);
        for (i, &profit) in profits.iter().enumerate() {
            stats.total_profit[i] = profit;
            stats.hands_played[i] = 1;
            stats.total_invested[i] = 10.0;
            if profit > 0.0 {
                stats.games_won[i] = 1;
            } else if profit < 0.0 {
                stats.games_lost[i] = 1;
            } else {
                stats.games_breakeven[i] = 1;
            }
        }
        let seat_stats: Vec<SeatStats> = (0..num_players)
            .map(|i| SeatStats::from_storage(&stats, i))
            .collect();
        GameResult {
            agent_names: names.iter().map(|s| s.to_string()).collect(),
            profits: profits.to_vec(),
            ending_round: round,
            seat_stats,
            big_blind: 10.0,
        }
    }

    #[test]
    fn test_new_state_is_empty() {
        let mut state = TuiState::new(Some(100));
        assert_eq!(state.games_completed(), 0);
        assert_eq!(state.games_target, Some(100));
        assert_eq!(state.street_dist().total(), 0);
        assert!(state.agent_display_data().is_empty());
    }

    #[test]
    fn test_update_single_game() {
        let mut state = TuiState::new(Some(10));
        let result = make_game_result(&["Alice", "Bob"], &[15.0, -15.0], RoundLabel::River);
        state.update(&result);

        assert_eq!(state.games_completed(), 1);
        assert_eq!(state.street_dist().river, 1);

        let agents = state.agent_display_data();
        assert_eq!(agents.len(), 2);
        // Sorted by profit desc, Alice should be first
        assert_eq!(agents[0].name, "Alice");
        assert_eq!(agents[0].total_profit, 15.0);
        assert_eq!(agents[1].name, "Bob");
        assert_eq!(agents[1].total_profit, -15.0);
    }

    #[test]
    fn test_update_multiple_games_accumulates() {
        let mut state = TuiState::new(None);
        state.update(&make_game_result(
            &["Alice", "Bob"],
            &[10.0, -10.0],
            RoundLabel::Flop,
        ));
        state.update(&make_game_result(
            &["Alice", "Bob"],
            &[-5.0, 5.0],
            RoundLabel::River,
        ));

        assert_eq!(state.games_completed(), 2);
        let agents = state.agent_display_data();
        let alice = agents.iter().find(|a| a.name == "Alice").unwrap();
        assert!((alice.total_profit - 5.0).abs() < 0.01);
        assert_eq!(alice.games_played, 2);
        assert_eq!(alice.wins, 1);
    }

    #[test]
    fn test_agent_profit_history_tracks_running_total() {
        let mut state = TuiState::new(None);
        state.update(&make_game_result(&["Alice"], &[10.0], RoundLabel::Preflop));
        state.update(&make_game_result(&["Alice"], &[-3.0], RoundLabel::Preflop));
        state.update(&make_game_result(&["Alice"], &[7.0], RoundLabel::Preflop));

        let histories = state.profit_histories();
        let alice_history = histories.get("Alice").unwrap();
        assert_eq!(alice_history.values.len(), 3);
        assert!((alice_history.values[0] - 10.0).abs() < 0.01);
        assert!((alice_history.values[1] - 7.0).abs() < 0.01);
        assert!((alice_history.values[2] - 14.0).abs() < 0.01);
    }

    /// Regression test for M8: once the profit history's ring buffer
    /// has evicted old samples, `first_game_index` must advance so the
    /// chart keeps labelling games by their absolute index (not 0..len
    /// starting fresh).
    #[test]
    fn test_profit_history_tracks_first_game_index_after_eviction() {
        let mut state = TuiState::new(None);
        let extra = 5;
        for _ in 0..(MAX_PROFIT_HISTORY + extra) {
            state.update(&make_game_result(&["Alice"], &[1.0], RoundLabel::Preflop));
        }

        let histories = state.profit_histories();
        let alice = histories.get("Alice").unwrap();
        assert_eq!(alice.values.len(), MAX_PROFIT_HISTORY);
        // The first retained sample is for game (extra + 1), since the
        // first `extra` were evicted from the front.
        assert_eq!(alice.first_game_index, extra + 1);
        // And x_at(0) reflects that offset.
        assert_eq!(alice.x_at(0), extra + 1);
        assert_eq!(
            alice.x_at(alice.values.len() - 1),
            MAX_PROFIT_HISTORY + extra
        );
    }

    #[test]
    fn test_street_distribution_counts_all_rounds() {
        let mut state = TuiState::new(None);
        state.update(&make_game_result(&["A"], &[1.0], RoundLabel::Preflop));
        state.update(&make_game_result(&["A"], &[1.0], RoundLabel::Flop));
        state.update(&make_game_result(&["A"], &[1.0], RoundLabel::Turn));
        state.update(&make_game_result(&["A"], &[1.0], RoundLabel::River));
        state.update(&make_game_result(&["A"], &[1.0], RoundLabel::Showdown));

        assert_eq!(state.street_dist().preflop, 1);
        assert_eq!(state.street_dist().flop, 1);
        assert_eq!(state.street_dist().turn, 1);
        assert_eq!(state.street_dist().river, 1);
        assert_eq!(state.street_dist().showdown, 1);
        assert_eq!(state.street_dist().total(), 5);
    }

    #[test]
    fn test_progress_calculations() {
        let mut state = TuiState::new(Some(100));
        for _ in 0..50 {
            state.update(&make_game_result(&["A"], &[1.0], RoundLabel::Preflop));
        }
        assert_eq!(state.games_completed(), 50);
        assert!(state.games_per_second() > 0.0);
    }

    #[test]
    fn test_eta_returns_none_when_no_target() {
        let state = TuiState::new(None);
        assert!(state.eta().is_none());
    }

    #[test]
    fn test_eta_returns_none_when_complete() {
        let mut state = TuiState::new(Some(1));
        state.update(&make_game_result(&["A"], &[1.0], RoundLabel::Preflop));
        assert!(state.eta().is_none());
    }

    #[test]
    fn test_agent_display_data_sorted_by_profit() {
        let mut state = TuiState::new(None);
        state.update(&make_game_result(
            &["Worst", "Best", "Mid"],
            &[-10.0, 20.0, 5.0],
            RoundLabel::River,
        ));

        let agents = state.agent_display_data();
        assert_eq!(agents[0].name, "Best");
        assert_eq!(agents[1].name, "Mid");
        assert_eq!(agents[2].name, "Worst");
    }

    #[test]
    fn test_duplicate_agent_name_single_profit_history_entry() {
        let mut state = TuiState::new(None);
        // Same agent in both seats (random with replacement)
        state.update(&make_game_result(
            &["Bot", "Bot"],
            &[10.0, -10.0],
            RoundLabel::River,
        ));

        let agents = state.agent_display_data();
        assert_eq!(agents.len(), 1);
        assert_eq!(agents[0].name, "Bot");
        // Net profit: 10 + (-10) = 0
        assert!((agents[0].total_profit - 0.0).abs() < 0.01);
        // Should have exactly 1 history entry, not 2
        let histories = state.profit_histories();
        let bot_history = histories.get("Bot").unwrap();
        assert_eq!(bot_history.values.len(), 1);
        assert!((bot_history.values[0] - 0.0).abs() < 0.01);
        // Both seats count as hands played
        assert_eq!(agents[0].games_played, 2);
    }

    #[test]
    fn test_seat_stats_roundtrip() {
        let mut source = make_stats(3);
        source.total_profit[1] = 42.0;
        source.hands_played[1] = 5;
        source.games_won[1] = 3;

        let seat = SeatStats::from_storage(&source, 1);
        assert_eq!(seat.total_profit, 42.0);
        assert_eq!(seat.hands_played, 5);
        assert_eq!(seat.games_won, 3);

        let mut dest = make_stats(1);
        seat.merge_into(&mut dest);
        assert_eq!(dest.total_profit[0], 42.0);
        assert_eq!(dest.hands_played[0], 5);
        assert_eq!(dest.games_won[0], 3);
    }

    #[test]
    fn test_panel_cycles_through_three() {
        assert_eq!(Panel::Table.next(), Panel::GameLog);
        assert_eq!(Panel::GameLog.next(), Panel::Filter);
        assert_eq!(Panel::Filter.next(), Panel::Table);
    }

    #[test]
    fn test_filter_state_default_is_inactive() {
        let filter = FilterState::default();
        assert!(!filter.is_active());
    }

    #[test]
    fn test_filter_toggle_winner() {
        let mut filter = FilterState::default();
        filter.toggle_winner("Alice");
        assert!(filter.is_active());
        assert!(filter.winners.contains("Alice"));
        // Toggle off
        filter.toggle_winner("Alice");
        assert!(!filter.is_active());
    }

    #[test]
    fn test_filter_toggle_participant() {
        let mut filter = FilterState::default();
        filter.toggle_participant("Bob");
        assert!(filter.participants.contains("Bob"));
        filter.toggle_participant("Bob");
        assert!(!filter.participants.contains("Bob"));
    }

    #[test]
    fn test_filter_toggle_street() {
        let mut filter = FilterState::default();
        filter.toggle_street(RoundLabel::Flop);
        assert!(filter.streets.contains(&RoundLabel::Flop));
        filter.toggle_street(RoundLabel::Flop);
        assert!(!filter.streets.contains(&RoundLabel::Flop));
    }

    #[test]
    fn test_filter_clear() {
        let mut filter = FilterState::default();
        filter.toggle_winner("Alice");
        filter.toggle_participant("Bob");
        filter.toggle_street(RoundLabel::River);
        assert!(filter.is_active());
        filter.clear();
        assert!(!filter.is_active());
    }

    fn make_entry(
        game_number: usize,
        names: &[&str],
        profits: &[f32],
        round: RoundLabel,
    ) -> GameLogEntry {
        GameLogEntry::new(
            game_number,
            names.iter().map(|s| s.to_string()).collect(),
            profits.to_vec(),
            round,
            10.0,
        )
    }

    #[test]
    fn test_game_log_entry_new_derived_fields() {
        // big blind of 10.0 → chip amounts normalized to big blinds.
        let entry = make_entry(1, &["Alice", "Bob"], &[15.0, -15.0], RoundLabel::River);
        assert_eq!(entry.winner_name, "Alice");
        assert!((entry.winner_profit - 1.5).abs() < 0.01);
        assert_eq!(entry.loser_name, "Bob");
        assert!((entry.loser_loss - (-1.5)).abs() < 0.01);
        assert!((entry.pot_size - 1.5).abs() < 0.01);
    }

    #[test]
    fn test_game_log_entry_three_players() {
        let entry = make_entry(
            1,
            &["A", "B", "C"],
            &[20.0, -5.0, -15.0],
            RoundLabel::Showdown,
        );
        assert_eq!(entry.winner_name, "A");
        assert!((entry.winner_profit - 2.0).abs() < 0.01);
        assert_eq!(entry.loser_name, "C");
        assert!((entry.loser_loss - (-1.5)).abs() < 0.01);
        assert!((entry.pot_size - 2.0).abs() < 0.01);
    }

    #[test]
    fn test_profit_bucket_from_bb() {
        assert_eq!(ProfitBucket::from_bb(0.0), ProfitBucket::Small);
        assert_eq!(ProfitBucket::from_bb(4.9), ProfitBucket::Small);
        assert_eq!(ProfitBucket::from_bb(5.0), ProfitBucket::Medium);
        assert_eq!(ProfitBucket::from_bb(19.9), ProfitBucket::Medium);
        assert_eq!(ProfitBucket::from_bb(20.0), ProfitBucket::Large);
        assert_eq!(ProfitBucket::from_bb(99.9), ProfitBucket::Large);
        assert_eq!(ProfitBucket::from_bb(100.0), ProfitBucket::Huge);
        assert_eq!(ProfitBucket::from_bb(500.0), ProfitBucket::Huge);
    }

    #[test]
    fn test_profit_bucket_label() {
        assert_eq!(ProfitBucket::Small.label(), "0-5bb");
        assert_eq!(ProfitBucket::Medium.label(), "5-20bb");
        assert_eq!(ProfitBucket::Large.label(), "20-100bb");
        assert_eq!(ProfitBucket::Huge.label(), "100+bb");
    }

    #[test]
    fn test_filter_matches_entry_no_filters() {
        let filter = FilterState::default();
        let entry = make_entry(1, &["Alice", "Bob"], &[10.0, -10.0], RoundLabel::River);
        assert!(filter.matches_entry(&entry));
    }

    #[test]
    fn test_filter_matches_winner() {
        let mut filter = FilterState::default();
        filter.toggle_winner("Alice");
        let entry = make_entry(1, &["Alice", "Bob"], &[10.0, -10.0], RoundLabel::River);
        assert!(filter.matches_entry(&entry));

        // Bob is not a winner in this entry
        let mut filter2 = FilterState::default();
        filter2.toggle_winner("Bob");
        assert!(!filter2.matches_entry(&entry));
    }

    #[test]
    fn test_filter_matches_loser() {
        let mut filter = FilterState::default();
        filter.toggle_loser("Bob");
        let entry = make_entry(1, &["Alice", "Bob"], &[10.0, -10.0], RoundLabel::River);
        assert!(filter.matches_entry(&entry));

        let mut filter2 = FilterState::default();
        filter2.toggle_loser("Alice");
        assert!(!filter2.matches_entry(&entry));
    }

    #[test]
    fn test_filter_matches_participant() {
        let mut filter = FilterState::default();
        filter.toggle_participant("Bob");
        let entry = make_entry(1, &["Alice", "Bob"], &[10.0, -10.0], RoundLabel::River);
        assert!(filter.matches_entry(&entry));

        let mut filter2 = FilterState::default();
        filter2.toggle_participant("Charlie");
        assert!(!filter2.matches_entry(&entry));
    }

    #[test]
    fn test_filter_matches_street() {
        let mut filter = FilterState::default();
        filter.toggle_street(RoundLabel::River);
        let river_entry = make_entry(1, &["A"], &[1.0], RoundLabel::River);
        let flop_entry = make_entry(2, &["A"], &[1.0], RoundLabel::Flop);
        assert!(filter.matches_entry(&river_entry));
        assert!(!filter.matches_entry(&flop_entry));
    }

    #[test]
    fn test_filter_matches_win_size() {
        let mut filter = FilterState::default();
        filter.toggle_win_size(ProfitBucket::Medium);
        // 10.0 profit / 10.0 bb = 1.0bb => Small, should not match
        let entry = make_entry(1, &["A", "B"], &[10.0, -10.0], RoundLabel::River);
        assert!(!filter.matches_entry(&entry));
        // 100.0 profit / 10.0 bb = 10.0bb => Medium, should match
        let entry2 = make_entry(2, &["A", "B"], &[100.0, -100.0], RoundLabel::River);
        assert!(filter.matches_entry(&entry2));
    }

    #[test]
    fn test_filter_matches_loss_size() {
        let mut filter = FilterState::default();
        filter.toggle_loss_size(ProfitBucket::Large);
        // loss = 10.0 / 10.0bb = 1.0bb => Small, should not match
        let entry = make_entry(1, &["A", "B"], &[10.0, -10.0], RoundLabel::River);
        assert!(!filter.matches_entry(&entry));
        // loss = 500.0 / 10.0bb = 50.0bb => Large, should match
        let entry2 = make_entry(2, &["A", "B"], &[500.0, -500.0], RoundLabel::River);
        assert!(filter.matches_entry(&entry2));
    }

    #[test]
    fn test_filter_and_semantics() {
        // Winner=Alice AND Street=River: both must match
        let mut filter = FilterState::default();
        filter.toggle_winner("Alice");
        filter.toggle_street(RoundLabel::River);

        let matching = make_entry(1, &["Alice", "Bob"], &[10.0, -10.0], RoundLabel::River);
        assert!(filter.matches_entry(&matching));

        // Alice wins but wrong street
        let wrong_street = make_entry(2, &["Alice", "Bob"], &[10.0, -10.0], RoundLabel::Flop);
        assert!(!filter.matches_entry(&wrong_street));

        // Right street but Alice lost
        let alice_lost = make_entry(3, &["Alice", "Bob"], &[-10.0, 10.0], RoundLabel::River);
        assert!(!filter.matches_entry(&alice_lost));
    }

    #[test]
    fn test_all_agent_names() {
        let mut state = TuiState::new(None);
        state.update(&make_game_result(
            &["Charlie", "Alice"],
            &[10.0, -10.0],
            RoundLabel::River,
        ));
        state.update(&make_game_result(
            &["Bob", "Alice"],
            &[5.0, -5.0],
            RoundLabel::Flop,
        ));
        let names = state.all_agent_names();
        assert_eq!(names, vec!["Alice", "Bob", "Charlie"]);
    }
}