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
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
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
//! Twins Module - Semantic Duplicate Detection
//!
//! Finds two types of code issues:
//! 1. **Dead Parrots**: Exported symbols with zero imports
//! 2. **Exact Twins**: Symbols with the same name exported from different files
//!
//! These are candidates for removal or consolidation.
//!
//! # Philosophy
//!
//! Not all exports need imports to be useful:
//! - Library entry points (lib.rs, index.ts)
//! - CLI handlers (main.rs)
//! - Test fixtures
//! - Framework magic (Next.js pages, Tauri commands)
//!
//! This module focuses on **internal application code** where zero imports
//! or duplicate names usually indicate dead code or naming conflicts.

use serde::Serialize;
use std::collections::HashMap;

use crate::types::{FileAnalysis, OutputMode};

/// A single symbol entry in the registry
#[derive(Debug, Clone, Serialize)]
pub struct SymbolEntry {
    /// Symbol name
    pub name: String,
    /// Symbol kind (function, type, const, class, interface, re-export)
    pub kind: String,
    /// File path where symbol is exported
    pub file_path: String,
    /// Line number (if available)
    pub line: usize,
    /// Number of files that import this symbol
    pub import_count: usize,
}

/// Result of twins analysis
#[derive(Debug, Clone, Serialize)]
pub struct TwinsResult {
    /// All dead parrots (0 imports)
    pub dead_parrots: Vec<SymbolEntry>,
    /// Total symbols analyzed
    pub total_symbols: usize,
    /// Total files analyzed
    pub total_files: usize,
}

/// Build symbol registry from file analyses
///
/// Counts how many times each symbol is imported across the codebase.
/// If `include_tests` is false, test files and fixtures are excluded.
pub fn build_symbol_registry(
    analyses: &[FileAnalysis],
    include_tests: bool,
) -> HashMap<(String, String), SymbolEntry> {
    use crate::analyzer::classify::should_exclude_from_reports;
    let mut registry: HashMap<(String, String), SymbolEntry> = HashMap::new();

    // First pass: Register all exports
    for analysis in analyses {
        // Skip test files to avoid pytest/Jest fixtures being treated as dead parrots
        if !include_tests && analysis.is_test {
            continue;
        }
        // Skip test fixtures and mock files
        if !include_tests && should_exclude_from_reports(&analysis.path) {
            continue;
        }
        for export in &analysis.exports {
            let key = (analysis.path.clone(), export.name.clone());
            registry.insert(
                key,
                SymbolEntry {
                    name: export.name.clone(),
                    kind: export.kind.clone(),
                    file_path: analysis.path.clone(),
                    line: export.line.unwrap_or(0),
                    import_count: 0,
                },
            );
        }
    }

    // Second pass: Count imports
    for analysis in analyses {
        for import in &analysis.imports {
            // Get resolved path (or fall back to source)
            let target_path = import.resolved_path.as_ref().unwrap_or(&import.source);

            // Count each imported symbol
            for symbol in &import.symbols {
                let symbol_name = if symbol.is_default {
                    "default".to_string()
                } else {
                    symbol.name.clone()
                };

                let key = (target_path.clone(), symbol_name);
                if let Some(entry) = registry.get_mut(&key) {
                    entry.import_count += 1;
                }
            }
        }
    }

    registry
}

/// Check if a file is an entry point that shouldn't have dead parrot warnings
fn is_entry_point(path: &str) -> bool {
    // Rust crate roots
    path == "lib.rs"
        || path == "main.rs"
        || path.ends_with("/lib.rs")
        || path.ends_with("/main.rs")
        // TypeScript/JavaScript index entry points
        || path.ends_with("/index.ts")
        || path.ends_with("/index.tsx")
        || path.ends_with("/index.js")
        || path.ends_with("/index.jsx")
        || path.ends_with("/index.mjs")
        // TypeScript/JavaScript App entry points (React, Vue, Tauri, etc.)
        || path.ends_with("/App.tsx")
        || path.ends_with("/App.jsx")
        || path.ends_with("/App.ts")
        || path.ends_with("/App.js")
        || path.ends_with("/app.tsx")
        || path.ends_with("/app.jsx")
        // TypeScript/JavaScript main entry points (Vite, Tauri, Electron, etc.)
        || path.ends_with("/main.ts")
        || path.ends_with("/main.tsx")
        || path.ends_with("/main.js")
        || path.ends_with("/main.jsx")
        // Next.js special files (App Router + Pages Router)
        || path.ends_with("/_app.tsx")
        || path.ends_with("/_app.jsx")
        || path.ends_with("/_document.tsx")
        || path.ends_with("/_document.jsx")
        || path.ends_with("/layout.tsx")
        || path.ends_with("/layout.jsx")
        || path.ends_with("/page.tsx")
        || path.ends_with("/page.jsx")
        // Python package roots
        || path.ends_with("/__init__.py")
        // Go package main
        || (path.ends_with(".go") && path.contains("/cmd/"))
        // Custom application entry points (common naming patterns)
        || is_application_entry_pattern(path)
}

/// Check if file matches common application entry point naming patterns
fn is_application_entry_pattern(path: &str) -> bool {
    // Extract filename from path
    let filename = path.rsplit('/').next().unwrap_or(path);
    let name_lower = filename.to_lowercase();

    // Common entry point patterns (case-insensitive base check)
    // MainApplication.tsx, AppEntry.ts, Bootstrap.tsx, etc.
    let entry_patterns = [
        "application.", // MainApplication.tsx, Application.tsx
        "bootstrap.",   // Bootstrap.tsx, bootstrap.ts
        "entry.",       // Entry.tsx, AppEntry.ts
        "appshell.",    // AppShell.tsx
        "appinit.",     // AppInit.tsx
    ];

    for pattern in entry_patterns {
        if name_lower.contains(pattern) {
            return true;
        }
    }

    // Also check for app-shell directory pattern (common in Tauri/Electron)
    if path.contains("/app-shell/") || path.contains("/app_shell/") {
        return true;
    }

    false
}

/// Check if a file is a mod.rs (Rust module declaration file)
fn is_mod_rs(path: &str) -> bool {
    path == "mod.rs" || path.ends_with("/mod.rs")
}

/// Check if export is a common framework magic pattern
fn is_framework_magic(name: &str, kind: &str) -> bool {
    // Python dunder methods
    if name.starts_with("__") && name.ends_with("__") {
        return true;
    }
    // React/Svelte component conventions (PascalCase default exports)
    if kind == "default"
        && name
            .chars()
            .next()
            .map(|c| c.is_uppercase())
            .unwrap_or(false)
    {
        return true;
    }
    // Common framework hooks
    if name.starts_with("use")
        && name.len() > 3
        && name
            .chars()
            .nth(3)
            .map(|c| c.is_uppercase())
            .unwrap_or(false)
    {
        return true;
    }
    // Django/Python mixins
    if kind == "class" && name.ends_with("Mixin") {
        return true;
    }
    // Rust trait implementations often not directly imported
    if kind == "impl" || kind == "trait" {
        return true;
    }
    false
}

/// Check if symbol name is a common re-export pattern (barrel exports)
fn is_barrel_reexport(_name: &str, kind: &str) -> bool {
    // Re-exports are not dead - they're forwarding from another module
    kind == "re-export" || kind == "reexport"
}

/// Find dead parrots - symbols with 0 imports
pub fn find_dead_parrots(
    analyses: &[FileAnalysis],
    _dead_only: bool,
    include_tests: bool,
) -> TwinsResult {
    let registry = build_symbol_registry(analyses, include_tests);

    // Build set of Tauri handlers (registered commands)
    let tauri_handlers: std::collections::HashSet<String> = analyses
        .iter()
        .flat_map(|a| a.tauri_registered_handlers.iter().cloned())
        .collect();

    // Build set of locally used symbols per file
    let all_local_uses: std::collections::HashSet<String> = analyses
        .iter()
        .flat_map(|a| a.local_uses.iter().cloned())
        .collect();

    // Build set of all imported symbol names (fallback for unresolved paths)
    let all_imported_names: std::collections::HashSet<String> = analyses
        .iter()
        .flat_map(|a| a.imports.iter())
        .flat_map(|imp| imp.symbols.iter())
        .map(|sym| {
            if sym.is_default {
                "default".to_string()
            } else {
                sym.name.clone()
            }
        })
        .collect();

    // Build set of dynamically imported file paths (React lazy, Vue async components, etc.)
    // These typically import the default export, so we track which files are dynamically imported
    // Use normalize_module_id to get consistent path format for matching
    use super::root_scan::normalize_module_id;
    use crate::types::ImportKind;

    // Build set of normalized file paths that are dynamically imported
    let mut dynamic_import_targets: std::collections::HashSet<String> =
        std::collections::HashSet::new();

    // First, collect from ImportEntry items with ImportKind::Dynamic (has resolved_path)
    // This is more reliable than raw dynamic_imports strings
    for analysis in analyses {
        for imp in &analysis.imports {
            if matches!(imp.kind, ImportKind::Dynamic) {
                // Use resolved path if available (most reliable)
                if let Some(resolved) = &imp.resolved_path {
                    dynamic_import_targets.insert(normalize_module_id(resolved).as_key());
                }
                // Also add the raw source path normalized
                dynamic_import_targets.insert(normalize_module_id(&imp.source).as_key());
            }
        }
    }

    // Also check raw dynamic_imports strings as fallback and for matching
    for analysis in analyses {
        for dyn_imp in &analysis.dynamic_imports {
            let dyn_norm = normalize_module_id(dyn_imp);
            dynamic_import_targets.insert(dyn_norm.as_key());

            // Also add suffix-matched files (handles ./components/X matching src/components/X)
            let dyn_alias = dyn_norm
                .path
                .trim_start_matches("./")
                .trim_start_matches('@')
                .to_string();
            for a in analyses {
                let a_norm = normalize_module_id(&a.path);
                if a_norm.path.ends_with(&dyn_alias) {
                    dynamic_import_targets.insert(a_norm.as_key());
                }
            }
        }
    }

    let mut dead_parrots: Vec<SymbolEntry> = registry
        .values()
        .filter(|entry| {
            // Skip if has imports
            if entry.import_count > 0 {
                return false;
            }
            // Skip Tauri commands
            if tauri_handlers.contains(&entry.name) {
                return false;
            }
            // Skip locally used symbols
            if all_local_uses.contains(&entry.name) {
                return false;
            }
            // Skip if imported by name anywhere (handles unresolved paths)
            if all_imported_names.contains(&entry.name) {
                return false;
            }
            // Skip entry points (lib.rs, index.ts, __init__.py, etc.)
            if is_entry_point(&entry.file_path) {
                return false;
            }
            // Skip mod.rs files (Rust module declarations)
            if is_mod_rs(&entry.file_path) {
                return false;
            }
            // Skip framework magic patterns
            if is_framework_magic(&entry.name, &entry.kind) {
                return false;
            }
            // Skip barrel re-exports
            if is_barrel_reexport(&entry.name, &entry.kind) {
                return false;
            }
            // Skip default exports from dynamically imported files (React lazy, Vue async, etc.)
            // Dynamic imports like lazy(() => import('./Component')) only consume the default export
            // Normalize the file path the same way dynamic imports are normalized
            let file_norm = normalize_module_id(&entry.file_path).as_key();
            if dynamic_import_targets.contains(&file_norm) {
                return false;
            }
            true
        })
        .cloned()
        .collect();

    // Sort by file path, then symbol name for consistent output
    dead_parrots.sort_by(|a, b| {
        a.file_path
            .cmp(&b.file_path)
            .then_with(|| a.name.cmp(&b.name))
    });

    TwinsResult {
        dead_parrots,
        total_symbols: registry.len(),
        total_files: analyses.len(),
    }
}

/// Print twins results in human-readable format
pub fn print_twins_human(result: &TwinsResult) {
    if result.dead_parrots.is_empty() {
        println!("No dead parrots found - all exports are imported!");
        return;
    }

    println!("DEAD PARROTS ({} found)", result.dead_parrots.len());
    println!();

    // Group by file for cleaner output
    let mut by_file: HashMap<String, Vec<&SymbolEntry>> = HashMap::new();
    for entry in &result.dead_parrots {
        by_file
            .entry(entry.file_path.clone())
            .or_default()
            .push(entry);
    }

    let mut files: Vec<_> = by_file.keys().collect();
    files.sort();

    for file in files {
        let entries = &by_file[file];
        println!("  {}", file);
        for entry in entries {
            println!(
                "    ├─ {} ({}:{}) - {} imports",
                entry.name, entry.kind, entry.line, entry.import_count
            );
        }
        println!();
    }

    println!("Summary:");
    println!("  Total symbols: {}", result.total_symbols);
    println!("  Dead parrots: {}", result.dead_parrots.len());
    println!("  Files analyzed: {}", result.total_files);
}

/// Print twins results in JSON format
pub fn print_twins_json(result: &TwinsResult) {
    let output = serde_json::json!({
        "dead_parrots": result.dead_parrots.iter().map(|e| {
            serde_json::json!({
                "name": e.name,
                "file": e.file_path,
                "line": e.line,
                "kind": e.kind,
                "import_count": e.import_count,
            })
        }).collect::<Vec<_>>(),
        "summary": {
            "symbols": result.total_symbols,
            "files": result.total_files,
            "dead_parrots": result.dead_parrots.len(),
        }
    });

    println!("{}", serde_json::to_string_pretty(&output).unwrap());
}

/// Print twins results based on output mode
pub fn print_twins_result(result: &TwinsResult, output: OutputMode) {
    match output {
        OutputMode::Json | OutputMode::Jsonl => print_twins_json(result),
        OutputMode::Human => print_twins_human(result),
    }
}

// ============================================================================
// EXACT TWIN DETECTION
// ============================================================================

/// A location where an exact twin symbol is found
#[derive(Clone, Debug, Serialize)]
pub struct TwinLocation {
    /// File path where the symbol is exported
    pub file_path: String,
    /// Line number (1-based)
    pub line: usize,
    /// Export kind: "export", "re-export", "type", "default", etc.
    pub kind: String,
    /// Number of imports of this specific export
    pub import_count: usize,
    /// True if this is the "source of truth" (canonical definition)
    pub is_canonical: bool,
    /// Signature fingerprint for functions (sorted types used in params/return)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signature_fingerprint: Option<String>,
}

/// An exact twin - a symbol exported from multiple files
#[derive(Clone, Debug, Serialize)]
pub struct ExactTwin {
    /// Symbol name
    pub name: String,
    /// All locations where this symbol is exported
    pub locations: Vec<TwinLocation>,
    /// Signature similarity score (0.0 = different, 1.0 = identical signatures)
    /// None if signatures couldn't be computed (non-functions, missing data)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signature_similarity: Option<f32>,
}

/// Language category for twin classification
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)]
pub enum Language {
    TypeScript,
    JavaScript,
    Rust,
    Python,
    Go,
    Other,
}

/// Twin category based on language distribution
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub enum TwinCategory {
    /// All locations are in the same language (likely a real duplicate)
    SameLanguage(Language),
    /// Locations span multiple languages (likely intentional FE/BE pair)
    CrossLanguage,
}

/// Detect language from file extension
pub fn detect_language(path: &str) -> Language {
    if path.ends_with(".ts") || path.ends_with(".tsx") || path.ends_with(".mts") {
        Language::TypeScript
    } else if path.ends_with(".js")
        || path.ends_with(".jsx")
        || path.ends_with(".mjs")
        || path.ends_with(".cjs")
    {
        Language::JavaScript
    } else if path.ends_with(".rs") {
        Language::Rust
    } else if path.ends_with(".py") || path.ends_with(".pyi") {
        Language::Python
    } else if path.ends_with(".go") {
        Language::Go
    } else {
        Language::Other
    }
}

/// Categorize a twin based on languages of its locations
pub fn categorize_twin(twin: &ExactTwin) -> TwinCategory {
    let languages: std::collections::HashSet<Language> = twin
        .locations
        .iter()
        .map(|loc| detect_language(&loc.file_path))
        .collect();

    if languages.len() == 1 {
        TwinCategory::SameLanguage(languages.into_iter().next().unwrap())
    } else {
        TwinCategory::CrossLanguage
    }
}

/// Generic method names that should be excluded from twin detection
/// These are common names that appear in many files by design, not by accident.
pub const GENERIC_METHOD_NAMES: &[&str] = &[
    // Rust/OOP constructors and traits
    "new",
    "default",
    "from",
    "into",
    "clone",
    "drop",
    "deref",
    "as_ref",
    "as_mut",
    "try_from",
    "try_into",
    "with_config",
    // Entry points (every binary has one)
    "main",
    "app",
    "App",
    // Lifecycle methods
    "init",
    "setup",
    "teardown",
    "cleanup",
    "dispose",
    "destroy",
    "mount",
    "unmount",
    // CRUD operations
    "create",
    "read",
    "update",
    "delete",
    "get",
    "set",
    "load",
    "save",
    "fetch",
    "store",
    // Process/execution
    "run",
    "start",
    "stop",
    "execute",
    "process",
    "handle",
    "dispatch",
    // I/O operations
    "open",
    "close",
    "write",
    "send",
    "receive",
    "connect",
    "disconnect",
    // Serialization
    "parse",
    "format",
    "serialize",
    "deserialize",
    "encode",
    "decode",
    "to_string",
    "from_str",
    "to_json",
    "from_json",
    "to_bytes",
    "from_bytes",
    "as_str",
    "as_bytes",
    "into_inner",
    "inner",
    "get_inner",
    "unwrap",
    "unwrap_or",
    "ok",
    "err",
    // State management
    "reset",
    "clear",
    "flush",
    "refresh",
    // UI/rendering
    "render",
    "draw",
    "display",
    "show",
    "hide",
    // Validation/configuration
    "validate",
    "configure",
    "build",
    // Testing (fixtures, setup)
    "test",
    "fixture",
    "mock",
    "stub",
    "spy",
    // Python special methods
    "__init__",
    "__new__",
    "__str__",
    "__repr__",
    // Common generic names
    "apply",
    "call",
    "invoke",
    "notify",
    "emit",
    "on",
    "off",
    "add",
    "remove",
    "insert",
    "push",
    "pop",
    "len",
    "size",
    "count",
    "index",
    "find",
    "search",
    "filter",
    "map",
    "reduce",
    "sort",
    "compare",
    "equals",
    "hash",
    "copy",
    "merge",
    "split",
    "join",
    "concat",
    "append",
    "extend",
    "contains",
    "exists",
    "is_empty",
    "is_valid",
    "check",
    "verify",
    "assert",
    "expect",
    "should",
    "must",
    "can",
    "will",
    "with",
    "label",
    "name",
    "id",
    "key",
    "value",
    "data",
    "info",
    "error",
    "warn",
    "debug",
    "log",
    "print",
    "trace",
];

fn is_generic_method(name: &str) -> bool {
    GENERIC_METHOD_NAMES.contains(&name)
}

/// Compute a fingerprint for a function's signature based on its parameter and return types.
/// Returns a sorted, normalized string like "String,User|Result<bool>" (params|return).
fn compute_signature_fingerprint(
    analyses: &[FileAnalysis],
    file_path: &str,
    function_name: &str,
) -> Option<String> {
    // Find the FileAnalysis for this file
    let analysis = analyses.iter().find(|a| a.path == file_path)?;

    // Collect types used in this function's signature
    let mut param_types: Vec<String> = Vec::new();
    let mut return_types: Vec<String> = Vec::new();

    for sig_use in &analysis.signature_uses {
        if sig_use.function == function_name {
            match sig_use.usage {
                crate::types::SignatureUseKind::Parameter => {
                    param_types.push(sig_use.type_name.clone());
                }
                crate::types::SignatureUseKind::Return => {
                    return_types.push(sig_use.type_name.clone());
                }
            }
        }
    }

    // If no signature info found, return None
    if param_types.is_empty() && return_types.is_empty() {
        return None;
    }

    // Sort for consistent comparison
    param_types.sort();
    return_types.sort();

    // Create fingerprint: "param1,param2|return1,return2"
    let params_str = param_types.join(",");
    let returns_str = return_types.join(",");

    Some(format!("{}|{}", params_str, returns_str))
}

/// Compute Jaccard similarity between two fingerprints.
/// Returns 1.0 for identical, 0.0 for completely different.
fn fingerprint_similarity(fp1: &str, fp2: &str) -> f32 {
    if fp1 == fp2 {
        return 1.0;
    }

    // Split into individual types
    let types1: std::collections::HashSet<&str> =
        fp1.split([',', '|']).filter(|s| !s.is_empty()).collect();
    let types2: std::collections::HashSet<&str> =
        fp2.split([',', '|']).filter(|s| !s.is_empty()).collect();

    if types1.is_empty() && types2.is_empty() {
        return 1.0; // Both empty = same
    }

    let intersection = types1.intersection(&types2).count();
    let union = types1.union(&types2).count();

    if union == 0 {
        return 0.0;
    }

    intersection as f32 / union as f32
}

/// Compute average pairwise similarity for a group of fingerprints.
fn compute_group_similarity(fingerprints: &[Option<String>]) -> Option<f32> {
    let valid_fps: Vec<&String> = fingerprints.iter().filter_map(|f| f.as_ref()).collect();

    if valid_fps.len() < 2 {
        return None; // Need at least 2 to compare
    }

    let mut total_similarity = 0.0;
    let mut count = 0;

    for i in 0..valid_fps.len() {
        for j in (i + 1)..valid_fps.len() {
            total_similarity += fingerprint_similarity(valid_fps[i], valid_fps[j]);
            count += 1;
        }
    }

    if count == 0 {
        return None;
    }

    Some(total_similarity / count as f32)
}

/// Detect exact twins: symbols with the same name exported from different files
///
/// This is the simple version without framework awareness.
/// For framework-aware filtering, use `detect_exact_twins_with_frameworks`.
pub fn detect_exact_twins(analyses: &[FileAnalysis], include_tests: bool) -> Vec<ExactTwin> {
    detect_exact_twins_with_frameworks(analyses, include_tests, None)
}

/// Detect exact twins with framework-aware filtering
///
/// # Arguments
/// * `analyses` - File analysis data
/// * `include_tests` - Whether to include test files
/// * `frameworks` - Optional list of detected frameworks. When provided, intentional
///   framework conventions (like GET in SvelteKit +server.ts) are filtered out.
///   Pass `None` or `&[]` to show all duplicates.
pub fn detect_exact_twins_with_frameworks(
    analyses: &[FileAnalysis],
    include_tests: bool,
    frameworks: Option<&[crate::analyzer::frameworks::Framework]>,
) -> Vec<ExactTwin> {
    let registry = build_symbol_registry(analyses, include_tests);

    // Build map: symbol_name -> Vec<(file_path, line, kind, import_count)>
    let mut symbol_map: HashMap<String, Vec<(String, usize, String, usize)>> = HashMap::new();

    for ((file_path, symbol_name), entry) in &registry {
        // Skip re-exports and __all__ entries - they're intentional API design, not duplicates
        // __all__ in Python is a declaration of public API, not a new definition
        if entry.kind == "reexport" || entry.kind == "re-export" || entry.kind == "__all__" {
            continue;
        }
        symbol_map.entry(symbol_name.clone()).or_default().push((
            file_path.clone(),
            entry.line,
            entry.kind.clone(),
            entry.import_count,
        ));
    }

    // Get frameworks slice for filtering
    let fw_slice = frameworks.unwrap_or(&[]);

    // Filter to only symbols exported from multiple files
    let mut twins: Vec<ExactTwin> = Vec::new();

    for (name, locations_raw) in symbol_map {
        // Skip generic method names (new, from, clone, etc.)
        if is_generic_method(&name) {
            continue;
        }

        // Skip if only one location (not a duplicate)
        if locations_raw.len() <= 1 {
            continue;
        }

        // Framework convention filtering:
        // If ALL locations are framework conventions for the same export,
        // it's an intentional pattern (e.g., GET in every +server.ts)
        if !fw_slice.is_empty() {
            let all_are_conventions = locations_raw.iter().all(|(file_path, _, _, _)| {
                crate::analyzer::frameworks::is_framework_convention(&name, file_path, fw_slice)
            });
            if all_are_conventions {
                continue;
            }
        }

        // Build locations with import counts and signature fingerprints
        let mut locations: Vec<TwinLocation> = locations_raw
            .iter()
            .map(|(file, line, kind, import_count)| {
                // Compute signature fingerprint for functions (including const arrow functions)
                // TS arrow functions: export const foo = () => {}
                // Named exports that might be functions
                let signature_fingerprint = if kind == "function"
                    || kind == "var"
                    || kind == "decl"
                    || kind == "const"
                    || kind == "named"
                {
                    compute_signature_fingerprint(analyses, file, &name)
                } else {
                    None
                };

                TwinLocation {
                    file_path: file.clone(),
                    line: *line,
                    kind: kind.clone(),
                    import_count: *import_count,
                    is_canonical: false, // Will determine below
                    signature_fingerprint,
                }
            })
            .collect();

        // Compute signature similarity across all locations
        let fingerprints: Vec<Option<String>> = locations
            .iter()
            .map(|l| l.signature_fingerprint.clone())
            .collect();
        let signature_similarity = compute_group_similarity(&fingerprints);

        // Determine canonical location:
        // 1. Most imports
        // 2. If tie, shortest path (likely more central)
        // 3. If still tie, first alphabetically (deterministic)
        if !locations.is_empty() {
            let max_imports = locations.iter().map(|l| l.import_count).max().unwrap_or(0);

            let mut canonicals: Vec<&mut TwinLocation> = locations
                .iter_mut()
                .filter(|l| l.import_count == max_imports)
                .collect();

            // If multiple have max imports, pick shortest path
            if canonicals.len() > 1 {
                canonicals.sort_by_key(|l| l.file_path.len());
            }

            // Mark first as canonical
            if let Some(canonical) = canonicals.first_mut() {
                canonical.is_canonical = true;
            }
        }

        twins.push(ExactTwin {
            name,
            locations,
            signature_similarity,
        });
    }

    // Sort by number of locations (most duplicated first)
    twins.sort_by(|a, b| b.locations.len().cmp(&a.locations.len()));

    twins
}

/// Print exact twins in human-readable format
pub fn print_exact_twins_human(twins: &[ExactTwin]) {
    if twins.is_empty() {
        println!("No exact twins found - all symbol names are unique!");
        return;
    }

    // Categorize twins
    let (same_lang, cross_lang): (Vec<_>, Vec<_>) = twins
        .iter()
        .partition(|twin| matches!(categorize_twin(twin), TwinCategory::SameLanguage(_)));

    println!("EXACT TWINS ({} found)", twins.len());
    println!();

    // Same-language twins (actionable)
    if !same_lang.is_empty() {
        println!(
            "  [!] SAME-LANGUAGE DUPLICATES ({} groups) - likely need consolidation:",
            same_lang.len()
        );
        println!();
        for twin in &same_lang {
            print_twin_details(twin);
        }
    }

    // Cross-language twins (informational)
    if !cross_lang.is_empty() {
        println!(
            "  [i] CROSS-LANGUAGE PAIRS ({} groups) - likely intentional FE/BE mirrors:",
            cross_lang.len()
        );
        println!();
        for twin in &cross_lang {
            print_twin_details(twin);
        }
    }

    println!("Summary:");
    println!(
        "  Same-language duplicates: {} (actionable)",
        same_lang.len()
    );
    println!("  Cross-language pairs: {} (usually OK)", cross_lang.len());
    let total_dups: usize = twins.iter().map(|t| t.locations.len()).sum();
    println!("  Total duplicate definitions: {}", total_dups);
}

/// Helper to print individual twin details
fn print_twin_details(twin: &ExactTwin) {
    println!("  Symbol: {}", twin.name);
    for loc in &twin.locations {
        let canonical_marker = if loc.is_canonical { " CANONICAL" } else { "" };
        println!(
            "    ├─ {}:{} ({}) - {} imports{}",
            loc.file_path, loc.line, loc.kind, loc.import_count, canonical_marker
        );
    }
    // Add suggestion based on import counts
    let zero_import_count = twin
        .locations
        .iter()
        .filter(|l| l.import_count == 0)
        .count();
    if zero_import_count > 0 && zero_import_count < twin.locations.len() {
        println!(
            "    └─ [TIP] {} location(s) have 0 imports - candidates for removal or consolidation",
            zero_import_count
        );
    }
    println!();
}

/// Print exact twins in JSON format
pub fn print_exact_twins_json(twins: &[ExactTwin]) {
    // Categorize twins
    let (same_lang, cross_lang): (Vec<_>, Vec<_>) = twins
        .iter()
        .partition(|twin| matches!(categorize_twin(twin), TwinCategory::SameLanguage(_)));

    // Count twins with high signature similarity (likely real duplicates)
    let high_similarity_count = twins
        .iter()
        .filter(|t| t.signature_similarity.map(|s| s >= 0.8).unwrap_or(false))
        .count();

    let twin_to_json = |twin: &ExactTwin| {
        let category = categorize_twin(twin);
        let mut json = serde_json::json!({
            "name": twin.name,
            "category": match category {
                TwinCategory::SameLanguage(lang) => format!("same_language:{:?}", lang).to_lowercase(),
                TwinCategory::CrossLanguage => "cross_language".to_string(),
            },
            "locations": twin.locations.iter().map(|loc| {
                let mut loc_json = serde_json::json!({
                    "file": loc.file_path,
                    "line": loc.line,
                    "kind": loc.kind,
                    "imports": loc.import_count,
                    "canonical": loc.is_canonical,
                    "language": format!("{:?}", detect_language(&loc.file_path)).to_lowercase(),
                });
                // Add signature fingerprint if present
                if let Some(ref fp) = loc.signature_fingerprint {
                    loc_json["signature_fingerprint"] = serde_json::json!(fp);
                }
                loc_json
            }).collect::<Vec<_>>(),
        });
        // Add signature similarity if computed
        if let Some(sim) = twin.signature_similarity {
            json["signature_similarity"] = serde_json::json!(sim);
        }
        json
    };

    let output = serde_json::json!({
        "exact_twins": twins.iter().map(twin_to_json).collect::<Vec<_>>(),
        "summary": {
            "total_groups": twins.len(),
            "same_language_groups": same_lang.len(),
            "cross_language_groups": cross_lang.len(),
            "high_similarity_groups": high_similarity_count,
            "total_duplicates": twins.iter().map(|t| t.locations.len()).sum::<usize>(),
        }
    });

    println!("{}", serde_json::to_string_pretty(&output).unwrap());
}

/// Print exact twins based on output mode
pub fn print_exact_twins(twins: &[ExactTwin], output: OutputMode) {
    match output {
        OutputMode::Json | OutputMode::Jsonl => print_exact_twins_json(twins),
        OutputMode::Human => print_exact_twins_human(twins),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{ExportSymbol, ImportEntry, ImportKind, ImportSymbol};

    fn mock_file_with_exports(path: &str, exports: Vec<(&str, &str)>) -> FileAnalysis {
        FileAnalysis {
            path: path.to_string(),
            exports: exports
                .into_iter()
                .enumerate()
                .map(|(i, (name, kind))| ExportSymbol {
                    name: name.to_string(),
                    kind: kind.to_string(),
                    export_type: "named".to_string(),
                    line: Some(i + 1),
                    params: Vec::new(),
                })
                .collect(),
            ..Default::default()
        }
    }

    #[test]
    fn test_build_symbol_registry_empty() {
        let analyses: Vec<FileAnalysis> = vec![];
        let registry = build_symbol_registry(&analyses, false);
        assert!(registry.is_empty());
    }

    #[test]
    fn test_build_symbol_registry_no_imports() {
        let analyses = vec![
            mock_file_with_exports("a.ts", vec![("foo", "function")]),
            mock_file_with_exports("b.ts", vec![("bar", "function")]),
        ];

        let registry = build_symbol_registry(&analyses, false);
        assert_eq!(registry.len(), 2);

        let foo_entry = registry
            .get(&("a.ts".to_string(), "foo".to_string()))
            .unwrap();
        assert_eq!(foo_entry.import_count, 0);
    }

    #[test]
    fn test_build_symbol_registry_with_imports() {
        let exporter = mock_file_with_exports("utils.ts", vec![("helper", "function")]);
        let mut importer = FileAnalysis {
            path: "app.ts".to_string(),
            ..Default::default()
        };

        let mut import = ImportEntry::new("./utils".to_string(), ImportKind::Static);
        import.resolved_path = Some("utils.ts".to_string());
        import.symbols.push(ImportSymbol {
            name: "helper".to_string(),
            alias: None,
            is_default: false,
        });
        importer.imports.push(import);

        let registry = build_symbol_registry(&[exporter, importer], false);

        let helper_entry = registry
            .get(&("utils.ts".to_string(), "helper".to_string()))
            .unwrap();
        assert_eq!(helper_entry.import_count, 1);
    }

    #[test]
    fn test_build_symbol_registry_skips_tests() {
        let test_file = FileAnalysis {
            path: "tests/test_api_integration.py".to_string(),
            is_test: true,
            exports: vec![ExportSymbol {
                name: "TestHealthEndpoints".to_string(),
                kind: "class".to_string(),
                export_type: "named".to_string(),
                line: Some(10),
                params: Vec::new(),
            }],
            ..Default::default()
        };
        let normal_file = mock_file_with_exports("app.py", vec![("App", "class")]);

        // With include_tests=false, test files should be skipped
        let registry = build_symbol_registry(&[test_file.clone(), normal_file.clone()], false);
        assert_eq!(registry.len(), 1);
        assert!(registry.contains_key(&("app.py".to_string(), "App".to_string())));

        // With include_tests=true, test files should be included
        let registry_with_tests = build_symbol_registry(&[test_file, normal_file], true);
        assert_eq!(registry_with_tests.len(), 2);
    }

    #[test]
    fn test_find_dead_parrots() {
        let used_file = mock_file_with_exports("used.ts", vec![("used", "function")]);
        let dead_file = mock_file_with_exports("dead.ts", vec![("unused", "function")]);

        let mut importer = FileAnalysis {
            path: "app.ts".to_string(),
            ..Default::default()
        };

        let mut import = ImportEntry::new("./used".to_string(), ImportKind::Static);
        import.resolved_path = Some("used.ts".to_string());
        import.symbols.push(ImportSymbol {
            name: "used".to_string(),
            alias: None,
            is_default: false,
        });
        importer.imports.push(import);

        let result = find_dead_parrots(&[used_file, dead_file, importer], true, false);

        assert_eq!(result.dead_parrots.len(), 1);
        assert_eq!(result.dead_parrots[0].name, "unused");
        assert_eq!(result.total_symbols, 2);
    }

    #[test]
    fn test_find_dead_parrots_skips_dynamic_imports() {
        // Create a component that is dynamically imported via React lazy()
        let lazy_component = FileAnalysis {
            path: "src/components/PasswordResetModal.tsx".to_string(),
            exports: vec![ExportSymbol {
                name: "PasswordResetModal".to_string(),
                kind: "function".to_string(),
                export_type: "default".to_string(),
                line: Some(23),
                params: Vec::new(),
            }],
            ..Default::default()
        };

        // Create a file that imports it dynamically
        let importer = FileAnalysis {
            path: "src/App.tsx".to_string(),
            dynamic_imports: vec!["./components/PasswordResetModal".to_string()],
            ..Default::default()
        };

        // Create a truly dead file (no static or dynamic imports)
        let dead_file = mock_file_with_exports("dead.ts", vec![("unused", "function")]);

        let result = find_dead_parrots(&[lazy_component, importer, dead_file], true, false);

        // The dynamic import should NOT be marked as dead
        // Only the truly unused export should be in dead_parrots
        assert_eq!(result.dead_parrots.len(), 1);
        assert_eq!(result.dead_parrots[0].name, "unused");
    }

    // Exact twin detection tests
    #[test]
    fn test_detect_exact_twins_no_duplicates() {
        let analyses = vec![
            mock_file_with_exports("a.ts", vec![("foo", "function")]),
            mock_file_with_exports("b.ts", vec![("bar", "function")]),
        ];

        let twins = detect_exact_twins(&analyses, false);
        assert!(twins.is_empty());
    }

    #[test]
    fn test_detect_exact_twins_simple() {
        let analyses = vec![
            mock_file_with_exports("a.ts", vec![("Button", "class")]),
            mock_file_with_exports("b.ts", vec![("Button", "class")]),
        ];

        let twins = detect_exact_twins(&analyses, false);
        assert_eq!(twins.len(), 1);
        assert_eq!(twins[0].name, "Button");
        assert_eq!(twins[0].locations.len(), 2);
    }

    #[test]
    fn test_detect_exact_twins_canonical_by_path() {
        let analyses = vec![
            mock_file_with_exports("shared/types.ts", vec![("Message", "type")]),
            mock_file_with_exports("hooks/useChat.ts", vec![("Message", "type")]),
        ];

        let twins = detect_exact_twins(&analyses, false);
        assert_eq!(twins.len(), 1);

        // Canonical should be shortest path
        let canonical = twins[0].locations.iter().find(|l| l.is_canonical).unwrap();
        assert_eq!(canonical.file_path, "shared/types.ts");
    }

    #[test]
    fn test_detect_exact_twins_canonical_by_imports() {
        let a = mock_file_with_exports("a.ts", vec![("Foo", "type")]);
        let b = mock_file_with_exports("b.ts", vec![("Foo", "type")]);

        // Import from a.ts
        let mut importer = FileAnalysis {
            path: "app.ts".to_string(),
            ..Default::default()
        };
        let mut import = ImportEntry::new("./a".to_string(), ImportKind::Static);
        import.resolved_path = Some("a.ts".to_string());
        import.symbols.push(ImportSymbol {
            name: "Foo".to_string(),
            alias: None,
            is_default: false,
        });
        importer.imports.push(import);

        let twins = detect_exact_twins(&[a, b, importer], false);
        assert_eq!(twins.len(), 1);

        // Canonical should be the one with imports (a.ts)
        let canonical = twins[0].locations.iter().find(|l| l.is_canonical).unwrap();
        assert_eq!(canonical.file_path, "a.ts");
        assert_eq!(canonical.import_count, 1);
    }

    #[test]
    fn test_detect_exact_twins_three_locations() {
        let analyses = vec![
            mock_file_with_exports("a.ts", vec![("Common", "type")]),
            mock_file_with_exports("b.ts", vec![("Common", "type")]),
            mock_file_with_exports("c.ts", vec![("Common", "type")]),
        ];

        let twins = detect_exact_twins(&analyses, false);
        assert_eq!(twins.len(), 1);
        assert_eq!(twins[0].locations.len(), 3);
    }
}