whi 0.5.2

Stupid simple PATH management
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
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
use std::env;
use std::fs;
use std::io::{self, BufRead, BufWriter, StdoutLock, Write};
use std::path::{Path, PathBuf};

use crate::cli::{Args, ColorWhen};
use crate::executor::{ExecutableCheck, SearchResult};
use crate::history::{HistoryContext, HistoryScope};
use crate::output::OutputFormatter;
use crate::path::PathSearcher;
use crate::path_resolver;
use crate::shell_integration;
use crate::system;
use crate::venv_manager;

/// Get the session `PID` - either from `WHI_SESSION_PID` env var or fall back to parent `PID`
fn get_session_pid() -> Result<u32, std::io::Error> {
    if let Ok(pid_str) = env::var("WHI_SESSION_PID") {
        pid_str.parse::<u32>().map_err(|_| {
            std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "Invalid WHI_SESSION_PID value",
            )
        })
    } else {
        system::get_parent_pid()
    }
}

/// Write PATH snapshot to session tracker, with error handling
fn write_snapshot_safe(new_path: &str, args: &Args) {
    match history_for_current_scope() {
        Ok(history) => {
            if let Err(e) = history.write_snapshot(new_path) {
                if !args.quiet && !args.silent {
                    eprintln!("Warning: Failed to write snapshot: {e}");
                }
            }
        }
        Err(e) => {
            if !args.quiet && !args.silent {
                eprintln!("Warning: Failed to acquire history: {e}");
            }
        }
    }
}

fn history_for_current_scope() -> Result<HistoryContext, String> {
    let pid = get_session_pid().map_err(|e| e.to_string())?;

    if venv_manager::is_in_venv() {
        if let Ok(dir) = env::var("WHI_VENV_DIR") {
            if !dir.is_empty() {
                let path = PathBuf::from(dir);
                return HistoryContext::venv(pid, path.as_path());
            }
        }
    }

    HistoryContext::global(pid)
}

/// Output new PATH and flush, returning success code
fn output_path(out: &mut BufWriter<StdoutLock>, new_path: &str) -> i32 {
    writeln!(out, "{new_path}").ok();
    out.flush().ok();
    0
}

/// Handle Result from PATH operation: write snapshot on success, print error on failure
fn handle_path_result(
    result: Result<String, String>,
    args: &Args,
    out: &mut BufWriter<StdoutLock>,
) -> i32 {
    match result {
        Ok(new_path) => {
            write_snapshot_safe(&new_path, args);
            output_path(out, &new_path)
        }
        Err(e) => {
            if !args.silent {
                eprintln!("Error: {e}");
            }
            2
        }
    }
}

#[allow(clippy::too_many_lines)]
#[must_use]
pub fn run(args: &Args) -> i32 {
    if let Err(e) = crate::config::ensure_config_exists() {
        eprintln!("Error: {e}");
        return 2;
    }

    // Handle init subcommand
    if let Some(ref shell) = args.init_shell {
        match shell_integration::generate_init_script(shell) {
            Ok(script) => {
                print!("{script}");
                return 0;
            }
            Err(err) => {
                eprintln!("Error: {err}");
                return 2;
            }
        }
    }

    // Handle apply subcommand (renamed from save)
    if let Some(shell_opt) = &args.apply_shell {
        return handle_apply(shell_opt.as_ref(), args.no_protect, args.apply_force);
    }

    // Handle save profile subcommand
    if let Some(profile_name) = &args.save_profile {
        return handle_save_profile(profile_name);
    }

    // Handle load profile subcommand
    if let Some(profile_name) = &args.load_profile {
        return handle_load_profile(profile_name);
    }

    // Handle remove profile subcommand
    if let Some(profile_name) = &args.remove_profile {
        return handle_remove_profile(profile_name);
    }

    // Handle reset subcommand
    if args.reset {
        return handle_reset();
    }

    // Handle undo subcommand
    if let Some(count) = args.undo_count {
        return handle_undo(count);
    }

    // Handle redo subcommand
    if let Some(count) = args.redo_count {
        return handle_redo(count);
    }

    // Handle diff subcommand
    if args.diff {
        return handle_diff(args.diff_full);
    }

    let path_var = match &args.path_override {
        Some(p) => p.clone(),
        None => env::var("PATH").unwrap_or_default(),
    };

    let searcher = PathSearcher::new(&path_var);
    let stdout = io::stdout();
    let mut out = BufWriter::new(stdout.lock());

    // Handle --clean operation
    if args.clean {
        let (new_path, _removed_indices) = searcher.clean_duplicates();
        write_snapshot_safe(&new_path, args);
        return output_path(&mut out, &new_path);
    }

    // Handle --delete operation
    if !args.delete_targets.is_empty() {
        return handle_delete(&searcher, &args.delete_targets, args, &mut out);
    }

    // Handle --move operation
    if let Some((from, to)) = args.move_indices {
        return handle_path_result(searcher.move_entry(from, to), args, &mut out);
    }

    // Handle --swap operation
    if let Some((idx1, idx2)) = args.swap_indices {
        return handle_path_result(searcher.swap_entries(idx1, idx2), args, &mut out);
    }

    // Handle --prefer operation
    if let Some(ref target) = args.prefer_target {
        return handle_prefer(&searcher, target, args, &mut out);
    }

    let names = get_names(args);

    // If no names provided, show all PATH entries
    if names.is_empty() {
        let num_dirs = searcher.dirs().len();
        if num_dirs > 999 {
            if !args.silent {
                eprintln!("Error: PATH has {num_dirs} entries (max 999 supported)");
            }
            return 3;
        }

        for (idx, dir) in searcher.dirs().iter().enumerate() {
            if args.no_index {
                writeln!(out, "{}", dir.display()).ok();
            } else {
                writeln!(out, "{:>4} {}", format!("[{}]", idx + 1), dir.display()).ok();
            }
        }
        out.flush().ok();
        return 0;
    }

    let mut all_found = true;
    if names.is_empty() {
        eprintln!("Usage: whi [OPTIONS] [NAME]...\n       whi <COMMAND>\n\nTry 'whi --help' for more information.");
        return 2;
    }

    let stderr = io::stderr();
    let mut err = BufWriter::new(stderr.lock());

    let use_color = should_use_color(args);
    let mut formatter = OutputFormatter::new(use_color, args.print0);

    for name in names {
        let results = search_name(&searcher, &name, args);

        if results.is_empty() {
            all_found = false;

            if !args.silent && !args.quiet {
                writeln!(err, "{name}: not found").ok();
            }
            continue;
        }

        // Check max index
        let max_index = results.iter().map(|r| r.path_index).max().unwrap_or(0);
        if max_index > 999 {
            if !args.silent {
                eprintln!("Error: PATH index {max_index} exceeds max 999");
            }
            return 3;
        }

        // Output results
        for (i, result) in results.iter().enumerate() {
            let is_winner = i == 0;

            formatter
                .write_result(
                    &mut out,
                    result,
                    is_winner,
                    args.follow_symlinks,
                    !args.no_index,
                    3, // Always use 3-digit width
                )
                .ok();

            // By default, only show the winner (like `which`)
            // Show all with --all flag or --full flag (full implies all)
            if (!args.all && !args.full) || args.one {
                break;
            }
        }

        // If -f/--full, show full PATH listing after results
        if args.full {
            writeln!(out).ok();

            // Collect all path indices that contain matches
            let match_indices: std::collections::HashSet<usize> =
                results.iter().map(|r| r.path_index).collect();

            for (idx, dir) in searcher.dirs().iter().enumerate() {
                let path_index = idx + 1;
                let has_match = match_indices.contains(&path_index);

                if !args.no_index {
                    write!(out, "{:>4} ", format!("[{}]", path_index)).ok();
                }

                if use_color && has_match {
                    // Use yellow/dim color for directories containing matches
                    writeln!(out, "\x1b[33m{}\x1b[0m", dir.display()).ok();
                } else {
                    writeln!(out, "{}", dir.display()).ok();
                }
            }
        }
    }

    out.flush().ok();
    err.flush().ok();

    i32::from(!all_found)
}

fn get_names(args: &Args) -> Vec<String> {
    if !args.names.is_empty() {
        return args.names.clone();
    }

    // Only read from stdin if it's piped (not a TTY)
    if !atty::is(atty::Stream::Stdin) {
        let stdin = io::stdin();
        let mut names = Vec::new();
        for line in stdin.lock().lines().map_while(Result::ok) {
            let trimmed = line.trim();
            if !trimmed.is_empty() && !trimmed.starts_with('#') {
                names.push(trimmed.to_string());
            }
        }
        return names;
    }

    // No names and stdin is a TTY - return empty
    Vec::new()
}

fn search_name(searcher: &PathSearcher, name: &str, args: &Args) -> Vec<SearchResult> {
    // If name contains path separator, check it directly
    if name.contains('/') {
        let path = PathBuf::from(name);
        if let Some(result) = check_path(&path, args, 0) {
            return vec![result];
        }
        return vec![];
    }

    let mut results = Vec::new();
    let search_all = args.all || args.full;

    for (idx, dir) in searcher.dirs().iter().enumerate() {
        let candidate = dir.join(name);
        if let Some(result) = check_path(&candidate, args, idx + 1) {
            results.push(result);

            // Stop after first match if not searching for all (like `which`)
            if !search_all {
                break;
            }
        }
    }

    results
}

fn check_path(path: &Path, args: &Args, path_index: usize) -> Option<SearchResult> {
    let checker = ExecutableCheck::new(path);

    if !checker.exists() {
        return None;
    }

    let is_executable = checker.is_executable();

    if !is_executable && !args.show_nonexec {
        return None;
    }

    let canonical_path = if args.follow_symlinks {
        fs::canonicalize(path).ok()
    } else {
        None
    };

    let metadata = if args.stat {
        checker.get_file_metadata()
    } else {
        None
    };

    Some(SearchResult {
        path: path.to_path_buf(),
        canonical_path,
        metadata,
        path_index,
    })
}

fn should_use_color(args: &Args) -> bool {
    match args.color {
        ColorWhen::Always => true,
        ColorWhen::Never => false,
        ColorWhen::Auto => atty::is(atty::Stream::Stdout),
    }
}

/// Get the directory containing the current whi executable
fn get_current_exe_dir() -> Option<PathBuf> {
    env::current_exe()
        .ok()
        .and_then(|exe_path| exe_path.parent().map(std::path::Path::to_path_buf))
}

fn handle_prefer<W: Write>(
    searcher: &PathSearcher,
    target: &crate::cli::PreferTarget,
    args: &Args,
    out: &mut W,
) -> i32 {
    use crate::cli::PreferTarget;

    match target {
        PreferTarget::IndexBased { name, index } => {
            handle_prefer_index(searcher, name, *index, args, out)
        }
        PreferTarget::PathBased { name, path } => {
            handle_prefer_path(searcher, name, path, args, out)
        }
        PreferTarget::PathOnly { path } => handle_prefer_path_only(searcher, path, args, out),
    }
}

fn handle_prefer_index<W: Write>(
    searcher: &PathSearcher,
    name: &str,
    target_idx: usize,
    args: &Args,
    out: &mut W,
) -> i32 {
    // Need to search ALL occurrences for prefer logic to work
    let mut search_args = args.clone();
    search_args.all = true;
    let results = search_name(searcher, name, &search_args);

    if results.is_empty() {
        if !args.silent {
            eprintln!("Error: {name}: not found");
        }
        return 1;
    }

    // Find the current winner (first occurrence)
    let winner_idx = results[0].path_index;

    // Check if target_idx is in the results
    let target_result = results.iter().find(|r| r.path_index == target_idx);
    if target_result.is_none() {
        if !args.silent {
            eprintln!("Error: {name} not found at index {target_idx}");
        }
        return 2;
    }

    // Calculate the minimal move: move target to just before the winner
    let new_position = if target_idx > winner_idx {
        winner_idx
    } else {
        // Already before winner, no change needed
        if !args.silent {
            eprintln!(
                "Error: {name} at index {target_idx} is already preferred over index {winner_idx}"
            );
        }
        return 2;
    };

    match searcher.move_entry(target_idx, new_position) {
        Ok(new_path) => {
            write_snapshot_safe(&new_path, args);

            writeln!(out, "{new_path}").ok();
            out.flush().ok();
            0
        }
        Err(e) => {
            if !args.silent {
                eprintln!("Error: {e}");
            }
            2
        }
    }
}

fn handle_prefer_path<W: Write>(
    searcher: &PathSearcher,
    name: &str,
    path_str: &str,
    args: &Args,
    out: &mut W,
) -> i32 {
    use path_resolver::{looks_like_exact_path, resolve_path};

    let cwd = env::current_dir().unwrap_or_else(|_| PathBuf::from("."));

    // Determine if this is an exact path or fuzzy pattern
    if looks_like_exact_path(path_str) {
        // Exact path - resolve it
        match resolve_path(path_str, &cwd) {
            Ok(resolved_path) => {
                handle_prefer_exact_path(searcher, name, &resolved_path, args, out)
            }
            Err(e) => {
                if !args.silent {
                    eprintln!("Error resolving path: {e}");
                }
                2
            }
        }
    } else {
        // Fuzzy pattern
        handle_prefer_fuzzy(searcher, name, path_str, args, out)
    }
}

fn handle_prefer_exact_path<W: Write>(
    searcher: &PathSearcher,
    name: &str,
    path: &Path,
    args: &Args,
    out: &mut W,
) -> i32 {
    // Check if executable exists in the directory
    if !path.exists() {
        if !args.silent {
            eprintln!("Error: Directory does not exist: {}", path.display());
        }
        return 2;
    }

    // Check if path already exists in PATH
    if let Some(idx) = searcher.find_path_index(path) {
        // Path already in PATH - use traditional index-based prefer
        return handle_prefer_index(searcher, name, idx, args, out);
    }

    // Path not in PATH yet - verify executable exists before adding
    if !searcher.has_executable(path, name) {
        if !args.silent {
            eprintln!("Error: {} not found in {}", name, path.display());
        }
        return 2;
    }

    // Path not in PATH - need to add it at the right position
    // First, find where the executable currently wins (if it exists)
    let results = search_name(searcher, name, args);

    let insert_position = if results.is_empty() {
        // Executable doesn't exist anywhere - add at the beginning
        1
    } else {
        // Executable exists - add new path just before the current winner
        results[0].path_index
    };

    match searcher.add_path_at_position(path, insert_position) {
        Ok(new_path) => {
            if !args.silent {
                eprintln!(
                    "Added {} to PATH at index {}",
                    path.display(),
                    insert_position
                );
            }

            write_snapshot_safe(&new_path, args);

            writeln!(out, "{new_path}").ok();
            out.flush().ok();
            0
        }
        Err(e) => {
            if !args.silent {
                eprintln!("Error adding to PATH: {e}");
            }
            2
        }
    }
}

fn handle_prefer_path_only<W: Write>(
    searcher: &PathSearcher,
    path_str: &str,
    args: &Args,
    out: &mut W,
) -> i32 {
    use path_resolver::{looks_like_exact_path, resolve_path};

    let cwd = env::current_dir().unwrap_or_else(|_| PathBuf::from("."));

    // Resolve the path
    let resolved_path = if looks_like_exact_path(path_str) {
        match resolve_path(path_str, &cwd) {
            Ok(path) => path,
            Err(e) => {
                if !args.silent {
                    eprintln!("Error resolving path: {e}");
                }
                return 2;
            }
        }
    } else {
        // Not a path-like string - treat as relative
        cwd.join(path_str)
    };

    // Check if path already exists in PATH
    if let Some(_idx) = searcher.find_path_index(&resolved_path) {
        // Already in PATH - do nothing (no duplicate)
        if !args.silent {
            eprintln!("{} is already in PATH", resolved_path.display());
        }
        // Return current PATH unchanged
        writeln!(out, "{}", searcher.to_path_string()).ok();
        out.flush().ok();
        return 0;
    }

    match searcher.add_path(&resolved_path) {
        Ok((new_path, idx)) => {
            if !args.silent {
                eprintln!("Added {} to PATH at index {}", resolved_path.display(), idx);
            }

            write_snapshot_safe(&new_path, args);

            writeln!(out, "{new_path}").ok();
            out.flush().ok();
            0
        }
        Err(e) => {
            if !args.silent {
                eprintln!("Error adding to PATH: {e}");
            }
            2
        }
    }
}

fn handle_prefer_fuzzy<W: Write>(
    searcher: &PathSearcher,
    name: &str,
    pattern: &str,
    args: &Args,
    out: &mut W,
) -> i32 {
    // Find matching paths
    let matches = searcher.find_fuzzy_indices(pattern, Some(name));

    if matches.is_empty() {
        if !args.silent {
            eprintln!("Error: No PATH entries match pattern '{pattern}' containing '{name}'");
        }
        return 1;
    }

    if matches.len() > 1 {
        if !args.silent {
            eprintln!("Error: Multiple PATH entries match pattern '{pattern}':");
            for (idx, path) in &matches {
                eprintln!("  [{}] {}", idx, path.display());
            }
            eprintln!("Please be more specific or use an index directly.");
        }
        return 2;
    }

    // Single match - use it
    let (index, _) = matches[0];
    handle_prefer_index(searcher, name, index, args, out)
}

fn handle_delete<W: Write>(
    searcher: &PathSearcher,
    targets: &[crate::cli::DeleteTarget],
    args: &Args,
    out: &mut W,
) -> i32 {
    use crate::cli::DeleteTarget;
    use crate::path_resolver::{looks_like_exact_path, resolve_path};

    let cwd = env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    let mut indices_to_delete = Vec::new();

    for target in targets {
        match target {
            DeleteTarget::Index(idx) => {
                indices_to_delete.push(*idx);
            }

            DeleteTarget::Path(path_str) => {
                if looks_like_exact_path(path_str) {
                    // Exact path - resolve it
                    match resolve_path(path_str, &cwd) {
                        Ok(resolved) => {
                            if let Some(idx) = searcher.find_path_index(&resolved) {
                                indices_to_delete.push(idx);
                            } else {
                                if !args.silent {
                                    eprintln!(
                                        "Error: Path not found in PATH: {}",
                                        resolved.display()
                                    );
                                }
                                return 1;
                            }
                        }
                        Err(e) => {
                            if !args.silent {
                                eprintln!("Error resolving path: {e}");
                            }
                            return 2;
                        }
                    }
                } else {
                    // Fuzzy pattern - delete ALL matches
                    let matches = searcher.find_fuzzy_indices(path_str, None);

                    if matches.is_empty() {
                        if !args.silent {
                            eprintln!("Error: No PATH entries match pattern '{path_str}'");
                        }
                        return 1;
                    }

                    // Add all matching indices (delete ALL matches)
                    for (idx, _) in &matches {
                        indices_to_delete.push(*idx);
                    }
                }
            }
        }
    }

    // Get the paths to be deleted before deletion (for logging)
    let dirs = searcher.dirs();

    // Filter out the directory containing the current whi executable (silently)
    if let Some(exe_dir) = get_current_exe_dir() {
        // Try to canonicalize for better matching
        let canonical_exe_dir = fs::canonicalize(&exe_dir).unwrap_or_else(|_| exe_dir.clone());

        indices_to_delete.retain(|&idx| {
            if idx > 0 && idx <= dirs.len() {
                let path = &dirs[idx - 1];
                // Compare both as-is and canonicalized paths
                let canonical_path = fs::canonicalize(path).unwrap_or_else(|_| path.clone());

                // Keep the index if it doesn't match the executable's directory
                path != &exe_dir
                    && path != &canonical_exe_dir
                    && canonical_path != exe_dir
                    && canonical_path != canonical_exe_dir
            } else {
                true
            }
        });
    }

    // Remove duplicates before displaying
    indices_to_delete.sort_unstable();
    indices_to_delete.dedup();

    // Show list of entries being deleted (for multi-delete operations)
    if !args.silent && indices_to_delete.len() > 1 {
        for &idx in &indices_to_delete {
            if idx > 0 && idx <= dirs.len() {
                eprintln!("{:>4} {}", format!("[{}]", idx), dirs[idx - 1].display());
            }
        }
    }

    let result = if indices_to_delete.len() == 1 {
        searcher.delete_entry(indices_to_delete[0])
    } else {
        searcher.delete_entries(&indices_to_delete)
    };

    match result {
        Ok(new_path) => {
            write_snapshot_safe(&new_path, args);

            writeln!(out, "{new_path}").ok();
            out.flush().ok();
            0
        }
        Err(e) => {
            if !args.silent {
                eprintln!("Error: {e}");
            }
            2
        }
    }
}

#[allow(clippy::too_many_lines)]
fn handle_apply(shell_opt: Option<&String>, no_protect: bool, force: bool) -> i32 {
    use crate::config::load_config;
    use crate::config_manager::save_path;
    use crate::session_tracker::cleanup_old_sessions;
    use crate::shell_detect::{detect_current_shell, Shell};
    use std::collections::HashSet;

    if venv_manager::is_in_venv() && !force {
        eprintln!("Error: Refusing to run 'whi apply' inside an active PATH environment. Exit the venv or re-run with '--force' (optionally with '--no-protect').");
        return 2;
    }

    let mut path_var = env::var("PATH").unwrap_or_default();

    // Apply protected paths unless --no-protect is set
    if !no_protect {
        if let Ok(config) = load_config() {
            let current_paths: HashSet<String> = path_var
                .split(':')
                .filter(|s| !s.is_empty())
                .map(std::string::ToString::to_string)
                .collect();

            let protected_paths: Vec<String> = config
                .protected
                .paths
                .iter()
                .filter_map(|p| {
                    let path_str = p.to_string_lossy().to_string();
                    if current_paths.contains(&path_str) {
                        None
                    } else {
                        Some(path_str)
                    }
                })
                .collect();

            if !protected_paths.is_empty() {
                // Insert protected paths at the beginning
                let protected_count = protected_paths.len();
                path_var = format!("{}:{}", protected_paths.join(":"), path_var);

                eprintln!(
                    "Protected {} system path{}: {}",
                    protected_count,
                    if protected_count == 1 { "" } else { "s" },
                    protected_paths.join(", ")
                );
            }
        }
    }

    let result = match shell_opt {
        None => {
            let shell = match detect_current_shell() {
                Ok(s) => s,
                Err(e) => {
                    eprintln!("Error: {e}");
                    return 2;
                }
            };

            if let Err(e) = save_path(&shell, &path_var) {
                eprintln!("Error: {e}");
                return 2;
            }

            let num_entries = path_var.split(':').filter(|s| !s.is_empty()).count();
            println!(
                "Applied PATH to {} ({} entries)",
                shell.as_str(),
                num_entries
            );
            0
        }
        Some(shell_str) => {
            if shell_str.to_lowercase() == "all" {
                let shells = [Shell::Bash, Shell::Zsh, Shell::Fish];
                let mut all_ok = true;

                for shell in &shells {
                    if let Err(e) = save_path(shell, &path_var) {
                        eprintln!("Error applying to {}: {e}", shell.as_str());
                        all_ok = false;
                    } else {
                        let num_entries = path_var.split(':').filter(|s| !s.is_empty()).count();
                        println!(
                            "Applied PATH to {} ({} entries)",
                            shell.as_str(),
                            num_entries
                        );
                    }
                }

                if all_ok {
                    0
                } else {
                    2
                }
            } else {
                let shell = match shell_str.parse::<Shell>() {
                    Ok(s) => s,
                    Err(e) => {
                        eprintln!("Error: {e}");
                        return 2;
                    }
                };

                if let Err(e) = save_path(&shell, &path_var) {
                    eprintln!("Error: {e}");
                    return 2;
                }

                let num_entries = path_var.split(':').filter(|s| !s.is_empty()).count();
                println!(
                    "Applied PATH to {} ({} entries)",
                    shell.as_str(),
                    num_entries
                );
                0
            }
        }
    };

    if result == 0 {
        match history_for_current_scope() {
            Ok(history) => {
                if let Err(e) = history.reset_with_initial(&path_var) {
                    eprintln!("Warning: Failed to reinitialize history: {e}");
                }

                if history.scope() == HistoryScope::Global {
                    let _ = cleanup_old_sessions();
                }
            }
            Err(e) => {
                eprintln!("Warning: Failed to update history: {e}");
            }
        }
    }

    result
}

fn handle_diff(full: bool) -> i32 {
    use crate::path_diff::{compute_diff, format_diff_with_limit};

    let current_path = env::var("PATH").unwrap_or_default();
    let use_color = atty::is(atty::Stream::Stdout);

    let baseline_path = history_for_current_scope()
        .ok()
        .and_then(|history| history.initial_snapshot().ok().flatten())
        .unwrap_or_else(|| current_path.clone());

    let diff = compute_diff(&current_path, &baseline_path, full);
    let formatted = format_diff_with_limit(&diff, use_color, full);

    println!("{formatted}");

    0
}

fn handle_reset() -> i32 {
    use std::io::Write;

    match history_for_current_scope() {
        Ok(history) => match history.initial_snapshot() {
            Ok(Some(initial_path)) => {
                if let Err(e) = history.truncate(1) {
                    eprintln!("Warning: Failed to truncate snapshot history: {e}");
                }

                if let Err(e) = history.clear_cursor() {
                    eprintln!("Warning: Failed to reset history cursor: {e}");
                }

                let stdout = io::stdout();
                let mut out = BufWriter::new(stdout.lock());
                writeln!(out, "{initial_path}").ok();
                out.flush().ok();
                0
            }
            Ok(None) => {
                eprintln!(
                    "Error: No initial PATH found. No operations have been performed in this session."
                );
                1
            }
            Err(e) => {
                eprintln!("Error: {e}");
                2
            }
        },
        Err(e) => {
            eprintln!("Error: {e}");
            2
        }
    }
}

fn handle_undo(count: usize) -> i32 {
    use std::io::Write;

    if count == 0 {
        eprintln!("Error: Count must be at least 1");
        return 2;
    }

    match history_for_current_scope() {
        Ok(history) => match history.read_snapshots() {
            Ok(snapshots) => {
                if snapshots.is_empty() {
                    eprintln!(
                        "Error: No PATH history found. No operations have been performed in this session."
                    );
                    return 1;
                }

                let current_pos = match history.get_cursor() {
                    Ok(Some(pos)) => pos,
                    Ok(None) => snapshots.len() - 1,
                    Err(e) => {
                        eprintln!("Error: {e}");
                        return 2;
                    }
                };

                if current_pos < count {
                    if current_pos == 0 {
                        eprintln!("Error: Cannot undo further. Already at initial PATH state.");
                    } else {
                        eprintln!(
                            "Error: Can only undo {current_pos} more step(s). Use 'whi reset' to go back to the initial state."
                        );
                    }
                    return 1;
                }

                let target_index = current_pos - count;
                let target_snapshot = &snapshots[target_index];

                if let Err(e) = history.set_cursor(target_index) {
                    eprintln!("Error: Failed to set cursor: {e}");
                    return 2;
                }

                let stdout = io::stdout();
                let mut out = BufWriter::new(stdout.lock());
                writeln!(out, "{target_snapshot}").ok();
                out.flush().ok();
                0
            }
            Err(e) => {
                eprintln!("Error: {e}");
                2
            }
        },
        Err(e) => {
            eprintln!("Error: {e}");
            2
        }
    }
}

fn handle_redo(count: usize) -> i32 {
    use std::io::Write;

    if count == 0 {
        eprintln!("Error: Count must be at least 1");
        return 2;
    }

    match history_for_current_scope() {
        Ok(history) => match history.read_snapshots() {
            Ok(snapshots) => {
                if snapshots.is_empty() {
                    eprintln!("Error: No PATH history found. No operations have been performed in this session.");
                    return 1;
                }

                let current_pos = match history.get_cursor() {
                    Ok(Some(pos)) => pos,
                    Ok(None) => {
                        eprintln!("Error: Already at the latest state. Nothing to redo.");
                        return 1;
                    }
                    Err(e) => {
                        eprintln!("Error: {e}");
                        return 2;
                    }
                };

                let max_pos = snapshots.len() - 1;
                if current_pos + count > max_pos {
                    let available = max_pos - current_pos;
                    if available == 0 {
                        eprintln!("Error: Already at the latest state. Nothing to redo.");
                    } else {
                        eprintln!("Error: Can only redo {available} more step(s).");
                    }
                    return 1;
                }

                let target_index = current_pos + count;
                let target_snapshot = &snapshots[target_index];

                if target_index == max_pos {
                    if let Err(e) = history.clear_cursor() {
                        eprintln!("Error: Failed to clear cursor: {e}");
                        return 2;
                    }
                } else if let Err(e) = history.set_cursor(target_index) {
                    eprintln!("Error: Failed to set cursor: {e}");
                    return 2;
                }

                let stdout = io::stdout();
                let mut out = BufWriter::new(stdout.lock());
                writeln!(out, "{target_snapshot}").ok();
                out.flush().ok();
                0
            }
            Err(e) => {
                eprintln!("Error: {e}");
                2
            }
        },
        Err(e) => {
            eprintln!("Error: {e}");
            2
        }
    }
}

fn handle_save_profile(profile_name: &str) -> i32 {
    use crate::config_manager::save_profile;

    let path_var = env::var("PATH").unwrap_or_default();

    match save_profile(profile_name, &path_var) {
        Ok(()) => {
            let num_entries = path_var.split(':').filter(|s| !s.is_empty()).count();
            println!("Saved profile '{profile_name}' ({num_entries} entries)");
            0
        }
        Err(e) => {
            eprintln!("Error: {e}");
            2
        }
    }
}

fn handle_load_profile(profile_name: &str) -> i32 {
    use crate::config_manager::load_profile;
    use std::io::Write;

    match load_profile(profile_name) {
        Ok(parsed) => {
            let mut path_string = parsed.path;
            // Self-protection: ensure current whi directory is in PATH (silently append if missing)
            if let Some(exe_dir) = get_current_exe_dir() {
                let canonical_exe_dir =
                    fs::canonicalize(&exe_dir).unwrap_or_else(|_| exe_dir.clone());

                // Check if exe_dir is already in the loaded PATH
                let path_entries: Vec<&str> = path_string.split(':').collect();
                let mut found = false;

                for entry in &path_entries {
                    let entry_path = PathBuf::from(entry);
                    let canonical_entry =
                        fs::canonicalize(&entry_path).unwrap_or_else(|_| entry_path.clone());

                    if entry_path == exe_dir
                        || entry_path == canonical_exe_dir
                        || canonical_entry == exe_dir
                        || canonical_entry == canonical_exe_dir
                    {
                        found = true;
                        break;
                    }
                }

                // If not found, append it
                if !found {
                    if !path_string.is_empty() {
                        path_string.push(':');
                    }
                    path_string.push_str(&exe_dir.display().to_string());
                }
            }

            match history_for_current_scope() {
                Ok(history) => {
                    if let Err(e) = history.write_snapshot(&path_string) {
                        eprintln!("Warning: Failed to write snapshot for loaded profile: {e}");
                    }
                }
                Err(e) => {
                    eprintln!("Warning: Failed to acquire history for loaded profile: {e}");
                }
            }

            let stdout = io::stdout();
            let mut out = BufWriter::new(stdout.lock());
            writeln!(out, "{path_string}").ok();
            out.flush().ok();
            0
        }
        Err(e) => {
            eprintln!("Error: {e}");
            1
        }
    }
}

fn handle_remove_profile(profile_name: &str) -> i32 {
    use crate::config_manager::delete_profile;

    match delete_profile(profile_name) {
        Ok(()) => {
            println!("Removed profile '{profile_name}'");
            0
        }
        Err(e) => {
            eprintln!("Error: {e}");
            1
        }
    }
}

// TTY detection using isatty(3)
mod atty {
    use std::os::unix::io::AsRawFd;

    pub fn is(stream: Stream) -> bool {
        let fd = match stream {
            Stream::Stdout => std::io::stdout().as_raw_fd(),
            Stream::Stdin => std::io::stdin().as_raw_fd(),
        };

        crate::system::is_tty(fd)
    }

    #[derive(Copy, Clone)]
    pub enum Stream {
        Stdout,
        Stdin,
    }
}