mecha10-cli 0.6.3

Mecha10 CLI 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
//! Setup command handler
//!
//! Orchestrates environment setup and prerequisites checking.

use crate::context::CliContext;
use anyhow::Result;
use std::process::Command;

/// Arguments for setup command
#[derive(Debug, Clone)]
pub struct SetupArgs {
    pub check_only: bool,
    pub install_deps: bool,
}

/// Handle setup command
///
/// Checks and installs required dependencies for Mecha10 development.
///
/// # Arguments
///
/// * `ctx` - CLI execution context
/// * `args` - Setup command arguments
pub async fn handle_setup(ctx: &mut CliContext, args: &SetupArgs) -> Result<()> {
    println!();
    println!("🔧 Mecha10 Environment Setup");
    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    println!();

    let mut all_ok = true;

    // Check Rust installation
    println!("Checking prerequisites...");
    println!();

    println!("1. Rust toolchain:");
    let rust_ok = check_rust()?;
    if rust_ok {
        println!("   ✅ Rust installed");
    } else {
        println!("   ❌ Rust not found");
        all_ok = false;
    }

    // Check Cargo
    println!("2. Cargo:");
    let cargo_ok = check_cargo()?;
    if cargo_ok {
        println!("   ✅ Cargo installed");
    } else {
        println!("   ❌ Cargo not found");
        all_ok = false;
    }

    // Check Docker
    println!("3. Docker:");
    let docker = ctx.docker();
    let docker_installed = docker.check_installation().is_ok();
    let docker_daemon = docker.check_daemon().is_ok();
    let docker_ok = docker_installed && docker_daemon;

    if docker_ok {
        println!("   ✅ Docker installed and running");
    } else if docker_installed {
        println!("   ⚠️  Docker installed but daemon not running");
        println!("      Start Docker Desktop or run: sudo systemctl start docker");
        all_ok = false;
    } else {
        println!("   ⚠️  Docker not available");
        println!("      Required for control plane services (Redis, PostgreSQL)");
        all_ok = false;
    }

    // Check Redis CLI (optional)
    println!("4. Redis CLI (optional):");
    let redis_cli_ok = check_redis_cli()?;
    if redis_cli_ok {
        println!("   ✅ redis-cli installed");
    } else {
        println!("   ⬜ redis-cli not found (optional)");
    }

    // Check Python (required for AI model quantization)
    println!("5. Python 3:");
    let mut python_ok = check_python()?;
    if python_ok {
        println!("   ✅ Python 3 installed");
    } else {
        println!("   ⚠️  Python 3 not found (needed for AI model quantization)");
        all_ok = false;

        // Attempt to install Python 3 right here, before the venv (step 6) / deps (step 7)
        // steps below run - otherwise those steps would see the pre-install `python_ok = false`
        // and skip themselves even when the install that follows succeeds in this same run.
        if !args.check_only && args.install_deps {
            println!("   Attempting to install Python 3...");
            let pinned_version = format!("{}.{}", MIN_PYTHON_VERSION.0, MIN_PYTHON_VERSION.1);
            match install_python(&pinned_version).await {
                Ok(true) => {
                    println!("   ✅ Python 3 installed");
                    // Re-check now that the install ran, so a successful in-run install
                    // unblocks the venv (step 6) / deps (step 7) steps below instead of
                    // requiring a second `mecha10 setup` invocation.
                    python_ok = check_python()?;
                    if python_ok {
                        all_ok = rust_ok && cargo_ok && docker_ok && python_ok;
                    }
                }
                Ok(false) => {}
                Err(e) => println!("   ❌ Failed to install Python 3: {}", e),
            }
        }
    }

    println!();

    // Setup Python virtual environment and install dependencies if not in check-only mode
    if !args.check_only && python_ok {
        println!("6. Python Virtual Environment:");
        match setup_venv().await {
            Ok(true) => println!("   ✅ Virtual environment ready (.venv)"),
            Ok(false) => println!("   ✅ Using existing virtual environment (.venv)"),
            Err(e) => {
                println!("   ⚠️  Failed to create virtual environment: {}", e);
                println!("      Create manually with: python3 -m venv .venv");
            }
        }
        println!();

        println!("7. Python Dependencies:");
        match install_python_deps(ctx).await {
            Ok(true) => {
                println!("   ✅ Python dependencies installed in venv");
                println!();
                println!("   📝 To activate the virtual environment:");
                println!("      source .venv/bin/activate");
            }
            Ok(false) => println!("   ⬜ No requirements.txt found (skipping)"),
            Err(e) => {
                println!("   ⚠️  Failed to install Python dependencies: {}", e);
                println!("      Install manually with:");
                println!("        source .venv/bin/activate");
                println!("        pip install -r requirements.txt");
            }
        }
        println!();
    }

    // Check/download AI models if not in check-only mode
    if !args.check_only {
        println!("8. AI Models:");
        let models_result = check_and_download_models(ctx).await;
        match models_result {
            Ok(downloaded) => {
                if downloaded > 0 {
                    println!("   ✅ Downloaded {} recommended models", downloaded);
                } else {
                    println!("   ⬜ Not downloaded automatically — this step no longer runs during setup");
                    println!(
                        "      Run: mecha10 model pull --all (downloads this project's referenced models; \
                         or `mecha10 model pull <name>` per node)"
                    );
                }
            }
            Err(e) => {
                println!("   ⚠️  Failed to check models: {}", e);
                println!("      Download this project's models with: mecha10 model pull --all");
            }
        }
        println!();
    }

    // Summary
    if all_ok {
        println!("✨ Environment setup complete!");
        println!();
        println!("You're ready to use Mecha10:");
        println!("  • Create a project: mecha10 init");
        println!("  • Download this project's AI models (not done automatically by setup): mecha10 model pull --all");
        println!("  • Start services: mecha10 infrastructure start");
        println!("  • Start development: mecha10 dev");
    } else {
        println!("⚠️  Some prerequisites are missing");
        println!();

        if !rust_ok || !cargo_ok {
            println!("Install Rust:");
            println!("  curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh");
            println!();
        }

        if !docker_ok {
            println!("Install Docker:");
            println!("  https://docs.docker.com/get-docker/");
            println!();
        }

        if !python_ok {
            println!("Install Python 3:");
            println!(
                "  macOS: brew install python@{}.{}",
                MIN_PYTHON_VERSION.0, MIN_PYTHON_VERSION.1
            );
            println!("  Or: https://www.python.org/downloads/");
            println!();
        }

        if !python_ok && !args.install_deps {
            println!("Run with --install-deps to attempt automatic installation");
        }

        println!();

        if args.check_only {
            return Err(anyhow::anyhow!("Prerequisites check failed"));
        }
    }

    println!();
    Ok(())
}

/// Check if Rust is installed
fn check_rust() -> Result<bool> {
    let output = Command::new("rustc").arg("--version").output();
    Ok(output.map(|o| o.status.success()).unwrap_or(false))
}

/// Check if Cargo is installed
fn check_cargo() -> Result<bool> {
    let output = Command::new("cargo").arg("--version").output();
    Ok(output.map(|o| o.status.success()).unwrap_or(false))
}

/// Check if redis-cli is installed
fn check_redis_cli() -> Result<bool> {
    let output = Command::new("redis-cli").arg("--version").output();
    Ok(output.map(|o| o.status.success()).unwrap_or(false))
}

/// Minimum Python version mecha10's RL tooling requires.
///
/// Source of truth: `rl-task-runner/pyproject.toml`'s `requires-python` field in the standalone
/// `mecha-industries/mecha10-rl` repo (`>=3.12` as of writing - `mlflow-skinny` 3.15.x, one of
/// that package's dependencies, is what actually enforces the floor). That package used to live
/// in this repo at `packages/rl-task-runner` before being extracted out by LAB-1830 (see
/// `docs/architecture/SIMULATION_ARCHITECTURE.md`). The `mecha10` CLI ships as a standalone
/// binary without that file alongside it, so the minimum is hardcoded here rather than parsed
/// from it at runtime; keep the two in sync if the constraint ever changes.
const MIN_PYTHON_VERSION: (u32, u32) = (3, 12);

/// Parse a `(major, minor)` version out of `python --version`/`python -V` output,
/// e.g. `"Python 3.9.2\n"` -> `Some((3, 9))`. Returns `None` for unparseable
/// output (unexpected format, non-Python interpreter, etc).
fn parse_python_version(version_output: &str) -> Option<(u32, u32)> {
    let version_part = version_output.trim().strip_prefix("Python ")?;
    let mut parts = version_part.split('.');
    let major = parts.next()?.parse().ok()?;
    let minor = parts.next()?.parse().ok()?;
    Some((major, minor))
}

/// Whether `found` satisfies `minimum` under `(major, minor)` lexicographic
/// comparison (e.g. `(3, 12) >= (3, 9)`, `(3, 9) < (3, 12)`, `(4, 0) >= (3, 12)`).
fn meets_minimum_version(found: (u32, u32), minimum: (u32, u32)) -> bool {
    found >= minimum
}

/// Run `<candidate> --version` and parse the result, tolerating interpreters
/// that print the version to stderr (older Pythons did this for `-V`, though
/// not for `--version`) and swallowing spawn failures (candidate not on PATH).
fn probe_python_version(candidate: &str) -> Option<(u32, u32)> {
    let output = Command::new(candidate).arg("--version").output().ok()?;
    if !output.status.success() {
        return None;
    }
    parse_python_version(&String::from_utf8_lossy(&output.stdout))
        .or_else(|| parse_python_version(&String::from_utf8_lossy(&output.stderr)))
}

/// Check if a Python 3 interpreter meeting [`MIN_PYTHON_VERSION`] is installed.
fn check_python() -> Result<bool> {
    Ok(find_python_executable().is_ok())
}

/// Attempt to automatically install a Python 3 interpreter meeting
/// [`MIN_PYTHON_VERSION`], modeled on `scripts/dev/setup.sh`'s
/// `install_python_macos()`.
///
/// On macOS, installs via Homebrew if `brew` is on `PATH`. Otherwise (no
/// `brew` on macOS, or any non-macOS platform), prints manual installation
/// instructions and returns `Ok(false)` - not installed, but not a hard
/// error, matching how the Docker manual-instructions path behaves in
/// [`handle_setup`].
///
/// `pinned_version` is formatted like `"3.12"` (see [`MIN_PYTHON_VERSION`]).
async fn install_python(pinned_version: &str) -> Result<bool> {
    let brew_available = Command::new("brew")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false);

    match python_install_strategy(std::env::consts::OS, brew_available) {
        PythonInstallStrategy::Homebrew => {
            println!("   Installing Python {} via Homebrew...", pinned_version);
            let output = tokio::process::Command::new("brew")
                .args(["install", &format!("python@{}", pinned_version)])
                .output()
                .await?;

            if output.status.success() {
                return Ok(true);
            }

            let stderr = String::from_utf8_lossy(&output.stderr);
            println!("   Homebrew install failed: {}", stderr.trim());
            Ok(false)
        }
        PythonInstallStrategy::ManualLinux => {
            println!("Install Python 3:");
            println!("  Linux: apt install python{}", pinned_version);
            println!("  Or: https://www.python.org/downloads/");
            Ok(false)
        }
        PythonInstallStrategy::ManualOther => {
            println!("Install Python 3:");
            println!("  macOS: brew install python@{}", pinned_version);
            println!("  Or: https://www.python.org/downloads/");
            Ok(false)
        }
    }
}

/// How [`install_python`] should attempt to get Python 3 onto the machine,
/// decided purely from the OS name (as returned by `std::env::consts::OS`)
/// and whether `brew` is on `PATH` - factored out from [`install_python`]
/// itself so this decision can be unit tested without actually shelling out
/// to `brew` or touching the host.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PythonInstallStrategy {
    /// macOS with Homebrew available: run `brew install python@<version>`.
    Homebrew,
    /// Linux (or macOS without Homebrew is handled by `ManualOther`): print
    /// `apt install`-flavored manual instructions.
    ManualLinux,
    /// macOS without Homebrew, or any other/unknown OS: print
    /// `brew install`-flavored manual instructions as a fallback suggestion.
    ManualOther,
}

fn python_install_strategy(os: &str, brew_available: bool) -> PythonInstallStrategy {
    match os {
        "macos" if brew_available => PythonInstallStrategy::Homebrew,
        "linux" => PythonInstallStrategy::ManualLinux,
        _ => PythonInstallStrategy::ManualOther,
    }
}

/// Setup Python virtual environment
async fn setup_venv() -> Result<bool> {
    let venv_path = std::path::Path::new(".venv");

    // Check if venv already exists
    if venv_path.exists() {
        return Ok(false); // Already exists
    }

    // Find Python executable
    let python = find_python_executable()?;

    println!("   Creating virtual environment...");

    // Create venv
    let output = tokio::process::Command::new(&python)
        .args(["-m", "venv", ".venv"])
        .output()
        .await?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("venv creation failed: {}", stderr);
    }

    Ok(true) // Created new venv
}

/// Install Python dependencies from requirements.txt using venv
async fn install_python_deps(_ctx: &CliContext) -> Result<bool> {
    // Check if requirements.txt exists in the current directory
    let requirements_path = std::path::Path::new("requirements.txt");
    if !requirements_path.exists() {
        return Ok(false);
    }

    // Use the venv's Python executable if it exists, otherwise fall back to system Python
    let python = if std::path::Path::new(".venv/bin/python").exists() {
        ".venv/bin/python"
    } else if std::path::Path::new(".venv/Scripts/python.exe").exists() {
        ".venv/Scripts/python.exe" // Windows
    } else {
        &find_python_executable()?
    };

    println!("   Installing from requirements.txt...");

    // Run pip install -r requirements.txt
    //
    // Some requirements (e.g. the RL bundle's `git+ssh://` pins, LAB-1743) resolve via a `git
    // clone` shelled out to by pip. If that clone can't authenticate non-interactively (no SSH
    // key registered with GitHub, or an `https://` fallback that needs a PAT), git falls back to
    // an interactive username/password prompt on the terminal, which pip has no stdin to satisfy
    // - the process just hangs with no visible cause. `GIT_TERMINAL_PROMPT=0` makes git fail
    // immediately with a clear "could not read Username" error instead, which we then turn into
    // an actionable hint below.
    let output = tokio::process::Command::new(python)
        .args(["-m", "pip", "install", "-r", "requirements.txt"])
        .env("GIT_TERMINAL_PROMPT", "0")
        .output()
        .await?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        if stderr.contains("could not read Username")
            || stderr.contains("could not read Password")
            || stderr.contains("Permission denied (publickey)")
        {
            anyhow::bail!(
                "pip install failed: {}\n\nfailed to fetch RL training dependencies via git+ssh - \
                ensure your SSH key is added to GitHub (https://github.com/settings/keys) and \
                `ssh -T git@github.com` succeeds.",
                stderr
            );
        }
        anyhow::bail!("pip install failed: {}", stderr);
    }

    Ok(true)
}

/// Find a Python executable on `PATH` that satisfies [`MIN_PYTHON_VERSION`].
///
/// Tries `python3` then `python` (the same order `mecha10 setup` has always used), then finally
/// the pinned-version-specific name (e.g. `python3.12`) as a fallback, to pick up a Homebrew
/// `python@X.Y` keg-only install that never got symlinked to the generic names. Critically,
/// this now also checks the interpreter's *version*, not just that it's some Python 3.x: on a
/// system whose default `python3` predates [`MIN_PYTHON_VERSION`], `setup_venv` used to happily
/// create a `.venv` with it, and the failure only surfaced steps later as an opaque
/// `pip install` distribution error for `mlflow-skinny` (which requires the same floor
/// transitively via `mecha10-rl`'s `rl-task-runner`) - see this module's doc comment on
/// [`MIN_PYTHON_VERSION`] for why that floor exists. Failing here instead names the interpreter
/// that was found, its actual version, and the required version, so the fix is obvious.
fn find_python_executable() -> Result<String> {
    // Homebrew's `python@X.Y` formula is keg-only: it symlinks the version-specific binary
    // (e.g. `python3.12`) onto PATH but deliberately does NOT symlink the generic `python3`/
    // `python` names, to avoid clobbering a system/other Python. Probe the versioned name last,
    // as a fallback, so a machine with a perfectly good generic `python3` doesn't unnecessarily
    // prefer a Homebrew keg install over it - but so that a Homebrew-only install is still found.
    let versioned = format!("python{}.{}", MIN_PYTHON_VERSION.0, MIN_PYTHON_VERSION.1);
    find_python_executable_among(&["python3", "python", &versioned])
}

/// Same as [`find_python_executable`], parameterized over the candidate list so tests can point
/// it at synthetic interpreters instead of whatever's actually on the host's `PATH`.
///
/// If a Python 3 interpreter is found but is older than required, the error reports the newest
/// one seen so the message is actionable (rather than reporting whichever candidate happened to
/// be probed first).
fn find_python_executable_among(candidates: &[&str]) -> Result<String> {
    let mut newest_too_old: Option<((u32, u32), &str)> = None;

    for &candidate in candidates {
        let Some(version) = probe_python_version(candidate) else {
            continue;
        };

        if meets_minimum_version(version, MIN_PYTHON_VERSION) {
            return Ok(candidate.to_string());
        }

        let should_replace = match newest_too_old {
            Some((best, _)) => version > best,
            None => true,
        };
        if should_replace {
            newest_too_old = Some((version, candidate));
        }
    }

    if let Some(((major, minor), candidate)) = newest_too_old {
        anyhow::bail!(
            "Found Python {major}.{minor} at `{candidate}`, but mecha10 requires Python \
             {req_major}.{req_minor}+ (see mecha10-rl's rl-task-runner/pyproject.toml's \
             `requires-python`). Install a newer Python 3 and make sure it comes first on PATH, \
             then re-run `mecha10 setup`.",
            req_major = MIN_PYTHON_VERSION.0,
            req_minor = MIN_PYTHON_VERSION.1,
        );
    }

    anyhow::bail!("Python 3 not found. Install with: brew install python3 (macOS) or apt install python3 (Linux)")
}

/// Check and download recommended AI models
async fn check_and_download_models(_ctx: &CliContext) -> Result<usize> {
    // Note: Model auto-download during setup has been removed.
    // Users should explicitly pull models they need using: mecha10 model pull <name>
    //
    // This keeps setup fast and gives users control over which models to download.
    // The model catalog no longer has a "recommended" field - models are recommended
    // by being referenced in node configurations.

    Ok(0)
}

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

    #[test]
    fn parse_python_version_parses_standard_output() {
        assert_eq!(parse_python_version("Python 3.12.1\n"), Some((3, 12)));
        assert_eq!(parse_python_version("Python 3.9.2"), Some((3, 9)));
        assert_eq!(parse_python_version("Python 4.0.0"), Some((4, 0)));
    }

    #[test]
    fn parse_python_version_rejects_unparseable_output() {
        assert_eq!(parse_python_version(""), None);
        assert_eq!(parse_python_version("not python at all"), None);
        assert_eq!(parse_python_version("Python"), None);
        assert_eq!(parse_python_version("Python x.y.z"), None);
    }

    #[test]
    fn meets_minimum_version_compares_major_and_minor() {
        assert!(meets_minimum_version((3, 12), (3, 12)));
        assert!(meets_minimum_version((3, 13), (3, 12)));
        assert!(meets_minimum_version((4, 0), (3, 12)));
        assert!(!meets_minimum_version((3, 11), (3, 12)));
        assert!(!meets_minimum_version((2, 7), (3, 12)));
    }

    /// Builds a tiny shell script on `PATH`-independent disk that behaves like
    /// `<name> --version` printing a fixed Python version string, for exercising
    /// [`find_python_executable_among`] end-to-end without depending on whatever
    /// Python happens to be installed on the machine running the test.
    #[cfg(unix)]
    fn fake_python_binary(dir: &std::path::Path, name: &str, version_output: &str) -> String {
        use std::fs;
        use std::os::unix::fs::PermissionsExt;

        let path = dir.join(name);
        fs::write(&path, format!("#!/bin/sh\necho \"{version_output}\"\n")).unwrap();
        let mut perms = fs::metadata(&path).unwrap().permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&path, perms).unwrap();
        path.display().to_string()
    }

    #[cfg(unix)]
    #[test]
    fn find_python_executable_among_skips_too_old_interpreter_for_newer_one() {
        let dir = std::env::temp_dir().join(format!("mecha10-setup-test-{:?}", std::thread::current().id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();

        let old = fake_python_binary(&dir, "old-python", "Python 3.9.2");
        let new = fake_python_binary(&dir, "new-python", "Python 3.12.1");

        let found = find_python_executable_among(&[old.as_str(), new.as_str()]).unwrap();
        assert_eq!(found, new);

        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// Regression test for the Homebrew keg-only bug: `python@3.12` symlinks only the
    /// version-specific binary (`python3.12`) onto PATH, never the generic `python3`/`python`
    /// names. Simulates that by pointing the generic candidates at nonexistent paths and only
    /// providing a fake `python3.12`-style binary, mirroring the real candidate order
    /// `find_python_executable` builds (`python3`, `python`, then the versioned fallback).
    #[cfg(unix)]
    #[test]
    fn find_python_executable_among_falls_back_to_versioned_binary_when_generic_names_missing() {
        let dir = std::env::temp_dir().join(format!("mecha10-setup-test-kegonly-{:?}", std::thread::current().id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();

        let missing_python3 = dir.join("definitely-missing-python3").display().to_string();
        let missing_python = dir.join("definitely-missing-python").display().to_string();
        let versioned = fake_python_binary(&dir, "python3.12", "Python 3.12.4");

        let found =
            find_python_executable_among(&[missing_python3.as_str(), missing_python.as_str(), versioned.as_str()])
                .unwrap();
        assert_eq!(found, versioned);

        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// When a perfectly good generic `python3` is present, it should still be preferred over
    /// the versioned fallback name - the versioned probe exists to find Homebrew keg-only
    /// installs, not to override a fine system interpreter.
    #[cfg(unix)]
    #[test]
    fn find_python_executable_among_prefers_generic_name_over_versioned_fallback() {
        let dir = std::env::temp_dir().join(format!(
            "mecha10-setup-test-prefer-generic-{:?}",
            std::thread::current().id()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();

        let generic = fake_python_binary(&dir, "python3", "Python 3.13.0");
        let versioned = fake_python_binary(&dir, "python3.12", "Python 3.12.4");

        let found = find_python_executable_among(&[generic.as_str(), versioned.as_str()]).unwrap();
        assert_eq!(found, generic);

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn find_python_executable_among_fails_fast_with_actionable_message_when_only_too_old() {
        let dir = std::env::temp_dir().join(format!("mecha10-setup-test-old-only-{:?}", std::thread::current().id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();

        let old = fake_python_binary(&dir, "old-python", "Python 3.8.10");

        let err = find_python_executable_among(&[old.as_str()]).unwrap_err();
        let message = err.to_string();
        assert!(
            message.contains("3.8"),
            "message should report the found version: {message}"
        );
        assert!(
            message.contains("3.12"),
            "message should report the required version: {message}"
        );
        assert!(
            message.contains(&old),
            "message should name the interpreter that was found: {message}"
        );

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn find_python_executable_among_fails_when_nothing_found() {
        let err = find_python_executable_among(&["definitely-not-a-real-interpreter-xyz"]).unwrap_err();
        assert!(err.to_string().contains("Python 3 not found"));
    }

    #[test]
    fn python_install_strategy_uses_homebrew_on_macos_when_available() {
        assert_eq!(python_install_strategy("macos", true), PythonInstallStrategy::Homebrew);
    }

    #[test]
    fn python_install_strategy_falls_back_to_manual_on_macos_without_brew() {
        assert_eq!(
            python_install_strategy("macos", false),
            PythonInstallStrategy::ManualOther
        );
    }

    #[test]
    fn python_install_strategy_is_manual_apt_flavored_on_linux() {
        assert_eq!(
            python_install_strategy("linux", true),
            PythonInstallStrategy::ManualLinux
        );
        assert_eq!(
            python_install_strategy("linux", false),
            PythonInstallStrategy::ManualLinux
        );
    }

    #[test]
    fn python_install_strategy_falls_back_to_manual_on_unknown_os() {
        assert_eq!(
            python_install_strategy("windows", true),
            PythonInstallStrategy::ManualOther
        );
        assert_eq!(
            python_install_strategy("freebsd", false),
            PythonInstallStrategy::ManualOther
        );
    }
}