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
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
//! Limitless CLI — command-line entry point and orchestration.
//!
//! Every command routes through a small set of runner functions that reuse
//! the library modules for scanning, rendering, fixing and gamification:
//!
//! ```text
//! limit            → health audit → dashboard (same as `limit check`)
//! limit check      → health audit → dashboard
//! limit dev        → if 100% healthy: launch dev server
//!                     else: health audit → suggested fixes
//! limit fix --all  → identify fixable issues → run the auto-fix suite
//! limit fix        → interactive, approval-by-approval fixes
//! limit orbit      → planetary diagnostics → mission-control report
//! limit arcade     → SyntaxBreaker typing game → high scores
//! limit --help     → full help
//! ```
//!
//! After every run the badge engine (`modules::achievements`) records the
//! activity and prints popups for any newly-unlocked badges. Exit codes are
//! `0` on success and `1` when issues were found.

use clap::{Parser, Subcommand};
use colored::control;
use colored::Colorize;
use limitless_cli::models::{CheckStatus, EnvironmentState, ProjectStack};
use limitless_cli::modules::{
    achievements, arcade, auto_fix, config, diagnostics, fixes, planetary, progress, tui,
};
use limitless_cli::VERSION;
use std::io::{self, Write};
use std::path::Path;
use std::process::ExitCode;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

/// The project root always points at the current working directory.
const REPO_ROOT: &str = ".";

/// Recognized per-stack manifest files (in detection order).
const MANIFESTS: &[&str] = &[
    "package.json",
    "requirements.txt",
    "pyproject.toml",
    "setup.py",
    "Cargo.toml",
    "go.mod",
];

// ---------------------------------------------------------------------------
// CLI definition
// ---------------------------------------------------------------------------

#[derive(Parser, Clone)]
#[command(
    name = "limit",
    bin_name = "limit",
    about = "Limitless CLI — a beginner-friendly environment diagnostic tool",
    version = env!("CARGO_PKG_VERSION"),
    long_about = "Limitless CLI helps you detect, diagnose, and fix development environment issues.\nRun 'limit check' to scan your environment, or explore other commands in 'limit --help'."
)]
struct Args {
    /// Skip animations and progress trivia for fast, quiet output
    #[arg(short, long, global = true)]
    fast: bool,

    /// Show technical details behind every result
    #[arg(short, long, global = true)]
    verbose: bool,

    /// Force colored output, overriding `~/.limitless/config.json`
    #[arg(long, global = true)]
    color: bool,

    /// Disable colors entirely (for piping / plain-text logs)
    #[arg(long, global = true)]
    no_color: bool,

    #[command(subcommand)]
    command: Option<Command>,
}

#[derive(Subcommand, Clone)]
enum Command {
    /// Check / diagnose your development environment (stack, tools, config)
    Check,

    /// Inspect deeply; launch the dev server when the environment is clean
    Dev,

    /// Automatically fix detected environment issues
    Fix {
        /// Apply every fix without asking
        #[arg(long)]
        all: bool,
    },

    /// Run the planetary mission-control diagnostics
    Orbit,

    /// Launch the developer mini-games / challenges
    Arcade,
}

// ---------------------------------------------------------------------------
// Entry point
// ---------------------------------------------------------------------------

#[tokio::main]
async fn main() -> ExitCode {
    // Route root `--help`/`-h` to the comprehensive help renderer before clap
    // parses anything (subcommands like `limit dev --help` are handled by clap).
    let raw: Vec<String> = std::env::args().skip(1).collect();
    if raw.len() == 1 && (raw[0] == "--help" || raw[0] == "-h") {
        println!("{}", display_help());
        return ExitCode::SUCCESS;
    }

    match route(Args::parse()).await {
        Ok(0) => ExitCode::SUCCESS,
        Ok(code) => ExitCode::from(code.clamp(0, 255) as u8),
        Err(message) => {
            println!();
            eprintln!("{}{}", "error: ".red().bold(), screen_error(&message));
            ExitCode::from(1)
        }
    }
}

// ---------------------------------------------------------------------------
// Help system
// ---------------------------------------------------------------------------

/// Box rule framing the header and footer of the help output.
const HELP_RULE: &str = "═══════════════════════════════════════════════════";

/// Renders the complete help guide: command reference, options, examples,
/// feature list, FAQ and troubleshooting. Read-only — never touches disk or
/// network, so it is safe to call before config/bootstrap.
///
/// Example usage:
/// ```text
/// limit --help   → prints this guide
/// limit -h       → same guide, short form
/// ```
///
/// Error handling: this never fails; the content is a compile-time constant
/// text block. (There is no `io::Result` here by design — printing failures
/// are handled by the caller, not generated here.)
///
/// The returned string is the full guide kept in `format!` with the box rule
/// substituted so header and footer always match width.
pub fn display_help() -> String {
    format!(
        r#"{rule}
🚀 LIMITLESS v{version} — Developer Environment CLI
{rule}

USAGE:
  limit [COMMAND] [OPTIONS]

COMMANDS:
  check, (default)    Run complete environment audit
  dev                 Audit + launch dev server (if healthy)
  fix --all           Auto-fix all detected issues
  orbit               Sci-fi themed diagnostic view
  arcade              Terminal typing game
  --help              Show this help message

OPTIONS:
  --fast              Skip animations (speed up output)
  --verbose           Show technical error details
  --color             Force colored output
  --no-color          Disable colors
  --version           Show version

EXAMPLES:
  # Run a complete health check
  $ limit

  # Check health, then start dev server
  $ limit dev

  # Fix all issues automatically
  $ limit fix --all

  # View in sci-fi theme
  $ limit orbit

  # Play typing game
  $ limit arcade

WHAT LIMITLESS DOES:
  ✓ Detects your project stack (Node.js, Python, Rust, Docker)
  ✓ Checks runtime versions match requirements
  ✓ Audits .env configuration files
  ✓ Detects blocked ports (ghost processes)
  ✓ Inspects dependency health
  ✓ Translates errors into plain English
  ✓ Suggests one-click fixes

WHEN TO USE:
  - Starting a new project? → limit
  - Getting "port already in use" error? → limit fix --all
  - Want to understand your project setup? → limit orbit
  - Procrastinating on real work? → limit arcade 😄

LEARN MORE:
  GitHub: https://github.com/limitless-cli/limitless
  Docs: https://limitless-cli.dev/docs
  Issues: https://github.com/limitless-cli/limitless/issues

TROUBLESHOOTING:

Q: limit command not found
A: Make sure Limitless is installed:
   $ cargo install limitless-cli
   Then add ~/.cargo/bin to your PATH

Q: Permission denied errors
A: Some fixes (killing processes) need elevated privileges:
   $ sudo limit fix --all

Q: My project is not detected
A: Ensure you have:
   - Node: package.json
   - Python: requirements.txt or setup.py
   - Rust: Cargo.toml
   - Run from your project root: $ cd my-project && limit

{rule}
"#,
        rule = HELP_RULE,
        version = VERSION
    )
}

// ---------------------------------------------------------------------------
// Routing
// ---------------------------------------------------------------------------
/// Dispatches the parsed command, records badge-relevant activity, checks for
/// newly-unlocked badges, and returns the process exit code.
async fn route(args: Args) -> Result<i32, String> {
    // Preferences bootstrap `~/.limitless/` on first run and shape output.
    let settings = config::init_config()?;

    // Color trumps config: CLI flags win, config is the fallback default.
    // (`--no-color` also beats `--color` when both appear; last flag wins
    // is unusual in clap, so we prioritize the "disable" flag here.)
    let color_override = match (args.color, args.no_color) {
        (true, false) => true,
        (false, true) => false,
        (true, true) => false,
        (false, false) => settings.color_enabled,
    };
    control::set_override(color_override);

    let mut progress = load_progress();

    // Blend config preferences into the flags: a CLI flag always wins, and
    // config only ever *removes* colors/animations/details — never adds them.
    let effective = effective_args(&args, &settings);

    let code = match args.command {
        None | Some(Command::Check) => cmd_check(&effective, &mut progress)?,
        Some(Command::Dev) => cmd_dev(&effective, &mut progress).await?,
        Some(Command::Fix { all }) => cmd_fix(all, &effective, &mut progress).await?,
        Some(Command::Orbit) => cmd_orbit(&effective, &mut progress)?,
        Some(Command::Arcade) => cmd_arcade(&effective, &mut progress)?,
    };

    let newly_unlocked = progress.check_unlocked();
    if !newly_unlocked.is_empty() {
        print_new_badges(&newly_unlocked);
    }
    if progress.stats != achievements::ArcadeStats::default() || !newly_unlocked.is_empty() {
        save_progress(&progress)?;
        // Mirror the same counters into config's bare `stats.json`.
        config::save_stats(&progress.stats)?;
    }

    Ok(code)
}

/// Merges `~/.limitless/config.json` preferences into the parsed args:
/// animations off ⇒ fast; verbose preferred ⇒ verbose on; CLI flags win.
fn effective_args(args: &Args, settings: &config::LimitlessConfig) -> Args {
    Args {
        fast: args.fast || !settings.animation_enabled,
        verbose: args.verbose || settings.verbose_mode,
        color: args.color,
        no_color: args.no_color,
        command: args.command.clone(),
    }
}

/// `limit check` (and bare `limit`): full health audit, then the dashboard.
fn cmd_check(args: &Args, progress: &mut achievements::AchievementProgress) -> Result<i32, String> {
    ensure_project()?;
    if args.verbose {
        if let Some(manifest) = find_manifest() {
            println!("  {} {}", "Manifest:".bold(), manifest);
        }
    }

    let started = Instant::now();
    // `--fast` reuses a fresh cached snapshot when available.
    let cached = if args.fast {
        config::get_cached_diagnostics()
    } else {
        None
    };
    let reused = cached.is_some();
    let state = cached.unwrap_or_else(|| scan_with_progress(!args.fast));
    let elapsed_ms = started.elapsed().as_millis() as u32;

    print!("{}", tui::render_dashboard(&state));
    println!();
    if reused {
        println!(
            "  {}",
            "cached snapshot (≤5m old; run without --fast to rescan)".dimmed()
        );
    }
    if state.ready_for_dev() {
        println!(
            "{}",
            "  ✓ Environment is ready — happy coding!".green().bold()
        );
    } else {
        println!(
            "{}",
            "  ! Review the notes above before continuing.  (Run `limit fix --all` to fix issues.)"
                .yellow()
                .bold()
        );
    }

    // A reused cache is not a new scan: it must not inflate the counters.
    if !reused {
        progress.stats.record_diagnostic(elapsed_ms);
    }
    record_health(&mut progress.stats, &state);
    if args.verbose {
        print_diagnostic_details(&state);
    }

    Ok(exit_code_for(&state))
}

/// `limit dev`: launch the dev server only when the environment is perfect,
/// otherwise render the dashboard and suggest fixes.
async fn cmd_dev(
    args: &Args,
    progress: &mut achievements::AchievementProgress,
) -> Result<i32, String> {
    ensure_project()?;

    let started = Instant::now();
    let state = scan_with_progress(!args.fast);
    let elapsed_ms = started.elapsed().as_millis() as u32;

    progress.stats.record_diagnostic(elapsed_ms);
    record_health(&mut progress.stats, &state);

    if state.health_score.percentage == 100 {
        println!(
            "  ✓ Environment is 100% healthy — {}",
            "launching the dev server…".green().bold()
        );
        if args.verbose {
            println!("  {} {}", "Stack:".bold(), state.detected_stack.label());
        }
        launch_dev_server(&state.detected_stack)?;
        return Ok(0);
    }

    print!("{}", tui::render_dashboard(&state));
    println!();
    suggest_fixes(&state);
    Ok(exit_code_for(&state))
}

/// `limit fix`: `--all` runs the whole auto-fix suite; without `--all` it
/// walks each fix and asks for approval.
async fn cmd_fix(
    all: bool,
    args: &Args,
    progress: &mut achievements::AchievementProgress,
) -> Result<i32, String> {
    ensure_project()?;

    let started = Instant::now();
    let state = scan_with_progress(!args.fast);
    let elapsed_ms = started.elapsed().as_millis() as u32;

    progress.stats.record_diagnostic(elapsed_ms);
    record_health(&mut progress.stats, &state);

    if all {
        let issues = identify_fixable_issues(&state);
        println!();
        println!(
            "  Found {} fixable issue{s}. Applying the auto-fix suite…",
            issues.len(),
            s = if issues.len() == 1 { "" } else { "s" }
        );
        let report = auto_fix::run_auto_fix_all(&state, REPO_ROOT).await;
        for _ in 0..report.fixes_applied {
            progress.stats.record_fix();
        }
        Ok(if report.issues_remaining.is_empty() { 0 } else { 1 })
    } else {
        fixes::run_fix(false).await;
        Ok(exit_code_for(&state))
    }
}

/// `limit orbit`: deep-scan and the mission-control planetary report.
fn cmd_orbit(args: &Args, progress: &mut achievements::AchievementProgress) -> Result<i32, String> {
    ensure_project()?;

    let started = Instant::now();
    let state = scan_with_progress(!args.fast);
    let elapsed_ms = started.elapsed().as_millis() as u32;

    progress.stats.record_diagnostic(elapsed_ms);
    record_health(&mut progress.stats, &state);

    print!("{}", planetary::render_planetary_diagnostics(&state.diagnostics));
    println!();
    if args.verbose {
        print_diagnostic_details(&state);
    }
    Ok(exit_code_for(&state))
}

/// `limit arcade`: play SyntaxBreaker, then show the leaderboard.
fn cmd_arcade(args: &Args, progress: &mut achievements::AchievementProgress) -> Result<i32, String> {
    let result = arcade::run_typing_game();
    if args.verbose {
        println!(
            "  {} {} pts · {} wpm · {} snippets",
            "Result:".bold(),
            result.score,
            result.wpm,
            result.snippets_completed
        );
    }
    show_high_scores();
    progress.stats.record_arcade_game(result.score.max(0) as u32);
    Ok(0)
}

// ---------------------------------------------------------------------------
// Project detection
// ---------------------------------------------------------------------------

/// The recognized manifest file in `root`, if any.
fn find_manifest_at(root: &Path) -> Option<&'static str> {
    MANIFESTS
        .iter()
        .copied()
        .find(|manifest| root.join(manifest).is_file())
}

/// The recognized manifest file in the current directory, if any.
fn find_manifest() -> Option<&'static str> {
    find_manifest_at(Path::new(REPO_ROOT))
}

/// Fails with a beginner-friendly message when `root` is not a project root.
fn ensure_project_at(root: &Path) -> Result<(), String> {
    if !root.is_dir() {
        return Err("Run `limit` from your project root.".to_string());
    }
    if find_manifest_at(root).is_none() {
        return Err(
            "No package.json/requirements.txt/Cargo.toml found — run `limit` from your project root."
                .to_string(),
        );
    }
    Ok(())
}

/// Fails with a beginner-friendly message when the CWD is not a project root.
fn ensure_project() -> Result<(), String> {
    ensure_project_at(Path::new(REPO_ROOT))
}

// ---------------------------------------------------------------------------
// Scanning
// ---------------------------------------------------------------------------

/// Runs the full diagnostics for the current directory. With `animate` a
/// spinner plays in the main thread while the scan runs in a worker thread,
/// keeping the scan genuinely parallel with the animation. Every fresh scan
/// refreshes the 5-minute diagnostic cache (`~/.limitless/cache.json`).
fn scan_with_progress(animate: bool) -> EnvironmentState {
    let is_tty = crossterm::tty::IsTty::is_tty(&io::stdout());
    let state = if !animate || !is_tty {
        diagnostics::run_full_diagnostics(REPO_ROOT)
    } else {
        let snapshot = Arc::new(Mutex::new(None));
        let done = Arc::new(AtomicBool::new(false));
        let (slot, flag) = (Arc::clone(&snapshot), Arc::clone(&done));
        let handle = std::thread::spawn(move || {
            let state = diagnostics::run_full_diagnostics(REPO_ROOT);
            *slot.lock().expect("snapshot slot") = Some(state);
            flag.store(true, Ordering::SeqCst);
        });

        let mut out = io::stdout();
        let mut frame = 0usize;
        while !done.load(Ordering::SeqCst) {
            let line = progress::spinner_line("Scanning your environment", frame);
            let _ = out.write_all(line.as_bytes());
            let _ = out.flush();
            frame += 1;
            std::thread::sleep(Duration::from_millis(80));
        }
        let _ = handle.join();
        let _ = out.write_all(b"\r\x1b[2K");
        let _ = out.flush();

        let state = snapshot
            .lock()
            .expect("snapshot slot")
            .take()
            .expect("scan finished before snapshot was taken");
        state
    };
    let _ = config::cache_diagnostics(&state);
    state
}

// ---------------------------------------------------------------------------
// Fix suggestions
// ---------------------------------------------------------------------------

/// Names of every fixable issue the auto-fix suite would address.
fn identify_fixable_issues(state: &EnvironmentState) -> Vec<String> {
    auto_fix::build_auto_fixes(state, REPO_ROOT, true)
        .into_iter()
        .map(|fix| fix.name)
        .collect()
}

/// Prints beginner-friendly fix pointers for the issuing checks.
fn suggest_fixes(state: &EnvironmentState) {
    let suggestions = fixes::recommended_fixes(state, REPO_ROOT);
    if suggestions.is_empty() {
        println!(
            "  {} No auto-fixes available — review the manual notes above.",
            "Hint:".cyan().bold()
        );
        return;
    }
    println!("  {} Suggested fixes:", "🛠️".bold());
    for (i, fix) in suggestions.iter().enumerate() {
        let tag = if fix.requires_approval {
            "approval required".yellow()
        } else {
            "safe".green()
        };
        println!("   {}. {} — {tag}", i + 1, fix.name);
    }
    println!();
    println!(
        "  {} Run `limit fix --all` to apply everything automatically.",
        "Next:".cyan().bold()
    );
}

// ---------------------------------------------------------------------------
// Dev server
// ---------------------------------------------------------------------------

/// The command tuple to start a stack's dev server: `(program, arguments)`.
fn dev_command(stack: &ProjectStack) -> Option<(String, Vec<String>)> {
    match stack {
        ProjectStack::Node { package_manager, .. } => {
            let program = match package_manager.as_str() {
                "yarn" => "yarn",
                "pnpm" => "pnpm",
                _ => "npm",
            };
            Some((
                program.to_string(),
                if program == "npm" {
                    vec!["run".to_string(), "dev".to_string()]
                } else {
                    vec!["dev".to_string()]
                },
            ))
        }
        ProjectStack::Python { .. } => {
            let root = Path::new(REPO_ROOT);
            if root.join("manage.py").is_file() {
                Some((
                    "python".to_string(),
                    vec!["manage.py".to_string(), "runserver".to_string()],
                ))
            } else if root.join("main.py").is_file() || root.join("app.py").is_file() {
                Some((
                    "python".to_string(),
                    vec![
                        "-m".to_string(),
                        "uvicorn".to_string(),
                        "main:app".to_string(),
                        "--reload".to_string(),
                    ],
                ))
            } else {
                Some((
                    "python".to_string(),
                    vec!["-m".to_string(), "flask".to_string(), "run".to_string()],
                ))
            }
        }
        ProjectStack::Rust { .. } => {
            Some(("cargo".to_string(), vec!["run".to_string()]))
        }
        ProjectStack::Go { .. } => {
            Some(("go".to_string(), vec!["run".to_string(), ".".to_string()]))
        }
        ProjectStack::Java { .. } => {
            let root = Path::new(REPO_ROOT);
            if root.join("mvnw").is_file() || root.join("pom.xml").is_file() {
                Some(("mvn".to_string(), vec!["spring-boot:run".to_string()]))
            } else {
                Some(("./gradlew".to_string(), vec!["bootRun".to_string()]))
            }
        }
        ProjectStack::Docker => Some((
            "docker".to_string(),
            vec!["compose".to_string(), "up".to_string()],
        )),
        ProjectStack::Unknown => None,
    }
}

/// Launches the stack's dev server, handing the terminal over to it. Blocks
/// until the server exits (Ctrl+C to stop).
fn launch_dev_server(stack: &ProjectStack) -> Result<(), String> {
    let (program, args) = dev_command(stack).ok_or_else(|| {
        format!(
            "No dev-server recipe for {} — start it manually.",
            stack.label()
        )
    })?;
    let shown = format!("{program} {}", args.join(" "));
    println!(
        "{}",
        format!("🚀 {shown}").bold().cyan()
    );
    println!(
        "{}",
        "   Press Ctrl+C to stop the server.".dimmed()
    );

    let status = std::process::Command::new(&program)
        .args(&args)
        .status()
        .map_err(|err| {
            format!(
                "could not run `{shown}`: {err}. Install the runtime, or start the dev server yourself."
            )
        })?;

    if status.success() {
        Ok(())
    } else {
        Err(format!("`{shown}` exited with {status}."))
    }
}

// ---------------------------------------------------------------------------
// Arcade high scores
// ---------------------------------------------------------------------------

/// Loads and prints the persisted top-5 leaderboard.
fn show_high_scores() {
    let board = arcade::ArcadeScoreboard::load(&arcade::score_file_path());
    println!();
    print!("{}", arcade::render_scoreboard(&board));
}

// ---------------------------------------------------------------------------
// Exit codes
// ---------------------------------------------------------------------------

/// `0` when every check passed, `1` when any check failed.
fn exit_code_for(state: &EnvironmentState) -> i32 {
    if state.health_score.failed == 0 {
        0
    } else {
        1
    }
}

/// Tracks the perfect-health streak: any failed check resets it.
fn record_health(stats: &mut achievements::ArcadeStats, state: &EnvironmentState) {
    if state.health_score.failed == 0 {
        stats.record_perfect_health();
    } else {
        stats.reset_perfect_health();
    }
}

// ---------------------------------------------------------------------------
// Badges
// ---------------------------------------------------------------------------

/// Loads persisted badge progress from `~/.limitless/achievements.json`,
/// migrating the legacy `stats.json` file on first run.
fn load_progress() -> achievements::AchievementProgress {
    achievements::load_progress_migrated()
}

/// Persists badge progress, creating the directory as needed.
fn save_progress(progress: &achievements::AchievementProgress) -> Result<(), String> {
    if let Some(path) = achievements::progress_file_path() {
        progress
            .save(&path)
            .map_err(|err| format!("could not save badge progress: {err}"))?;
    }
    Ok(())
}

/// Renders the celebratory popup for every freshly-unlocked badge.
fn print_new_badges(names: &[String]) {
    for name in names {
        if let Some(badge) = achievements::BADGES.iter().find(|b| b.name == *name) {
            println!();
            println!("{}", achievements::render_badge_popup(badge));
        }
    }
}

// ---------------------------------------------------------------------------
// Verbose output
// ---------------------------------------------------------------------------

/// Dumps the raw check results when `--verbose` is passed.
fn print_diagnostic_details(state: &EnvironmentState) {
    println!();
    println!(
        "  {} ({})",
        "Technical details".dimmed().bold(),
        state.diagnostics.len()
    );
    for diagnostic in &state.diagnostics {
        let icon = match diagnostic.status {
            CheckStatus::Pass => "✓".green(),
            CheckStatus::Warn => "⚠".yellow(),
            CheckStatus::Fail => "✖".red(),
        };
        println!("   {icon} {}", diagnostic.check_name.dimmed());
        println!("       {}", diagnostic.message.dimmed());
        if let Some(step) = &diagnostic.remediation {
            println!(
                "       {} {}",
                "fix:".cyan().dimmed(),
                step.dimmed()
            );
        }
    }
}

// ---------------------------------------------------------------------------
// Error screening
// ---------------------------------------------------------------------------

/// Recasts raw errors into beginner-friendly hints where possible.
fn screen_error(raw: &str) -> String {
    let lower = raw.to_lowercase();
    if lower.contains("permission denied")
        || lower.contains("access is denied")
        || lower.contains("eacces")
        || lower.contains("access denied")
    {
        return format!(
            "{raw}\n   Hint: Run with sudo — process kills and file writes may need \
             elevated permissions."
        );
    }
    if lower.contains("timed out")
        || lower.contains("connection")
        || lower.contains("resolve")
        || lower.contains("network")
        || lower.contains("offline")
    {
        return format!("{raw}\n   Hint: Check your internet connection.");
    }
    raw.to_string()
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use limitless_cli::models::{DiagnosticResult, HealthScore};
    use std::fs;

    #[test]
    fn effective_args_applies_config_defaults_when_flags_absent() {
        let parsed = Args {
            fast: false,
            verbose: false,
            color: false,
            no_color: false,
            command: None,
        };
        let quiet = config::LimitlessConfig {
            animation_enabled: false,
            verbose_mode: true,
            ..config::LimitlessConfig::default()
        };
        let effective = effective_args(&parsed, &quiet);
        assert!(effective.fast);
        assert!(effective.verbose);
    }

    #[test]
    fn effective_args_cli_flags_always_win() {
        let parsed = Args {
            fast: true,
            verbose: true,
            color: false,
            no_color: false,
            command: None,
        };
        let loud = config::LimitlessConfig {
            animation_enabled: true,
            verbose_mode: false,
            color_enabled: true,
            ..config::LimitlessConfig::default()
        };
        let effective = effective_args(&parsed, &loud);
        assert!(effective.fast);
        assert!(effective.verbose);
    }

    #[test]
    fn display_help_lists_every_command_and_option() {
        let help = display_help();
        for section in [
            "USAGE:",
            "COMMANDS:",
            "OPTIONS:",
            "EXAMPLES:",
            "WHAT LIMITLESS DOES:",
            "WHEN TO USE:",
            "LEARN MORE:",
            "TROUBLESHOOTING:",
        ] {
            assert!(help.contains(section), "missing section: {section}");
        }
        for entry in [
            "check, (default)",
            "dev",
            "fix --all",
            "orbit",
            "arcade",
            "--fast",
            "--verbose",
            "--color",
            "--no-color",
            "--version",
        ] {
            assert!(help.contains(entry), "missing entry: {entry}");
        }
    }

    #[test]
    fn display_help_has_boxed_header_and_footer() {
        let help = display_help();
        assert!(help.starts_with(HELP_RULE));
        assert!(help.contains(&format!("🚀 LIMITLESS v{VERSION} — Developer Environment CLI")));
        assert!(help.trim_end().ends_with(HELP_RULE));
        assert_eq!(help.matches(HELP_RULE).count(), 3);
    }

    #[test]
    fn display_help_includes_troubleshooting_faq() {
        let help = display_help();
        for faq in ["limit command not found", "Permission denied errors", "My project is not detected"] {
            assert!(help.contains(faq), "missing FAQ: {faq}");
        }
        assert!(help.contains("$ cargo install limitless-cli"));
        assert!(help.contains("$ sudo limit fix --all"));
        assert!(help.contains("$ cd my-project && limit"));
    }

    fn temp_project(tag: &str, files: &[&str]) -> std::path::PathBuf {
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0);
        let dir = std::env::temp_dir().join(format!(
            "limitless_main_{}_{}_{}",
            tag,
            std::process::id(),
            nanos
        ));
        fs::create_dir_all(&dir).unwrap();
        for file in files {
            fs::write(dir.join(file), "x").unwrap();
        }
        dir
    }

    #[test]
    fn dev_command_for_node_defaults_to_npm_run_dev() {
        let stack = ProjectStack::Node {
            version: "22.0.0".into(),
            package_manager: "npm".into(),
        };
        assert_eq!(
            dev_command(&stack),
            Some(("npm".to_string(), vec!["run".to_string(), "dev".to_string()]))
        );
    }

    #[test]
    fn dev_command_honors_detected_package_manager() {
        let yarn = ProjectStack::Node {
            version: "22.0.0".into(),
            package_manager: "yarn".into(),
        };
        let pnpm = ProjectStack::Node {
            version: "22.0.0".into(),
            package_manager: "pnpm".into(),
        };
        assert_eq!(
            dev_command(&yarn),
            Some(("yarn".to_string(), vec!["dev".to_string()]))
        );
        assert_eq!(
            dev_command(&pnpm),
            Some(("pnpm".to_string(), vec!["dev".to_string()]))
        );
    }

    #[test]
    fn dev_command_for_python_rust_and_docker() {
        assert_eq!(
            dev_command(&ProjectStack::Python { version: "3.12".into() }),
            Some((
                "python".to_string(),
                vec!["-m".to_string(), "flask".to_string(), "run".to_string()]
            ))
        );
        assert_eq!(
            dev_command(&ProjectStack::Rust { version: "1.80".into() }),
            Some(("cargo".to_string(), vec!["run".to_string()]))
        );
        assert_eq!(
            dev_command(&ProjectStack::Docker),
            Some((
                "docker".to_string(),
                vec!["compose".to_string(), "up".to_string()]
            ))
        );
    }

    #[test]
    fn dev_command_for_unknown_stack_has_no_recipe() {
        assert_eq!(dev_command(&ProjectStack::Unknown), None);
    }

    #[test]
    fn find_manifest_recognizes_each_stack_marker() {
        let node = temp_project("manifest_node", &["package.json"]);
        assert_eq!(find_manifest_at(&node), Some("package.json"));

        let pyproject = temp_project("manifest_py", &["pyproject.toml"]);
        assert_eq!(find_manifest_at(&pyproject), Some("pyproject.toml"));

        let requirements = temp_project("manifest_reqs", &["requirements.txt"]);
        assert_eq!(find_manifest_at(&requirements), Some("requirements.txt"));

        let rust = temp_project("manifest_rust", &["Cargo.toml"]);
        assert_eq!(find_manifest_at(&rust), Some("Cargo.toml"));
    }

    #[test]
    fn find_manifest_none_for_empty_directory() {
        let empty = temp_project("manifest_empty", &[]);
        assert!(find_manifest_at(&empty).is_none());
    }

    #[test]
    fn ensure_project_errors_are_beginner_friendly() {
        let empty = temp_project("ensure_empty", &[]);
        let err = ensure_project_at(&empty).unwrap_err();
        assert!(err.contains("project root"));
        assert!(err.contains("package.json"));
        assert!(err.contains("requirements.txt"));
        assert!(err.contains("Cargo.toml"));
    }

    #[test]
    fn screen_error_adds_sudo_hint_for_permission_errors() {
        let msg = screen_error("Permission denied while writing .env");
        assert!(msg.contains("sudo"));
        assert!(msg.contains("permission"));
    }

    #[test]
    fn screen_error_adds_internet_hint_for_network_errors() {
        let msg = screen_error("Connection timed out resolving registry.npmjs.org");
        assert!(msg.contains("internet connection"));
    }

    #[test]
    fn screen_error_passes_through_other_errors() {
        let raw = "something completely unrelated";
        assert_eq!(screen_error(raw), raw);
    }

    fn fake_state(statuses: &[CheckStatus]) -> EnvironmentState {
        let diagnostics: Vec<DiagnosticResult> = statuses
            .iter()
            .enumerate()
            .map(|(i, status)| {
                DiagnosticResult::new(format!("Check {i}"), *status, "ok")
            })
            .collect();
        EnvironmentState {
            detected_stack: ProjectStack::Node {
                version: "22.0.0".into(),
                package_manager: "npm".into(),
            },
            runtime_version: None,
            env_file_exists: false,
            env_example_exists: true,
            dependencies_healthy: true,
            blocked_ports: vec![],
            health_score: HealthScore::from_results(&diagnostics),
            diagnostics,
        }
    }

    #[test]
    fn exit_code_mirrors_failed_diagnostics() {
        assert_eq!(exit_code_for(&fake_state(&[CheckStatus::Pass])), 0);
        assert_eq!(
            exit_code_for(&fake_state(&[CheckStatus::Pass, CheckStatus::Warn])),
            0
        );
        assert_eq!(
            exit_code_for(&fake_state(&[CheckStatus::Pass, CheckStatus::Fail])),
            1
        );
    }

    #[test]
    fn identify_fixable_issues_lists_ghost_and_env_fixes() {
        let mut state = fake_state(&[CheckStatus::Fail]);
        state.blocked_ports = vec![(3000, 1234)];
        let issues = identify_fixable_issues(&state);
        let joined = issues.join("\n");
        assert!(joined.contains("Kill"), "{joined}");
        assert!(joined.contains("Copy .env.example"), "{joined}");
    }

    #[test]
    fn perfect_health_streak_tracks_failed_checks() {
        use achievements::ArcadeStats;
        let mut stats = ArcadeStats::default();

        record_health(&mut stats, &fake_state(&[CheckStatus::Pass]));
        assert_eq!(stats.perfect_health_streak, 1);

        record_health(&mut stats, &fake_state(&[CheckStatus::Fail]));
        assert_eq!(stats.perfect_health_streak, 0);
    }
}