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
use std::path::PathBuf;
use std::time::{Duration, Instant};

use itertools::Itertools;
use rand::{RngExt, SeedableRng, rngs::StdRng};
use tracing::event;

use crate::arena::agent::{AgentConfig, ConfigAgentBuilder};
use crate::arena::game_state::{GameState, RandomGameStateGenerator};
#[cfg(feature = "open-hand-history")]
use crate::arena::historian::OpenHandHistoryHistorian;
use crate::arena::historian::{StatsStorage, StatsTrackingHistorian};
use crate::arena::{Agent, Historian, HoldemSimulationBuilder, seeded_rng};

use super::config::ComparisonConfig;
use super::error::{ComparisonError, Result};
use super::result::ComparisonResult;
use super::stats::AgentStatsBuilder;

/// Result from a single permutation within a comparison game.
#[derive(Debug, Clone)]
pub struct PermutationResult {
    /// Agent names in seat order for this permutation.
    pub agent_names: Vec<String>,
    /// Per-player stats from this game.
    pub stats: StatsStorage,
    /// How long this permutation took to simulate.
    pub duration: Duration,
}

/// Context for running permutations within a single game state.
/// Groups the mutable and shared state needed by `run_single_game_state`.
struct PermutationContext<'a, F> {
    agent_configs: &'a [AgentConfig],
    agent_names: &'a [String],
    builder: &'a mut AgentStatsBuilder,
    // Concrete `StdRng` (not `&mut dyn Rng`) so the runner's async body is
    // `Send` and can be driven from a `tokio::spawn`ed task.
    rng: &'a mut StdRng,
    #[cfg_attr(not(feature = "open-hand-history"), allow(dead_code))]
    ohh_output_path: Option<&'a PathBuf>,
    on_game: F,
}

/// Runs agent comparisons across all permutations of seat arrangements
///
/// This struct orchestrates the comparison of multiple poker agents by:
/// 1. Generating random game states
/// 2. Running all permutations of agent seat assignments
/// 3. Collecting and aggregating statistics
/// 4. Producing comparison results
#[derive(Debug)]
pub struct ArenaComparison {
    config: ComparisonConfig,
    agents: Vec<(String, AgentConfig)>,
}

impl ArenaComparison {
    /// Create a new ArenaComparison (internal - use ComparisonBuilder instead)
    pub(crate) fn new(config: ComparisonConfig, agents: Vec<(String, AgentConfig)>) -> Self {
        Self { config, agents }
    }

    /// Get the comparison configuration
    pub fn config(&self) -> &ComparisonConfig {
        &self.config
    }

    /// Get the configured agents
    pub fn agents(&self) -> &[(String, AgentConfig)] {
        &self.agents
    }

    /// Get the number of agents
    pub fn num_agents(&self) -> usize {
        self.agents.len()
    }

    /// Calculate the total number of permutations
    pub fn total_permutations(&self) -> usize {
        (0..self.agents.len())
            .permutations(self.config.players_per_table)
            .count()
    }

    /// Calculate the total number of games to simulate
    pub fn total_games(&self) -> usize {
        self.total_permutations() * self.config.num_games
    }

    /// Run the comparison and return results
    pub async fn run(&self) -> Result<ComparisonResult> {
        self.run_with_callback(|_| {}).await
    }

    /// Run the comparison, calling `on_game` after each permutation
    /// completes. The callback is always called to completion.
    pub async fn run_with_callback<F>(&self, mut on_game: F) -> Result<ComparisonResult>
    where
        F: FnMut(PermutationResult),
    {
        self.run_with_cancellable_callback(|perm| {
            on_game(perm);
            std::ops::ControlFlow::Continue(())
        })
        .await
    }

    /// Run the comparison, calling `on_game` after each permutation
    /// completes. The callback returns a `ControlFlow` value; returning
    /// `Break(())` cancels the comparison after the current permutation,
    /// leaving any remaining permutations unrun.
    ///
    /// Use this variant when a downstream consumer (e.g., a TUI that the
    /// user quit) wants the comparison to stop promptly rather than
    /// continuing to allocate CFR trees that will never be observed.
    pub async fn run_with_cancellable_callback<F>(&self, mut on_game: F) -> Result<ComparisonResult>
    where
        F: FnMut(PermutationResult) -> std::ops::ControlFlow<()>,
    {
        event!(
            tracing::Level::INFO,
            num_agents = self.agents.len(),
            num_games = self.config.num_games,
            players_per_table = self.config.players_per_table,
            "Starting agent comparison"
        );

        // Create RNG
        let mut rng = seeded_rng(self.config.seed);

        // Extract agent names and configs
        let agent_names: Vec<String> = self.agents.iter().map(|(name, _)| name.clone()).collect();
        let agent_configs: Vec<AgentConfig> = self.agents.iter().map(|(_, c)| c.clone()).collect();

        // Create stats builder
        let mut builder = AgentStatsBuilder::new(agent_names.clone());

        // Create game state generator (seeded if seed is provided)
        let min_stack = self.config.min_stack();
        let max_stack = self.config.max_stack();
        let mut game_state_gen = if let Some(seed) = self.config.seed {
            // Use a derived seed for game state generation to keep it separate from simulation RNG
            RandomGameStateGenerator::with_seed(
                self.config.players_per_table,
                min_stack,
                max_stack,
                self.config.big_blind,
                self.config.small_blind,
                self.config.ante,
                seed.wrapping_add(1),
            )
        } else {
            RandomGameStateGenerator::new(
                self.config.players_per_table,
                min_stack,
                max_stack,
                self.config.big_blind,
                self.config.small_blind,
                self.config.ante,
            )
        };

        // Compute OHH output path if output_dir is specified
        let ohh_output_path = self
            .config
            .output_dir
            .as_ref()
            .map(|dir| dir.join("hands.jsonl"));

        // Run simulations for each game state
        let total_permutations = self.total_permutations();
        let log_interval = 100; // Log progress every 100 game states

        for game_idx in 0..self.config.num_games {
            // Log progress every log_interval games
            if game_idx > 0 && game_idx % log_interval == 0 {
                let games_completed = game_idx * total_permutations;
                let total_games = self.config.num_games * total_permutations;
                let percent = (games_completed as f64 / total_games as f64) * 100.0;
                println!(
                    "Progress: {}/{} game states ({}/{} total games, {:.1}%)",
                    game_idx, self.config.num_games, games_completed, total_games, percent
                );
            }

            // Generate a game state
            let game_state = game_state_gen
                .next()
                .ok_or(ComparisonError::GameStateGeneratorExhausted)?;

            // Run all permutations with this game state
            let mut perm_ctx = PermutationContext {
                agent_configs: &agent_configs,
                agent_names: &agent_names,
                builder: &mut builder,
                rng: &mut rng,
                ohh_output_path: ohh_output_path.as_ref(),
                on_game: &mut on_game,
            };
            if self
                .run_single_game_state(game_state, &mut perm_ctx)
                .await?
                .is_break()
            {
                event!(tracing::Level::INFO, game_idx, "Comparison cancelled");
                break;
            }
        }

        // Build the final aggregated statistics
        let agent_stats = builder.build();
        let total_permutations = self.total_permutations();

        Ok(ComparisonResult::new(
            agent_names,
            agent_stats,
            self.config.clone(),
            total_permutations,
        ))
    }

    /// Run all permutations for a single game state. Returns
    /// `ControlFlow::Break(())` if the callback asked to cancel.
    async fn run_single_game_state<F>(
        &self,
        game_state: GameState,
        perm_ctx: &mut PermutationContext<'_, F>,
    ) -> Result<std::ops::ControlFlow<()>>
    where
        F: FnMut(PermutationResult) -> std::ops::ControlFlow<()>,
    {
        let agent_configs = perm_ctx.agent_configs;
        let agent_names = perm_ctx.agent_names;
        let builder = &mut perm_ctx.builder;
        let rng = &mut perm_ctx.rng;
        #[cfg(feature = "open-hand-history")]
        let ohh_output_path = perm_ctx.ohh_output_path;
        let on_game = &mut perm_ctx.on_game;
        let players_per_table = self.config.players_per_table;
        let total_permutations = (0..agent_configs.len())
            .permutations(players_per_table)
            .count();

        event!(
            tracing::Level::DEBUG,
            total_permutations,
            players_per_table,
            "Running permutations for game state"
        );

        // Generate all permutations of size players_per_table from num_agents
        for (perm_idx, permutation) in (0..agent_configs.len())
            .permutations(players_per_table)
            .enumerate()
        {
            event!(
                tracing::Level::TRACE,
                perm_idx,
                total_permutations,
                ?permutation,
                "Starting permutation"
            );
            // If any agent in this permutation is CFR-based, create shared
            // context so all CFR agents share the same state store and
            // traversal set.
            let cfr_context = AgentConfig::maybe_shared_cfr_context(
                permutation
                    .iter()
                    .map(|&agent_idx| &agent_configs[agent_idx]),
                &game_state,
                players_per_table,
            );

            // Create agents for this permutation
            let boxed_agents: Vec<Box<dyn Agent>> = permutation
                .iter()
                .enumerate()
                .map(|(idx, &agent_idx)| {
                    let mut builder = ConfigAgentBuilder::new(agent_configs[agent_idx].clone())
                        .expect("Failed to create agent builder")
                        .player_idx(idx);
                    // Inject shared CFR context BEFORE game_state to avoid
                    // wasted eager allocation in game_state()
                    if let Some((ref cfr_state, ref ts)) = cfr_context {
                        builder = builder.cfr_context(cfr_state.clone(), ts.clone());
                    }
                    builder = builder.game_state(game_state.clone());
                    // Derive a deterministic per-agent seed from the runner's RNG
                    builder = builder.rng_seed(rng.random::<u64>());
                    builder.build()
                })
                .collect();

            // Create stats historian and get a clone of its storage
            let stats_historian = StatsTrackingHistorian::new_with_num_players(players_per_table);
            let stats_storage = stats_historian.get_storage();

            // Build historians list
            #[allow(unused_mut)]
            let mut historians: Vec<Box<dyn Historian>> = vec![Box::new(stats_historian)];

            // Add OpenHandHistory historian if output path is specified
            #[cfg(feature = "open-hand-history")]
            if let Some(output_path) = ohh_output_path {
                historians.push(Box::new(OpenHandHistoryHistorian::new(output_path.clone())));
            }

            // Fork a fresh owned RNG per simulation. We cannot move/borrow the
            // runner's `rng` into the sim: `build_with_rng` takes the RNG by
            // value and stores it as `Box<dyn Rng>` so `run()` can be async
            // without holding `&mut R` across awaits, and the sim *uses* that
            // RNG during `run()` (dealing community cards via `deck.deal`).
            // Meanwhile the runner's `rng` is borrowed and must survive every
            // permutation and game state. `from_rng` derives a deterministic
            // independent sub-stream, advancing the runner's RNG for the next
            // permutation.
            let sub_rng = StdRng::from_rng(rng);
            let mut sim_builder = HoldemSimulationBuilder::default()
                .game_state(game_state.clone())
                .agents(boxed_agents)
                .historians(historians);
            if let Some((cfr_state, traversal_set)) = cfr_context {
                sim_builder = sim_builder.cfr_context(cfr_state, traversal_set, true);
            }
            let mut sim = sim_builder.build_with_rng(sub_rng)?;

            let perm_start = Instant::now();
            // `run` is async and the runner is now async too; await the
            // simulation directly so spawned CFR exploration tasks are driven
            // by the surrounding tokio runtime.
            sim.run().await;
            let perm_duration = perm_start.elapsed();

            event!(
                tracing::Level::TRACE,
                perm_idx,
                total_permutations,
                final_round = ?sim.game_state.round,
                "Completed permutation"
            );

            // Drop the simulation immediately to free the CFR tree
            // before we read stats or invoke the callback.
            drop(sim);

            // Extract statistics from the historian via the shared storage.
            // Clone out of the guard and release it immediately so we never
            // hold a read lock across the (potentially blocking) `on_game`
            // callback.
            let stats = {
                let guard =
                    stats_storage
                        .try_read()
                        .map_err(|e| ComparisonError::StatsUnavailable {
                            reason: e.to_string(),
                        })?;
                guard.clone()
            };

            // Notify the callback with per-permutation data
            let perm_names: Vec<String> = permutation
                .iter()
                .map(|&agent_idx| agent_names[agent_idx].clone())
                .collect();
            let control = on_game(PermutationResult {
                agent_names: perm_names,
                stats: stats.clone(),
                duration: perm_duration,
            });

            // Merge the stats into the builder using agent indices
            builder.merge_permutation_stats(&permutation, &stats);

            if control.is_break() {
                return Ok(std::ops::ControlFlow::Break(()));
            }
        }

        Ok(std::ops::ControlFlow::Continue(()))
    }

    /// Print a summary of the configuration to stdout
    pub fn print_configuration_summary(&self) {
        println!("Agent Comparison Configuration");
        println!("==============================");
        println!();
        println!("Number of Agents: {}", self.agents.len());
        println!("Players per Table: {}", self.config.players_per_table);
        println!("Number of Games: {}", self.config.num_games);
        println!();
        println!("Game Settings:");
        println!("  Big Blind: {}", self.config.big_blind);
        println!("  Small Blind: {}", self.config.small_blind);
        if self.config.ante > 0.0 {
            println!("  Ante: {}", self.config.ante);
        }
        println!(
            "  Stack Range: {}-{} BB",
            self.config.min_stack_bb, self.config.max_stack_bb
        );
        if let Some(seed) = self.config.seed {
            println!("  Random Seed: {}", seed);
        }
        if let Some(ref output_dir) = self.config.output_dir {
            println!("  Output Directory: {}", output_dir.display());
        }
        println!();
        println!("Loaded Agents:");
        for (name, _) in &self.agents {
            println!("  - {}", name);
        }
        println!();

        // Calculate and display permutation count
        let total_permutations = self.total_permutations();
        let total_games = self.total_games();

        println!("Simulation Scale:");
        println!("  Total permutations: {}", total_permutations);
        println!(
            "  Total games to simulate: {} × {} = {}",
            total_permutations, self.config.num_games, total_games
        );
        println!();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::arena::comparison::ComparisonBuilder;

    #[test]
    fn test_arena_comparison_total_permutations() {
        let comparison = ComparisonBuilder::new()
            .players_per_table(2)
            .add_agent_config(AgentConfig::Folding {
                name: Some("A".to_string()),
            })
            .add_agent_config(AgentConfig::Folding {
                name: Some("B".to_string()),
            })
            .add_agent_config(AgentConfig::Folding {
                name: Some("C".to_string()),
            })
            .build()
            .unwrap();

        // P(3, 2) = 3 * 2 = 6
        assert_eq!(comparison.total_permutations(), 6);
    }

    #[test]
    fn test_arena_comparison_total_games() {
        let comparison = ComparisonBuilder::new()
            .num_games(100)
            .players_per_table(2)
            .add_agent_config(AgentConfig::Folding {
                name: Some("A".to_string()),
            })
            .add_agent_config(AgentConfig::Folding {
                name: Some("B".to_string()),
            })
            .build()
            .unwrap();

        // P(2, 2) = 2, so total = 2 * 100 = 200
        assert_eq!(comparison.total_games(), 200);
    }

    #[tokio::test]
    async fn test_arena_comparison_run() {
        let comparison = ComparisonBuilder::new()
            .num_games(10)
            .players_per_table(2)
            .seed(42)
            .add_agent_config(AgentConfig::Folding {
                name: Some("Folder".to_string()),
            })
            .add_agent_config(AgentConfig::Calling {
                name: Some("Caller".to_string()),
            })
            .build()
            .unwrap();

        let result = comparison.run().await.unwrap();

        // Check we got results for both agents
        assert_eq!(result.agent_names().len(), 2);
        assert!(result.get_agent_stats("Folder").is_some());
        assert!(result.get_agent_stats("Caller").is_some());

        // Check total permutations
        assert_eq!(result.total_permutations(), 2);

        // Check total games
        assert_eq!(result.total_games(), 20);
    }

    /// Regression test for M5: a callback returning
    /// `ControlFlow::Break` must stop the comparison after the current
    /// permutation, leaving the remaining permutations unrun.
    #[tokio::test]
    async fn test_run_with_cancellable_callback_stops_early() {
        use std::ops::ControlFlow;
        use std::sync::atomic::{AtomicUsize, Ordering};

        let comparison = ComparisonBuilder::new()
            .num_games(100)
            .players_per_table(2)
            .seed(7)
            .add_agent_config(AgentConfig::Folding {
                name: Some("A".to_string()),
            })
            .add_agent_config(AgentConfig::Calling {
                name: Some("B".to_string()),
            })
            .build()
            .unwrap();

        let seen = AtomicUsize::new(0);
        let _ = comparison
            .run_with_cancellable_callback(|_perm| {
                let count = seen.fetch_add(1, Ordering::Relaxed) + 1;
                if count >= 3 {
                    ControlFlow::Break(())
                } else {
                    ControlFlow::Continue(())
                }
            })
            .await
            .unwrap();

        let count = seen.load(Ordering::Relaxed);
        assert!(
            count <= 4,
            "cancellation should stop after ~3 permutations, got {count}"
        );
    }

    #[tokio::test]
    async fn test_arena_comparison_run_with_three_agents() {
        let comparison = ComparisonBuilder::new()
            .num_games(5)
            .players_per_table(2)
            .seed(123)
            .add_agent_config(AgentConfig::Folding {
                name: Some("A".to_string()),
            })
            .add_agent_config(AgentConfig::Calling {
                name: Some("B".to_string()),
            })
            .add_agent_config(AgentConfig::AllIn {
                name: Some("C".to_string()),
            })
            .build()
            .unwrap();

        let result = comparison.run().await.unwrap();

        // P(3, 2) = 6 permutations
        assert_eq!(result.total_permutations(), 6);

        // Total games = 6 * 5 = 30
        assert_eq!(result.total_games(), 30);

        // All three agents should have stats
        assert!(result.get_agent_stats("A").is_some());
        assert!(result.get_agent_stats("B").is_some());
        assert!(result.get_agent_stats("C").is_some());
    }

    #[tokio::test]
    async fn test_arena_comparison_roi_tracking() {
        // Test that ROI is properly calculated based on investment
        let comparison = ComparisonBuilder::new()
            .num_games(20)
            .players_per_table(2)
            .seed(42)
            .add_agent_config(AgentConfig::Calling {
                name: Some("Caller".to_string()),
            })
            .add_agent_config(AgentConfig::Folding {
                name: Some("Folder".to_string()),
            })
            .build()
            .unwrap();

        let result = comparison.run().await.unwrap();

        let caller_stats = result.get_agent_stats("Caller").unwrap();
        let folder_stats = result.get_agent_stats("Folder").unwrap();

        // Caller should have some investment (they call bets)
        // We can't assert exact values due to randomness, but:
        // - If caller has positive profit and positive investment, ROI should be profit/investment * 100
        // - If caller has negative profit, ROI should be negative

        // Folder pays forced blinds every hand. FoldingAgent folds only when
        // facing a bet, so in BB it checks to showdown and wins some. Either
        // way, ROI must never fall below -100% — you cannot lose more than you
        // wager.
        assert!(
            folder_stats.roi_percent >= -100.0,
            "ROI must not fall below -100%, got {}",
            folder_stats.roi_percent
        );
        assert!(
            caller_stats.roi_percent >= -100.0,
            "ROI must not fall below -100%, got {}",
            caller_stats.roi_percent
        );

        // Caller invests money, so they should have non-zero ROI
        // (unless by chance they break exactly even on investment, which is unlikely)
        // We just verify that the stats exist and are reasonable
        assert!(
            caller_stats.total_games > 0,
            "Caller should have played games"
        );
    }

    #[tokio::test]
    async fn test_arena_comparison_position_stats() {
        // Test that position stats are tracked for each agent
        let comparison = ComparisonBuilder::new()
            .num_games(10)
            .players_per_table(2)
            .seed(999)
            .add_agent_config(AgentConfig::Calling {
                name: Some("Player1".to_string()),
            })
            .add_agent_config(AgentConfig::Folding {
                name: Some("Player2".to_string()),
            })
            .build()
            .unwrap();

        let result = comparison.run().await.unwrap();

        let player1 = result.get_agent_stats("Player1").unwrap();

        // With 2 agents and 2 players_per_table, each agent plays in both positions
        // Each agent should have played 10 games in each of 2 positions
        assert_eq!(
            player1.position_stats.len(),
            2,
            "Should have stats for both seat positions"
        );

        // Total games across positions should equal total games
        let total_position_games: usize =
            player1.position_stats.iter().map(|p| p.games_played).sum();
        assert_eq!(
            total_position_games, player1.total_games,
            "Position games should sum to total games"
        );
    }

    #[tokio::test]
    async fn test_arena_comparison_profit_zero_sum() {
        // In a heads-up game, total profit should be approximately zero
        // (one player's gain is another's loss)
        let comparison = ComparisonBuilder::new()
            .num_games(50)
            .players_per_table(2)
            .seed(12345)
            .add_agent_config(AgentConfig::Calling {
                name: Some("A".to_string()),
            })
            .add_agent_config(AgentConfig::Calling {
                name: Some("B".to_string()),
            })
            .build()
            .unwrap();

        let result = comparison.run().await.unwrap();

        let a_stats = result.get_agent_stats("A").unwrap();
        let b_stats = result.get_agent_stats("B").unwrap();

        // Total profit should sum to approximately zero (within floating point tolerance)
        let total_profit = a_stats.total_profit + b_stats.total_profit;
        assert!(
            total_profit.abs() < 1.0,
            "Total profit should be approximately zero, got {}",
            total_profit
        );
    }

    #[tokio::test]
    async fn test_arena_comparison_deterministic_with_seed() {
        // Running with the same seed should produce identical results
        let build_comparison = || {
            ComparisonBuilder::new()
                .num_games(10)
                .players_per_table(2)
                .seed(42)
                .add_agent_config(AgentConfig::Folding {
                    name: Some("A".to_string()),
                })
                .add_agent_config(AgentConfig::Calling {
                    name: Some("B".to_string()),
                })
                .build()
                .unwrap()
        };

        let result1 = build_comparison().run().await.unwrap();
        let result2 = build_comparison().run().await.unwrap();

        let a1 = result1.get_agent_stats("A").unwrap();
        let a2 = result2.get_agent_stats("A").unwrap();

        assert_eq!(
            a1.total_profit, a2.total_profit,
            "Same seed should produce same profit"
        );
        assert_eq!(a1.wins, a2.wins, "Same seed should produce same wins");
        assert_eq!(a1.losses, a2.losses, "Same seed should produce same losses");
    }

    /// Verifies that num_agents() returns the actual number of agents added.
    #[test]
    fn test_arena_comparison_num_agents() {
        let comparison = ComparisonBuilder::new()
            .players_per_table(2)
            .add_agent_config(AgentConfig::Folding {
                name: Some("A".to_string()),
            })
            .add_agent_config(AgentConfig::Calling {
                name: Some("B".to_string()),
            })
            .add_agent_config(AgentConfig::AllIn {
                name: Some("C".to_string()),
            })
            .build()
            .unwrap();

        assert_eq!(comparison.num_agents(), 3);
        assert_ne!(comparison.num_agents(), 0);
    }

    /// Verifies that agents() returns the agents with their correct names.
    #[test]
    fn test_arena_comparison_agents() {
        let comparison = ComparisonBuilder::new()
            .players_per_table(2)
            .add_agent_config(AgentConfig::Folding {
                name: Some("Agent1".to_string()),
            })
            .add_agent_config(AgentConfig::Calling {
                name: Some("Agent2".to_string()),
            })
            .build()
            .unwrap();

        let agents = comparison.agents();
        assert_eq!(agents.len(), 2);
        assert_eq!(agents[0].0, "Agent1");
        assert_eq!(agents[1].0, "Agent2");
    }

    /// Verifies that print_configuration_summary executes without panicking
    /// and uses the correct configuration values.
    #[test]
    fn test_arena_comparison_print_configuration_summary() {
        let comparison = ComparisonBuilder::new()
            .players_per_table(2)
            .add_agent_config(AgentConfig::Folding {
                name: Some("Tester".to_string()),
            })
            .add_agent_config(AgentConfig::Calling {
                name: Some("Caller".to_string()),
            })
            .build()
            .unwrap();

        // Capture stdout - we can't easily capture println!, but we can verify
        // the method doesn't panic and check the config values used
        comparison.print_configuration_summary();

        // If we get here without panic, the method executed.
        // We verify the data it would print:
        assert_eq!(comparison.agents().len(), 2);
        assert_eq!(comparison.config().players_per_table, 2);
    }

    /// Verifies that ante configuration is properly handled (positive ante vs zero ante).
    #[test]
    fn test_arena_comparison_ante_condition() {
        // When ante > 0.0, the ante line should be printed
        // When ante == 0.0, the ante line should NOT be printed
        let comparison_with_ante = ComparisonBuilder::new()
            .players_per_table(2)
            .ante(1.0)
            .add_agent_config(AgentConfig::Folding {
                name: Some("A".to_string()),
            })
            .add_agent_config(AgentConfig::Calling {
                name: Some("B".to_string()),
            })
            .build()
            .unwrap();

        let comparison_without_ante = ComparisonBuilder::new()
            .players_per_table(2)
            .ante(0.0)
            .add_agent_config(AgentConfig::Folding {
                name: Some("A".to_string()),
            })
            .add_agent_config(AgentConfig::Calling {
                name: Some("B".to_string()),
            })
            .build()
            .unwrap();

        // Verify ante values are correctly stored
        assert!(comparison_with_ante.config().ante > 0.0);
        assert_eq!(comparison_without_ante.config().ante, 0.0);

        // Print both - they should not panic and use different code paths
        comparison_with_ante.print_configuration_summary();
        comparison_without_ante.print_configuration_summary();
    }
}