similarity-ts 0.5.0

CLI tool for detecting code duplication in TypeScript/JavaScript projects
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
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
#![allow(clippy::uninlined_format_args)]

use clap::Parser;

mod check;
pub mod parallel;

#[derive(Parser)]
#[command(name = "similarity-ts")]
#[command(about = "TypeScript/JavaScript code similarity analyzer")]
#[command(version)]
struct Cli {
    /// Paths to analyze (files or directories)
    #[arg(default_value = ".")]
    paths: Vec<String>,

    /// Print code in output
    #[arg(short, long)]
    print: bool,

    /// Similarity threshold (0.0-1.0)
    #[arg(short, long, default_value = "0.87")]
    threshold: f64,

    /// Disable function similarity checking
    #[arg(long = "no-functions")]
    no_functions: bool,

    /// Enable type similarity checking (includes type literals by default)
    #[arg(long = "types", default_value = "true")]
    types: bool,

    /// Disable type similarity checking
    #[arg(long = "no-types", conflicts_with = "types")]
    no_types: bool,

    /// Enable class similarity checking
    #[arg(long = "classes", default_value = "false")]
    classes: bool,

    /// Only check classes (exclude functions and types)
    #[arg(long)]
    classes_only: bool,

    /// Include classes with inheritance (extends) - excluded by default
    #[arg(long)]
    include_inheritance: bool,

    /// Include classes with interface implementation (implements) - excluded by default
    #[arg(long)]
    include_implements: bool,

    /// Show refactoring suggestions for excluded classes
    #[arg(long)]
    suggest: bool,

    /// File extensions to check
    #[arg(short, long, value_delimiter = ',')]
    extensions: Option<Vec<String>>,

    /// Minimum lines for functions to be considered
    #[arg(short, long, default_value = "3")]
    min_lines: Option<u32>,

    /// Minimum tokens for functions to be considered
    #[arg(long)]
    min_tokens: Option<u32>,

    /// Rename cost for APTED algorithm
    #[arg(short, long, default_value = "0.3")]
    rename_cost: f64,

    /// Disable size penalty for very different sized functions
    #[arg(long)]
    no_size_penalty: bool,

    /// Filter functions by name (substring match)
    #[arg(long)]
    filter_function: Option<String>,

    /// Filter functions by body content (substring match)
    #[arg(long)]
    filter_function_body: Option<String>,

    /// Show functions, types, and classes ignored via similarity-ignore comments
    #[arg(long)]
    show_ignored: bool,

    /// Include both interfaces and type aliases (deprecated - both are included by default)
    #[arg(long, hide = true)]
    include_types: bool,

    /// Only check type aliases (excludes interfaces and type literals)
    #[arg(long)]
    types_only: bool,

    /// Only check interfaces (excludes type aliases and type literals)
    #[arg(long)]
    interfaces_only: bool,

    /// Allow comparison between interfaces and type aliases
    #[arg(long, default_value = "true")]
    allow_cross_kind: bool,

    /// Weight for structural similarity (0.0-1.0)
    #[arg(long, default_value = "0.6")]
    structural_weight: f64,

    /// Weight for naming similarity (0.0-1.0)
    #[arg(long, default_value = "0.4")]
    naming_weight: f64,

    /// Only check type literals (excludes type aliases and interfaces)
    #[arg(long)]
    type_literals_only: bool,

    /// Enable unified type comparison (default: true - compares across type aliases, interfaces, and type literals)
    #[arg(long, default_value = "true")]
    unified_types: bool,

    /// Disable unified type comparison
    #[arg(long, conflicts_with = "unified_types")]
    no_unified_types: bool,

    /// Disable fast mode with bloom filter pre-filtering
    #[arg(long = "no-fast")]
    no_fast: bool,

    /// Exclude directories matching the given patterns (can be specified multiple times)
    #[arg(long)]
    exclude: Vec<String>,

    /// Enable experimental overlap detection mode
    #[arg(long = "experimental-overlap")]
    overlap: bool,

    /// Minimum window size for overlap detection (number of nodes)
    #[arg(long, default_value = "8")]
    overlap_min_window: u32,

    /// Maximum window size for overlap detection (number of nodes)
    #[arg(long, default_value = "25")]
    overlap_max_window: u32,

    /// Size tolerance for overlap detection (0.0-1.0)
    #[arg(long, default_value = "0.25")]
    overlap_size_tolerance: f64,

    /// Exit with code 1 if duplicates are found
    #[arg(long)]
    fail_on_duplicates: bool,

    /// Use new generalized structure comparison framework (experimental)
    #[arg(long)]
    use_structure_comparison: bool,
}

fn main() -> anyhow::Result<()> {
    let cli = Cli::parse();

    let functions_enabled = !cli.no_functions && !cli.classes_only;
    let types_enabled = (cli.types && !cli.no_types) && !cli.classes_only;
    let classes_enabled = cli.classes || cli.classes_only;
    let overlap_enabled = cli.overlap;
    let unified_types_enabled = cli.unified_types && !cli.no_unified_types;
    let include_type_literals = true; // Always include type literals

    // Validate that at least one analyzer is enabled
    if !functions_enabled && !types_enabled && !classes_enabled && !overlap_enabled {
        eprintln!("Error: At least one analyzer must be enabled. Remove --no-types to enable type checking, use --classes for class checking, use --overlap for overlap detection, or remove --no-functions.");
        return Err(anyhow::anyhow!("No analyzer enabled"));
    }

    // Handle mutual exclusion of min_lines and min_tokens
    let (min_lines, min_tokens) = match (cli.min_lines, cli.min_tokens) {
        (Some(_), Some(tokens)) => {
            eprintln!(
                "Warning: Both --min-lines and --min-tokens specified. Using --min-tokens={}",
                tokens
            );
            (None, Some(tokens))
        }
        (lines, tokens) => (lines, tokens),
    };

    println!("Analyzing code similarity...\n");

    let separator = "-".repeat(60);
    let mut total_duplicates = 0;

    // Run functions analysis if enabled
    if functions_enabled {
        println!("=== Function Similarity ===");
        let duplicate_count = check::check_paths(
            cli.paths.clone(),
            cli.threshold,
            cli.rename_cost,
            cli.extensions.as_ref(),
            min_lines.unwrap_or(3),
            min_tokens,
            cli.no_size_penalty,
            cli.print,
            !cli.no_fast,
            cli.filter_function.as_ref(),
            cli.filter_function_body.as_ref(),
            &cli.exclude,
            cli.show_ignored,
        )?;
        total_duplicates += duplicate_count;
    }

    // Run types analysis if enabled
    if types_enabled && functions_enabled {
        println!("\n{}\n", separator);
    }

    if types_enabled {
        println!("=== Type Similarity ===");
        let type_duplicate_count = check_types(
            cli.paths.clone(),
            cli.threshold,
            cli.extensions.as_ref(),
            cli.print,
            cli.types_only,
            cli.interfaces_only,
            cli.type_literals_only,
            cli.allow_cross_kind,
            cli.structural_weight,
            cli.naming_weight,
            include_type_literals,
            unified_types_enabled,
            &cli.exclude,
            cli.use_structure_comparison,
            cli.show_ignored,
        )?;
        total_duplicates += type_duplicate_count;
    }

    // Run class analysis if enabled
    if classes_enabled && (functions_enabled || types_enabled) {
        println!("\n{}\n", separator);
    }

    if classes_enabled {
        println!("=== Class Similarity ===");
        let class_duplicate_count = check_classes(
            cli.paths.clone(),
            cli.threshold,
            cli.extensions.as_ref(),
            cli.print,
            !cli.include_inheritance,
            !cli.include_implements,
            cli.suggest,
            &cli.exclude,
            cli.show_ignored,
        )?;
        total_duplicates += class_duplicate_count;
    }

    // Run overlap analysis if enabled
    if overlap_enabled && (functions_enabled || types_enabled || classes_enabled) {
        println!("\n{}\n", separator);
    }

    if overlap_enabled {
        println!("=== Overlap Detection ===");
        let overlap_duplicate_count = check_overlaps(
            cli.paths,
            cli.threshold,
            cli.extensions.as_ref(),
            cli.print,
            cli.overlap_min_window,
            cli.overlap_max_window,
            cli.overlap_size_tolerance,
            &cli.exclude,
        )?;
        total_duplicates += overlap_duplicate_count;
    }

    // Exit with code 1 if duplicates found and --fail-on-duplicates is set
    if cli.fail_on_duplicates && total_duplicates > 0 {
        std::process::exit(1);
    }

    Ok(())
}

fn create_exclude_matcher(exclude_patterns: &[String]) -> Option<globset::GlobSet> {
    if exclude_patterns.is_empty() {
        return None;
    }

    let mut builder = globset::GlobSetBuilder::new();
    for pattern in exclude_patterns {
        // Add the pattern as-is
        if let Ok(glob) = globset::Glob::new(pattern) {
            builder.add(glob);
        }

        // If the pattern doesn't start with **, also add a **/ prefix version
        // This allows "tests/fixtures" to match "any/path/tests/fixtures"
        if !pattern.starts_with("**") {
            let prefixed = format!("**/{}", pattern);
            if let Ok(glob) = globset::Glob::new(&prefixed) {
                builder.add(glob);
            }

            // Also add a suffix version for matching files within the directory
            let suffixed = format!("{}/**", pattern.trim_end_matches('/'));
            if let Ok(glob) = globset::Glob::new(&suffixed) {
                builder.add(glob);
            }

            // And both prefix and suffix
            let both = format!("**/{}", suffixed);
            if let Ok(glob) = globset::Glob::new(&both) {
                builder.add(glob);
            }
        }
    }

    builder.build().ok()
}

#[allow(clippy::too_many_arguments)]
fn check_types(
    paths: Vec<String>,
    threshold: f64,
    extensions: Option<&Vec<String>>,
    print: bool,
    types_only: bool,
    interfaces_only: bool,
    type_literals_only: bool,
    allow_cross_kind: bool,
    structural_weight: f64,
    naming_weight: f64,
    include_type_literals: bool,
    unified_types: bool,
    exclude_patterns: &[String],
    use_structure_comparison: bool,
    show_ignored: bool,
) -> anyhow::Result<usize> {
    use ignore::WalkBuilder;
    use similarity_core::{
        extract_type_literals_from_code, extract_types_from_code, find_similar_type_literals,
        find_similar_types, find_similar_unified_types, find_similar_unified_types_structured,
        ComparisonOptions, TypeComparisonOptions, TypeKind, UnifiedType,
    };
    use std::collections::HashSet;
    use std::fs;
    use std::path::Path;

    let default_extensions = vec!["ts", "tsx", "mts", "cts"];
    let exts: Vec<&str> =
        extensions.map_or(default_extensions, |v| v.iter().map(String::as_str).collect());

    let exclude_matcher = create_exclude_matcher(exclude_patterns);
    let mut files = Vec::new();
    let mut visited = HashSet::new();

    // Process each path
    for path_str in &paths {
        let path = Path::new(path_str);

        if path.is_file() {
            // If it's a file, check extension and add it
            if let Some(ext) = path.extension() {
                if let Some(ext_str) = ext.to_str() {
                    if exts.contains(&ext_str) {
                        if let Ok(canonical) = path.canonicalize() {
                            if visited.insert(canonical.clone()) {
                                files.push(path.to_path_buf());
                            }
                        }
                    }
                }
            }
        } else if path.is_dir() {
            // If it's a directory, walk it respecting .gitignore
            let walker = WalkBuilder::new(path)
                .follow_links(false)
                .git_ignore(true) // Respect .gitignore files
                .git_global(true) // Respect global gitignore
                .git_exclude(true) // Respect .git/info/exclude
                .build();

            for entry in walker {
                let entry = entry?;
                let entry_path = entry.path();

                // Skip if not a file
                if !entry_path.is_file() {
                    continue;
                }

                // Check if path should be excluded
                if let Some(ref matcher) = exclude_matcher {
                    // Check both the full path and relative path from the search root
                    if matcher.is_match(entry_path) {
                        continue;
                    }

                    // Also check relative path from current directory
                    if let Ok(current_dir) = std::env::current_dir() {
                        if let Ok(relative) = entry_path.strip_prefix(&current_dir) {
                            if matcher.is_match(relative) {
                                continue;
                            }
                        }
                    }
                }

                // Check extension
                if let Some(ext) = entry_path.extension() {
                    if let Some(ext_str) = ext.to_str() {
                        if exts.contains(&ext_str) {
                            // Get canonical path to avoid duplicates
                            if let Ok(canonical) = entry_path.canonicalize() {
                                if visited.insert(canonical.clone()) {
                                    files.push(entry_path.to_path_buf());
                                }
                            }
                        }
                    }
                }
            }
        } else {
            eprintln!("Warning: Path not found: {}", path_str);
        }
    }

    if files.is_empty() {
        println!("No TypeScript files found in specified paths");
        return Ok(0);
    }

    println!("Checking {} files for similar types...\n", files.len());

    // Extract types from all files
    let mut all_types = Vec::new();
    let mut all_type_literals = Vec::new();
    let mut ignored_types = Vec::new();

    for file in &files {
        match fs::read_to_string(file) {
            Ok(content) => {
                let file_str = file.to_string_lossy();

                // Extract regular types unless type_literals_only is set
                if !type_literals_only {
                    match extract_types_from_code(&content, &file_str) {
                        Ok(mut types) => {
                            if show_ignored {
                                ignored_types.extend(
                                    types.iter().filter(|ty| ty.has_ignore_directive).map(|ty| {
                                        (file.display().to_string(), ty.name.clone(), ty.start_line)
                                    }),
                                );
                            }
                            types.retain(|ty| !ty.has_ignore_directive);

                            // Filter types based on command line options
                            if types_only {
                                types.retain(|t| t.kind == TypeKind::TypeAlias);
                            } else if interfaces_only {
                                types.retain(|t| t.kind == TypeKind::Interface);
                            }
                            all_types.extend(types);
                        }
                        Err(e) => {
                            // Skip files with parse errors silently
                            if !e.contains("Parse errors:") {
                                eprintln!("Error in {}: {}", file.display(), e);
                            }
                        }
                    }
                }

                // Extract type literals if requested
                if include_type_literals {
                    match extract_type_literals_from_code(&content, &file_str) {
                        Ok(type_literals) => {
                            all_type_literals.extend(type_literals);
                        }
                        Err(e) => {
                            // Skip files with parse errors silently
                            if !e.contains("Parse errors:") {
                                eprintln!("Error in {}: {}", file.display(), e);
                            }
                        }
                    }
                }
            }
            Err(e) => {
                eprintln!("Error reading {}: {}", file.display(), e);
            }
        }
    }

    if all_types.is_empty() && all_type_literals.is_empty() {
        println!("No type definitions or type literals found!");
        return Ok(0);
    }

    println!("Found {} type definitions", all_types.len());
    if include_type_literals {
        println!("Found {} type literals", all_type_literals.len());
    }
    if show_ignored && !ignored_types.is_empty() {
        println!("Ignored {} type(s) via similarity-ignore directive:", ignored_types.len());
        for (file, name, line) in &ignored_types {
            println!("  {}:{} {}", file, line, name);
        }
    }

    // Set up comparison options
    let options = TypeComparisonOptions {
        allow_cross_kind_comparison: allow_cross_kind,
        structural_weight,
        naming_weight,
        ..Default::default()
    };

    // Validate weights
    if (structural_weight + naming_weight - 1.0).abs() > 0.001 {
        eprintln!("Warning: structural_weight + naming_weight should equal 1.0");
    }

    // Handle unified type comparison if enabled
    let (similar_pairs, type_literal_pairs, type_literal_to_literal_pairs) = if unified_types {
        // Use unified comparison that combines all types
        let unified_pairs = if use_structure_comparison {
            // Use new generalized structure comparison framework
            let structure_options = ComparisonOptions {
                name_weight: naming_weight,
                structure_weight: structural_weight,
                threshold,
                ..Default::default()
            };
            find_similar_unified_types_structured(
                &all_types,
                &all_type_literals,
                threshold,
                Some(structure_options),
            )
        } else {
            // Use existing comparison method
            find_similar_unified_types(&all_types, &all_type_literals, threshold, &options)
        };

        // Convert unified pairs to the existing format for display (for now)
        let mut regular_pairs = Vec::new();
        let mut literal_to_def_pairs = Vec::new();
        let mut literal_to_literal_pairs = Vec::new();

        for pair in unified_pairs {
            match (&pair.type1, &pair.type2) {
                (UnifiedType::TypeDef(def1), UnifiedType::TypeDef(def2)) => {
                    regular_pairs.push(similarity_core::SimilarTypePair {
                        type1: def1.clone(),
                        type2: def2.clone(),
                        result: pair.result,
                    });
                }
                (UnifiedType::TypeLiteral(lit), UnifiedType::TypeDef(def))
                | (UnifiedType::TypeDef(def), UnifiedType::TypeLiteral(lit)) => {
                    literal_to_def_pairs.push(similarity_core::TypeLiteralComparisonPair {
                        type_literal: lit.clone(),
                        type_definition: def.clone(),
                        result: pair.result,
                    });
                }
                (UnifiedType::TypeLiteral(lit1), UnifiedType::TypeLiteral(lit2)) => {
                    literal_to_literal_pairs.push((lit1.clone(), lit2.clone(), pair.result));
                }
            }
        }

        (regular_pairs, literal_to_def_pairs, literal_to_literal_pairs)
    } else {
        // Use existing separate comparison methods
        let similar_pairs = if type_literals_only {
            Vec::new()
        } else {
            find_similar_types(&all_types, threshold, &options)
        };

        let type_literal_pairs = if include_type_literals && !type_literals_only {
            find_similar_type_literals(&all_type_literals, &all_types, threshold, &options)
        } else {
            Vec::new()
        };

        let type_literal_to_literal_pairs = if include_type_literals {
            similarity_core::find_similar_type_literals_pairs(
                &all_type_literals,
                threshold,
                &options,
            )
        } else {
            Vec::new()
        };

        (similar_pairs, type_literal_pairs, type_literal_to_literal_pairs)
    };

    if similar_pairs.is_empty()
        && type_literal_pairs.is_empty()
        && type_literal_to_literal_pairs.is_empty()
    {
        println!("\nNo similar types found!");
    } else {
        if !similar_pairs.is_empty() {
            println!("\nSimilar types found:");
            println!("{}", "-".repeat(60));

            for pair in &similar_pairs {
                // Get relative paths
                let relative_path1 = get_relative_path(&pair.type1.file_path);
                let relative_path2 = get_relative_path(&pair.type2.file_path);

                println!(
                    "\nSimilarity: {:.2}% (structural: {:.2}%, naming: {:.2}%)",
                    pair.result.similarity * 100.0,
                    pair.result.structural_similarity * 100.0,
                    pair.result.naming_similarity * 100.0
                );
                println!(
                    "  {}:{} | L{}-{} similar-type: {} ({})",
                    relative_path1,
                    pair.type1.start_line,
                    pair.type1.start_line,
                    pair.type1.end_line,
                    pair.type1.name,
                    format_type_kind(&pair.type1.kind)
                );
                println!(
                    "  {}:{} | L{}-{} similar-type: {} ({})",
                    relative_path2,
                    pair.type2.start_line,
                    pair.type2.start_line,
                    pair.type2.end_line,
                    pair.type2.name,
                    format_type_kind(&pair.type2.kind)
                );

                if print {
                    show_type_details(&pair.type1);
                    show_type_details(&pair.type2);
                    show_comparison_details(&pair.result);
                }
            }

            println!("\nTotal similar type pairs found: {}", similar_pairs.len());
        }

        if !type_literal_pairs.is_empty() {
            println!("\nType literals similar to type definitions:");
            println!("{}", "-".repeat(60));

            for pair in &type_literal_pairs {
                let literal_path = get_relative_path(&pair.type_literal.file_path);
                let def_path = get_relative_path(&pair.type_definition.file_path);

                println!(
                    "\nSimilarity: {:.2}% (structural: {:.2}%, naming: {:.2}%)",
                    pair.result.similarity * 100.0,
                    pair.result.structural_similarity * 100.0,
                    pair.result.naming_similarity * 100.0
                );
                println!(
                    "  {}:{} | L{} similar-type-literal: {}",
                    literal_path,
                    pair.type_literal.start_line,
                    pair.type_literal.start_line,
                    pair.type_literal.name
                );
                println!(
                    "  {}:{} | L{}-{} similar-type: {} ({})",
                    def_path,
                    pair.type_definition.start_line,
                    pair.type_definition.start_line,
                    pair.type_definition.end_line,
                    pair.type_definition.name,
                    format_type_kind(&pair.type_definition.kind)
                );

                if print {
                    show_type_literal_details(&pair.type_literal);
                    show_type_details(&pair.type_definition);
                    show_comparison_details(&pair.result);
                }
            }

            println!("\nTotal type literal pairs found: {}", type_literal_pairs.len());
        }

        if !type_literal_to_literal_pairs.is_empty() {
            println!("\nSimilar type literals found:");
            println!("{}", "-".repeat(60));

            for (literal1, literal2, result) in &type_literal_to_literal_pairs {
                let path1 = get_relative_path(&literal1.file_path);
                let path2 = get_relative_path(&literal2.file_path);

                println!(
                    "\nSimilarity: {:.2}% (structural: {:.2}%, naming: {:.2}%)",
                    result.similarity * 100.0,
                    result.structural_similarity * 100.0,
                    result.naming_similarity * 100.0
                );
                println!(
                    "  {}:{} | L{} type-literal: {}",
                    path1, literal1.start_line, literal1.start_line, literal1.name
                );
                println!(
                    "  {}:{} | L{} type-literal: {}",
                    path2, literal2.start_line, literal2.start_line, literal2.name
                );

                if print {
                    show_type_literal_details(literal1);
                    show_type_literal_details(literal2);
                    show_comparison_details(result);
                }
            }

            println!(
                "\nTotal similar type literal pairs found: {}",
                type_literal_to_literal_pairs.len()
            );
        }
    }

    Ok(similar_pairs.len() + type_literal_pairs.len() + type_literal_to_literal_pairs.len())
}

fn get_relative_path(file_path: &str) -> String {
    if let Ok(current_dir) = std::env::current_dir() {
        std::path::Path::new(file_path)
            .strip_prefix(&current_dir)
            .unwrap_or(std::path::Path::new(file_path))
            .to_string_lossy()
            .to_string()
    } else {
        file_path.to_string()
    }
}

fn format_type_kind(kind: &similarity_core::TypeKind) -> &'static str {
    match kind {
        similarity_core::TypeKind::Interface => "interface",
        similarity_core::TypeKind::TypeAlias => "type",
        similarity_core::TypeKind::TypeLiteral => "type literal",
    }
}

fn show_type_details(type_def: &similarity_core::TypeDefinition) {
    println!("\n\x1b[36m--- {} ({}) ---\x1b[0m", type_def.name, format_type_kind(&type_def.kind));

    if !type_def.generics.is_empty() {
        println!("Generics: <{}>", type_def.generics.join(", "));
    }

    if !type_def.extends.is_empty() {
        println!("Extends: {}", type_def.extends.join(", "));
    }

    if !type_def.properties.is_empty() {
        println!("Properties:");
        for prop in &type_def.properties {
            let modifiers = if prop.readonly { "readonly " } else { "" };
            let optional = if prop.optional { "?" } else { "" };
            println!("  {}{}{}: {}", modifiers, prop.name, optional, prop.type_annotation);
        }
    }
}

fn show_type_literal_details(type_literal: &similarity_core::TypeLiteralDefinition) {
    println!("\n\x1b[36m--- {} (type literal) ---\x1b[0m", type_literal.name);

    println!("Context: {}", format_type_literal_context(&type_literal.context));

    if !type_literal.properties.is_empty() {
        println!("Properties:");
        for prop in &type_literal.properties {
            let modifiers = if prop.readonly { "readonly " } else { "" };
            let optional = if prop.optional { "?" } else { "" };
            println!("  {}{}{}: {}", modifiers, prop.name, optional, prop.type_annotation);
        }
    }
}

fn format_type_literal_context(context: &similarity_core::TypeLiteralContext) -> String {
    match context {
        similarity_core::TypeLiteralContext::FunctionReturn(name) => {
            format!("Function '{}' return type", name)
        }
        similarity_core::TypeLiteralContext::FunctionParameter(func_name, param_name) => {
            format!("Function '{}' parameter '{}'", func_name, param_name)
        }
        similarity_core::TypeLiteralContext::VariableDeclaration(name) => {
            format!("Variable '{}' type annotation", name)
        }
        similarity_core::TypeLiteralContext::ArrowFunctionReturn(name) => {
            format!("Arrow function '{}' return type", name)
        }
    }
}

#[allow(clippy::too_many_arguments)]
fn check_overlaps(
    paths: Vec<String>,
    threshold: f64,
    extensions: Option<&Vec<String>>,
    print: bool,
    min_window_size: u32,
    max_window_size: u32,
    size_tolerance: f64,
    exclude_patterns: &[String],
) -> anyhow::Result<usize> {
    use ignore::WalkBuilder;
    use similarity_core::{find_overlaps_across_files, OverlapOptions};
    use std::collections::{HashMap, HashSet};
    use std::fs;
    use std::path::Path;

    let default_extensions = vec!["js", "ts", "jsx", "tsx", "mjs", "mts", "cjs", "cts"];
    let exts: Vec<&str> =
        extensions.map_or(default_extensions, |v| v.iter().map(String::as_str).collect());

    let exclude_matcher = create_exclude_matcher(exclude_patterns);
    let mut files = Vec::new();
    let mut visited = HashSet::new();

    // Process each path
    for path_str in &paths {
        let path = Path::new(path_str);

        if path.is_file() {
            // If it's a file, check extension and add it
            if let Some(ext) = path.extension() {
                if let Some(ext_str) = ext.to_str() {
                    if exts.contains(&ext_str) {
                        if let Ok(canonical) = path.canonicalize() {
                            if visited.insert(canonical.clone()) {
                                files.push(path.to_path_buf());
                            }
                        }
                    }
                }
            }
        } else if path.is_dir() {
            // If it's a directory, walk it respecting .gitignore
            let walker = WalkBuilder::new(path)
                .follow_links(false)
                .git_ignore(true) // Respect .gitignore files
                .git_global(true) // Respect global gitignore
                .git_exclude(true) // Respect .git/info/exclude
                .build();

            for entry in walker {
                let entry = entry?;
                let entry_path = entry.path();

                // Skip if not a file
                if !entry_path.is_file() {
                    continue;
                }

                // Check if path should be excluded
                if let Some(ref matcher) = exclude_matcher {
                    // Check both the full path and relative path from the search root
                    if matcher.is_match(entry_path) {
                        continue;
                    }

                    // Also check relative path from current directory
                    if let Ok(current_dir) = std::env::current_dir() {
                        if let Ok(relative) = entry_path.strip_prefix(&current_dir) {
                            if matcher.is_match(relative) {
                                continue;
                            }
                        }
                    }
                }

                // Check extension
                if let Some(ext) = entry_path.extension() {
                    if let Some(ext_str) = ext.to_str() {
                        if exts.contains(&ext_str) {
                            // Get canonical path to avoid duplicates
                            if let Ok(canonical) = entry_path.canonicalize() {
                                if visited.insert(canonical.clone()) {
                                    files.push(entry_path.to_path_buf());
                                }
                            }
                        }
                    }
                }
            }
        } else {
            eprintln!("Warning: Path not found: {}", path_str);
        }
    }

    if files.is_empty() {
        println!("No JavaScript/TypeScript files found in specified paths");
        return Ok(0);
    }

    println!("Checking {} files for overlapping code...\n", files.len());

    // Read all file contents
    let mut file_contents = HashMap::new();
    for file in &files {
        match fs::read_to_string(file) {
            Ok(content) => {
                let file_str = file.to_string_lossy().to_string();
                file_contents.insert(file_str, content);
            }
            Err(e) => {
                eprintln!("Error reading {}: {}", file.display(), e);
            }
        }
    }

    // Set up overlap options
    let options = OverlapOptions { min_window_size, max_window_size, threshold, size_tolerance };

    // Find overlaps
    let overlaps = find_overlaps_across_files(&file_contents, &options)?;

    if overlaps.is_empty() {
        println!("\nNo code overlaps found!");
    } else {
        println!("\nCode overlaps found:");
        println!("{}", "-".repeat(60));

        for overlap_with_files in &overlaps {
            let overlap = &overlap_with_files.overlap;
            let source_path = get_relative_path(&overlap_with_files.source_file);
            let target_path = get_relative_path(&overlap_with_files.target_file);

            println!(
                "\nSimilarity: {:.2}% | {} nodes | {}",
                overlap.similarity * 100.0,
                overlap.node_count,
                overlap.node_type
            );
            println!(
                "  {}:{} | L{}-{} in function: {}",
                source_path,
                overlap.source_lines.0,
                overlap.source_lines.0,
                overlap.source_lines.1,
                overlap.source_function
            );
            println!(
                "  {}:{} | L{}-{} in function: {}",
                target_path,
                overlap.target_lines.0,
                overlap.target_lines.0,
                overlap.target_lines.1,
                overlap.target_function
            );

            if print {
                // Extract and display the overlapping code
                if let Some(source_content) = file_contents.get(&overlap_with_files.source_file) {
                    if let Some(target_content) = file_contents.get(&overlap_with_files.target_file)
                    {
                        println!("\n\x1b[36m--- Source Code ---\x1b[0m");
                        if let Ok(source_segment) = extract_code_lines(
                            source_content,
                            overlap.source_lines.0,
                            overlap.source_lines.1,
                        ) {
                            println!("{}", source_segment);
                        }

                        println!("\n\x1b[36m--- Target Code ---\x1b[0m");
                        if let Ok(target_segment) = extract_code_lines(
                            target_content,
                            overlap.target_lines.0,
                            overlap.target_lines.1,
                        ) {
                            println!("{}", target_segment);
                        }
                    }
                }
            }
        }

        println!("\nTotal overlaps found: {}", overlaps.len());
    }

    Ok(overlaps.len())
}

fn extract_code_lines(code: &str, start_line: u32, end_line: u32) -> Result<String, String> {
    let lines: Vec<_> = code.lines().collect();

    if start_line as usize > lines.len() || end_line as usize > lines.len() {
        return Err("Line numbers out of bounds".to_string());
    }

    let start = (start_line as usize).saturating_sub(1);
    let end = (end_line as usize).min(lines.len());

    Ok(lines[start..end].join("\n"))
}

fn show_comparison_details(result: &similarity_core::TypeComparisonResult) {
    if !result.differences.missing_properties.is_empty() {
        println!("Missing properties: {}", result.differences.missing_properties.join(", "));
    }

    if !result.differences.extra_properties.is_empty() {
        println!("Extra properties: {}", result.differences.extra_properties.join(", "));
    }

    if !result.differences.type_mismatches.is_empty() {
        println!("Type mismatches:");
        for mismatch in &result.differences.type_mismatches {
            println!("  {}: {} vs {}", mismatch.property, mismatch.type1, mismatch.type2);
        }
    }

    if !result.differences.optionality_differences.is_empty() {
        println!(
            "Optionality differences: {}",
            result.differences.optionality_differences.join(", ")
        );
    }
}

#[allow(clippy::too_many_arguments)]
fn check_classes(
    paths: Vec<String>,
    threshold: f64,
    extensions: Option<&Vec<String>>,
    print: bool,
    no_inheritance: bool,
    no_implements: bool,
    suggest: bool,
    exclude_patterns: &[String],
    show_ignored: bool,
) -> anyhow::Result<usize> {
    use ignore::WalkBuilder;
    use similarity_core::{extract_classes_from_code, find_similar_classes};
    use std::collections::HashSet;
    use std::fs;
    use std::path::Path;

    let default_extensions = vec!["ts", "tsx", "mts", "cts"];
    let exts: Vec<&str> =
        extensions.map_or(default_extensions, |v| v.iter().map(String::as_str).collect());

    let exclude_matcher = create_exclude_matcher(exclude_patterns);
    let mut files = Vec::new();
    let mut visited = HashSet::new();

    // Process each path
    for path_str in &paths {
        let path = Path::new(path_str);

        if path.is_file() {
            // If it's a file, check extension and add it
            if let Some(ext) = path.extension() {
                if let Some(ext_str) = ext.to_str() {
                    if exts.contains(&ext_str) {
                        if let Ok(canonical) = path.canonicalize() {
                            if visited.insert(canonical.clone()) {
                                files.push(path.to_path_buf());
                            }
                        }
                    }
                }
            }
        } else if path.is_dir() {
            // If it's a directory, walk it respecting .gitignore
            let walker = WalkBuilder::new(path)
                .follow_links(false)
                .git_ignore(true) // Respect .gitignore files
                .git_global(true) // Respect global gitignore
                .git_exclude(true) // Respect .git/info/exclude
                .build();

            for entry in walker {
                let entry = entry?;
                let entry_path = entry.path();

                // Skip if not a file
                if !entry_path.is_file() {
                    continue;
                }

                // Check if path should be excluded
                if let Some(ref matcher) = exclude_matcher {
                    // Check both the full path and relative path from the search root
                    if matcher.is_match(entry_path) {
                        continue;
                    }

                    // Also check relative path from current directory
                    if let Ok(current_dir) = std::env::current_dir() {
                        if let Ok(relative) = entry_path.strip_prefix(&current_dir) {
                            if matcher.is_match(relative) {
                                continue;
                            }
                        }
                    }
                }

                // Check extension
                if let Some(ext) = entry_path.extension() {
                    if let Some(ext_str) = ext.to_str() {
                        if exts.contains(&ext_str) {
                            // Get canonical path to avoid duplicates
                            if let Ok(canonical) = entry_path.canonicalize() {
                                if visited.insert(canonical.clone()) {
                                    files.push(entry_path.to_path_buf());
                                }
                            }
                        }
                    }
                }
            }
        } else {
            eprintln!("Warning: Path not found: {}", path_str);
        }
    }

    if files.is_empty() {
        println!("No TypeScript files found in specified paths");
        return Ok(0);
    }

    println!("Checking {} files for similar classes...\n", files.len());

    // Extract classes from all files
    let mut all_classes = Vec::new();
    let mut excluded_classes = Vec::new();
    let mut ignored_classes = Vec::new();

    for file in &files {
        match fs::read_to_string(file) {
            Ok(content) => {
                let file_str = file.to_string_lossy();

                // Extract classes
                match extract_classes_from_code(&content, &file_str) {
                    Ok(classes) => {
                        for class in classes {
                            if class.has_ignore_directive {
                                if show_ignored {
                                    ignored_classes.push((
                                        file.display().to_string(),
                                        class.name.clone(),
                                        class.start_line,
                                    ));
                                }
                                continue;
                            }

                            // Check if class should be excluded
                            let excluded_by_inheritance = no_inheritance && class.extends.is_some();
                            let excluded_by_implements =
                                no_implements && !class.implements.is_empty();

                            if excluded_by_inheritance || excluded_by_implements {
                                excluded_classes.push(class);
                            } else {
                                all_classes.push(class);
                            }
                        }
                    }
                    Err(e) => {
                        // Skip files with parse errors silently
                        if !e.contains("Parse errors:") {
                            eprintln!("Error in {}: {}", file.display(), e);
                        }
                    }
                }
            }
            Err(e) => {
                eprintln!("Error reading {}: {}", file.display(), e);
            }
        }
    }

    if all_classes.is_empty() {
        println!("No class definitions found!");
        return Ok(0);
    }

    println!("Found {} class definitions", all_classes.len());
    if show_ignored && !ignored_classes.is_empty() {
        println!("Ignored {} class(es) via similarity-ignore directive:", ignored_classes.len());
        for (file, name, line) in &ignored_classes {
            println!("  {}:{} {}", file, line, name);
        }
        println!();
    }

    if !excluded_classes.is_empty() {
        println!("Excluded {} classes:", excluded_classes.len());
        for class in &excluded_classes {
            let reason = if class.extends.is_some() && !class.implements.is_empty() {
                "extends & implements"
            } else if class.extends.is_some() {
                "extends"
            } else {
                "implements"
            };
            println!("  - {} ({})", class.name, reason);
        }
        println!();
    }

    // Find similar classes across all files
    let similar_pairs = find_similar_classes(&all_classes, threshold);

    if similar_pairs.is_empty() {
        println!("\nNo similar classes found!");
    } else {
        println!("\nSimilar classes found:");
        println!("{}", "-".repeat(60));

        for pair in &similar_pairs {
            // Get relative paths
            let relative_path1 = get_relative_path(&pair.class1.file_path);
            let relative_path2 = get_relative_path(&pair.class2.file_path);

            println!(
                "\nSimilarity: {:.2}% (structural: {:.2}%, naming: {:.2}%)",
                pair.result.similarity * 100.0,
                pair.result.structural_similarity * 100.0,
                pair.result.naming_similarity * 100.0
            );
            println!(
                "  {}:{} | L{}-{} similar-class: {}",
                relative_path1,
                pair.class1.start_line,
                pair.class1.start_line,
                pair.class1.end_line,
                pair.class1.name
            );
            println!(
                "  {}:{} | L{}-{} similar-class: {}",
                relative_path2,
                pair.class2.start_line,
                pair.class2.start_line,
                pair.class2.end_line,
                pair.class2.name
            );

            if print {
                show_class_details(&pair.class1);
                show_class_details(&pair.class2);
                show_class_comparison_details(&pair.result);
            }
        }

        println!("\nTotal similar class pairs found: {}", similar_pairs.len());
    }

    // Suggest possible interface implementations (only when --suggest is enabled)
    if suggest && !excluded_classes.is_empty() {
        println!("\n{}", "=".repeat(60));
        println!("💡 Refactoring suggestions:");

        // Check if excluded classes could implement a common interface
        let implements_classes: Vec<_> =
            excluded_classes.iter().filter(|c| !c.implements.is_empty()).collect();

        if !implements_classes.is_empty() {
            println!("\nClasses implementing interfaces that could be unified:");
            for class in &implements_classes {
                println!("  - {} implements {}", class.name, class.implements.join(", "));
            }
        }

        // Check if excluded classes with same base could be refactored
        let mut extends_map = std::collections::HashMap::new();
        for class in &excluded_classes {
            if let Some(base) = &class.extends {
                extends_map.entry(base.clone()).or_insert(Vec::new()).push(class.name.clone());
            }
        }

        if !extends_map.is_empty() {
            println!("\nClasses extending same base class:");
            for (base, classes) in extends_map {
                if classes.len() > 1 {
                    println!("  - Base: {} -> [{}]", base, classes.join(", "));
                }
            }
        }

        // Suggest looking for similar classes if found
        if !similar_pairs.is_empty() {
            println!(
                "\n⚠️  Found {} similar class pairs that might benefit from:",
                similar_pairs.len()
            );
            println!("  - Extracting a common interface");
            println!("  - Creating a shared base class");
            println!("  - Using composition instead of duplication");
        }
    }

    Ok(similar_pairs.len())
}

fn show_class_details(class: &similarity_core::ClassDefinition) {
    println!("\n\x1b[36m--- Class {} ---\x1b[0m", class.name);

    if let Some(extends) = &class.extends {
        println!("Extends: {}", extends);
    }

    if !class.implements.is_empty() {
        println!("Implements: {}", class.implements.join(", "));
    }

    if !class.properties.is_empty() {
        println!("Properties:");
        for prop in &class.properties {
            let modifiers = format!(
                "{}{}{}",
                if prop.is_static { "static " } else { "" },
                if prop.is_readonly { "readonly " } else { "" },
                if prop.is_private { "private " } else { "" }
            );
            let optional = if prop.is_optional { "?" } else { "" };
            println!("  {}{}{}: {}", modifiers, prop.name, optional, prop.type_annotation);
        }
    }

    if !class.methods.is_empty() {
        println!("Methods:");
        for method in &class.methods {
            let modifiers = format!(
                "{}{}{}{}",
                if method.is_static { "static " } else { "" },
                if method.is_private { "private " } else { "" },
                if method.is_async { "async " } else { "" },
                if method.is_generator { "*" } else { "" }
            );
            let kind_str = match method.kind {
                similarity_core::MethodKind::Getter => "get ",
                similarity_core::MethodKind::Setter => "set ",
                _ => "",
            };
            println!(
                "  {}{}{}({}): {}",
                modifiers,
                kind_str,
                method.name,
                method.parameters.join(", "),
                method.return_type
            );
        }
    }
}

fn show_class_comparison_details(result: &similarity_core::ClassComparisonResult) {
    if !result.differences.missing_properties.is_empty() {
        println!("Missing properties: {}", result.differences.missing_properties.join(", "));
    }

    if !result.differences.extra_properties.is_empty() {
        println!("Extra properties: {}", result.differences.extra_properties.join(", "));
    }

    if !result.differences.missing_methods.is_empty() {
        println!("Missing methods: {}", result.differences.missing_methods.join(", "));
    }

    if !result.differences.extra_methods.is_empty() {
        println!("Extra methods: {}", result.differences.extra_methods.join(", "));
    }

    if !result.differences.property_type_mismatches.is_empty() {
        println!("Property type mismatches:");
        for mismatch in &result.differences.property_type_mismatches {
            println!("  {}: {} vs {}", mismatch.name, mismatch.type1, mismatch.type2);
        }
    }

    if !result.differences.method_signature_mismatches.is_empty() {
        println!("Method signature mismatches:");
        for mismatch in &result.differences.method_signature_mismatches {
            println!("  {}: {} vs {}", mismatch.name, mismatch.signature1, mismatch.signature2);
        }
    }
}