limitless-cli 1.0.0

A beginner-friendly environment diagnostic tool
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
//! **Achievements** — a badge / unlock system for Limitless CLI.
//!
//! Usage is tracked in an [`ArcadeStats`] counter bundle; a fixed registry
//! ([`BADGES`]) maps conditions to five unlockable badges, and
//! [`check_badges`] reports which ones the current stats satisfy. Progress
//! is persisted to `~/.limitless/achievements.json` (in the user's home
//! directory; stats.json there belongs to `crate::modules::config`) through
//! [`AchievementProgress`], which records newly-unlocked badges and renders
//! their shareable popup via [`render_badge_popup`].
//!
//! ```
//! use limitless_cli::modules::achievements::{
//!     AchievementProgress, ArcadeStats, BADGES, check_badges,
//! };
//!
//! // The registry has the five spec'd badges.
//! assert_eq!(BADGES.len(), 5);
//!
//! // Pure condition check over stats.
//! let mut stats = ArcadeStats::default();
//! stats.processes_killed = 5;
//! assert_eq!(check_badges(&stats), vec!["Port Whisperer"]);
//!
//! // The store only reports *newly* unlocked badges, once.
//! let mut progress = AchievementProgress::default();
//! progress.stats.processes_killed = 5;
//! assert_eq!(progress.check_unlocked(), vec!["Port Whisperer"]);
//! assert!(progress.check_unlocked().is_empty());
//! ```

use std::collections::HashMap;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

/// Width in characters of the badge popup frame.
pub const POPUP_WIDTH: usize = 60;

/// Inner text width between the two vertical frame bars.
const POPUP_INNER: usize = POPUP_WIDTH - 4;

/// Number of ghost processes [`BadgeCondition::PortWhisperer`] requires.
pub const GHOST_PROCESS_TARGET: u32 = 5;

/// Number of `.env` files [`BadgeCondition::EnvMaster`] requires.
pub const ENV_MASTER_TARGET: u32 = 10;

/// Diagnostic duration (ms) [`BadgeCondition::SpeedRunner`] requires.
pub const SPEED_RUNNER_MS: u32 = 5000;

/// Earliest local hour (inclusive) for [`BadgeCondition::NightOwl`].
pub const NIGHT_OWL_FROM_HOUR: u32 = 2;

/// Latest local hour (inclusive) for [`BadgeCondition::NightOwl`].
pub const NIGHT_OWL_TO_HOUR: u32 = 5;

// ---------------------------------------------------------------------------
// Badge conditions
// ---------------------------------------------------------------------------

/// A predicate over [`ArcadeStats`] that decides when a badge unlocks.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BadgeCondition {
    /// Applying at least one auto-fix.
    FirstFixExecuted,
    /// Reaching `count` consecutive perfectly-healthy runs.
    PerfectHealth { count: u32 },
    /// Killing at least [`GHOST_PROCESS_TARGET`] ghost processes.
    PortWhisperer,
    /// Creating at least [`ENV_MASTER_TARGET`] `.env` files.
    EnvMaster,
    /// Reserved: no current data source, never triggered by the shipped
    /// badges. Kept so the condition vocabulary matches the design spec.
    DependencyHero,
    /// Beating `score` points in SyntaxBreaker.
    ArcadeWin { score: u32 },
    /// A diagnostic scan completing under [`SPEED_RUNNER_MS`] milliseconds.
    SpeedRunner,
    /// Having run Limitless during a local hour in
    /// [`NIGHT_OWL_FROM_HOUR`]..=[`NIGHT_OWL_TO_HOUR`].
    NightOwl,
}

impl BadgeCondition {
    /// Whether `stats` satisfy this condition.
    pub fn matches(&self, stats: &ArcadeStats) -> bool {
        match *self {
            BadgeCondition::FirstFixExecuted => stats.fixes_applied > 0,
            BadgeCondition::PerfectHealth { count } => {
                stats.perfect_health_streak >= count
            }
            BadgeCondition::PortWhisperer => stats.processes_killed >= GHOST_PROCESS_TARGET,
            BadgeCondition::EnvMaster => stats.env_files_created >= ENV_MASTER_TARGET,
            BadgeCondition::DependencyHero => false,
            BadgeCondition::ArcadeWin { score } => stats.best_arcade_score > score,
            BadgeCondition::SpeedRunner => stats
                .last_diagnostic_time_ms
                .is_some_and(|t| t < SPEED_RUNNER_MS),
            BadgeCondition::NightOwl => stats.times_run.iter().any(|(&hour, &count)| {
                count > 0 && (NIGHT_OWL_FROM_HOUR..=NIGHT_OWL_TO_HOUR).contains(&hour)
            }),
        }
    }
}

// ---------------------------------------------------------------------------
// Badge registry
// ---------------------------------------------------------------------------

/// One unlockable badge. The emoji is a single Unicode scalar so it can be
/// embedded in share messages and popup frames.
///
/// ```
/// use limitless_cli::modules::achievements::Badge;
/// let badge = Badge {
///     id: "port-whisperer",
///     name: "Port Whisperer",
///     description: "Kill 5 ghost processes.",
///     emoji: '\u{1F527}',
///     unlock_condition: limitless_cli::modules::achievements::BadgeCondition::PortWhisperer,
/// };
/// assert_eq!(badge.emoji, '\u{1F527}');
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Badge {
    /// Stable, kebab-case identifier (used for persistence).
    pub id: &'static str,
    /// Human-friendly display name.
    pub name: &'static str,
    /// Short flavour text shown inside the popup.
    pub description: &'static str,
    /// Single-char emoji shown alongside the name.
    pub emoji: char,
    /// What unlocks this badge.
    pub unlock_condition: BadgeCondition,
}

/// The full badge database.
///
/// ```
/// use limitless_cli::modules::achievements::BADGES;
/// assert_eq!(BADGES.len(), 5);
/// let names: Vec<&str> = BADGES.iter().map(|b| b.name).collect();
/// assert_eq!(
///     names,
///     vec!["Port Whisperer", "Env Master", "Speed Runner",
///          "Arcade Champion", "Night Owl"]
/// );
/// ```
pub const BADGES: &[Badge] = &[
    Badge {
        id: "port-whisperer",
        name: "Port Whisperer",
        description: "Kill 5 ghost processes.",
        emoji: '\u{1F527}',
        unlock_condition: BadgeCondition::PortWhisperer,
    },
    Badge {
        id: "env-master",
        name: "Env Master",
        description: "Create 10 .env files.",
        emoji: '\u{1F6E1}',
        unlock_condition: BadgeCondition::EnvMaster,
    },
    Badge {
        id: "speed-runner",
        name: "Speed Runner",
        description: "Finish a diagnostic scan in under 5 seconds.",
        emoji: '\u{1F4A8}',
        unlock_condition: BadgeCondition::SpeedRunner,
    },
    Badge {
        id: "arcade-champion",
        name: "Arcade Champion",
        description: "Score over 500 in SyntaxBreaker.",
        emoji: '\u{1F3AE}',
        unlock_condition: BadgeCondition::ArcadeWin { score: 500 },
    },
    Badge {
        id: "night-owl",
        name: "Night Owl",
        description: "Run Limitless between 2 AM and 5 AM.",
        emoji: '\u{1F319}',
        unlock_condition: BadgeCondition::NightOwl,
    },
];

/// Looks up a badge by its stable id.
pub fn badge_by_id(id: &str) -> Option<&Badge> {
    BADGES.iter().find(|b| b.id == id)
}

// ---------------------------------------------------------------------------
// Usage stats
// ---------------------------------------------------------------------------

/// Lifetime usage counters that drive badge unlocks.
///
/// ```
/// use limitless_cli::modules::achievements::ArcadeStats;
/// let mut stats = ArcadeStats::default();
/// stats.record_diagnostic_at(4200, 3);
/// stats.record_fix();
/// stats.record_arcade_game(800);
/// assert_eq!(stats.diagnostics_run, 1);
/// assert_eq!(stats.last_diagnostic_time_ms, Some(4200));
/// assert_eq!(stats.times_run.get(&3), Some(&1));
/// assert_eq!(stats.best_arcade_score, 800);
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
pub struct ArcadeStats {
    /// Total diagnostic scans run.
    pub diagnostics_run: u32,
    /// Total fixes applied.
    pub fixes_applied: u32,
    /// Consecutive runs where every check passed.
    pub perfect_health_streak: u32,
    /// Ghost processes killed.
    pub processes_killed: u32,
    /// `.env` files created.
    pub env_files_created: u32,
    /// Games played in SyntaxBreaker.
    pub total_arcade_plays: u32,
    /// Best SyntaxBreaker score.
    pub best_arcade_score: u32,
    /// Duration (ms) of the most recent diagnostic scan, for
    /// [`BadgeCondition::SpeedRunner`]. `None` until the first scan.
    pub last_diagnostic_time_ms: Option<u32>,
    /// Map of local hour → number of runs started at that hour, for
    /// [`BadgeCondition::NightOwl`].
    pub times_run: HashMap<u32, u32>,
}

impl ArcadeStats {
    /// Records a diagnostic scan, its duration, and the current UTC hour.
    /// Local-hour bookkeeping on non-UTC machines uses the configured offset;
    /// [`record_diagnostic_at`](ArcadeStats::record_diagnostic_at) is the
    /// deterministic variant used by tests.
    pub fn record_diagnostic(&mut self, duration_ms: u32) {
        self.record_diagnostic_at(duration_ms, utc_hour_now());
    }

    /// Records a diagnostic scan with an explicit hour-of-day.
    pub fn record_diagnostic_at(&mut self, duration_ms: u32, hour: u32) {
        self.diagnostics_run = self.diagnostics_run.saturating_add(1);
        self.last_diagnostic_time_ms = Some(duration_ms);
        let slot = self.times_run.entry(hour).or_insert(0);
        *slot = slot.saturating_add(1);
    }

    /// Marks the current run as happy, extending the perfect-health streak.
    pub fn record_perfect_health(&mut self) {
        self.perfect_health_streak = self.perfect_health_streak.saturating_add(1);
    }

    /// Ends a streak (a run with a failing check).
    pub fn reset_perfect_health(&mut self) {
        self.perfect_health_streak = 0;
    }

    /// Records an applied fix.
    pub fn record_fix(&mut self) {
        self.fixes_applied = self.fixes_applied.saturating_add(1);
    }

    /// Records a killed ghost process.
    pub fn record_process_killed(&mut self) {
        self.processes_killed = self.processes_killed.saturating_add(1);
    }

    /// Records a created `.env` file.
    pub fn record_env_created(&mut self) {
        self.env_files_created = self.env_files_created.saturating_add(1);
    }

    /// Records a finished SyntaxBreaker game, keeping the best score.
    pub fn record_arcade_game(&mut self, score: u32) {
        self.total_arcade_plays = self.total_arcade_plays.saturating_add(1);
        self.best_arcade_score = self.best_arcade_score.max(score);
    }
}

// ---------------------------------------------------------------------------
// Condition checking
// ---------------------------------------------------------------------------

/// Every badge name (in registry order) whose condition `stats` satisfies.
///
/// ```
/// use limitless_cli::modules::achievements::{ArcadeStats, check_badges};
/// let mut stats = ArcadeStats::default();
/// stats.processes_killed = 5;
/// stats.env_files_created = 12;
/// stats.best_arcade_score = 900;
/// stats.times_run.insert(3, 1);
/// assert_eq!(
///     check_badges(&stats),
///     vec!["Port Whisperer", "Env Master", "Arcade Champion", "Night Owl"]
/// );
/// ```
pub fn check_badges(stats: &ArcadeStats) -> Vec<String> {
    BADGES
        .iter()
        .filter(|badge| badge.unlock_condition.matches(stats))
        .map(|badge| badge.name.to_string())
        .collect()
}

// ---------------------------------------------------------------------------
// Popup rendering
// ---------------------------------------------------------------------------

/// The share line displayed at the bottom of an unlock popup.
///
/// ```
/// use limitless_cli::modules::achievements::{badge_by_id, share_text};
/// let badge = badge_by_id("port-whisperer").unwrap();
/// assert_eq!(
///     share_text(badge),
///     "Share: \"I unlocked \u{1F527} Port Whisperer in Limitless\""
/// );
/// ```
pub fn share_text(badge: &Badge) -> String {
    format!("Share: \"I unlocked {} {} in Limitless\"", badge.emoji, badge.name)
}

fn popup_border(top: bool) -> String {
    let (left, right) = if top { ('┌', '┐') } else { ('└', '┘') };
    format!("{left}{}{right}", "─".repeat(POPUP_WIDTH - 2))
}

fn popup_row(content: &str) -> String {
    format!("│ {} │", pad(content))
}

fn pad(content: &str) -> String {
    let used = content.chars().count();
    format!("{content}{}", " ".repeat(POPUP_INNER.saturating_sub(used)))
}

fn centered(content: &str) -> String {
    let used = content.chars().count();
    if used >= POPUP_INNER {
        return content.to_string();
    }
    let total = POPUP_INNER - used;
    let left = total / 2;
    let right = total - left;
    format!("{}{}{}", " ".repeat(left), content, " ".repeat(right))
}

/// Renders a celebratory popup for a freshly unlocked badge.
///
/// ```
/// use limitless_cli::modules::achievements::{
///     badge_by_id, render_badge_popup, POPUP_WIDTH,
/// };
/// let popup = render_badge_popup(badge_by_id("env-master").unwrap());
/// assert!(popup.contains("🎉 BADGE UNLOCKED!"));
/// assert!(popup.contains("Share: \"I unlocked \u{1F6E1} Env Master in Limitless\""));
/// for line in popup.lines() {
///     assert_eq!(line.chars().count(), POPUP_WIDTH);
/// }
/// ```
pub fn render_badge_popup(badge: &Badge) -> String {
    [
        popup_border(true),
        popup_row(&centered("🎉 BADGE UNLOCKED!")),
        popup_row(""),
        popup_row(&centered(&format!("{}  {}", badge.emoji, badge.name))),
        popup_row(&centered(badge.description)),
        popup_row(""),
        popup_row(&centered(&share_text(badge))),
        popup_border(false),
    ]
    .join("\n")
}

// ---------------------------------------------------------------------------
// Persistence
// ---------------------------------------------------------------------------

/// Best-effort home directory: `%USERPROFILE%` on Windows, `$HOME` elsewhere.
pub fn home_dir() -> Option<PathBuf> {
    std::env::var_os("USERPROFILE")
        .map(PathBuf::from)
        .or_else(|| std::env::var_os("HOME").map(PathBuf::from))
}

/// Where per-user progress lives: `<home>/.limitless/achievements.json`.
pub fn progress_file_path() -> Option<PathBuf> {
    home_dir().map(|home| home.join(".limitless").join("achievements.json"))
}

/// Legacy location that held badge progress before config.rs took over
/// `stats.json`. Exists only to migrate old installs.
pub fn legacy_progress_path() -> Option<PathBuf> {
    home_dir().map(|home| home.join(".limitless").join("stats.json"))
}

/// Loads progress from the current location, migrating the legacy
/// `~/.limitless/stats.json` file on first run after an upgrade.
pub fn load_progress_migrated() -> AchievementProgress {
    match home_dir() {
        Some(home) => load_progress_at_home(&home),
        None => AchievementProgress::default(),
    }
}

/// Loads progress relative to an explicit home directory, migrating the legacy
/// `stats.json` file (which config.rs now owns for bare [`ArcadeStats`]).
fn load_progress_at_home(home: &Path) -> AchievementProgress {
    let limitless = home.join(".limitless");
    let path = limitless.join("achievements.json");
    let progress = AchievementProgress::load(&path);
    if !path.exists() {
        if let Ok(raw) = fs::read_to_string(limitless.join("stats.json")) {
            if let Ok(mut migrated) = serde_json::from_str::<AchievementProgress>(&raw) {
                migrated.normalize();
                let _ = migrated.save(&path);
                return migrated;
            }
        }
    }
    progress
}

/// Persisted badge progress: the lifetime counters plus which badge names
/// have already been unlocked.
///
/// ```
/// use limitless_cli::modules::achievements::AchievementProgress;
/// let mut progress = AchievementProgress::default();
/// progress.stats.processes_killed = 5;
/// assert_eq!(progress.check_unlocked(), vec!["Port Whisperer"]);
/// assert!(progress.check_unlocked().is_empty());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
pub struct AchievementProgress {
    /// Lifetime usage counters.
    pub stats: ArcadeStats,
    /// Badge names already unlocked, kept unique.
    pub unlocked: Vec<String>,
}

impl AchievementProgress {
    /// Loads progress from `path`; missing or corrupt files yield defaults.
    pub fn load(path: &Path) -> Self {
        match fs::read_to_string(path) {
            Ok(raw) => serde_json::from_str::<AchievementProgress>(&raw)
                .map(|mut p| {
                    p.normalize();
                    p
                })
                .unwrap_or_default(),
            Err(_) => Self::default(),
        }
    }

    /// Persists progress to `path`, creating parent directories as needed.
    pub fn save(&self, path: &Path) -> io::Result<()> {
        if let Some(parent) = path.parent() {
            if !parent.as_os_str().is_empty() {
                fs::create_dir_all(parent)?;
            }
        }
        fs::write(path, serde_json::to_string_pretty(self)?)
    }

    /// Deduplicates `unlocked`, keeping the first occurrence order.
    pub fn normalize(&mut self) {
        let mut seen = Vec::with_capacity(self.unlocked.len());
        self.unlocked.retain(|name| {
            if seen.contains(name) {
                false
            } else {
                seen.push(name.clone());
                true
            }
        });
    }

    /// Which badges the current stats satisfy, minus ones already unlocked.
    pub fn satisfied(&self) -> Vec<String> {
        check_badges(&self.stats)
            .into_iter()
            .filter(|name| !self.unlocked.contains(name))
            .collect()
    }

    /// Records and returns the *newly* unlocked badge names (a subset of
    /// [`check_badges`]). Repeats return nothing until stats change.
    pub fn check_unlocked(&mut self) -> Vec<String> {
        let new = self.satisfied();
        self.unlocked.extend(new.iter().cloned());
        new
    }
}

/// Current hour of day (UTC) derived from the system clock.
fn utc_hour_now() -> u32 {
    let secs = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    ((secs / 3600) % 24) as u32
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    fn stats() -> ArcadeStats {
        ArcadeStats::default()
    }

    struct TempDir(PathBuf);

    impl TempDir {
        fn new(tag: &str) -> Self {
            let nanos = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .map(|d| d.as_nanos())
                .unwrap_or(0);
            let path = std::env::temp_dir().join(format!(
                "limitless_achievements_{}_{}_{}",
                tag,
                std::process::id(),
                nanos
            ));
            fs::create_dir_all(&path).expect("create temp dir");
            Self(path)
        }

        fn path(&self) -> &Path {
            &self.0
        }
    }

    impl Drop for TempDir {
        fn drop(&mut self) {
            let _ = fs::remove_dir_all(&self.0);
        }
    }

    #[test]
    fn registry_has_all_five_badges_in_order() {
        let ids: Vec<&str> = BADGES.iter().map(|b| b.id).collect();
        assert_eq!(
            ids,
            vec![
                "port-whisperer",
                "env-master",
                "speed-runner",
                "arcade-champion",
                "night-owl",
            ]
        );
        assert_eq!(BADGES.len(), 5);
        assert!(BADGES[0].name.contains("Port"));
        assert!(BADGES[4].name.contains("Night"));
    }

    #[test]
    fn badge_emojis_are_single_unicode_scalars() {
        for badge in BADGES {
            assert_ne!(badge.emoji, '\0', "{}", badge.id);
            assert!(!badge.emoji.is_ascii(), "{}", badge.id);
        }
    }

    #[test]
    fn badge_ids_are_unique() {
        let mut ids: Vec<&str> = BADGES.iter().map(|b| b.id).collect();
        ids.sort_unstable();
        let mut dedup = ids.clone();
        dedup.dedup();
        assert_eq!(ids, dedup);
    }

    #[test]
    fn badge_by_id_finds_known_and_misses_unknown() {
        assert!(badge_by_id("night-owl").is_some());
        assert_eq!(badge_by_id("night-owl").unwrap().emoji, '\u{1F319}');
        assert!(badge_by_id("nope").is_none());
    }

    #[test]
    fn port_whisperer_threshold() {
        let mut s = stats();
        assert!(!BadgeCondition::PortWhisperer.matches(&s));
        s.processes_killed = GHOST_PROCESS_TARGET - 1;
        assert!(!BadgeCondition::PortWhisperer.matches(&s));
        s.processes_killed = GHOST_PROCESS_TARGET;
        assert!(BadgeCondition::PortWhisperer.matches(&s));
        s.processes_killed = 99;
        assert!(BadgeCondition::PortWhisperer.matches(&s));
    }

    #[test]
    fn env_master_threshold() {
        let mut s = stats();
        s.env_files_created = ENV_MASTER_TARGET - 1;
        assert!(!BadgeCondition::EnvMaster.matches(&s));
        s.env_files_created = ENV_MASTER_TARGET;
        assert!(BadgeCondition::EnvMaster.matches(&s));
    }

    #[test]
    fn speed_runner_threshold_is_strictly_below_once_scanned() {
        let s = stats();
        assert!(!BadgeCondition::SpeedRunner.matches(&s));
        let mut s = s;
        s.last_diagnostic_time_ms = Some(SPEED_RUNNER_MS);
        assert!(!BadgeCondition::SpeedRunner.matches(&s));
        s.last_diagnostic_time_ms = Some(SPEED_RUNNER_MS - 1);
        assert!(BadgeCondition::SpeedRunner.matches(&s));
    }

    #[test]
    fn arcade_win_threshold_is_strictly_above() {
        let mut s = stats();
        s.best_arcade_score = 500;
        assert!(!BadgeCondition::ArcadeWin { score: 500 }.matches(&s));
        s.best_arcade_score = 501;
        assert!(BadgeCondition::ArcadeWin { score: 500 }.matches(&s));
    }

    #[test]
    fn night_owl_only_matches_hours_2_to_5() {
        let s = stats();
        assert!(!BadgeCondition::NightOwl.matches(&s));
        for hour in 0..=23 {
            let mut probe = stats();
            probe.times_run.insert(hour, 1);
            assert_eq!(
                BadgeCondition::NightOwl.matches(&probe),
                (NIGHT_OWL_FROM_HOUR..=NIGHT_OWL_TO_HOUR).contains(&hour),
                "hour {hour}"
            );
        }
    }

    #[test]
    fn night_owl_requires_a_nonzero_count() {
        let mut s = stats();
        s.times_run.insert(3, 0);
        assert!(!BadgeCondition::NightOwl.matches(&s));
        s.times_run.insert(3, 1);
        assert!(BadgeCondition::NightOwl.matches(&s));
    }

    #[test]
    fn first_fix_and_perfect_health_match() {
        let mut s = stats();
        assert!(!BadgeCondition::FirstFixExecuted.matches(&s));
        s.record_fix();
        assert!(BadgeCondition::FirstFixExecuted.matches(&s));

        assert!(!BadgeCondition::PerfectHealth { count: 3 }.matches(&s));
        for _ in 0..3 {
            s.record_perfect_health();
        }
        assert!(BadgeCondition::PerfectHealth { count: 3 }.matches(&s));
        s.reset_perfect_health();
        assert!(!BadgeCondition::PerfectHealth { count: 3 }.matches(&s));
    }

    #[test]
    fn dependency_hero_is_reserved() {
        let mut s = stats();
        s.fixes_applied = 50;
        s.processes_killed = 50;
        s.env_files_created = 50;
        s.best_arcade_score = 100_000;
        s.perfect_health_streak = 50;
        assert!(!BadgeCondition::DependencyHero.matches(&s));
    }

    #[test]
    fn check_badges_empty_stats_is_empty() {
        assert!(check_badges(&stats()).is_empty());
    }

    #[test]
    fn check_badges_reports_only_satisfied_in_registry_order() {
        let mut s = stats();
        s.processes_killed = 5;
        s.best_arcade_score = 501;
        assert_eq!(check_badges(&s), vec!["Port Whisperer", "Arcade Champion"]);
    }

    #[test]
    fn check_badges_speed_runner_and_night_owl() {
        let mut s = stats();
        s.last_diagnostic_time_ms = Some(4999);
        s.times_run.insert(2, 1);
        assert_eq!(check_badges(&s), vec!["Speed Runner", "Night Owl"]);
    }

    #[test]
    fn share_text_matches_spec_format() {
        let badge = badge_by_id("port-whisperer").unwrap();
        assert_eq!(
            share_text(badge),
            "Share: \"I unlocked \u{1F527} Port Whisperer in Limitless\""
        );
    }

    #[test]
    fn popup_renders_header_name_and_share_line() {
        let popup = render_badge_popup(badge_by_id("env-master").unwrap());
        assert!(popup.contains("🎉 BADGE UNLOCKED!"));
        assert!(popup.contains("Env Master"));
        assert!(popup.contains("Create 10 .env files."));
        assert!(popup.contains(&share_text(badge_by_id("env-master").unwrap())));
        assert!(popup.lines().next().unwrap().starts_with('┌'));
        assert!(popup.lines().last().unwrap().starts_with('└'));
    }

    #[test]
    fn popup_rows_have_constant_width() {
        for badge in BADGES {
            for line in render_badge_popup(badge).lines() {
                assert_eq!(line.chars().count(), POPUP_WIDTH, "{}", badge.id);
            }
        }
    }

    #[test]
    fn popup_is_single_block_with_no_message_wrap() {
        for badge in BADGES {
            let popup = render_badge_popup(badge);
            assert_eq!(popup.lines().count(), 8);
        }
    }

    #[test]
    fn stats_recording_helpers_bump_counters() {
        let mut s = stats();
        s.record_diagnostic_at(100, 4);
        s.record_diagnostic_at(200, 4);
        s.record_diagnostic_at(300, 10);
        assert_eq!(s.diagnostics_run, 3);
        assert_eq!(s.last_diagnostic_time_ms, Some(300));
        assert_eq!(s.times_run.get(&4), Some(&2));
        assert_eq!(s.times_run.get(&10), Some(&1));
        assert_eq!(s.times_run.len(), 2);

        s.record_fix();
        s.record_process_killed();
        s.record_env_created();
        assert_eq!(s.fixes_applied, 1);
        assert_eq!(s.processes_killed, 1);
        assert_eq!(s.env_files_created, 1);

        s.record_arcade_game(100);
        s.record_arcade_game(900);
        assert_eq!(s.total_arcade_plays, 2);
        assert_eq!(s.best_arcade_score, 900);
    }

    #[test]
    fn record_diagnostic_uses_a_valid_hour() {
        let mut s = stats();
        s.record_diagnostic(123);
        assert_eq!(s.diagnostics_run, 1);
        assert!(s.times_run.values().all(|&c| c == 1));
        let (hour, _) = s.times_run.iter().next().unwrap();
        assert!((0..24).contains(hour));
    }

    #[test]
    fn progress_only_reports_newly_unlocked_once() {
        let mut p = AchievementProgress::default();
        p.stats.processes_killed = 5;
        assert_eq!(p.check_unlocked(), vec!["Port Whisperer"]);
        assert!(p.check_unlocked().is_empty());
        assert_eq!(p.unlocked, vec!["Port Whisperer"]);

        p.stats.best_arcade_score = 900;
        assert_eq!(p.check_unlocked(), vec!["Arcade Champion"]);
    }

    #[test]
    fn progress_normalize_deduplicates_keeping_order() {
        let mut p = AchievementProgress {
            unlocked: vec!["b".into(), "a".into(), "b".into(), "c".into()],
            ..Default::default()
        };
        p.normalize();
        assert_eq!(p.unlocked, vec!["b", "a", "c"]);
    }

    #[test]
    fn satisfied_excludes_already_unlocked() {
        let mut p = AchievementProgress::default();
        p.stats.processes_killed = 5;
        p.unlocked = vec!["Port Whisperer".into()];
        assert!(p.satisfied().is_empty());
    }

    #[test]
    fn progress_round_trips_through_json() {
        let mut p = AchievementProgress::default();
        p.stats.diagnostics_run = 7;
        p.stats.times_run.insert(3, 4);
        assert_eq!(p.check_unlocked(), vec!["Night Owl"]);
        p.stats.best_arcade_score = 800;
        assert_eq!(p.check_unlocked(), vec!["Arcade Champion"]);

        let json = serde_json::to_string(&p).unwrap();
        let back: AchievementProgress = serde_json::from_str(&json).unwrap();
        assert_eq!(back, p);
        assert_eq!(back.unlocked, vec!["Night Owl", "Arcade Champion"]);
        assert_eq!(back.stats.diagnostics_run, 7);
        assert_eq!(back.stats.times_run.get(&3), Some(&4));
    }

    #[test]
    fn refine_save_and_load_round_trip() {
        let dir = TempDir::new("roundtrip");
        let path = dir.path().join("stats.json");

        let mut p = AchievementProgress::default();
        p.stats.env_files_created = 10;
        p.check_unlocked();
        p.save(&path).unwrap();
        assert!(path.exists());

        let back = AchievementProgress::load(&path);
        assert_eq!(back.unlocked, vec!["Env Master"]);
        assert_eq!(back.stats.env_files_created, 10);
    }

    #[test]
    fn load_missing_or_corrupt_file_yields_default() {
        let dir = TempDir::new("missing");
        let missing = AchievementProgress::load(&dir.path().join("nope.json"));
        assert!(missing.stats.diagnostics_run == 0 && missing.unlocked.is_empty());

        let path = dir.path().join("bad.json");
        fs::write(&path, "not json").unwrap();
        let corrupt = AchievementProgress::load(&path);
        assert!(corrupt.stats.diagnostics_run == 0 && corrupt.unlocked.is_empty());
    }

    #[test]
    fn progress_file_path_points_into_home_dir() {
        let path = progress_file_path().expect("home dir should exist in tests");
        assert_eq!(path.file_name().unwrap(), "achievements.json");
        assert_eq!(path.parent().unwrap().file_name().unwrap(), ".limitless");
    }

    #[test]
    fn load_progress_at_home_migrates_legacy_stats_file() {
        let dir = TempDir::new("migrate");
        fs::create_dir_all(dir.path().join(".limitless")).unwrap();

        let mut from_the_past = AchievementProgress::default();
        from_the_past.stats.record_fix();
        from_the_past.stats.record_diagnostic(700);
        from_the_past.unlocked.push("Env Master".into());
        let legacy = dir.path().join(".limitless").join("stats.json");
        fs::write(&legacy, serde_json::to_string_pretty(&from_the_past).unwrap()).unwrap();

        let migrated = load_progress_at_home(dir.path());

        assert_eq!(migrated, from_the_past);
        assert!(dir.path().join(".limitless").join("achievements.json").is_file());

        // Migration keeps legacy file intact (config.rs owns stats.json now).
        assert!(legacy.exists());
    }

    #[test]
    fn load_progress_at_home_skips_migration_when_present() {
        let dir = TempDir::new("skipmig");
        fs::create_dir_all(dir.path().join(".limitless")).unwrap();

        let mut current = AchievementProgress::default();
        current.stats.record_diagnostic(900);
        fs::write(
            dir.path().join(".limitless").join("achievements.json"),
            serde_json::to_string_pretty(&current).unwrap(),
        )
        .unwrap();
        // A legacy file that disagrees with the current one must be ignored.
        let mut stale = AchievementProgress::default();
        stale.stats.record_diagnostic(100);
        fs::write(
            dir.path().join(".limitless").join("stats.json"),
            serde_json::to_string_pretty(&stale).unwrap(),
        )
        .unwrap();

        assert_eq!(load_progress_at_home(dir.path()), current);
    }

    #[test]
    fn test_badge_unlock_logic() {
        // Fresh stats unlock nothing.
        assert_eq!(check_badges(&ArcadeStats::default()), Vec::<String>::new());

        // Each threshold trips exactly the badge it targets.
        let near = ArcadeStats {
            processes_killed: 4,
            ..ArcadeStats::default()
        };
        assert!(!check_badges(&near).contains(&"Port Whisperer".to_string()));
        let port = ArcadeStats {
            processes_killed: 5,
            ..ArcadeStats::default()
        };
        assert!(check_badges(&port).contains(&"Port Whisperer".to_string()));

        let env = ArcadeStats {
            env_files_created: 12,
            ..ArcadeStats::default()
        };
        assert!(check_badges(&env).contains(&"Env Master".to_string()));

        let arcade = ArcadeStats {
            best_arcade_score: 600,
            ..ArcadeStats::default()
        };
        assert!(check_badges(&arcade).contains(&"Arcade Champion".to_string()));

        // Night Owl unlocks for a run in the 2 AM - 5 AM window.
        let owl = ArcadeStats {
            times_run: {
                let mut m = std::collections::HashMap::new();
                m.insert(3, 1);
                m
            },
            ..ArcadeStats::default()
        };
        assert!(check_badges(&owl).contains(&"Night Owl".to_string()));

        // Only runs between 2:00 and 4:59 count: daytime runs do not.
        let day = ArcadeStats {
            times_run: {
                let mut m = std::collections::HashMap::new();
                m.insert(14, 1);
                m
            },
            ..ArcadeStats::default()
        };
        assert!(!check_badges(&day).contains(&"Night Owl".to_string()));

        // Badges are independent: meeting several thresholds lists several.
        let combined = ArcadeStats {
            processes_killed: 5,
            env_files_created: 12,
            best_arcade_score: 600,
            ..ArcadeStats::default()
        };
        let unlocked = check_badges(&combined);
        assert!(unlocked.contains(&"Port Whisperer".to_string()));
        assert!(unlocked.contains(&"Env Master".to_string()));
        assert!(unlocked.contains(&"Arcade Champion".to_string()));
        assert_eq!(unlocked.len(), 3);
    }
}