projm 0.7.5

CLI for projm — project organizer and navigator
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
use anyhow::{Context, Result};
use clap::CommandFactory;
use colored::Colorize;
use dialoguer::{theme::ColorfulTheme, Confirm, FuzzySelect, Input, Select};
use std::{fs, path::Path, path::PathBuf, process::Command};

use crate::completions;
use projm_core::{config, editors};

const PROJM_BLOCK_START: &str = "# >>> projm >>>";
const PROJM_BLOCK_END: &str = "# <<< projm <<<";

pub fn run(
    alias: &str,
    non_interactive: bool,
    shell_override: Option<completions::CompletionShell>,
    profile_override: Option<PathBuf>,
) -> Result<()> {
    // Create default rules.toml if not already present
    projm_core::rules::init_default_rules()?;

    let is_interactive = !non_interactive && console::user_attended();
    let detected_shell = shell_override.unwrap_or_else(detect_shell);

    if is_interactive {
        run_wizard(alias, detected_shell, profile_override)?;
    } else {
        run_non_interactive(alias, detected_shell, profile_override)?;
    }

    Ok(())
}

fn run_non_interactive(
    alias: &str,
    shell: completions::CompletionShell,
    profile_override: Option<PathBuf>,
) -> Result<()> {
    eprintln!("[1/3] checking zoxide...");

    if has_zoxide() {
        eprintln!("      {} already installed", "✓".green().bold());
    } else {
        eprintln!("      not found");
        install_zoxide()?;
    }

    eprintln!("[2/3] writing completions...");
    let completion_file = completion_path(shell);
    write_completions(shell, &completion_file)?;
    eprintln!(
        "      {} {}",
        "✓".green().bold(),
        completion_file.display().to_string().dimmed()
    );

    eprintln!("[3/3] updating shell profile...");
    let profile = profile_override.unwrap_or_else(|| default_profile_path(shell));
    update_shell_profile(shell, &profile, alias, &completion_file)?;
    eprintln!(
        "\n  {} updated {}",
        "done.".green().bold(),
        profile.display()
    );

    Ok(())
}

fn run_wizard(
    alias: &str,
    detected_shell: completions::CompletionShell,
    profile_override: Option<PathBuf>,
) -> Result<()> {
    println!();
    println!(
        "{}",
        "  ┌────────────────────────────────────────────────────────┐".cyan()
    );
    println!(
        "{}",
        "  │  🚀 Welcome to projm                                   │"
            .cyan()
            .bold()
    );
    println!(
        "{}",
        "  │  The developer-first project organizer & navigator.    │".cyan()
    );
    println!(
        "{}",
        "  └────────────────────────────────────────────────────────┘".cyan()
    );
    println!();
    println!("  Let's configure your development environment. This wizard will guide you through:");
    println!("    ⚙️  Setting your base directory");
    println!("    📝 Picking your preferred editor");
    println!("    🐚 Setting up shell completions & the fuzzy-jump alias");
    println!("    🎮 Running an interactive 1-minute sandbox showcase");
    println!();

    let theme = ColorfulTheme::default();

    // 1. Configure Base Directory
    let current_base = config::load().base;
    let default_base_str = current_base.to_string_lossy().to_string();
    let base_input: String = Input::with_theme(&theme)
        .with_prompt("Where would you like to store your organized projects?")
        .default(default_base_str)
        .interact_text()?;

    let base_path = PathBuf::from(&base_input);
    if base_path != current_base {
        config::set_base(&base_path)?;
    }
    println!();

    // 2. Select Preferred Editor
    let installed = editors::detect_installed();
    let mut selected_editor = String::new();

    if installed.is_empty() {
        println!(
            "  {}",
            "No supported editors detected on your $PATH.".yellow()
        );
        let manual_entry: String = Input::with_theme(&theme)
            .with_prompt(
                "Please enter your editor command (e.g. nvim, code, helix) or press Enter to skip:",
            )
            .default("".to_string())
            .interact_text()?;
        if !manual_entry.is_empty() {
            selected_editor = manual_entry;
            println!("  Default editor set to: {}", selected_editor.bold());
        }
    } else {
        println!("  Detected the following editors installed on your machine:");
        let labels: Vec<String> = installed
            .iter()
            .map(|e| format!("  {} ({})", e.name, e.binary))
            .collect();
        let chosen = Select::with_theme(&theme)
            .with_prompt("Choose your preferred editor")
            .items(&labels)
            .default(0)
            .interact()?;
        selected_editor = installed[chosen].binary.to_owned();
        println!(
            "  {} Preferred editor set to: {}",
            "✓".green(),
            selected_editor.bold()
        );
    }
    println!();

    // 3. Select Target Shell
    let shells = [
        ("Zsh", completions::CompletionShell::Zsh),
        ("Bash", completions::CompletionShell::Bash),
        ("Fish", completions::CompletionShell::Fish),
        ("PowerShell", completions::CompletionShell::Powershell),
        ("Nushell", completions::CompletionShell::Nushell),
    ];
    let shell_labels: Vec<String> = shells.iter().map(|(n, _)| n.to_string()).collect();
    let default_shell_idx = shells
        .iter()
        .position(|(_, s)| *s == detected_shell)
        .unwrap_or(0);

    let chosen_shell_idx = Select::with_theme(&theme)
        .with_prompt("Which shell would you like to configure?")
        .items(&shell_labels)
        .default(default_shell_idx)
        .interact()?;

    let chosen_shell = shells[chosen_shell_idx].1;
    println!(
        "  {} Target shell set to: {}",
        "✓".green(),
        shells[chosen_shell_idx].0.bold()
    );
    println!();

    // 4. Configure Alias
    let chosen_alias: String = Input::with_theme(&theme)
        .with_prompt("What alias would you like to use for fuzzy-navigation?")
        .default(alias.to_string())
        .interact_text()?;
    println!();

    // 5. Configure Profile Path
    let default_profile = profile_override
        .clone()
        .unwrap_or_else(|| default_profile_path(chosen_shell));
    let use_default_profile = Confirm::with_theme(&theme)
        .with_prompt(format!(
            "Use default profile path: {}?",
            default_profile.display().to_string().cyan()
        ))
        .default(true)
        .interact()?;

    let final_profile = if use_default_profile {
        default_profile
    } else {
        let custom_profile_input: String = Input::with_theme(&theme)
            .with_prompt("Enter custom profile path")
            .default(default_profile.display().to_string())
            .interact_text()?;
        PathBuf::from(custom_profile_input)
    };
    println!();

    // 6. Check & Install Zoxide
    println!("{}", "[1/3] checking zoxide...".bold());
    if has_zoxide() {
        println!("      {} already installed", "✓".green().bold());
    } else {
        println!("      zoxide not found. It is highly recommended for project navigation.");
        let install_z = Confirm::with_theme(&theme)
            .with_prompt("Would you like to try installing zoxide automatically now?")
            .default(true)
            .interact()?;
        if install_z {
            if let Err(e) = install_zoxide() {
                println!("      {} {}", "✗".red().bold(), e);
            }
        }
    }
    println!();

    // 7. Setup completions & shell profile
    println!("{}", "[2/3] writing completions...".bold());
    let completion_file = completion_path(chosen_shell);
    write_completions(chosen_shell, &completion_file)?;
    println!(
        "      {} {}",
        "✓".green().bold(),
        completion_file.display().to_string().dimmed()
    );
    println!();

    println!("{}", "[3/3] updating shell profile...".bold());
    update_shell_profile(
        chosen_shell,
        &final_profile,
        &chosen_alias,
        &completion_file,
    )?;
    println!(
        "      {} updated {}",
        "✓".green().bold(),
        final_profile.display()
    );
    println!();

    println!(
        "{}",
        "🎉 Configuration successfully complete!".green().bold()
    );
    println!();

    // 8. Interactive sandbox demo!
    let run_demo = Confirm::with_theme(&theme)
        .with_prompt("Would you like to run a quick 1-minute sandbox demo of projm?")
        .default(true)
        .interact()?;

    if run_demo {
        run_sandbox_demo(&selected_editor)?;
    }

    println!();
    println!("  To start using projm, restart your shell or run:");
    match chosen_shell {
        completions::CompletionShell::Zsh
        | completions::CompletionShell::Bash
        | completions::CompletionShell::Fish
        | completions::CompletionShell::Nushell => {
            println!("  {}", format!("source {}", final_profile.display()).cyan());
        }
        completions::CompletionShell::Powershell => {
            println!("  {}", format!(". \"{}\"", final_profile.display()).cyan());
        }
    }
    println!();

    Ok(())
}

fn run_sandbox_demo(preferred_editor: &str) -> Result<()> {
    println!();
    println!("{}", "🎮 Starting Sandbox Demo...".cyan().bold());
    println!("  We will scaffold a temporary workspace to show how projm classifies and navigates projects.");

    // Create temp directory
    let temp_dir = tempfile::tempdir()?;
    let sandbox_path = temp_dir.path();
    let source_dump = sandbox_path.join("source-dump");
    let demo_base = sandbox_path.join("demo-base");

    fs::create_dir_all(&source_dump)?;
    fs::create_dir_all(&demo_base)?;

    // 1. Scaffold mock projects
    let rust_proj = source_dump.join("rust-telemetry-server");
    let react_proj = source_dump.join("react-dashboard-ui");
    let python_proj = source_dump.join("python-ml-model");

    fs::create_dir_all(&rust_proj)?;
    fs::create_dir_all(&react_proj)?;
    fs::create_dir_all(&python_proj)?;

    fs::write(
        rust_proj.join("Cargo.toml"),
        r#"[package]
name = "rust-telemetry-server"
version = "0.1.0"
[dependencies]
tokio = "1"
"#,
    )?;

    fs::write(
        react_proj.join("package.json"),
        r#"{
  "name": "react-dashboard-ui",
  "dependencies": {
    "react": "^18.0.0",
    "vite": "^4.0.0"
  }
}"#,
    )?;

    fs::write(
        python_proj.join("pyproject.toml"),
        r#"[project]
name = "python-ml-model"
dependencies = [
    "torch>=2.0"
]
"#,
    )?;

    println!();
    println!(
        "  ⚡ {}",
        "Step 1: Automatic Classification & Organization".bold()
    );
    println!("  Scaffolded 3 unorganized mock projects in a temporary dump folder:");
    println!("    📁 rust-telemetry-server/ (contains Cargo.toml)");
    println!("    📁 react-dashboard-ui/    (contains package.json)");
    println!("    📁 python-ml-model/        (contains pyproject.toml)");
    println!();
    println!("  Running 'projm organize' to scan, classify, and group them into 'demo-base/'...");
    println!();

    // Run our custom run_with_base on the sandbox
    projm_core::organize::run_with_base(&source_dump, &demo_base, false)?;

    println!();
    println!("  ⚡ {}", "Step 2: Fuzzy Navigation Showcase".bold());
    println!("  Now let's test how you will navigate between them.");
    println!("  We will open a mini-version of our fuzzy navigator.");
    println!("  Use your Arrow Keys to select, or start typing to search:");
    println!();

    // Display Fuzzy Picker loaded with mock projects
    let demo_projects = [
        (
            "services",
            "rust-telemetry-server",
            demo_base.join("services/rust-telemetry-server"),
        ),
        (
            "ui",
            "react-dashboard-ui",
            demo_base.join("ui/react-dashboard-ui"),
        ),
        (
            "ml",
            "python-ml-model",
            demo_base.join("ml/python-ml-model"),
        ),
    ];

    let labels: Vec<String> = demo_projects
        .iter()
        .map(|(cat, name, _)| format!("  {:<10}  {}", format!("[{}]", cat).cyan(), name.bold()))
        .collect();

    let chosen = FuzzySelect::with_theme(&ColorfulTheme::default())
        .with_prompt("jump to")
        .items(&labels)
        .default(0)
        .interact()?;

    let (chosen_cat, chosen_name, chosen_path) = &demo_projects[chosen];

    println!();
    println!("  🎉 {}", "Awesome choice!".green().bold());
    println!(
        "  You selected: {} {}",
        format!("[{}]", chosen_cat).cyan(),
        chosen_name.bold()
    );
    println!("  Path: {}", chosen_path.display().to_string().dimmed());
    println!();
    if !preferred_editor.is_empty() {
        println!(
            "  In a real terminal shell, running 'pg' would instantly jump to this folder\n  and run: {} .",
            preferred_editor.bold()
        );
    } else {
        println!(
            "  In a real terminal shell, running 'pg' would instantly jump to this folder\n  and open your default editor."
        );
    }
    println!();

    println!("{}", "  Onboarding complete! You are ready to organize and navigate your codebases like a pro. 🚀".green());
    println!();

    Ok(())
}

fn detect_shell() -> completions::CompletionShell {
    if let Ok(shell_env) = std::env::var("SHELL") {
        let shell_lower = shell_env.to_lowercase();
        if shell_lower.contains("zsh") {
            return completions::CompletionShell::Zsh;
        } else if shell_lower.contains("fish") {
            return completions::CompletionShell::Fish;
        } else if shell_lower.contains("bash") {
            return completions::CompletionShell::Bash;
        } else if shell_lower.contains("nu") {
            return completions::CompletionShell::Nushell;
        }
    }

    if std::env::var("PSModulePath").is_ok()
        || std::env::var("POWERSHELL_DISTRIBUTION_CHANNEL").is_ok()
    {
        return completions::CompletionShell::Powershell;
    }

    if std::env::consts::OS == "windows" {
        completions::CompletionShell::Powershell
    } else {
        completions::CompletionShell::Zsh
    }
}

fn default_profile_path(shell: completions::CompletionShell) -> PathBuf {
    let home = dirs::home_dir().unwrap_or_else(|| PathBuf::from("."));
    match shell {
        completions::CompletionShell::Zsh => {
            if let Ok(zdotdir) = std::env::var("ZDOTDIR") {
                let path = PathBuf::from(zdotdir).join(".zshrc");
                if path.parent().is_some_and(|p| p.exists()) {
                    return path;
                }
            }
            home.join(".zshrc")
        }
        completions::CompletionShell::Bash => {
            if std::env::consts::OS == "macos" {
                home.join(".bash_profile")
            } else {
                home.join(".bashrc")
            }
        }
        completions::CompletionShell::Fish => home.join(".config/fish/config.fish"),
        completions::CompletionShell::Powershell => {
            if let Some(path) = query_shell_profile("pwsh", &["-NoProfile", "-Command", "$PROFILE"])
            {
                return path;
            }
            if let Some(path) =
                query_shell_profile("powershell", &["-NoProfile", "-Command", "$PROFILE"])
            {
                return path;
            }
            if cfg!(target_os = "windows") {
                home.join("Documents/PowerShell/Microsoft.PowerShell_profile.ps1")
            } else {
                home.join(".config/powershell/Microsoft.PowerShell_profile.ps1")
            }
        }
        completions::CompletionShell::Nushell => {
            if let Some(path) = query_shell_profile("nu", &["-c", "$nu.config-path"]) {
                return path;
            }
            if cfg!(target_os = "windows") {
                dirs::config_dir()
                    .map(|p| p.join("nushell/config.nu"))
                    .unwrap_or_else(|| home.join("AppData/Roaming/nushell/config.nu"))
            } else {
                home.join(".config/nushell/config.nu")
            }
        }
    }
}

fn query_shell_profile(binary: &str, args: &[&str]) -> Option<PathBuf> {
    let output = Command::new(binary).args(args).output().ok()?;
    if output.status.success() {
        let path_str = String::from_utf8_lossy(&output.stdout).trim().to_string();
        if !path_str.is_empty() {
            return Some(PathBuf::from(path_str));
        }
    }
    None
}

fn completion_path(shell: completions::CompletionShell) -> PathBuf {
    let home = dirs::home_dir().unwrap_or_else(|| PathBuf::from("."));
    match shell {
        completions::CompletionShell::Zsh => home.join(".config/zsh/completions/_projm"),
        completions::CompletionShell::Bash => home.join(".config/projm/completions/projm.bash"),
        completions::CompletionShell::Fish => home.join(".config/fish/completions/projm.fish"),
        completions::CompletionShell::Powershell => {
            home.join(".config/powershell/completions/projm.ps1")
        }
        completions::CompletionShell::Nushell => home.join(".config/projm/completions/projm.nu"),
    }
}

fn write_completions(shell: completions::CompletionShell, path: &PathBuf) -> Result<()> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }
    let script = match shell {
        completions::CompletionShell::Zsh => completions::zsh_script()?,
        completions::CompletionShell::Powershell => completions::powershell_script()?,
        completions::CompletionShell::Nushell => completions::nushell_script()?,
        completions::CompletionShell::Bash => {
            let mut cmd = crate::main_cli::Cli::command();
            let mut buf = Vec::new();
            clap_complete::generate(clap_complete::shells::Bash, &mut cmd, "projm", &mut buf);
            String::from_utf8(buf)?
        }
        completions::CompletionShell::Fish => {
            let mut cmd = crate::main_cli::Cli::command();
            let mut buf = Vec::new();
            clap_complete::generate(clap_complete::shells::Fish, &mut cmd, "projm", &mut buf);
            String::from_utf8(buf)?
        }
    };
    fs::write(path, script)?;
    Ok(())
}

fn update_shell_profile(
    shell: completions::CompletionShell,
    profile: &Path,
    alias: &str,
    completion_path: &Path,
) -> Result<()> {
    if let Some(parent) = profile.parent() {
        fs::create_dir_all(parent)?;
    }

    let old = fs::read_to_string(profile).unwrap_or_default();
    let updated = match shell {
        completions::CompletionShell::Zsh => {
            let comp_dir = completion_path
                .parent()
                .unwrap_or(completion_path)
                .to_string_lossy()
                .to_string();
            let block = format!(
                "{start}\n{alias}() {{\n    local cmd\n    cmd=$(projm g \"$@\" 2>/dev/tty </dev/tty) || return\n    [ -n \"$cmd\" ] && eval \"$cmd\"\n}}\npn() {{\n    projm run \"$@\"\n}}\nfpath=(\"{comp_dir}\" $fpath)\nautoload -Uz compinit && compinit\n{end}\n",
                alias = alias,
                comp_dir = comp_dir,
                start = PROJM_BLOCK_START,
                end = PROJM_BLOCK_END
            );
            let with_projm = ensure_projm_block(&old, &block);
            ensure_line(&with_projm, "eval \"$(zoxide init zsh)\"")
        }
        completions::CompletionShell::Bash => {
            let comp_file = completion_path.to_string_lossy().to_string();
            let block = format!(
                "{start}\n{alias}() {{\n    local cmd\n    cmd=$(projm g \"$@\" 2>/dev/tty </dev/tty) || return\n    [ -n \"$cmd\" ] && eval \"$cmd\"\n}}\npn() {{\n    projm run \"$@\"\n}}\n. \"{comp_file}\"\n{end}\n",
                alias = alias,
                comp_file = comp_file,
                start = PROJM_BLOCK_START,
                end = PROJM_BLOCK_END
            );
            let with_projm = ensure_projm_block(&old, &block);
            ensure_line(&with_projm, "eval \"$(zoxide init bash)\"")
        }
        completions::CompletionShell::Fish => {
            let block = format!(
                "{start}\nfunction {alias}\n    set -l cmd (projm g $argv 2>/dev/tty </dev/tty)\n    if test -n \"$cmd\"\n        eval $cmd\n    end\nend\nfunction pn\n    projm run $argv\nend\n{end}\n",
                alias = alias,
                start = PROJM_BLOCK_START,
                end = PROJM_BLOCK_END
            );
            let with_projm = ensure_projm_block(&old, &block);
            ensure_line(&with_projm, "zoxide init fish | source")
        }
        completions::CompletionShell::Powershell => {
            let comp_file = completion_path.to_string_lossy().to_string();
            let block = format!(
                "{start}\nfunction {alias} {{\n  $cmd = projm g $args\n  if ($cmd) {{ Invoke-Expression $cmd }}\n}}\nfunction pn {{\n  projm run $args\n}}\n. \"{comp_file}\"\n{end}\n",
                alias = alias,
                comp_file = comp_file,
                start = PROJM_BLOCK_START,
                end = PROJM_BLOCK_END
            );
            let with_projm = ensure_projm_block(&old, &block);
            ensure_line(
                &with_projm,
                "Invoke-Expression (& { (zoxide init powershell | Out-String) })",
            )
        }
        completions::CompletionShell::Nushell => {
            let comp_file = completion_path.to_string_lossy().to_string();
            let block = format!(
                "{start}\ndef --env {alias} [...args] {{\n    let cmd = (projm g ...$args | into string | str trim)\n    if ($cmd | is-empty) == false {{\n        let parts = ($cmd | split row \" && \")\n        if ($parts | length) >= 2 {{\n            let cd_part = ($parts | get 0)\n            let edit_part = ($parts | get 1)\n            let path = ($cd_part | str replace -r \"^(cd|z)\\s+'(.*)'$\" \"$2\")\n            cd $path\n            let editor = ($edit_part | str replace -r \"\\s+\\.$\" \"\")\n            run-external $editor \".\"\n        }}\n    }}\n}}\ndef --env pn [...args] {{\n    projm run ...$args\n}}\nsource \"{comp_file}\"\n{end}\n",
                alias = alias,
                comp_file = comp_file,
                start = PROJM_BLOCK_START,
                end = PROJM_BLOCK_END
            );
            let with_projm = ensure_projm_block(&old, &block);
            ensure_line(&with_projm, "zoxide init nushell | source")
        }
    };

    if updated != old {
        fs::write(profile, updated).with_context(|| format!("write {}", profile.display()))?;
    }

    Ok(())
}

fn ensure_projm_block(content: &str, block: &str) -> String {
    if let (Some(start_idx), Some(end_idx)) = (
        content.find(PROJM_BLOCK_START),
        content.find(PROJM_BLOCK_END),
    ) {
        if start_idx < end_idx {
            let mut new_content = content[..start_idx].to_owned();
            new_content.push_str(block);
            new_content
                .push_str(content[end_idx + PROJM_BLOCK_END.len()..].trim_start_matches('\n'));
            return new_content;
        }
    }

    if content.trim().is_empty() {
        block.to_owned()
    } else {
        format!("{}\n\n{}", content.trim_end(), block)
    }
}

fn ensure_line(content: &str, line: &str) -> String {
    if content.lines().any(|l| l.trim() == line.trim()) {
        return content.to_owned();
    }
    if content.trim().is_empty() {
        format!("{}\n", line)
    } else {
        format!("{}\n{}\n", content.trim_end(), line)
    }
}

fn has_zoxide() -> bool {
    Command::new("zoxide")
        .arg("--version")
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .is_ok_and(|s| s.success())
}

fn install_zoxide() -> Result<()> {
    let plan = installer_plan(std::env::consts::OS, os_release().as_deref());
    for cmd in &plan {
        eprintln!("      trying: {}", cmd.dimmed());
        if run_install_command(cmd) {
            eprintln!("      {} installed zoxide", "✓".green().bold());
            return Ok(());
        }
    }

    anyhow::bail!(
        "failed to install zoxide automatically. install it manually, then run `projm init` again"
    )
}

fn run_install_command(cmd: &str) -> bool {
    #[cfg(target_os = "windows")]
    {
        return Command::new("cmd")
            .args(["/C", cmd])
            .status()
            .is_ok_and(|s| s.success());
    }

    #[cfg(not(target_os = "windows"))]
    {
        Command::new("sh")
            .args(["-c", cmd])
            .status()
            .is_ok_and(|s| s.success())
    }
}

fn os_release() -> Option<String> {
    let data = fs::read_to_string("/etc/os-release").ok()?;
    Some(data.to_lowercase())
}

pub fn installer_plan(os: &str, os_release: Option<&str>) -> Vec<String> {
    if os == "windows" {
        return vec![
            "winget install --id ajeetdsouza.zoxide -e --source winget".into(),
            "choco install zoxide -y".into(),
            "scoop install zoxide".into(),
            "cargo install zoxide".into(),
        ];
    }

    if os == "macos" {
        return vec!["brew install zoxide".into(), "cargo install zoxide".into()];
    }

    if os == "linux" {
        let release = os_release.unwrap_or_default();
        if release.contains("arch") || release.contains("manjaro") {
            return vec![
                "pacman -S --noconfirm zoxide".into(),
                "yay -S --noconfirm zoxide".into(),
                "paru -S --noconfirm zoxide".into(),
                "cargo install zoxide".into(),
            ];
        }
        if release.contains("ubuntu") || release.contains("debian") {
            return vec![
                "apt update && apt install -y zoxide".into(),
                "cargo install zoxide".into(),
            ];
        }

        return vec!["cargo install zoxide".into()];
    }

    vec!["cargo install zoxide".into()]
}

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

    #[test]
    fn ensure_line_is_idempotent() {
        let a = ensure_line("hello", "world");
        let b = ensure_line(&a, "world");
        assert_eq!(a, b);
    }

    #[test]
    fn ensure_line_on_empty_content_has_no_leading_newline() {
        let line = ensure_line("", "world");
        assert_eq!(line, "world\n");
    }

    #[test]
    fn ensure_projm_block_is_idempotent() {
        let block = format!("{}\nsome block\n{}", PROJM_BLOCK_START, PROJM_BLOCK_END);
        let a = ensure_projm_block("", &block);
        let b = ensure_projm_block(&a, &block);
        assert_eq!(a, b);
    }

    #[test]
    fn ensure_projm_block_custom_alias() {
        let test_comp = PathBuf::from("test_comp");
        let old = "";
        let alias = "pj";

        let comp_dir = test_comp
            .parent()
            .unwrap_or(&test_comp)
            .to_string_lossy()
            .to_string();
        let block_content = format!(
            "{start}\n{alias}() {{\n    local cmd\n    cmd=$(projm g \"$@\" 2>/dev/tty </dev/tty) || return\n    [ -n \"$cmd\" ] && eval \"$cmd\"\n}}\npn() {{\n    projm run \"$@\"\n}}\nfpath=(\"{comp_dir}\" $fpath)\nautoload -Uz compinit && compinit\n{end}\n",
            alias = alias,
            comp_dir = comp_dir,
            start = PROJM_BLOCK_START,
            end = PROJM_BLOCK_END
        );
        let updated = ensure_projm_block(old, &block_content);
        assert!(updated.contains("pj() {"));
        assert!(!updated.contains("pg() {"));
    }

    #[test]
    fn arch_plan_prefers_pacman_then_helpers_then_cargo() {
        let plan = installer_plan("linux", Some("id=arch"));
        assert_eq!(
            plan,
            vec![
                "pacman -S --noconfirm zoxide",
                "yay -S --noconfirm zoxide",
                "paru -S --noconfirm zoxide",
                "cargo install zoxide"
            ]
        );
    }

    #[test]
    fn debian_plan_prefers_apt_then_cargo() {
        let plan = installer_plan("linux", Some("id=ubuntu"));
        assert_eq!(
            plan,
            vec![
                "apt update && apt install -y zoxide",
                "cargo install zoxide"
            ]
        );
    }

    #[test]
    fn windows_plan_prefers_winget_then_choco_then_scoop_then_cargo() {
        let plan = installer_plan("windows", None);
        assert_eq!(
            plan,
            vec![
                "winget install --id ajeetdsouza.zoxide -e --source winget",
                "choco install zoxide -y",
                "scoop install zoxide",
                "cargo install zoxide"
            ]
        );
    }
}