loctree 0.8.16

Structural code intelligence for AI agents. Scan once, query everything.
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
//! Dispatcher for the new command interface.
//!
//! This module converts `Command` variants into `ParsedArgs` and dispatches
//! to the existing handlers. This provides a bridge between the new CLI
//! interface and the existing implementation.

mod handlers;

use std::path::PathBuf;

use crate::args::{ParsedArgs, SearchQueryMode};
use crate::types::{DEFAULT_LOC_THRESHOLD, Mode, OutputMode};

use super::command::*;

/// Convert a Command and GlobalOptions into ParsedArgs for backward compatibility.
///
/// This allows us to reuse existing handlers while providing the new CLI interface.
pub fn command_to_parsed_args(cmd: &Command, global: &GlobalOptions) -> ParsedArgs {
    // Initialize with global options applied
    let mut parsed = ParsedArgs {
        output: if global.json {
            OutputMode::Json
        } else {
            OutputMode::Human
        },
        verbose: global.verbose,
        color: global.color,
        ..Default::default()
    };
    parsed.library_mode = global.library_mode;
    parsed.python_library = global.python_library;
    parsed.py_roots = global.py_roots.clone();

    // Convert command-specific options
    match cmd {
        Command::Auto(opts) => {
            // Auto mode: full scan with stack detection, write cached artifacts (see LOCT_CACHE_DIR).
            // Maps to Mode::Init (which does scan + snapshot)
            // Unless --for-agent-feed is set, then use Mode::ForAi
            if opts.for_agent_feed {
                parsed.mode = Mode::ForAi;
                parsed.output = if opts.agent_json {
                    OutputMode::Json
                } else {
                    OutputMode::Jsonl
                };
                parsed.for_agent_feed = true;
                parsed.agent_json = opts.agent_json;
                parsed.force_full_scan = true; // don't reuse snapshot for agent feed
            } else {
                parsed.mode = Mode::Init;
                parsed.auto_outputs = true;
            }
            parsed.root_list = if opts.roots.is_empty() {
                vec![PathBuf::from(".")]
            } else {
                opts.roots.clone()
            };
            parsed.suppress_duplicates = opts.suppress_duplicates;
            parsed.suppress_dynamic = opts.suppress_dynamic;
            parsed.full_scan = opts.full_scan;
            parsed.scan_all = opts.scan_all;
            parsed.use_gitignore = true; // Auto mode respects gitignore by default
        }

        Command::Scan(opts) => {
            parsed.mode = Mode::Init;
            parsed.root_list = if opts.roots.is_empty() {
                vec![PathBuf::from(".")]
            } else {
                opts.roots.clone()
            };
            parsed.full_scan = opts.full_scan;
            parsed.scan_all = opts.scan_all;
            parsed.use_gitignore = true;
        }

        Command::Tree(opts) => {
            parsed.mode = Mode::Tree;
            parsed.root_list = if opts.roots.is_empty() {
                vec![PathBuf::from(".")]
            } else {
                opts.roots.clone()
            };
            parsed.max_depth = opts.depth;
            if let Some(limit) = opts.summary {
                parsed.summary = true;
                parsed.summary_limit = limit;
            }
            parsed.summary_only = opts.summary_only;
            parsed.loc_threshold = opts.loc_threshold.unwrap_or(DEFAULT_LOC_THRESHOLD);
            parsed.show_hidden = opts.show_hidden;
            parsed.find_artifacts = opts.find_artifacts;
            parsed.show_ignored = opts.show_ignored;
            if opts.show_ignored {
                parsed.use_gitignore = true;
            }
        }

        Command::Slice(opts) => {
            parsed.mode = Mode::Slice;
            parsed.slice_target = Some(opts.target.clone());
            parsed.slice_consumers = opts.consumers;
            parsed.slice_rescan = opts.rescan;
            parsed.root_list = if let Some(ref root) = opts.root {
                vec![root.clone()]
            } else {
                vec![PathBuf::from(".")]
            };
        }

        Command::Find(opts) => {
            parsed.mode = Mode::Search;
            parsed.search_query_mode = SearchQueryMode::Single;
            parsed.search_queries.clear();

            parsed.search_query = opts
                .query
                .clone()
                .or_else(|| opts.symbol.clone())
                .or_else(|| opts.similar.clone())
                .or_else(|| opts.impact.clone())
                .or_else(|| {
                    if opts.queries.is_empty() {
                        return None;
                    }

                    // Multi-arg positional query handling:
                    // - `loct find A B C` => split-mode (separate subqueries + cross-match)
                    // - `loct find "A B C"` => AND-mode (intersection)
                    // - `loct find --or A B C` => legacy OR (A|B|C)
                    if opts.queries.len() >= 2 {
                        if opts.or_mode {
                            Some(opts.queries.join("|"))
                        } else {
                            parsed.search_query_mode = SearchQueryMode::Split;
                            parsed.search_queries = opts.queries.clone();
                            None
                        }
                    } else {
                        // Single positional query: if it contains whitespace, treat as AND-mode.
                        let raw = opts.queries[0].trim().to_string();
                        if raw.chars().any(|c| c.is_whitespace()) && !raw.contains('|') {
                            let terms: Vec<String> =
                                raw.split_whitespace().map(|t| t.to_string()).collect();
                            if terms.len() >= 2 {
                                parsed.search_query_mode = SearchQueryMode::And;
                                parsed.search_queries = terms;
                                None
                            } else {
                                Some(raw)
                            }
                        } else {
                            Some(raw)
                        }
                    }
                });
            parsed.symbol = opts.symbol.clone();
            parsed.impact = opts.impact.clone();
            parsed.check_sim = opts.similar.clone();
            parsed.search_dead_only = opts.dead_only;
            parsed.search_exported_only = opts.exported_only;
            parsed.search_lang = opts.lang.clone();
            parsed.search_limit = opts.limit;
            parsed.root_list = vec![PathBuf::from(".")];
        }

        Command::Findings(opts) => {
            parsed.mode = if opts.summary {
                Mode::Summary
            } else {
                Mode::Findings
            };
            parsed.output = OutputMode::Json;
            parsed.root_list = if opts.roots.is_empty() {
                vec![PathBuf::from(".")]
            } else {
                opts.roots.clone()
            };
            parsed.use_gitignore = true;
        }

        Command::Dead(opts) => {
            parsed.mode = Mode::AnalyzeImports;
            parsed.dead_exports = true;
            parsed.root_list = if opts.roots.is_empty() {
                vec![PathBuf::from(".")]
            } else {
                opts.roots.clone()
            };
            parsed.dead_confidence = opts.confidence.clone();
            parsed.top_dead_symbols = if opts.full {
                usize::MAX
            } else if let Some(top) = opts.top {
                top
            } else {
                parsed.top_dead_symbols
            };
            parsed.use_gitignore = true;
            parsed.with_tests = opts.with_tests;
            parsed.with_helpers = opts.with_helpers;
        }

        Command::Cycles(opts) => {
            parsed.mode = Mode::AnalyzeImports;
            parsed.circular = true;
            parsed.root_list = if opts.roots.is_empty() {
                vec![PathBuf::from(".")]
            } else {
                opts.roots.clone()
            };
            parsed.use_gitignore = true;
        }

        Command::Trace(_) => {
            // Trace is handled specially in dispatch_command
        }

        Command::Commands(opts) => {
            // Commands shows Tauri command bridges
            parsed.mode = Mode::AnalyzeImports;
            parsed.tauri_preset = true;
            parsed.root_list = if opts.roots.is_empty() {
                vec![PathBuf::from(".")]
            } else {
                opts.roots.clone()
            };
            parsed.use_gitignore = true;
            parsed.commands_name_filter = opts.name_filter.clone();
            parsed.commands_missing_only = opts.missing_only;
            parsed.commands_unused_only = opts.unused_only;
            parsed.suppress_duplicates = opts.suppress_duplicates;
            parsed.suppress_dynamic = opts.suppress_dynamic;
        }

        Command::Events(opts) => {
            // Events analysis (ghost/orphan/races)
            parsed.mode = Mode::AnalyzeImports;
            parsed.root_list = if opts.roots.is_empty() {
                vec![PathBuf::from(".")]
            } else {
                opts.roots.clone()
            };
            // Enable race detection if specified
            parsed.py_races = opts.races;
            parsed.use_gitignore = true;
            parsed.suppress_duplicates = opts.suppress_duplicates;
            parsed.suppress_dynamic = opts.suppress_dynamic;
        }
        Command::Pipelines(opts) => {
            parsed.mode = Mode::AnalyzeImports;
            parsed.root_list = if opts.roots.is_empty() {
                vec![PathBuf::from(".")]
            } else {
                opts.roots.clone()
            };
            parsed.use_gitignore = true;
        }
        Command::Insights(opts) => {
            parsed.mode = Mode::AnalyzeImports;
            parsed.root_list = if opts.roots.is_empty() {
                vec![PathBuf::from(".")]
            } else {
                opts.roots.clone()
            };
            parsed.use_gitignore = true;
        }
        Command::Manifests(opts) => {
            parsed.mode = Mode::AnalyzeImports;
            parsed.root_list = if opts.roots.is_empty() {
                vec![PathBuf::from(".")]
            } else {
                opts.roots.clone()
            };
            parsed.use_gitignore = true;
        }

        Command::Info(_opts) => {
            // Info command - show snapshot metadata
            // For now, map to Init which will show info if snapshot exists
            parsed.mode = Mode::Init;
            parsed.root_list = vec![PathBuf::from(".")];
        }

        Command::Lint(opts) => {
            parsed.mode = Mode::AnalyzeImports;
            parsed.entrypoints = opts.entrypoints;
            parsed.sarif = opts.sarif;
            parsed.tauri_preset = opts.tauri;
            parsed.root_list = if opts.roots.is_empty() {
                vec![PathBuf::from(".")]
            } else {
                opts.roots.clone()
            };
            if opts.fail {
                parsed.fail_on_missing_handlers = true;
                parsed.fail_on_ghost_events = true;
            }
            parsed.use_gitignore = true;
            parsed.suppress_duplicates = opts.suppress_duplicates;
            parsed.suppress_dynamic = opts.suppress_dynamic;
        }

        Command::Report(opts) => {
            parsed.mode = Mode::AnalyzeImports;
            parsed.auto_outputs = true;
            parsed.root_list = if opts.roots.is_empty() {
                vec![PathBuf::from(".")]
            } else {
                opts.roots.clone()
            };
            if let Some(ref output) = opts.output {
                parsed.report_path = Some(output.clone());
            }
            parsed.serve = opts.serve;
            parsed.serve_port = opts.port;
            if let Some(ref editor) = opts.editor {
                parsed.editor_kind = Some(editor.clone());
            }
            parsed.use_gitignore = true;
        }

        Command::Help(opts) => {
            if opts.legacy {
                parsed.show_help_full = true; // Show legacy help
            } else {
                parsed.show_help = true;
            }
        }

        Command::Version => {
            parsed.show_version = true;
        }

        Command::Query(_) => {
            // Query is handled specially in dispatch_command
            // as it doesn't go through ParsedArgs
        }

        Command::Impact(_) => {
            // Impact is handled specially in dispatch_command
            // as it doesn't go through ParsedArgs
        }

        Command::Diff(_) => {
            // Diff is handled specially in dispatch_command
            // as it doesn't go through ParsedArgs
        }

        Command::Memex(_) => {
            // Memex is handled specially in dispatch_command
            // as it doesn't go through ParsedArgs
        }

        Command::Crowd(_) => {
            // Crowd is handled specially in dispatch_command
            // as it doesn't go through ParsedArgs
        }

        Command::Tagmap(_) => {
            // Tagmap is handled specially in dispatch_command
            // as it doesn't go through ParsedArgs
        }

        Command::Twins(_) => {
            // Twins is handled specially in dispatch_command
            // as it doesn't go through ParsedArgs
        }

        Command::Sniff(_) => {
            // Sniff is handled specially in dispatch_command
            // as it doesn't go through ParsedArgs
        }

        Command::Suppress(_) => {
            // Suppress is handled specially in dispatch_command
            // as it doesn't go through ParsedArgs
        }

        Command::Routes(_) => {
            // Routes is handled specially in dispatch_command
        }

        Command::Dist(_) => {
            // Dist is handled specially in dispatch_command
        }

        Command::Coverage(_) => {
            // Coverage is handled specially in dispatch_command
        }

        Command::JqQuery(_) => {
            // JqQuery is handled specially in dispatch_command
            // It doesn't use ParsedArgs, will be handled by jaq executor
        }

        Command::Focus(_) => {
            // Focus is handled specially in dispatch_command
            // as it doesn't go through ParsedArgs
        }

        Command::Hotspots(_) => {
            // Hotspots is handled specially in dispatch_command
            // as it doesn't go through ParsedArgs
        }

        Command::Layoutmap(_) => {
            // Layoutmap is handled specially in dispatch_command
            // as it doesn't go through ParsedArgs
        }

        Command::Zombie(_) => {
            // Zombie is handled specially in dispatch_command
            // as it doesn't go through ParsedArgs
        }

        Command::Health(_) => {
            // Health is handled specially in dispatch_command
            // as it doesn't go through ParsedArgs
        }

        Command::Audit(_) => {
            // Audit is handled specially in dispatch_command
            // as it doesn't go through ParsedArgs
        }

        Command::Doctor(_) => {
            // Doctor is handled specially in dispatch_command
            // as it doesn't go through ParsedArgs
        }

        Command::Plan(_) => {
            // Plan is handled specially in dispatch_command
            // as it doesn't go through ParsedArgs
        }

        Command::Cache(_) => {
            // Cache is handled specially in dispatch_command
        }
    }

    parsed
}

/// Result type for command dispatch.
pub enum DispatchResult {
    /// Command was handled, return this exit code
    Exit(i32),
    /// Show main help
    ShowHelp,
    /// Show legacy help
    ShowLegacyHelp,
    /// Show version
    ShowVersion,
    /// Continue with normal execution using ParsedArgs (boxed to reduce enum size)
    Continue(Box<ParsedArgs>),
}

/// Dispatch a parsed command.
///
/// Returns a DispatchResult indicating what action to take.
pub fn dispatch_command(parsed_cmd: &ParsedCommand) -> DispatchResult {
    // Emit deprecation warning if this was from legacy syntax
    parsed_cmd.emit_deprecation_warning();

    // Handle special cases first
    match &parsed_cmd.command {
        Command::Help(opts) if opts.legacy => {
            return DispatchResult::ShowLegacyHelp;
        }
        Command::Help(opts) if opts.full => {
            return DispatchResult::ShowLegacyHelp; // Full help shows legacy too
        }
        Command::Help(opts) if opts.command.is_some() => {
            let cmd_name = opts.command.clone().unwrap();
            if let Some(text) = Command::format_command_help(&cmd_name) {
                println!("{}", text);
                return DispatchResult::Exit(0);
            } else {
                eprintln!(
                    "Unknown command '{}'. Run 'loct --help' for available commands.",
                    cmd_name
                );
                return DispatchResult::Exit(1);
            }
        }
        Command::Help(_) => {
            return DispatchResult::ShowHelp;
        }
        Command::Version => {
            return DispatchResult::ShowVersion;
        }
        Command::Query(opts) => {
            // Execute query and return result
            return handlers::query::handle_query_command(opts, &parsed_cmd.global);
        }
        Command::Impact(opts) => {
            // Execute impact analysis and return result
            return handlers::diff::handle_impact_command(opts, &parsed_cmd.global);
        }
        Command::Diff(opts) => {
            // Execute diff and return result
            return handlers::diff::handle_diff_command(opts, &parsed_cmd.global);
        }
        Command::Memex(opts) => {
            // Execute memex and return result
            return handlers::ai::handle_memex_command(opts, &parsed_cmd.global);
        }
        Command::Crowd(opts) => {
            return handlers::ai::handle_crowd_command(opts, &parsed_cmd.global);
        }
        Command::Tagmap(opts) => {
            return handlers::ai::handle_tagmap_command(opts, &parsed_cmd.global);
        }
        Command::Twins(opts) => {
            return handlers::ai::handle_twins_command(opts, &parsed_cmd.global);
        }
        Command::Sniff(opts) => {
            return handlers::ai::handle_sniff_command(opts, &parsed_cmd.global);
        }
        Command::Suppress(opts) => {
            return handlers::ai::handle_suppress_command(opts, &parsed_cmd.global);
        }
        Command::Dead(opts) => {
            return handlers::analysis::handle_dead_command(opts, &parsed_cmd.global);
        }
        Command::Cycles(opts) => {
            return handlers::analysis::handle_cycles_command(opts, &parsed_cmd.global);
        }
        Command::Trace(opts) => {
            return handlers::analysis::handle_trace_command(opts, &parsed_cmd.global);
        }
        Command::Commands(opts) => {
            return handlers::analysis::handle_commands_command(opts, &parsed_cmd.global);
        }
        Command::Routes(opts) => {
            return handlers::analysis::handle_routes_command(opts, &parsed_cmd.global);
        }
        Command::Events(opts) => {
            return handlers::analysis::handle_events_command(opts, &parsed_cmd.global);
        }
        Command::Pipelines(opts) => {
            return handlers::analysis::handle_pipelines_command(opts, &parsed_cmd.global);
        }
        Command::Insights(opts) => {
            return handlers::analysis::handle_insights_command(opts, &parsed_cmd.global);
        }
        Command::Manifests(opts) => {
            return handlers::analysis::handle_manifests_command(opts, &parsed_cmd.global);
        }
        Command::Lint(opts) => {
            return handlers::output::handle_lint_command(opts, &parsed_cmd.global);
        }
        Command::Dist(opts) => {
            return handlers::output::handle_dist_command(opts, &parsed_cmd.global);
        }
        Command::Coverage(opts) => {
            return handlers::watch::handle_coverage_command(opts, &parsed_cmd.global);
        }
        Command::JqQuery(opts) => {
            return handlers::query::handle_jq_query_command(opts, &parsed_cmd.global);
        }
        Command::Focus(opts) => {
            return handlers::analysis::handle_focus_command(opts, &parsed_cmd.global);
        }
        Command::Hotspots(opts) => {
            return handlers::analysis::handle_hotspots_command(opts, &parsed_cmd.global);
        }
        Command::Layoutmap(opts) => {
            return handlers::analysis::handle_layoutmap_command(opts, &parsed_cmd.global);
        }
        Command::Zombie(opts) => {
            return handlers::analysis::handle_zombie_command(opts, &parsed_cmd.global);
        }
        Command::Health(opts) => {
            return handlers::analysis::handle_health_command(opts, &parsed_cmd.global);
        }
        Command::Audit(opts) => {
            return handlers::analysis::handle_audit_command(opts, &parsed_cmd.global);
        }
        Command::Doctor(opts) => {
            return handlers::analysis::handle_doctor_command(opts, &parsed_cmd.global);
        }
        Command::Plan(opts) => {
            return handlers::analysis::handle_plan_command(opts, &parsed_cmd.global);
        }
        Command::Cache(opts) => {
            return handlers::cache::handle_cache_command(opts);
        }
        Command::Scan(opts) if opts.watch => {
            return handlers::watch::handle_scan_watch_command(opts, &parsed_cmd.global);
        }
        // Note: Command::Report falls through to ParsedArgs flow to use full analysis pipeline
        // which includes twins data, graph visualization, and proper Leptos SSR rendering
        _ => {}
    }

    // Convert to ParsedArgs for the existing handlers
    let parsed_args = command_to_parsed_args(&parsed_cmd.command, &parsed_cmd.global);
    DispatchResult::Continue(Box::new(parsed_args))
}

/// Load existing snapshot or create one if missing (used by handler submodules)
///
/// Respects global flags:
/// - `--fresh`: Force rescan even if snapshot exists
/// - `--no-scan`: Fail if no snapshot exists (don't auto-scan)
/// - `--fail-stale`: Fail if snapshot git_head differs from current HEAD
pub(crate) fn load_or_create_snapshot_for_roots(
    roots: &[std::path::PathBuf],
    global: &GlobalOptions,
) -> std::io::Result<crate::snapshot::Snapshot> {
    use crate::args::ParsedArgs;
    use crate::snapshot::Snapshot;
    use crate::snapshot::resolve_snapshot_root;

    let snapshot_root = resolve_snapshot_root(roots);
    let requested_roots =
        normalize_roots_for_scope_compare(roots.iter().map(|p| p.as_path()), &snapshot_root);

    // If --fresh, skip loading and go straight to scan
    if !global.fresh {
        match Snapshot::load(&snapshot_root) {
            Ok(s) => {
                // Guard against stale scope reuse: if snapshot roots differ from requested roots,
                // force a rescan (or fail with --no-scan).
                let snapshot_roots = normalize_roots_for_scope_compare(
                    s.metadata.roots.iter().map(std::path::Path::new),
                    &snapshot_root,
                );
                if requested_roots != snapshot_roots {
                    if global.no_scan {
                        return Err(std::io::Error::other(format!(
                            "Snapshot scope mismatch and --no-scan is set.\nrequested roots: [{}]\nsnapshot roots:  [{}]\nRun `loct scan` (or the command without --no-scan) to refresh scope.",
                            requested_roots.join(", "),
                            snapshot_roots.join(", ")
                        )));
                    }
                    if !global.quiet {
                        eprintln!(
                            "[loct] Snapshot roots differ from requested roots; refreshing snapshot scope.\n  requested: [{}]\n  snapshot:  [{}]",
                            requested_roots.join(", "),
                            snapshot_roots.join(", ")
                        );
                    }
                } else if s.is_stale(&snapshot_root) {
                    // Snapshot is stale (git HEAD moved or worktree dirty).
                    // --fail-stale / --no-scan: hard fail for CI pipelines.
                    // Default: auto-rescan to keep data fresh (core refactoring workflow).
                    if global.fail_stale || global.no_scan {
                        let snap_commit = s.metadata.git_commit.as_deref().unwrap_or("unknown");
                        let current = get_current_git_head(&snapshot_root)
                            .unwrap_or_else(|| "unknown".into());
                        return Err(std::io::Error::other(format!(
                            "Snapshot is stale: snapshot commit={} but current HEAD={}. Run 'loct scan' to refresh.",
                            &snap_commit[..7.min(snap_commit.len())],
                            &current[..7.min(current.len())]
                        )));
                    }
                    if !global.quiet {
                        eprintln!("[loct] Snapshot stale, rescanning...");
                    }
                } else {
                    // Snapshot is fresh — use it directly.
                    return Ok(s);
                }
            }
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                // No snapshot - check if --no-scan forbids auto-scan
                if global.no_scan {
                    return Err(std::io::Error::other(
                        "No snapshot found and --no-scan is set. Run 'loct' first to create a snapshot.",
                    ));
                }
                if !global.quiet {
                    eprintln!("[loct] No snapshot found, running initial scan...");
                }
            }
            Err(e) => return Err(e), // Other errors (corruption, etc.) - fail
        }
    } else {
        // --fresh: force rescan
        if !global.quiet {
            eprintln!("[loct] --fresh: forcing rescan...");
        }
    }

    // Create minimal ParsedArgs for scan, propagating output mode
    let parsed = ParsedArgs {
        verbose: global.verbose,
        use_gitignore: true,
        output: if global.json {
            OutputMode::Json
        } else {
            OutputMode::Human
        },
        ..Default::default()
    };

    // Run scan (suppress summary in json/quiet mode to keep stdout clean)
    crate::snapshot::run_init_with_options(roots, &parsed, global.json || global.quiet)?;

    // Now load the freshly created snapshot
    Snapshot::load(&snapshot_root)
}

/// Normalize root paths for scope comparison between requested roots and snapshot metadata.
///
/// - Resolves relative paths against snapshot_root
/// - Canonicalizes when possible
/// - Normalizes separators
/// - Sorts and deduplicates
fn normalize_roots_for_scope_compare<'a, I>(
    roots: I,
    snapshot_root: &std::path::Path,
) -> Vec<String>
where
    I: Iterator<Item = &'a std::path::Path>,
{
    let mut normalized = Vec::new();
    for root in roots {
        let candidate = if root.is_absolute() {
            root.to_path_buf()
        } else {
            snapshot_root.join(root)
        };
        let canon = candidate.canonicalize().unwrap_or(candidate);
        normalized.push(canon.to_string_lossy().replace('\\', "/"));
    }
    normalized.sort();
    normalized.dedup();
    normalized
}

pub(crate) fn load_or_create_snapshot(
    root: &std::path::Path,
    global: &GlobalOptions,
) -> std::io::Result<crate::snapshot::Snapshot> {
    let root_list = vec![root.to_path_buf()];
    load_or_create_snapshot_for_roots(&root_list, global)
}

/// Get current git HEAD commit hash
fn get_current_git_head(root: &std::path::Path) -> Option<String> {
    std::process::Command::new("git")
        .args(["rev-parse", "HEAD"])
        .current_dir(root)
        .output()
        .ok()
        .and_then(|output| {
            if output.status.success() {
                String::from_utf8(output.stdout)
                    .ok()
                    .map(|s| s.trim().to_string())
            } else {
                None
            }
        })
}

/// Check if a file is a test file (used by handler submodules)
pub(crate) fn is_test_file(path: &str) -> bool {
    let path_lower = path.to_lowercase();
    let filename = std::path::Path::new(path)
        .file_name()
        .and_then(|f| f.to_str())
        .unwrap_or("")
        .to_lowercase();

    // Directory patterns: tests/, __tests__/, test/, spec/
    if path_lower.contains("/tests/")
        || path_lower.contains("/__tests__/")
        || path_lower.contains("/test/")
        || path_lower.contains("/spec/")
        || path_lower.contains("/fixtures/")
        || path_lower.contains("/mocks/")
    {
        return true;
    }

    // File patterns: *_test.*, *.test.*, *_spec.*, *.spec.*, test_*, tests.*
    if filename.contains("_test.")
        || filename.contains(".test.")
        || filename.contains("_spec.")
        || filename.contains(".spec.")
        || filename.contains("_tests.") // Rust: module_tests.rs
        || filename.starts_with("test_")
        || filename.starts_with("spec_")
        || filename.starts_with("tests.") // tests.rs
        || filename == "conftest.py"
    {
        return true;
    }

    false
}

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

    #[test]
    fn test_auto_command_to_parsed_args() {
        let cmd = Command::Auto(AutoOptions {
            roots: vec![PathBuf::from(".")],
            full_scan: true,
            scan_all: false,
            for_agent_feed: false,
            agent_json: false,
            suppress_duplicates: false,
            suppress_dynamic: false,
        });
        let global = GlobalOptions::default();
        let parsed = command_to_parsed_args(&cmd, &global);

        assert!(matches!(parsed.mode, Mode::Init));
        assert!(parsed.full_scan);
        assert!(!parsed.scan_all);
    }

    #[test]
    fn test_dead_command_to_parsed_args() {
        let cmd = Command::Dead(DeadOptions {
            roots: vec![],
            confidence: Some("high".into()),
            top: Some(10),
            full: false,
            path_filter: None,
            with_tests: false,
            with_helpers: false,
            with_shadows: false,
            with_ambient: false,
            with_dynamic: false,
        });
        let global = GlobalOptions {
            json: true,
            ..Default::default()
        };
        let parsed = command_to_parsed_args(&cmd, &global);

        assert!(matches!(parsed.mode, Mode::AnalyzeImports));
        assert!(parsed.dead_exports);
        assert_eq!(parsed.dead_confidence, Some("high".into()));
        assert_eq!(parsed.top_dead_symbols, 10);
        assert!(!parsed.with_tests);
        assert!(!parsed.with_helpers);
        assert!(matches!(parsed.output, OutputMode::Json));
    }

    #[test]
    fn test_tree_command_to_parsed_args() {
        let cmd = Command::Tree(TreeOptions {
            roots: vec![PathBuf::from("src")],
            depth: Some(3),
            summary: Some(5),
            summary_only: false,
            loc_threshold: Some(500),
            show_hidden: true,
            find_artifacts: false,
            show_ignored: false,
        });
        let global = GlobalOptions::default();
        let parsed = command_to_parsed_args(&cmd, &global);

        assert!(matches!(parsed.mode, Mode::Tree));
        assert_eq!(parsed.max_depth, Some(3));
        assert!(parsed.summary);
        assert_eq!(parsed.summary_limit, 5);
        assert_eq!(parsed.loc_threshold, 500);
        assert!(parsed.show_hidden);
    }

    #[test]
    fn test_parse_findings_command_to_parsed_args() {
        let cmd = Command::Findings(FindingsOptions {
            roots: vec![PathBuf::from("src")],
            summary: true,
        });
        let global = GlobalOptions::default();
        let parsed = command_to_parsed_args(&cmd, &global);

        assert!(matches!(parsed.mode, Mode::Summary));
        assert!(matches!(parsed.output, OutputMode::Json));
        assert_eq!(parsed.root_list, vec![PathBuf::from("src")]);
    }

    #[test]
    fn test_slice_command_to_parsed_args() {
        let cmd = Command::Slice(SliceOptions {
            target: "src/main.rs".into(),
            root: None,
            consumers: true,
            depth: None,
            rescan: false,
        });
        let global = GlobalOptions {
            json: true,
            ..Default::default()
        };
        let parsed = command_to_parsed_args(&cmd, &global);

        assert!(matches!(parsed.mode, Mode::Slice));
        assert_eq!(parsed.slice_target, Some("src/main.rs".into()));
        assert!(parsed.slice_consumers);
        assert!(matches!(parsed.output, OutputMode::Json));
    }

    #[test]
    fn test_normalize_roots_for_scope_compare_relative_and_absolute_match() {
        let tmp = TempDir::new().expect("temp dir");
        std::fs::create_dir_all(tmp.path().join("src")).expect("create src");

        let relative = normalize_roots_for_scope_compare(
            [std::path::Path::new("src")].into_iter(),
            tmp.path(),
        );
        let absolute = normalize_roots_for_scope_compare(
            [tmp.path().join("src")].iter().map(|p| p.as_path()),
            tmp.path(),
        );

        assert_eq!(relative, absolute);
        assert_eq!(relative.len(), 1);
    }

    #[test]
    fn test_normalize_roots_for_scope_compare_sorted_and_deduped() {
        let tmp = TempDir::new().expect("temp dir");
        std::fs::create_dir_all(tmp.path().join("a")).expect("create a");
        std::fs::create_dir_all(tmp.path().join("b")).expect("create b");

        let normalized = normalize_roots_for_scope_compare(
            [
                std::path::Path::new("b"),
                std::path::Path::new("./a"),
                std::path::Path::new("b"),
            ]
            .into_iter(),
            tmp.path(),
        );

        assert_eq!(normalized.len(), 2);
        assert!(normalized[0] <= normalized[1]);
    }

    #[test]
    fn test_find_multi_arg_defaults_to_split_mode() {
        let cmd = Command::Find(FindOptions {
            queries: vec!["Props".into(), "Options".into(), "ViewModel".into()],
            ..Default::default()
        });
        let global = GlobalOptions::default();
        let parsed = command_to_parsed_args(&cmd, &global);

        assert!(matches!(parsed.mode, Mode::Search));
        assert!(matches!(parsed.search_query_mode, SearchQueryMode::Split));
        assert_eq!(parsed.search_queries, vec!["Props", "Options", "ViewModel"]);
        assert!(parsed.search_query.is_none());
    }

    #[test]
    fn test_find_single_arg_with_spaces_defaults_to_and_mode() {
        let cmd = Command::Find(FindOptions {
            queries: vec!["Props Options ViewModel".into()],
            ..Default::default()
        });
        let global = GlobalOptions::default();
        let parsed = command_to_parsed_args(&cmd, &global);

        assert!(matches!(parsed.mode, Mode::Search));
        assert!(matches!(parsed.search_query_mode, SearchQueryMode::And));
        assert_eq!(parsed.search_queries, vec!["Props", "Options", "ViewModel"]);
        assert!(parsed.search_query.is_none());
    }

    #[test]
    fn test_find_multi_arg_can_force_legacy_or_mode() {
        let cmd = Command::Find(FindOptions {
            queries: vec!["Props".into(), "Options".into()],
            or_mode: true,
            ..Default::default()
        });
        let global = GlobalOptions::default();
        let parsed = command_to_parsed_args(&cmd, &global);

        assert!(matches!(parsed.mode, Mode::Search));
        assert!(matches!(parsed.search_query_mode, SearchQueryMode::Single));
        assert_eq!(parsed.search_query.as_deref(), Some("Props|Options"));
        assert!(parsed.search_queries.is_empty());
    }

    #[test]
    fn test_find_single_arg_with_pipe_stays_single_mode() {
        let cmd = Command::Find(FindOptions {
            queries: vec!["Props|Options|ViewModel".into()],
            ..Default::default()
        });
        let global = GlobalOptions::default();
        let parsed = command_to_parsed_args(&cmd, &global);

        assert!(matches!(parsed.mode, Mode::Search));
        assert!(matches!(parsed.search_query_mode, SearchQueryMode::Single));
        assert_eq!(
            parsed.search_query.as_deref(),
            Some("Props|Options|ViewModel")
        );
        assert!(parsed.search_queries.is_empty());
    }

    #[test]
    fn test_dispatch_help_command() {
        let parsed_cmd = ParsedCommand::new(
            Command::Help(HelpOptions::default()),
            GlobalOptions::default(),
        );
        let result = dispatch_command(&parsed_cmd);
        assert!(matches!(result, DispatchResult::ShowHelp));
    }

    #[test]
    fn test_dispatch_legacy_help_command() {
        let parsed_cmd = ParsedCommand::new(
            Command::Help(HelpOptions {
                legacy: true,
                ..Default::default()
            }),
            GlobalOptions::default(),
        );
        let result = dispatch_command(&parsed_cmd);
        assert!(matches!(result, DispatchResult::ShowLegacyHelp));
    }

    #[test]
    fn test_dispatch_version_command() {
        let parsed_cmd = ParsedCommand::new(Command::Version, GlobalOptions::default());
        let result = dispatch_command(&parsed_cmd);
        assert!(matches!(result, DispatchResult::ShowVersion));
    }

    #[test]
    fn test_crowd_command_to_dispatch() {
        let tmp = TempDir::new().expect("temp dir");
        let parsed_cmd = ParsedCommand::new(
            Command::Crowd(CrowdOptions {
                pattern: Some("message".into()),
                roots: vec![tmp.path().to_path_buf()],
                ..Default::default()
            }),
            GlobalOptions::default(),
        );
        // Verify dispatch completes without scanning the live repo under the current working directory.
        let result = dispatch_command(&parsed_cmd);
        assert!(matches!(result, DispatchResult::Exit(_)));
    }
}