arc-agi-rs 0.1.0

🤖 A Rust client SDK for the ARC-AGI-3 API.
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
// Copyright 2026 Mahmoud Harmouch.
//
// Licensed under the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! # Scorecard Tracking
//!
//! This module ports the Python `arc_agi.scorecard` module and provides the
//! data structures and logic needed to track, compute, and summarise scores
//! across game runs entirely within Rust - no server connection required.
//!
//! ## Type Overview
//!
//! | Type | Python Equivalent | Description |
//! |------|-------------------|-------------|
//! | [`LevelAction`] | tuple `(level, actions)` | Actions-by-level checkpoint |
//! | [`Card`] | `scorecard.Card` | Per-game run tracker |
//! | [`Scorecard`] | `scorecard.Scorecard` | Full in-memory scorecard |
//! | [`ScorecardManager`] | `scorecard.ScorecardManager` | Multi-scorecard registry |
//! | [`EnvironmentScoreCalculator`] | `scorecard.EnvironmentScoreCalculator` | Weighted score aggregator |
//! | [`EnvironmentScore`] | `scorecard.EnvironmentScore` | Computed score for one run |
//! | [`EnvironmentScoreList`] | `scorecard.EnvironmentScoreList` | All runs for one game |
//! | [`ComputedScorecard`] | `scorecard.EnvironmentScorecard` | Full computed scorecard |
//!
//! ## See Also
//!
//! - [ARC-AGI-3 Reference](https://arcprize.org/arc-agi/3)

use crate::models::{EnvironmentInfo, GameState};
use chrono::{DateTime, Utc};
use serde_json::Value;
use std::collections::{HashMap, HashSet};
use std::env;
use uuid::Uuid;

/// The maximum score a single level can contribute (capped at 115%).
const MAX_LEVEL_SCORE: f64 = 115.0;
/// Default stale-scorecard threshold in minutes.
const DEFAULT_STALE_MINUTES: i64 = 15;
/// Default maximum open-for threshold in minutes (3 days).
const DEFAULT_MAX_OPEN_FOR_MINUTES: i64 = 4320;

// ─── LevelAction ─────────────────────────────────────────────────────────────

/// A (level_index, cumulative_actions) checkpoint recorded each time the player
/// advances to a new level.
///
/// Equivalent to the Python `tuple[int, int]` stored in `Card.actions_by_level`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LevelAction {
    /// Zero-based level index reached.
    pub level: u32,
    /// Cumulative action count at the moment the level was reached.
    pub cumulative_actions: u32,
}

// ─── Card ─────────────────────────────────────────────────────────────────────

/// A per-game run tracker.
///
/// A game can be played more than once; every play-through is tracked by
/// parallel `Vec` fields indexed by play count.
///
/// # Example
/// ```rust
/// use arc_agi_rs::scorecard::Card;
///
/// let mut card = Card::new("ls20".to_string());
/// card.new_play("run-guid-1");
/// assert_eq!(card.total_plays, 1);
/// ```
#[derive(Debug, Clone)]
pub struct Card {
    /// Game identifier this card tracks.
    pub game_id: String,
    /// Total number of play-throughs started.
    pub total_plays: usize,
    /// Run GUIDs in play order.
    pub guids: Vec<String>,
    /// Levels completed per play-through.
    pub levels_completed: Vec<u32>,
    /// Terminal state per play-through.
    pub states: Vec<GameState>,
    /// Total action count per play-through.
    pub actions: Vec<u32>,
    /// Reset count per play-through.
    pub resets: Vec<u32>,
    /// Level-advancement checkpoints per play-through.
    pub actions_by_level: Vec<Vec<LevelAction>>,
}

impl Card {
    /// Creates a new, empty `Card` for the given game.
    pub fn new(game_id: String) -> Self {
        Self {
            game_id,
            total_plays: 0,
            guids: Vec::new(),
            levels_completed: Vec::new(),
            states: Vec::new(),
            actions: Vec::new(),
            resets: Vec::new(),
            actions_by_level: Vec::new(),
        }
    }

    /// Returns the current (most recent) play index, or `None` when no plays exist.
    pub fn current_idx(&self) -> Option<usize> {
        (self.total_plays > 0).then(|| self.total_plays - 1)
    }

    /// Returns `true` when at least one play has been started.
    pub fn started(&self) -> bool {
        self.total_plays > 0
    }

    /// Returns the index of the given `guid` within [`guids`](Self::guids),
    /// scanning backwards to find the most recent occurrence.
    pub fn index_of_guid(&self, guid: &str) -> usize {
        for idx in (0..self.guids.len()).rev() {
            if self.guids[idx] == guid {
                return idx;
            }
        }
        self.total_plays.saturating_sub(1)
    }

    /// Records the start of a new play-through.
    pub fn new_play(&mut self, guid: &str) {
        self.total_plays += 1;
        self.guids.push(guid.to_string());
        self.levels_completed.push(0);
        self.states.push(GameState::NotFinished);
        self.actions.push(0);
        self.resets.push(0);
        self.actions_by_level.push(Vec::new());
    }

    /// Increments the reset counter and the action counter for the given `guid`.
    pub fn increment_reset(&mut self, guid: &str) {
        if self.started() {
            let idx = self.index_of_guid(guid);
            self.resets[idx] += 1;
            self.actions[idx] += 1;
        }
    }

    /// Increments the action counter for the given `guid`.
    pub fn increment_action(&mut self, guid: &str) {
        if self.started() {
            let idx = self.index_of_guid(guid);
            self.actions[idx] += 1;
        }
    }

    /// Sets the terminal state for the given `guid`.
    pub fn set_state(&mut self, guid: &str, state: GameState) {
        if self.started() {
            let idx = self.index_of_guid(guid);
            self.states[idx] = state;
        }
    }

    /// Updates the levels-completed counter and records a level checkpoint
    /// when the value changes.
    pub fn set_levels_completed(&mut self, guid: &str, current: u32) {
        if self.started() {
            let idx = self.index_of_guid(guid);
            if current != self.levels_completed[idx] {
                self.actions_by_level[idx].push(LevelAction {
                    level: current,
                    cumulative_actions: self.actions[idx],
                });
            }
            self.levels_completed[idx] = current;
        }
    }

    /// Returns the highest `levels_completed` value across all play-throughs.
    pub fn most_levels_completed(&self) -> u32 {
        self.levels_completed.iter().copied().max().unwrap_or(0)
    }

    /// Returns the total action count across all play-throughs.
    pub fn total_actions(&self) -> u32 {
        self.actions.iter().sum()
    }
}

// ─── Scorecard ───────────────────────────────────────────────────────────────

/// In-memory scorecard tracking all games for a single submission.
///
/// This mirrors the Python `Scorecard` Pydantic model and is managed by
/// [`ScorecardManager`].
///
/// # Example
/// ```rust
/// use arc_agi_rs::scorecard::Scorecard;
///
/// let mut sc = Scorecard::new("sc-abc", "my-api-key");
/// sc.new_play("ls20", "run-guid-1");
/// assert!(sc.cards.contains_key("ls20"));
/// ```
#[derive(Debug, Clone)]
pub struct Scorecard {
    /// Unique scorecard identifier.
    pub card_id: String,
    /// API key that owns this scorecard.
    pub api_key: String,
    /// Optional submission URL.
    pub source_url: Option<String>,
    /// Classification tags.
    pub tags: Option<Vec<String>>,
    /// Freeform opaque metadata.
    pub opaque: Option<Value>,
    /// Whether competition-mode semantics apply.
    pub competition_mode: Option<bool>,
    /// Per-game card records.
    pub cards: HashMap<String, Card>,
    /// Timestamp when the scorecard was opened.
    pub open_at: DateTime<Utc>,
    /// Timestamp of the most recent update.
    pub last_update: DateTime<Utc>,
}

impl Scorecard {
    /// Creates a new, empty `Scorecard`.
    pub fn new(card_id: impl Into<String>, api_key: impl Into<String>) -> Self {
        let now = Utc::now();
        Self {
            card_id: card_id.into(),
            api_key: api_key.into(),
            source_url: None,
            tags: None,
            opaque: None,
            competition_mode: None,
            cards: HashMap::new(),
            open_at: now,
            last_update: now,
        }
    }

    /// Records the start of a new play-through for the given game.
    pub fn new_play(&mut self, game_id: &str, guid: &str) {
        self.cards
            .entry(game_id.to_string())
            .or_insert_with(|| Card::new(game_id.to_string()))
            .new_play(guid);
        self.last_update = Utc::now();
    }

    /// Records a reset action for the given game run.
    pub fn reset(&mut self, game_id: &str, guid: &str) {
        if let Some(card) = self.cards.get_mut(game_id) {
            card.increment_reset(guid);
        }
        self.last_update = Utc::now();
    }

    /// Records a regular action for the given game run.
    pub fn take_action(&mut self, game_id: &str, guid: &str) {
        if let Some(card) = self.cards.get_mut(game_id) {
            card.increment_action(guid);
        }
        self.last_update = Utc::now();
    }

    /// Marks the given game run as won.
    pub fn win(&mut self, game_id: &str, guid: &str) {
        if let Some(card) = self.cards.get_mut(game_id) {
            card.set_state(guid, GameState::Win);
        }
        self.last_update = Utc::now();
    }

    /// Marks the given game run as game-over.
    pub fn game_over(&mut self, game_id: &str, guid: &str) {
        if let Some(card) = self.cards.get_mut(game_id) {
            card.set_state(guid, GameState::GameOver);
        }
        self.last_update = Utc::now();
    }

    /// Updates the levels-completed counter for the given game run.
    pub fn set_levels_completed(&mut self, game_id: &str, guid: &str, level: u32) {
        if let Some(card) = self.cards.get_mut(game_id) {
            card.set_levels_completed(guid, level);
        }
        self.last_update = Utc::now();
    }

    /// Returns `true` when the scorecard contains any record for the given game.
    pub fn has_environment(&self, game_id: &str) -> bool {
        self.cards.keys().any(|k| k.starts_with(game_id))
    }

    /// Returns the total actions across all games.
    pub fn total_actions(&self) -> u32 {
        self.cards.values().map(|c| c.total_actions()).sum()
    }

    /// Returns the total wins across all games.
    pub fn won(&self) -> usize {
        self.cards
            .values()
            .filter(|c| c.states.contains(&GameState::Win))
            .count()
    }

    /// Returns the number of games that have had at least one play.
    pub fn played(&self) -> usize {
        self.cards.values().filter(|c| !c.states.is_empty()).count()
    }
}

// ─── ScorecardManager ────────────────────────────────────────────────────────

/// Registry that manages multiple in-flight [`Scorecard`]s.
///
/// The manager maps GUIDs to scorecard IDs for fast lookup when incoming
/// frames arrive, and evicts stale scorecards based on idle / open-for thresholds.
///
/// This mirrors the Python `ScorecardManager` class from `arc_agi.scorecard`.
///
/// # Example
/// ```rust
/// use arc_agi_rs::scorecard::ScorecardManager;
///
/// let mut mgr = ScorecardManager::new();
/// let card_id = mgr.new_scorecard("my-api-key", None, None, None, None);
/// assert!(mgr.get_scorecard(&card_id, "my-api-key").is_some());
/// ```
#[derive(Debug)]
pub struct ScorecardManager {
    /// Active scorecards keyed by card ID.
    pub scorecards: HashMap<String, Scorecard>,
    /// GUID → card_id reverse mapping.
    pub guids: HashMap<String, String>,
    /// Maximum idle duration (seconds) before auto-close.
    pub stale_seconds: i64,
    /// Maximum total open duration (seconds) before auto-close.
    pub max_open_seconds: i64,
}

impl ScorecardManager {
    /// Creates a new, empty `ScorecardManager` with default thresholds read from
    /// `STALE_MINUTES` and `MAX_OPEN_FOR_MINUTES` environment variables.
    pub fn new() -> Self {
        let stale_min = env::var("STALE_MINUTES")
            .ok()
            .and_then(|v| v.parse::<i64>().ok())
            .unwrap_or(DEFAULT_STALE_MINUTES)
            .clamp(1, 60);

        let max_open_min = env::var("MAX_OPEN_FOR_MINUTES")
            .ok()
            .and_then(|v| v.parse::<i64>().ok())
            .unwrap_or(DEFAULT_MAX_OPEN_FOR_MINUTES)
            .clamp(60, 60 * 24 * 7);

        Self {
            scorecards: HashMap::new(),
            guids: HashMap::new(),
            stale_seconds: stale_min * 60,
            max_open_seconds: max_open_min * 60,
        }
    }

    /// Creates a new scorecard and returns its ID.
    pub fn new_scorecard(
        &mut self,
        api_key: &str,
        source_url: Option<String>,
        tags: Option<Vec<String>>,
        opaque: Option<Value>,
        competition_mode: Option<bool>,
    ) -> String {
        let card_id = Uuid::new_v4().to_string();
        let mut sc = Scorecard::new(&card_id, api_key);
        sc.source_url = source_url;
        sc.tags = tags;
        sc.opaque = opaque;
        sc.competition_mode = competition_mode;
        self.scorecards.insert(card_id.clone(), sc);
        card_id
    }

    /// Returns the [`Scorecard`] for the given ID and API key, or `None`.
    pub fn get_scorecard(&self, card_id: &str, api_key: &str) -> Option<&Scorecard> {
        self.scorecards
            .get(card_id)
            .filter(|sc| sc.api_key == api_key)
    }

    /// Returns a mutable reference to the [`Scorecard`] for the given ID and key.
    pub fn get_scorecard_mut(&mut self, card_id: &str, api_key: &str) -> Option<&mut Scorecard> {
        self.scorecards
            .get_mut(card_id)
            .filter(|sc| sc.api_key == api_key)
    }

    /// Returns the [`Scorecard`] containing the given GUID, or `None`.
    pub fn get_scorecard_from_guid(&self, guid: &str) -> Option<&Scorecard> {
        let card_id = self.guids.get(guid)?;
        self.scorecards.get(card_id)
    }

    /// Closes and removes the scorecard, returning it along with all GUIDs.
    ///
    /// Returns `None` when the scorecard is not found or the key does not match.
    pub fn close_scorecard(
        &mut self,
        card_id: &str,
        api_key: Option<&str>,
    ) -> Option<(Scorecard, Vec<String>)> {
        let matches = self
            .scorecards
            .get(card_id)
            .is_some_and(|sc| api_key.is_none_or(|k| sc.api_key == k));
        if !matches {
            return None;
        }
        let sc = self.scorecards.remove(card_id)?;
        let guids: Vec<String> = sc.cards.values().flat_map(|c| c.guids.clone()).collect();
        for guid in &guids {
            self.guids.remove(guid);
        }
        Some((sc, guids))
    }

    /// Associates the given GUID with a scorecard, creating a GUID→card mapping.
    pub fn add_game(&mut self, card_id: &str, guid: &str) {
        if self.scorecards.contains_key(card_id) {
            self.guids.insert(guid.to_string(), card_id.to_string());
        }
    }

    /// Returns the IDs of all scorecards that have exceeded their stale threshold.
    pub fn get_stale_cards(&self) -> Vec<String> {
        let now = Utc::now();
        self.scorecards
            .iter()
            .filter(|(_, sc)| {
                let idle = (now - sc.last_update).num_seconds();
                let open = (now - sc.open_at).num_seconds();
                idle >= self.stale_seconds || open >= self.max_open_seconds
            })
            .map(|(id, _)| id.clone())
            .collect()
    }
}

impl Default for ScorecardManager {
    fn default() -> Self {
        Self::new()
    }
}

// ─── Score Computation ───────────────────────────────────────────────────────

/// Accumulates per-level scores using the weighted formula from the ARC-AGI-3
/// scoring specification.
///
/// Mirrors the Python `EnvironmentScoreCalculator` class.
///
/// # Formula
///
/// For a completed level: `score = min((baseline / taken)² × 100, 115)`
///
/// The final aggregate is a level-index-weighted average, ensuring later
/// levels contribute more to the overall score.
///
/// # Example
/// ```rust
/// use arc_agi_rs::scorecard::EnvironmentScoreCalculator;
///
/// let mut calc = EnvironmentScoreCalculator::new("ls20");
/// calc.add_level(1, true, 10, 10, Some("ls20"));  // perfect score
/// let score = calc.to_score(true);
/// assert!((score.score - 100.0).abs() < f64::EPSILON);
/// ```
#[derive(Debug, Clone)]
pub struct EnvironmentScoreCalculator {
    /// Optional run identifier.
    pub id: Option<String>,
    /// Optional run GUID.
    pub guid: Option<String>,
    /// Optional reset count.
    pub resets: Option<u32>,
    /// Terminal game state.
    pub state: Option<GameState>,
    /// Whether the environment was fully completed.
    pub completed: Option<bool>,
    level_indices: Vec<u32>,
    level_scores: Vec<f64>,
    level_actions: Vec<u32>,
    level_baseline_actions: Vec<u32>,
    levels_completed: u32,
    total_actions: u32,
    environments: HashSet<String>,
}

impl EnvironmentScoreCalculator {
    /// Creates a new calculator for the given game.
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: Some(id.into()),
            guid: None,
            resets: None,
            state: None,
            completed: None,
            level_indices: Vec::new(),
            level_scores: Vec::new(),
            level_actions: Vec::new(),
            level_baseline_actions: Vec::new(),
            levels_completed: 0,
            total_actions: 0,
            environments: HashSet::new(),
        }
    }

    /// Adds one level's worth of data to the accumulator.
    ///
    /// # Arguments
    /// * `level_index` - 1-based level number (used as weight).
    /// * `completed` - Whether the level was solved.
    /// * `actions_taken` - Actions the agent used.
    /// * `baseline_actions` - Human baseline action count.
    /// * `game_id` - Optional game ID tracked for tag aggregation.
    pub fn add_level(
        &mut self,
        level_index: u32,
        completed: bool,
        actions_taken: u32,
        baseline_actions: u32,
        game_id: Option<&str>,
    ) {
        self.total_actions += actions_taken;
        if let Some(gid) = game_id {
            self.environments.insert(gid.to_string());
        }
        let score = if completed && actions_taken > 0 {
            let ratio = baseline_actions as f64 / actions_taken as f64;
            (ratio * ratio * 100.0).min(MAX_LEVEL_SCORE)
        } else {
            0.0
        };
        if completed {
            self.levels_completed += 1;
        }
        self.level_indices.push(level_index);
        self.level_scores.push(score);
        self.level_actions.push(actions_taken);
        self.level_baseline_actions.push(baseline_actions);
    }

    /// Computes the aggregate [`EnvironmentScore`].
    ///
    /// When `include_levels` is `false`, per-level arrays are omitted and
    /// aggregate counts are returned instead (used for tag-level summaries).
    pub fn to_score(&self, include_levels: bool) -> EnvironmentScore {
        let score = if self.level_scores.is_empty() {
            0.0
        } else {
            let mut total_score = 0.0_f64;
            let mut total_weights = 0_u32;
            let mut max_weights = 0_u32;
            for (i, &s) in self.level_scores.iter().enumerate() {
                let w = self.level_indices[i];
                total_score += s * w as f64;
                total_weights += w;
                if s > 0.0 {
                    max_weights += w;
                }
            }
            if total_weights == 0 {
                0.0
            } else {
                let raw = total_score / total_weights as f64;
                let cap = max_weights as f64 / total_weights as f64 * 100.0;
                raw.min(cap)
            }
        };

        EnvironmentScore {
            id: self.id.clone(),
            guid: self.guid.clone(),
            score,
            levels_completed: self.levels_completed,
            actions: self.total_actions,
            resets: self.resets,
            state: self.state.clone(),
            completed: self.completed,
            level_scores: include_levels.then(|| self.level_scores.clone()),
            level_actions: include_levels.then(|| self.level_actions.clone()),
            level_baseline_actions: include_levels.then(|| {
                self.level_baseline_actions
                    .iter()
                    .map(|&v| v as i32)
                    .collect()
            }),
            number_of_levels: (!include_levels).then_some(self.level_scores.len() as u32),
            number_of_environments: (!include_levels).then_some(self.environments.len() as u32),
            message: None,
        }
    }
}

// ─── Output types ────────────────────────────────────────────────────────────

/// Computed score for a single game run.
///
/// These are produced by [`EnvironmentScoreCalculator::to_score`] and
/// collected into [`EnvironmentScoreList`] / [`ComputedScorecard`].
#[derive(Debug, Clone)]
pub struct EnvironmentScore {
    /// Game identifier.
    pub id: Option<String>,
    /// Run GUID.
    pub guid: Option<String>,
    /// Aggregate score (0.0–115.0).
    pub score: f64,
    /// Levels completed.
    pub levels_completed: u32,
    /// Total actions taken.
    pub actions: u32,
    /// Reset count.
    pub resets: Option<u32>,
    /// Terminal game state.
    pub state: Option<GameState>,
    /// Whether the environment was fully completed.
    pub completed: Option<bool>,
    /// Per-level scores.
    pub level_scores: Option<Vec<f64>>,
    /// Per-level action counts.
    pub level_actions: Option<Vec<u32>>,
    /// Per-level human baseline action counts.
    pub level_baseline_actions: Option<Vec<i32>>,
    /// Total level count (tag-level summary only).
    pub number_of_levels: Option<u32>,
    /// Distinct environment count (tag-level summary only).
    pub number_of_environments: Option<u32>,
    /// Optional diagnostic message.
    pub message: Option<String>,
}

/// All runs for a single game environment.
#[derive(Debug, Clone)]
pub struct EnvironmentScoreList {
    /// Game identifier.
    pub id: String,
    /// Individual run scores.
    pub runs: Vec<EnvironmentScore>,
}

impl EnvironmentScoreList {
    /// Best score across all runs.
    pub fn score(&self) -> f64 {
        self.runs
            .iter()
            .map(|r| r.score)
            .fold(f64::NEG_INFINITY, f64::max)
    }
    /// Total actions across all runs.
    pub fn actions(&self) -> u32 {
        self.runs.iter().map(|r| r.actions).sum()
    }
    /// Maximum levels completed across all runs.
    pub fn levels_completed(&self) -> u32 {
        self.runs
            .iter()
            .map(|r| r.levels_completed)
            .max()
            .unwrap_or(0)
    }
    /// Whether any run reached a completed state.
    pub fn completed(&self) -> bool {
        self.runs.iter().any(|r| r.completed.unwrap_or(false))
    }
    /// Maximum level count across all runs.
    pub fn level_count(&self) -> u32 {
        self.runs
            .iter()
            .map(|r| r.level_scores.as_ref().map_or(0, |v| v.len() as u32))
            .max()
            .unwrap_or(0)
    }
    /// Total resets across all runs.
    pub fn resets(&self) -> u32 {
        self.runs.iter().map(|r| r.resets.unwrap_or(0)).sum()
    }
}

/// A fully computed scorecard derived from a [`Scorecard`] and a list of
/// [`EnvironmentInfo`] objects.
///
/// Mirrors the Python `EnvironmentScorecard.from_scorecard()` result.
#[derive(Debug, Clone)]
pub struct ComputedScorecard {
    /// Scorecard identifier.
    pub card_id: String,
    /// Optional submission URL.
    pub source_url: Option<String>,
    /// Classification tags.
    pub tags: Option<Vec<String>>,
    /// Competition mode flag.
    pub competition_mode: Option<bool>,
    /// Aggregate score across all environments.
    pub score: f64,
    /// Per-environment scored results.
    pub environments: Vec<EnvironmentScoreList>,
    /// Per-tag aggregate scores.
    pub tags_scores: Vec<EnvironmentScore>,
    /// When the scorecard was opened.
    pub open_at: DateTime<Utc>,
    /// When the scorecard was last updated.
    pub last_update: DateTime<Utc>,
}

impl ComputedScorecard {
    /// Computes a [`ComputedScorecard`] from a raw [`Scorecard`] and the
    /// corresponding [`EnvironmentInfo`] list.
    ///
    /// Mirrors `EnvironmentScorecard.from_scorecard()` in Python.
    pub fn from_scorecard(scorecard: &Scorecard, environment_infos: &[EnvironmentInfo]) -> Self {
        let info_map: HashMap<&str, &EnvironmentInfo> = environment_infos
            .iter()
            .map(|e| (e.game_id.as_str(), e))
            .collect();

        let mut game_scores: HashMap<String, EnvironmentScoreList> = HashMap::new();
        let mut tags_accum: HashMap<String, EnvironmentScoreCalculator> = HashMap::new();

        for (game_id, card) in &scorecard.cards {
            // Identify the best play (most levels completed)
            let best_idx = card
                .levels_completed
                .iter()
                .enumerate()
                .max_by_key(|&(_, lc)| lc)
                .map(|(i, _)| i);

            let Some(best_idx) = best_idx else { continue };
            if best_idx >= card.guids.len() {
                continue;
            }

            let mut all_scores: Vec<EnvironmentScore> = Vec::new();

            for idx in 0..card.total_plays {
                let env_info = info_map.get(game_id.as_str()).copied();
                let is_best = idx == best_idx;
                let score = Self::calculate_score(
                    card,
                    game_id,
                    idx,
                    env_info,
                    is_best.then_some(&mut tags_accum),
                );
                all_scores.push(score);
            }

            if !all_scores.is_empty() {
                game_scores.insert(
                    game_id.clone(),
                    EnvironmentScoreList {
                        id: game_id.clone(),
                        runs: all_scores,
                    },
                );
            }
        }

        let environment_list: Vec<EnvironmentScoreList> = game_scores.into_values().collect();
        let tags_list: Vec<EnvironmentScore> =
            tags_accum.values().map(|c| c.to_score(false)).collect();

        let score = if environment_list.is_empty() {
            0.0
        } else {
            environment_list.iter().map(|e| e.score()).sum::<f64>() / environment_list.len() as f64
        };

        Self {
            card_id: scorecard.card_id.clone(),
            source_url: scorecard.source_url.clone(),
            tags: scorecard.tags.clone(),
            competition_mode: scorecard.competition_mode,
            score,
            environments: environment_list,
            tags_scores: tags_list,
            open_at: scorecard.open_at,
            last_update: scorecard.last_update,
        }
    }

    /// Computes the score for one play-through of one game.
    fn calculate_score(
        card: &Card,
        game_id: &str,
        idx: usize,
        env_info: Option<&EnvironmentInfo>,
        mut tags_accum: Option<&mut HashMap<String, EnvironmentScoreCalculator>>,
    ) -> EnvironmentScore {
        let levels_completed = card.levels_completed.get(idx).copied().unwrap_or(0);
        let guid = card.guids.get(idx).cloned().unwrap_or_default();
        let actions = card.actions.get(idx).copied().unwrap_or(0);
        let resets = card.resets.get(idx).copied().unwrap_or(0);
        let state = card
            .states
            .get(idx)
            .cloned()
            .unwrap_or(GameState::NotPlayed);
        let completed = state == GameState::Win;

        let baseline = match env_info {
            None => None,
            Some(info) if info.baseline_actions.as_ref().is_none_or(|b| b.is_empty()) => None,
            Some(info) => info.baseline_actions.as_ref(),
        };

        let Some(baseline) = baseline else {
            // No baseline available - return raw data only
            let actions_by_level = card
                .actions_by_level
                .get(idx)
                .map(|a| a.as_slice())
                .unwrap_or(&[]);
            let raw_level_actions: Vec<u32> = {
                let mut prev = 0u32;
                let mut out = Vec::new();
                for la in actions_by_level {
                    out.push(la.cumulative_actions.saturating_sub(prev));
                    prev = la.cumulative_actions;
                }
                if state != GameState::Win {
                    out.push(actions.saturating_sub(prev));
                }
                out
            };
            let n = raw_level_actions.len();
            return EnvironmentScore {
                id: Some(card.game_id.clone()),
                guid: Some(guid),
                score: 0.0,
                levels_completed,
                actions,
                resets: Some(resets),
                state: Some(state),
                completed: Some(completed),
                level_actions: Some(raw_level_actions),
                level_baseline_actions: Some(vec![-1; n]),
                level_scores: Some(vec![0.0; n]),
                number_of_levels: None,
                number_of_environments: None,
                message: env_info
                    .map(|_| {
                        "Human baseline actions are not available for this environment".to_string()
                    })
                    .or_else(|| Some(format!("No matching EnvironmentInfo found for {game_id}"))),
            };
        };

        // Full score calculation
        let mut calc = EnvironmentScoreCalculator::new(card.game_id.clone());
        calc.guid = Some(guid);
        calc.resets = Some(resets);
        calc.state = Some(state);
        calc.completed = Some(completed);

        let actions_by_level = card
            .actions_by_level
            .get(idx)
            .map(|a| a.as_slice())
            .unwrap_or(&[]);
        let mut prev_actions = 0u32;

        for (level_idx, bl) in baseline.iter().enumerate() {
            let (level_actions, level_completed) = if let Some(la) = actions_by_level.get(level_idx)
            {
                let taken = la.cumulative_actions.saturating_sub(prev_actions);
                prev_actions = la.cumulative_actions;
                (taken, level_idx < actions_by_level.len() || completed)
            } else {
                let taken = actions.saturating_sub(prev_actions);
                prev_actions = actions;
                (taken, false)
            };

            calc.add_level(
                (level_idx + 1) as u32,
                level_completed,
                level_actions,
                *bl,
                Some(game_id),
            );

            if let (Some(ta), Some(tags)) =
                (tags_accum.as_mut(), env_info.and_then(|e| e.tags.as_ref()))
            {
                for tag in tags {
                    ta.entry(tag.clone())
                        .or_insert_with(|| EnvironmentScoreCalculator::new(tag.clone()))
                        .add_level(
                            (level_idx + 1) as u32,
                            level_completed,
                            level_actions,
                            *bl,
                            Some(game_id),
                        );
                }
            }
        }

        calc.to_score(true)
    }

    /// Returns the number of environments that are fully completed.
    pub fn total_environments_completed(&self) -> usize {
        self.environments.iter().filter(|e| e.completed()).count()
    }

    /// Returns the total number of environments.
    pub fn total_environments(&self) -> usize {
        self.environments.len()
    }

    /// Returns the total levels completed across all environments.
    pub fn total_levels_completed(&self) -> u32 {
        self.environments.iter().map(|e| e.levels_completed()).sum()
    }

    /// Returns the total levels across all environments.
    pub fn total_levels(&self) -> u32 {
        self.environments.iter().map(|e| e.level_count()).sum()
    }

    /// Returns the total actions taken across all environments.
    pub fn total_actions(&self) -> u32 {
        self.environments.iter().map(|e| e.actions()).sum()
    }
}

// Copyright 2026 Mahmoud Harmouch.
//
// Licensed under the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.