tldr-core 0.1.2

Core analysis engine for TLDR code analysis tool
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
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
//! Clone Detection v2 Tests
//!
//! These tests define CORRECT behavior for the v2 rewrite of clone detection.
//! They target the six known bugs in v1:
//!
//! - BUG-1: Fabricated line numbers (not from tree-sitter)
//! - BUG-2: min_lines parameter ignored
//! - BUG-3: include_within_file logic error (only skips overlapping same-file)
//! - BUG-4: Catastrophic false positives from normalization + bag-of-tokens
//! - BUG-5: CloneFragment.preview never populated
//! - BUG-6: Fixed 25-token windows instead of syntactic boundaries
//!
//! These tests verify the clones detection module.
//! That is expected -- this is the TDD "write failing tests first" phase.
//!
//! # Test Categories
//!
//! 1. Accurate line numbers (BUG-1 fix)
//! 2. Function-level fragment extraction (BUG-6 fix)
//! 3. No false positives (BUG-4 fix)
//! 4. Preview populated (BUG-5 fix)
//! 5. include_within_file semantics (BUG-3 fix)
//! 6. min_lines enforced (BUG-2 fix)
//! 7. Sequence matching (prior art: Type-1/2/3 detection)
//! 8. JSON serialization preserved (backward compat)
//! 9. Existing preserved behaviors (is_test_file, is_generated_file, defaults)


// =============================================================================
// Fixture Helpers
// =============================================================================

/// Helper module for creating temp directories with known source files
mod v2_fixtures {
    use std::path::{Path, PathBuf};
    use tempfile::TempDir;

    /// Temporary directory that cleans up on drop
    pub struct V2TestDir {
        pub dir: TempDir,
    }

    impl V2TestDir {
        pub fn new() -> std::io::Result<Self> {
            Ok(Self {
                dir: TempDir::new()?,
            })
        }

        pub fn path(&self) -> &Path {
            self.dir.path()
        }

        /// Write a file relative to the temp dir, creating parent dirs as needed
        pub fn write_file(&self, rel_path: &str, content: &str) -> std::io::Result<PathBuf> {
            let path = self.dir.path().join(rel_path);
            if let Some(parent) = path.parent() {
                std::fs::create_dir_all(parent)?;
            }
            std::fs::write(&path, content)?;
            Ok(path)
        }
    }

    // =========================================================================
    // Python fixtures -- three functions with known line numbers
    // =========================================================================

    /// A Python file with exactly 3 functions at known line positions.
    /// Line 1:  def add(a, b):
    /// Line 2:      return a + b
    /// Line 3:  (blank)
    /// Line 4:  def multiply(a, b):
    /// Line 5:      result = a * b
    /// Line 6:      return result
    /// Line 7:  (blank)
    /// Line 8:  def factorial(n):
    /// Line 9:      if n <= 1:
    /// Line 10:         return 1
    /// Line 11:     return n * factorial(n - 1)
    pub const PYTHON_THREE_FUNCTIONS: &str = "def add(a, b):\n    return a + b\n\ndef multiply(a, b):\n    result = a * b\n    return result\n\ndef factorial(n):\n    if n <= 1:\n        return 1\n    return n * factorial(n - 1)\n";

    /// Python file: function starts at line 1, ends at line 15
    pub const PYTHON_LONG_FUNCTION_A: &str = "\
def process_records(records):
    results = []
    for record in records:
        name = record.get('name', '')
        age = record.get('age', 0)
        email = record.get('email', '')
        if not name:
            continue
        if age < 0:
            continue
        processed = {'name': name, 'age': age, 'email': email}
        results.append(processed)
    return results
";

    /// Identical function with different name (Type-1 after normalization / raw Type-2)
    pub const PYTHON_LONG_FUNCTION_B: &str = "\
def process_records(records):
    results = []
    for record in records:
        name = record.get('name', '')
        age = record.get('age', 0)
        email = record.get('email', '')
        if not name:
            continue
        if age < 0:
            continue
        processed = {'name': name, 'age': age, 'email': email}
        results.append(processed)
    return results
";

    /// Same structure, renamed identifiers (Type-2 clone)
    pub const PYTHON_LONG_FUNCTION_RENAMED: &str = "\
def handle_entries(entries):
    output = []
    for entry in entries:
        label = entry.get('label', '')
        count = entry.get('count', 0)
        addr = entry.get('addr', '')
        if not label:
            continue
        if count < 0:
            continue
        item = {'label': label, 'count': count, 'addr': addr}
        output.append(item)
    return output
";

    /// Completely different function -- must NOT match
    pub const PYTHON_UNRELATED_FUNCTION: &str = "\
def fibonacci(n):
    if n <= 0:
        return 0
    elif n == 1:
        return 1
    a, b = 0, 1
    for _ in range(2, n + 1):
        a, b = b, a + b
    return b
";

    /// Two functions that share keywords but have different identifiers and structure
    pub const PYTHON_KEYWORD_OVERLAP_A: &str = "\
def check_permissions(user, resource):
    if user.is_admin:
        return True
    if resource.is_public:
        return True
    for role in user.roles:
        if role.has_access(resource):
            return True
    return False
";

    pub const PYTHON_KEYWORD_OVERLAP_B: &str = "\
def validate_input(data, schema):
    if data is None:
        return False
    if schema is None:
        return True
    for field in schema.fields:
        if field.required and field.name not in data:
            return False
    return True
";

    /// Import-heavy files that differ only in imports
    pub const PYTHON_IMPORT_HEAVY_A: &str = "\
from os import path
from sys import argv
from collections import defaultdict
from typing import List, Dict, Optional

def compute(x):
    return x * 2
";

    pub const PYTHON_IMPORT_HEAVY_B: &str = "\
from json import loads
from io import StringIO
from functools import reduce
from typing import Tuple, Set, Any

def transform(y):
    return y + 1
";

    /// A 3-line function (below min_lines=5 threshold)
    pub const PYTHON_SHORT_3_LINES: &str = "\
def tiny(x):
    y = x + 1
    return y
";

    /// A 5-line function (exactly at min_lines=5 threshold)
    pub const PYTHON_EXACTLY_5_LINES: &str = "\
def medium(data):
    result = []
    for item in data:
        result.append(item * 2)
    return result
";

    /// Same as medium but renamed (for min_lines boundary testing)
    pub const PYTHON_EXACTLY_5_LINES_COPY: &str = "\
def medium_copy(data):
    result = []
    for item in data:
        result.append(item * 2)
    return result
";

    /// File with two non-overlapping functions for within-file testing
    pub const PYTHON_TWO_FUNCTIONS_SAME_FILE: &str = "\
def handler_create(request):
    data = request.get_json()
    if not data:
        return {'error': 'No data provided'}, 400
    if 'name' not in data:
        return {'error': 'Name required'}, 400
    result = create_item(data)
    return {'id': result.id}, 201

def handler_update(request, item_id):
    data = request.get_json()
    if not data:
        return {'error': 'No data provided'}, 400
    if 'name' not in data:
        return {'error': 'Name required'}, 400
    result = update_item(item_id, data)
    return {'id': result.id}, 200
";

    // =========================================================================
    // Rust fixtures -- impl block with methods
    // =========================================================================

    /// Rust file with an impl block containing two methods.
    /// The impl block starts at line 5, method `new` at line 6, `area` at line 13.
    pub const RUST_IMPL_BLOCK: &str = "\
struct Rectangle {
    width: f64,
    height: f64,
}

impl Rectangle {
    fn new(width: f64, height: f64) -> Self {
        Self {
            width,
            height,
        }
    }

    fn area(&self) -> f64 {
        self.width * self.height
    }

    fn perimeter(&self) -> f64 {
        2.0 * (self.width + self.height)
    }
}
";

    // =========================================================================
    // Type-3 gap fixtures
    // =========================================================================

    /// Original function for Type-3 testing (~14 lines of code)
    pub const PYTHON_TYPE3_BASE: &str = "\
def process_data(data):
    result = []
    for item in data:
        if item is None:
            continue
        processed = transform(item)
        if processed.is_valid():
            result.append(processed)
    return result
";

    /// Same function with 2 added logging statements (~70-90% similar)
    pub const PYTHON_TYPE3_WITH_LOGGING: &str = "\
def process_data_logged(data):
    print('Starting processing')
    result = []
    for item in data:
        if item is None:
            continue
        processed = transform(item)
        print(f'Processed: {processed}')
        if processed.is_valid():
            result.append(processed)
    return result
";

    /// Completely different function -- must NOT be a Type-3 match
    pub const PYTHON_TYPE3_UNRELATED: &str = "\
def render_template(name, context):
    loader = FileSystemLoader('templates')
    env = Environment(loader=loader)
    template = env.get_template(name)
    output = template.render(context)
    return output
";

    // =========================================================================
    // Sequence matching fixtures (identical / renamed / gapped / different)
    // =========================================================================

    /// Two files with identical token sequences (Type-1, similarity 1.0)
    pub const SEQ_IDENTICAL_A: &str = "\
def compute_sum(values):
    total = 0
    for v in values:
        total += v
    return total
";

    pub const SEQ_IDENTICAL_B: &str = "\
def compute_sum(values):
    total = 0
    for v in values:
        total += v
    return total
";

    /// Renamed identifiers but same structure (Type-2, 0.9+)
    pub const SEQ_RENAMED_A: &str = "\
def calculate_total(numbers):
    accumulator = 0
    for num in numbers:
        accumulator += num
    return accumulator
";

    pub const SEQ_RENAMED_B: &str = "\
def sum_values(items):
    result = 0
    for item in items:
        result += item
    return result
";

    /// A few statements added/removed (Type-3, 0.7-0.9)
    pub const SEQ_GAPPED_A: &str = "\
def fetch_data(url):
    response = requests.get(url)
    if response.status_code != 200:
        raise Exception('Failed')
    data = response.json()
    return data
";

    pub const SEQ_GAPPED_B: &str = "\
def fetch_data_with_retry(url):
    for attempt in range(3):
        response = requests.get(url)
        if response.status_code != 200:
            continue
        data = response.json()
        return data
    raise Exception('All retries failed')
";

    /// Completely different (no match expected)
    pub const SEQ_DIFFERENT_A: &str = "\
def sort_descending(items):
    return sorted(items, reverse=True)
";

    pub const SEQ_DIFFERENT_B: &str = "\
class DatabaseConnection:
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.connected = False
";
}

// =============================================================================
// 1. ACCURATE LINE NUMBERS (BUG-1 fix)
// =============================================================================

#[cfg(test)]
mod accurate_line_numbers {
    use super::v2_fixtures::*;
    use crate::analysis::clones::detect_clones;

    /// Test: Python file with 3 functions -- each function should have exact
    /// start/end lines from tree-sitter, not fabricated from token indices.
    ///
    /// BUG-1 in v1: line numbers are computed as `tokens.len() / 5 + 1` or
    /// `start / 10 + 1` which are arbitrary approximations.
    ///
    /// v2 REQ-3: Use `node.start_position().row + 1` from tree-sitter.
    #[test]
    fn test_python_function_line_numbers_match_tree_sitter() {
        let td = V2TestDir::new().unwrap();
        td.write_file("a.py", PYTHON_THREE_FUNCTIONS).unwrap();
        // Write a second copy so detection has something to compare against
        td.write_file("b.py", PYTHON_THREE_FUNCTIONS).unwrap();

        let opts = crate::analysis::clones::ClonesOptions { language: Some("python".to_string()), min_tokens: 5, min_lines: 1, ..Default::default() };

        let report = detect_clones(td.path(), &opts).unwrap();

        // We should have at least some clone pairs between a.py and b.py
        assert!(
            !report.clone_pairs.is_empty(),
            "Expected clone pairs between identical files"
        );

        // Verify that line numbers are within actual file bounds (11 lines)
        for pair in &report.clone_pairs {
            assert!(
                pair.fragment1.start_line >= 1,
                "start_line must be >= 1, got {}",
                pair.fragment1.start_line
            );
            assert!(
                pair.fragment1.end_line <= 11,
                "end_line must be <= 11 (actual file length), got {}. \
                 This suggests fabricated line numbers (BUG-1).",
                pair.fragment1.end_line
            );
            assert!(
                pair.fragment1.start_line <= pair.fragment1.end_line,
                "start_line ({}) must be <= end_line ({})",
                pair.fragment1.start_line,
                pair.fragment1.end_line
            );
            // Same checks for fragment2
            assert!(
                pair.fragment2.start_line >= 1 && pair.fragment2.end_line <= 11,
                "fragment2 line numbers out of bounds: {}-{}",
                pair.fragment2.start_line,
                pair.fragment2.end_line
            );
        }
    }

    /// Test: Rust file with impl block -- methods should have correct line ranges
    /// from tree-sitter, not token-index heuristics.
    #[test]
    fn test_rust_impl_block_method_line_ranges() {
        let td = V2TestDir::new().unwrap();
        td.write_file("a.rs", RUST_IMPL_BLOCK).unwrap();
        td.write_file("b.rs", RUST_IMPL_BLOCK).unwrap();

        let opts = crate::analysis::clones::ClonesOptions { language: Some("rust".to_string()), min_tokens: 5, min_lines: 1, ..Default::default() };

        let report = detect_clones(td.path(), &opts).unwrap();

        // Verify line numbers are within file bounds (22 lines)
        for pair in &report.clone_pairs {
            assert!(
                pair.fragment1.end_line <= 22,
                "Rust fragment end_line {} exceeds file length 22 (BUG-1 fabrication)",
                pair.fragment1.end_line
            );
            assert!(
                pair.fragment2.end_line <= 22,
                "Rust fragment2 end_line {} exceeds file length 22",
                pair.fragment2.end_line
            );
        }
    }

    /// Test: Line numbers for a 14-line Python function should never exceed 14.
    /// v1 with 50 tokens would report end_line = 50/5+1 = 11 (coincidentally close)
    /// but for different token counts the heuristic diverges wildly.
    #[test]
    fn test_line_numbers_not_derived_from_token_count() {
        let td = V2TestDir::new().unwrap();
        td.write_file("a.py", PYTHON_LONG_FUNCTION_A).unwrap();
        td.write_file("b.py", PYTHON_LONG_FUNCTION_B).unwrap();

        let opts = crate::analysis::clones::ClonesOptions { language: Some("python".to_string()), min_tokens: 5, min_lines: 1, ..Default::default() };

        let report = detect_clones(td.path(), &opts).unwrap();

        assert!(
            !report.clone_pairs.is_empty(),
            "Expected at least one clone pair"
        );

        for pair in &report.clone_pairs {
            // PYTHON_LONG_FUNCTION_A has 14 lines of text
            let frag = &pair.fragment1;
            let line_count = frag.end_line - frag.start_line + 1;

            // The function is ~14 lines. With v1's heuristic of tokens/5,
            // a function with 40+ tokens would report end_line > 14.
            // v2 must report actual line numbers.
            assert!(
                frag.end_line <= 14,
                "Fragment end_line {} exceeds actual file line count 14. \
                 Likely derived from token count, not tree-sitter. (BUG-1)",
                frag.end_line
            );
            assert!(
                line_count >= 5,
                "A 14-line function should produce a fragment of at least 5 lines, got {}",
                line_count
            );
        }
    }
}

// =============================================================================
// 2. FUNCTION-LEVEL FRAGMENT EXTRACTION (BUG-6 fix)
// =============================================================================

#[cfg(test)]
mod function_level_extraction {
    use super::v2_fixtures::*;
    use crate::analysis::clones::{detect_clones, CloneType};

    /// Test: Two identical Python functions in separate files -> detected as clone.
    /// v2 REQ-1: Use tree-sitter to extract function_definition nodes.
    #[test]
    fn test_identical_functions_detected_as_clone() {
        let td = V2TestDir::new().unwrap();
        td.write_file("src/a.py", PYTHON_LONG_FUNCTION_A).unwrap();
        td.write_file("src/b.py", PYTHON_LONG_FUNCTION_B).unwrap();

        let opts = crate::analysis::clones::ClonesOptions { language: Some("python".to_string()), min_tokens: 10, min_lines: 3, ..Default::default() };

        let report = detect_clones(td.path(), &opts).unwrap();

        assert_eq!(
            report.clone_pairs.len(),
            1,
            "Two identical functions should produce exactly 1 clone pair"
        );

        let pair = &report.clone_pairs[0];
        assert_eq!(
            pair.clone_type,
            CloneType::Type1,
            "Identical functions should be Type-1"
        );
        assert!(
            (pair.similarity - 1.0).abs() < 1e-6,
            "Type-1 clone should have similarity ~1.0, got {}",
            pair.similarity
        );
    }

    /// Test: Two completely different Python functions -> NOT detected as clones.
    /// This is the false positive guard.
    #[test]
    fn test_different_functions_not_detected() {
        let td = V2TestDir::new().unwrap();
        td.write_file("src/a.py", PYTHON_LONG_FUNCTION_A).unwrap();
        td.write_file("src/b.py", PYTHON_UNRELATED_FUNCTION)
            .unwrap();

        let opts = crate::analysis::clones::ClonesOptions { language: Some("python".to_string()), min_tokens: 10, min_lines: 3, ..Default::default() };

        let report = detect_clones(td.path(), &opts).unwrap();

        assert_eq!(
            report.clone_pairs.len(),
            0,
            "Completely different functions should NOT be detected as clones"
        );
    }

    /// Test: Fragment boundaries align with function definitions,
    /// not arbitrary token windows.
    /// v1 BUG-6: Fixed 25-token sliding windows cut through function boundaries.
    #[test]
    fn test_fragment_boundaries_are_syntactic() {
        let td = V2TestDir::new().unwrap();
        // A file with 3 separate functions
        td.write_file("a.py", PYTHON_THREE_FUNCTIONS).unwrap();
        td.write_file("b.py", PYTHON_THREE_FUNCTIONS).unwrap();

        let opts = crate::analysis::clones::ClonesOptions { language: Some("python".to_string()), min_tokens: 3, min_lines: 1, ..Default::default() };

        let report = detect_clones(td.path(), &opts).unwrap();

        // Each clone pair fragment should correspond to a function boundary.
        // In PYTHON_THREE_FUNCTIONS:
        //   add:       lines 1-2
        //   multiply:  lines 4-6
        //   factorial:  lines 8-11
        // Fragments should NOT have start_line in the middle of a function.
        for pair in &report.clone_pairs {
            let frag = &pair.fragment1;
            // Valid function start lines in our fixture are: 1, 4, 8
            let valid_starts = [1, 4, 8];
            assert!(
                valid_starts.contains(&frag.start_line),
                "Fragment start_line {} does not align with any function definition \
                 start (expected one of {:?}). This suggests token-window fragmentation \
                 instead of syntactic extraction (BUG-6).",
                frag.start_line,
                valid_starts
            );
        }
    }

    /// Test: Import-only differences do not create false positives.
    /// v2 should skip import/use statements during fragment extraction.
    #[test]
    fn test_import_differences_not_false_positive() {
        let td = V2TestDir::new().unwrap();
        td.write_file("src/a.py", PYTHON_IMPORT_HEAVY_A).unwrap();
        td.write_file("src/b.py", PYTHON_IMPORT_HEAVY_B).unwrap();

        let opts = crate::analysis::clones::ClonesOptions { language: Some("python".to_string()), min_tokens: 3, min_lines: 1, ..Default::default() };

        let report = detect_clones(td.path(), &opts).unwrap();

        // The actual function bodies (compute vs transform) are completely different.
        // Only the import patterns are structurally similar. Should NOT match.
        assert_eq!(
            report.clone_pairs.len(),
            0,
            "Files with different functions but similar import patterns \
             should NOT be detected as clones"
        );
    }

    /// Test: Renamed identifiers detected as Type-2
    #[test]
    fn test_renamed_identifiers_detected_as_type2() {
        let td = V2TestDir::new().unwrap();
        td.write_file("src/a.py", PYTHON_LONG_FUNCTION_A).unwrap();
        td.write_file("src/b.py", PYTHON_LONG_FUNCTION_RENAMED)
            .unwrap();

        let opts = crate::analysis::clones::ClonesOptions { language: Some("python".to_string()), min_tokens: 10, min_lines: 3, ..Default::default() };

        let report = detect_clones(td.path(), &opts).unwrap();

        assert_eq!(
            report.clone_pairs.len(),
            1,
            "Functions with renamed identifiers should produce 1 clone pair"
        );

        let pair = &report.clone_pairs[0];
        assert!(
            pair.clone_type == CloneType::Type2 || pair.clone_type == CloneType::Type1,
            "Renamed identifiers should be at least Type-2, got {:?}",
            pair.clone_type
        );
        assert!(
            pair.similarity >= 0.9,
            "Type-2 clone should have similarity >= 0.9, got {}",
            pair.similarity
        );
    }
}

// =============================================================================
// 3. NO FALSE POSITIVES (BUG-4 fix)
// =============================================================================

#[cfg(test)]
mod no_false_positives {
    use super::v2_fixtures::*;
    use crate::analysis::clones::detect_clones;

    /// Test: Two files with same keywords but different identifiers and structure
    /// should have similarity < 0.7 (below threshold).
    ///
    /// BUG-4: When normalization=All, all identifiers become $ID, making
    /// unrelated code appear similar in bag-of-tokens comparison.
    #[test]
    fn test_keyword_overlap_below_threshold() {
        let td = V2TestDir::new().unwrap();
        td.write_file("src/a.py", PYTHON_KEYWORD_OVERLAP_A).unwrap();
        td.write_file("src/b.py", PYTHON_KEYWORD_OVERLAP_B).unwrap();

        let opts = crate::analysis::clones::ClonesOptions { language: Some("python".to_string()), min_tokens: 10, min_lines: 3, ..Default::default() };

        let report = detect_clones(td.path(), &opts).unwrap();

        // These functions share keywords (if, return, True, False, for, in)
        // but have different identifiers and logic. Should NOT be clones.
        assert_eq!(
            report.clone_pairs.len(),
            0,
            "Functions with same keywords but different structure/identifiers \
             should NOT be detected as clones. This is the BUG-4 false positive."
        );
    }

    /// Test: Two files with `from X import Y` patterns are NOT clones.
    /// Import statements should be filtered out of fragment comparison.
    #[test]
    fn test_import_pattern_not_clones() {
        let td = V2TestDir::new().unwrap();
        td.write_file("src/a.py", PYTHON_IMPORT_HEAVY_A).unwrap();
        td.write_file("src/b.py", PYTHON_IMPORT_HEAVY_B).unwrap();

        let opts = crate::analysis::clones::ClonesOptions { language: Some("python".to_string()), min_tokens: 3, min_lines: 1, ..Default::default() };

        let report = detect_clones(td.path(), &opts).unwrap();

        assert_eq!(
            report.clone_pairs.len(),
            0,
            "Import-heavy files with different function bodies must not match"
        );
    }

    /// Test: Two structurally different functions that happen to use same
    /// keywords are NOT clones -- even with normalization=All.
    ///
    /// v2 REQ-7: Use raw tokens for Dice similarity, not normalized.
    #[test]
    fn test_different_structure_same_keywords_not_clones() {
        // check_permissions: if/return/for/if/return pattern
        // validate_input: if/return/if/return/for/if/return pattern
        // Structurally similar keyword flow but semantically different
        let td = V2TestDir::new().unwrap();
        td.write_file("src/check.py", PYTHON_KEYWORD_OVERLAP_A)
            .unwrap();
        td.write_file("src/validate.py", PYTHON_KEYWORD_OVERLAP_B)
            .unwrap();

        let mut opts = crate::analysis::clones::ClonesOptions { language: Some("python".to_string()), min_tokens: 5, min_lines: 3, ..Default::default() };
        // Explicitly use All normalization to stress-test BUG-4 fix
        opts.normalization = crate::analysis::clones::NormalizationMode::All;

        let report = detect_clones(td.path(), &opts).unwrap();

        assert_eq!(
            report.clone_pairs.len(),
            0,
            "Even with normalization=All, structurally different functions \
             should NOT be matched. v2 REQ-7 requires raw tokens for Dice."
        );
    }

    /// Test: An unrelated function should never match a real function.
    /// This is a basic sanity check for false positive rate.
    #[test]
    fn test_unrelated_functions_no_match() {
        let td = V2TestDir::new().unwrap();
        td.write_file("src/process.py", PYTHON_LONG_FUNCTION_A)
            .unwrap();
        td.write_file("src/fibonacci.py", PYTHON_UNRELATED_FUNCTION)
            .unwrap();
        td.write_file("src/render.py", PYTHON_TYPE3_UNRELATED)
            .unwrap();

        let opts = crate::analysis::clones::ClonesOptions { language: Some("python".to_string()), min_tokens: 5, min_lines: 3, ..Default::default() };

        let report = detect_clones(td.path(), &opts).unwrap();

        assert_eq!(
            report.clone_pairs.len(),
            0,
            "Three unrelated functions should produce zero clone pairs"
        );
    }
}

// =============================================================================
// 4. PREVIEW POPULATED (BUG-5 fix)
// =============================================================================

#[cfg(test)]
mod preview_populated {
    use super::v2_fixtures::*;
    use crate::analysis::clones::detect_clones;

    /// Test: Every CloneFragment in results has preview != None.
    /// BUG-5: v1 never calls `.with_preview()`, so preview is always None.
    /// v2 REQ-4: Populate preview from source lines.
    #[test]
    fn test_all_fragments_have_preview() {
        let td = V2TestDir::new().unwrap();
        td.write_file("src/a.py", PYTHON_LONG_FUNCTION_A).unwrap();
        td.write_file("src/b.py", PYTHON_LONG_FUNCTION_B).unwrap();

        let opts = crate::analysis::clones::ClonesOptions { language: Some("python".to_string()), min_tokens: 10, min_lines: 3, ..Default::default() };

        let report = detect_clones(td.path(), &opts).unwrap();

        assert!(
            !report.clone_pairs.is_empty(),
            "Need at least one pair to test preview"
        );

        for (i, pair) in report.clone_pairs.iter().enumerate() {
            assert!(
                pair.fragment1.preview.is_some(),
                "Clone pair {} fragment1 has preview=None (BUG-5 not fixed)",
                i + 1
            );
            assert!(
                pair.fragment2.preview.is_some(),
                "Clone pair {} fragment2 has preview=None (BUG-5 not fixed)",
                i + 1
            );
        }
    }

    /// Test: Preview contains actual source code from the file.
    /// The preview should be the first ~100 chars of the fragment's source lines.
    #[test]
    fn test_preview_contains_source_code() {
        let td = V2TestDir::new().unwrap();
        td.write_file("src/a.py", PYTHON_LONG_FUNCTION_A).unwrap();
        td.write_file("src/b.py", PYTHON_LONG_FUNCTION_B).unwrap();

        let opts = crate::analysis::clones::ClonesOptions { language: Some("python".to_string()), min_tokens: 10, min_lines: 3, ..Default::default() };

        let report = detect_clones(td.path(), &opts).unwrap();

        assert!(!report.clone_pairs.is_empty());

        let preview = report.clone_pairs[0].fragment1.preview.as_ref().unwrap();

        // The function starts with "def process_records"
        assert!(
            preview.contains("def process_records") || preview.contains("process_records"),
            "Preview should contain actual source code from the fragment, \
             got: {:?}",
            preview
        );
    }

    /// Test: Preview is truncated to 100 characters (with "..." suffix).
    #[test]
    fn test_preview_truncated_to_100_chars() {
        let td = V2TestDir::new().unwrap();
        td.write_file("src/a.py", PYTHON_LONG_FUNCTION_A).unwrap();
        td.write_file("src/b.py", PYTHON_LONG_FUNCTION_B).unwrap();

        let opts = crate::analysis::clones::ClonesOptions { language: Some("python".to_string()), min_tokens: 10, min_lines: 3, ..Default::default() };

        let report = detect_clones(td.path(), &opts).unwrap();

        assert!(!report.clone_pairs.is_empty());

        for pair in &report.clone_pairs {
            if let Some(ref preview) = pair.fragment1.preview {
                assert!(
                    preview.len() <= 103, // 100 chars + "..."
                    "Preview should be truncated to ~100 chars, got {} chars",
                    preview.len()
                );
            }
        }
    }
}

// =============================================================================
// 5. INCLUDE_WITHIN_FILE SEMANTICS (BUG-3 fix)
// =============================================================================

#[cfg(test)]
mod include_within_file {
    use super::v2_fixtures::*;
    use crate::analysis::clones::detect_clones;

    /// Test: With include_within_file=false, NO same-file pairs returned.
    /// BUG-3: v1 only skips OVERLAPPING same-file pairs. Non-overlapping
    /// same-file function pairs slip through.
    /// v2 REQ-5: Skip ALL same-file pairs unconditionally.
    #[test]
    fn test_within_file_false_excludes_all_same_file() {
        let td = V2TestDir::new().unwrap();
        // This file has two similar but non-overlapping handler functions
        td.write_file("src/handlers.py", PYTHON_TWO_FUNCTIONS_SAME_FILE)
            .unwrap();

        let mut opts = crate::analysis::clones::ClonesOptions { language: Some("python".to_string()), min_tokens: 10, min_lines: 3, ..Default::default() };
        opts.include_within_file = false; // <-- the flag under test

        let report = detect_clones(td.path(), &opts).unwrap();

        // With only one file and include_within_file=false, there should
        // be ZERO pairs. BUG-3 would leak non-overlapping same-file pairs.
        for pair in &report.clone_pairs {
            assert_ne!(
                pair.fragment1.file, pair.fragment2.file,
                "include_within_file=false should exclude ALL same-file pairs, \
                 but found pair with both fragments in {:?} (BUG-3)",
                pair.fragment1.file
            );
        }
    }

    /// Test: With include_within_file=true, same-file non-overlapping
    /// pairs ARE returned.
    #[test]
    fn test_within_file_true_includes_same_file_pairs() {
        let td = V2TestDir::new().unwrap();
        td.write_file("src/handlers.py", PYTHON_TWO_FUNCTIONS_SAME_FILE)
            .unwrap();

        let mut opts = crate::analysis::clones::ClonesOptions { language: Some("python".to_string()), min_tokens: 10, min_lines: 3, ..Default::default() };
        opts.include_within_file = true; // <-- allow same-file pairs

        let report = detect_clones(td.path(), &opts).unwrap();

        // handler_create and handler_update are structurally very similar
        // (Type-2 or Type-3 clones). With within-file enabled, should detect.
        assert!(
            !report.clone_pairs.is_empty(),
            "include_within_file=true should detect similar non-overlapping \
             functions in the same file"
        );

        // Verify at least one pair has both fragments from the same file
        let has_same_file_pair = report
            .clone_pairs
            .iter()
            .any(|p| p.fragment1.file == p.fragment2.file);
        assert!(
            has_same_file_pair,
            "Expected at least one same-file clone pair with include_within_file=true"
        );
    }

    /// Test: Same-file OVERLAPPING fragments are always excluded,
    /// regardless of include_within_file setting.
    #[test]
    fn test_overlapping_same_file_always_excluded() {
        let td = V2TestDir::new().unwrap();
        td.write_file("src/handlers.py", PYTHON_TWO_FUNCTIONS_SAME_FILE)
            .unwrap();

        let mut opts = crate::analysis::clones::ClonesOptions { language: Some("python".to_string()), min_tokens: 5, min_lines: 1, ..Default::default() };
        opts.include_within_file = true;

        let report = detect_clones(td.path(), &opts).unwrap();

        // No pair should have overlapping line ranges within the same file
        for pair in &report.clone_pairs {
            if pair.fragment1.file == pair.fragment2.file {
                let f1_start = pair.fragment1.start_line;
                let f1_end = pair.fragment1.end_line;
                let f2_start = pair.fragment2.start_line;
                let f2_end = pair.fragment2.end_line;

                let overlaps = f1_start <= f2_end && f2_start <= f1_end;
                assert!(
                    !overlaps,
                    "Same-file overlapping fragments must always be excluded. \
                     Got overlap: [{}-{}] and [{}-{}] in {:?}",
                    f1_start, f1_end, f2_start, f2_end, pair.fragment1.file
                );
            }
        }
    }
}

// =============================================================================
// 6. MIN_LINES ENFORCED (BUG-2 fix)
// =============================================================================

#[cfg(test)]
mod min_lines_enforced {
    use super::v2_fixtures::*;
    use crate::analysis::clones::detect_clones;

    /// Test: With min_lines=5, fragments with fewer than 5 lines are excluded.
    /// BUG-2: v1 ignores the min_lines parameter entirely (_min_lines).
    /// v2 REQ-6: Enforce fragment.line_count() >= min_lines.
    #[test]
    fn test_min_lines_excludes_short_fragments() {
        let td = V2TestDir::new().unwrap();
        // PYTHON_SHORT_3_LINES is only 3 lines
        td.write_file("src/a.py", PYTHON_SHORT_3_LINES).unwrap();
        td.write_file("src/b.py", PYTHON_SHORT_3_LINES).unwrap();

        let mut opts = crate::analysis::clones::ClonesOptions { language: Some("python".to_string()), min_tokens: 3, min_lines: 5, ..Default::default() }; // <-- 3-line functions should be excluded
        opts.include_within_file = false;

        let report = detect_clones(td.path(), &opts).unwrap();

        assert_eq!(
            report.clone_pairs.len(),
            0,
            "A 3-line clone pair should NOT be reported when min_lines=5. \
             This suggests min_lines is being ignored (BUG-2)."
        );
    }

    /// Test: A 3-line clone pair is NOT reported when min_lines=5.
    /// Explicit regression test for BUG-2.
    #[test]
    fn test_3_line_clone_not_reported_with_min_lines_5() {
        let td = V2TestDir::new().unwrap();
        // These are 3-line functions: def tiny(x): / y = x + 1 / return y
        let short_a = "def tiny_a(x):\n    y = x + 1\n    return y\n";
        let short_b = "def tiny_b(x):\n    y = x + 1\n    return y\n";
        td.write_file("src/a.py", short_a).unwrap();
        td.write_file("src/b.py", short_b).unwrap();

        let opts = crate::analysis::clones::ClonesOptions { language: Some("python".to_string()), min_tokens: 3, min_lines: 5, ..Default::default() };

        let report = detect_clones(td.path(), &opts).unwrap();

        assert_eq!(
            report.clone_pairs.len(),
            0,
            "3-line functions must be excluded when min_lines=5"
        );
    }

    /// Test: Exactly 5-line functions ARE reported when min_lines=5.
    /// Boundary condition: line_count == min_lines should pass.
    #[test]
    fn test_exactly_min_lines_included() {
        let td = V2TestDir::new().unwrap();
        td.write_file("src/a.py", PYTHON_EXACTLY_5_LINES).unwrap();
        td.write_file("src/b.py", PYTHON_EXACTLY_5_LINES_COPY)
            .unwrap();

        let opts = crate::analysis::clones::ClonesOptions { language: Some("python".to_string()), min_tokens: 3, min_lines: 5, ..Default::default() };

        let report = detect_clones(td.path(), &opts).unwrap();

        // 5-line functions with min_lines=5 should pass the filter
        assert!(
            !report.clone_pairs.is_empty(),
            "5-line functions should be included when min_lines=5 (boundary condition)"
        );
    }

    /// Test: All reported fragments respect the min_lines constraint.
    #[test]
    fn test_all_fragments_respect_min_lines() {
        let td = V2TestDir::new().unwrap();
        td.write_file("src/a.py", PYTHON_LONG_FUNCTION_A).unwrap();
        td.write_file("src/b.py", PYTHON_LONG_FUNCTION_B).unwrap();
        // Also add short functions that should be filtered out
        td.write_file("src/tiny.py", PYTHON_SHORT_3_LINES).unwrap();

        let opts = crate::analysis::clones::ClonesOptions { language: Some("python".to_string()), min_tokens: 3, min_lines: 5, ..Default::default() };

        let report = detect_clones(td.path(), &opts).unwrap();

        for pair in &report.clone_pairs {
            let f1_lines = pair.fragment1.end_line - pair.fragment1.start_line + 1;
            let f2_lines = pair.fragment2.end_line - pair.fragment2.start_line + 1;
            assert!(
                f1_lines >= 5,
                "Fragment1 has {} lines, below min_lines=5 (BUG-2)",
                f1_lines
            );
            assert!(
                f2_lines >= 5,
                "Fragment2 has {} lines, below min_lines=5 (BUG-2)",
                f2_lines
            );
        }
    }
}

// =============================================================================
// 7. SEQUENCE MATCHING (prior art: Type-1/2/3 detection)
// =============================================================================

#[cfg(test)]
mod sequence_matching {
    use super::v2_fixtures::*;
    use crate::analysis::clones::{detect_clones, CloneType};

    /// Test: Two identical token sequences -> Type-1 (similarity 1.0)
    #[test]
    fn test_identical_sequences_type1() {
        let td = V2TestDir::new().unwrap();
        td.write_file("src/a.py", SEQ_IDENTICAL_A).unwrap();
        td.write_file("src/b.py", SEQ_IDENTICAL_B).unwrap();

        let opts = crate::analysis::clones::ClonesOptions { language: Some("python".to_string()), min_tokens: 5, min_lines: 3, ..Default::default() };

        let report = detect_clones(td.path(), &opts).unwrap();

        assert_eq!(report.clone_pairs.len(), 1, "Expected exactly 1 clone pair");

        let pair = &report.clone_pairs[0];
        assert_eq!(pair.clone_type, CloneType::Type1);
        assert!(
            (pair.similarity - 1.0).abs() < 1e-6,
            "Type-1 should have similarity == 1.0, got {}",
            pair.similarity
        );
    }

    /// Test: Two sequences with renamed identifiers but same structure -> Type-2 (0.9+)
    #[test]
    fn test_renamed_identifiers_type2() {
        let td = V2TestDir::new().unwrap();
        td.write_file("src/a.py", SEQ_RENAMED_A).unwrap();
        td.write_file("src/b.py", SEQ_RENAMED_B).unwrap();

        let opts = crate::analysis::clones::ClonesOptions { language: Some("python".to_string()), min_tokens: 5, min_lines: 3, ..Default::default() };

        let report = detect_clones(td.path(), &opts).unwrap();

        assert_eq!(report.clone_pairs.len(), 1, "Expected exactly 1 clone pair");

        let pair = &report.clone_pairs[0];
        assert!(
            pair.clone_type == CloneType::Type2 || pair.clone_type == CloneType::Type1,
            "Renamed identifiers should be Type-2 (or Type-1 after normalization), got {:?}",
            pair.clone_type
        );
        assert!(
            pair.similarity >= 0.9,
            "Type-2 should have similarity >= 0.9, got {}",
            pair.similarity
        );
    }

    /// Test: Two sequences with added/removed statements -> Type-3 (0.7-0.9)
    #[test]
    fn test_gapped_sequences_type3() {
        let td = V2TestDir::new().unwrap();
        td.write_file("src/a.py", SEQ_GAPPED_A).unwrap();
        td.write_file("src/b.py", SEQ_GAPPED_B).unwrap();

        let opts = crate::analysis::clones::ClonesOptions { language: Some("python".to_string()), min_tokens: 5, min_lines: 3, ..Default::default() };

        let report = detect_clones(td.path(), &opts).unwrap();

        // Should detect as Type-3 (gapped) if similarity is 0.7+
        if !report.clone_pairs.is_empty() {
            let pair = &report.clone_pairs[0];
            assert_eq!(
                pair.clone_type,
                CloneType::Type3,
                "Gapped clone should be Type-3, got {:?}",
                pair.clone_type
            );
            assert!(
                pair.similarity >= 0.7 && pair.similarity < 0.9,
                "Type-3 should have 0.7 <= similarity < 0.9, got {}",
                pair.similarity
            );
        }
        // It's acceptable if the gap is too large and no match is found,
        // but if found it must be classified correctly.
    }

    /// Test: Two completely different sequences -> no match
    #[test]
    fn test_completely_different_no_match() {
        let td = V2TestDir::new().unwrap();
        td.write_file("src/a.py", SEQ_DIFFERENT_A).unwrap();
        td.write_file("src/b.py", SEQ_DIFFERENT_B).unwrap();

        let opts = crate::analysis::clones::ClonesOptions { language: Some("python".to_string()), min_tokens: 3, min_lines: 1, ..Default::default() };

        let report = detect_clones(td.path(), &opts).unwrap();

        assert_eq!(
            report.clone_pairs.len(),
            0,
            "Completely different code should produce zero clone pairs"
        );
    }

    /// Test: Type-3 detection with logging-augmented function
    #[test]
    fn test_type3_logging_augmented() {
        let td = V2TestDir::new().unwrap();
        td.write_file("src/base.py", PYTHON_TYPE3_BASE).unwrap();
        td.write_file("src/logged.py", PYTHON_TYPE3_WITH_LOGGING)
            .unwrap();

        let mut opts = crate::analysis::clones::ClonesOptions { language: Some("python".to_string()), min_tokens: 5, min_lines: 3, ..Default::default() };
        opts.threshold = 0.7;

        let report = detect_clones(td.path(), &opts).unwrap();

        // These are structurally similar with added logging. Should be Type-3.
        if !report.clone_pairs.is_empty() {
            let pair = &report.clone_pairs[0];
            assert!(
                pair.similarity >= 0.7,
                "Logging-augmented function should have similarity >= 0.7, got {}",
                pair.similarity
            );
            assert!(
                pair.clone_type == CloneType::Type3 || pair.clone_type == CloneType::Type2,
                "Expected Type-3 or Type-2 for logging-augmented clone"
            );
        }
    }
}

// =============================================================================
// 8. JSON SERIALIZATION PRESERVED
// =============================================================================

#[cfg(test)]
mod json_serialization {
    use crate::analysis::clones::{
        CloneConfig, CloneFragment, ClonePair, CloneStats, CloneType, ClonesReport,
        NormalizationMode,
    };
    use std::path::PathBuf;

    /// Test: ClonesReport serializes with same serde rules as v1.
    /// The JSON structure must be byte-compatible with v1 output.
    #[test]
    fn test_clones_report_serialization_format() {
        let report = ClonesReport {
            root: PathBuf::from("/tmp/test"),
            language: "auto".to_string(),
            clone_pairs: vec![],
            clone_classes: vec![],
            stats: CloneStats::default(),
            config: CloneConfig::default(),
        };

        let json = serde_json::to_value(&report).unwrap();

        // clone_classes should be ABSENT (not null, not empty array) when empty
        assert!(
            json.get("clone_classes").is_none(),
            "clone_classes should be absent from JSON when empty, not {:?}",
            json.get("clone_classes")
        );

        // Required fields must be present
        assert!(json.get("root").is_some());
        assert!(json.get("language").is_some());
        assert!(json.get("clone_pairs").is_some());
        assert!(json.get("stats").is_some());
        assert!(json.get("config").is_some());
    }

    /// Test: CloneType serializes as "Type-1", "Type-2", "Type-3"
    #[test]
    fn test_clone_type_serde_renames() {
        let type1 = serde_json::to_string(&CloneType::Type1).unwrap();
        let type2 = serde_json::to_string(&CloneType::Type2).unwrap();
        let type3 = serde_json::to_string(&CloneType::Type3).unwrap();

        assert_eq!(type1, "\"Type-1\"", "Type1 should serialize as \"Type-1\"");
        assert_eq!(type2, "\"Type-2\"", "Type2 should serialize as \"Type-2\"");
        assert_eq!(type3, "\"Type-3\"", "Type3 should serialize as \"Type-3\"");

        // Round-trip deserialization
        let rt: CloneType = serde_json::from_str("\"Type-1\"").unwrap();
        assert_eq!(rt, CloneType::Type1);
        let rt: CloneType = serde_json::from_str("\"Type-2\"").unwrap();
        assert_eq!(rt, CloneType::Type2);
        let rt: CloneType = serde_json::from_str("\"Type-3\"").unwrap();
        assert_eq!(rt, CloneType::Type3);
    }

    /// Test: NormalizationMode serializes as lowercase strings
    #[test]
    fn test_normalization_mode_serde() {
        let none = serde_json::to_string(&NormalizationMode::None).unwrap();
        let ident = serde_json::to_string(&NormalizationMode::Identifiers).unwrap();
        let lit = serde_json::to_string(&NormalizationMode::Literals).unwrap();
        let all = serde_json::to_string(&NormalizationMode::All).unwrap();

        assert_eq!(none, "\"none\"");
        assert_eq!(ident, "\"identifiers\"");
        assert_eq!(lit, "\"literals\"");
        assert_eq!(all, "\"all\"");
    }

    /// Test: Optional fields are absent (not null) in JSON when None.
    #[test]
    fn test_optional_fields_absent_not_null() {
        let fragment = CloneFragment::new(PathBuf::from("test.py"), 1, 10, 50);
        let json = serde_json::to_value(&fragment).unwrap();

        // function and preview are None by default
        assert!(
            json.get("function").is_none(),
            "function=None should be absent, not null"
        );
        assert!(
            json.get("preview").is_none(),
            "preview=None should be absent, not null"
        );

        // lines should be present (it's auto-computed to Some(10))
        assert!(
            json.get("lines").is_some(),
            "lines should be present when computed"
        );
    }

    /// Test: ClonePair interpretation field absent when None.
    #[test]
    fn test_interpretation_absent_when_none() {
        let pair = ClonePair::new(
            1,
            CloneType::Type1,
            1.0,
            CloneFragment::new(PathBuf::from("a.py"), 1, 5, 20),
            CloneFragment::new(PathBuf::from("b.py"), 1, 5, 20),
        );

        let json = serde_json::to_value(&pair).unwrap();

        // interpretation should be present (ClonePair::new auto-populates it)
        assert!(
            json.get("interpretation").is_some(),
            "interpretation should be set by ClonePair::new"
        );
    }

    /// Test: CloneStats.class_count absent when None.
    #[test]
    fn test_class_count_absent_when_none() {
        let stats = CloneStats::default();
        let json = serde_json::to_value(&stats).unwrap();

        assert!(
            json.get("class_count").is_none(),
            "class_count=None should be absent from JSON"
        );
    }

    /// Test: CloneConfig.type_filter absent when None.
    #[test]
    fn test_type_filter_absent_when_none() {
        let config = CloneConfig::default();
        let json = serde_json::to_value(&config).unwrap();

        assert!(
            json.get("type_filter").is_none(),
            "type_filter=None should be absent from JSON"
        );
    }

    /// Test: Full round-trip serialization/deserialization.
    #[test]
    fn test_full_report_round_trip() {
        let report = ClonesReport {
            root: PathBuf::from("/tmp/project"),
            language: "python".to_string(),
            clone_pairs: vec![ClonePair::new(
                1,
                CloneType::Type2,
                0.95,
                CloneFragment::new(PathBuf::from("a.py"), 1, 10, 30)
                    .with_preview("def foo():".to_string()),
                CloneFragment::new(PathBuf::from("b.py"), 5, 14, 30)
                    .with_preview("def bar():".to_string()),
            )],
            clone_classes: vec![],
            stats: CloneStats {
                files_analyzed: 2,
                total_tokens: 60,
                clones_found: 1,
                type1_count: 0,
                type2_count: 1,
                type3_count: 0,
                class_count: None,
                detection_time_ms: 42,
            },
            config: CloneConfig::default(),
        };

        let json_str = serde_json::to_string_pretty(&report).unwrap();
        let deserialized: ClonesReport = serde_json::from_str(&json_str).unwrap();

        assert_eq!(deserialized.root, report.root);
        assert_eq!(deserialized.language, report.language);
        assert_eq!(deserialized.clone_pairs.len(), 1);
        assert_eq!(deserialized.clone_pairs[0].clone_type, CloneType::Type2);
        assert_eq!(deserialized.stats.files_analyzed, 2);
        assert_eq!(deserialized.stats.clones_found, 1);
    }
}

// =============================================================================
// 9. EXISTING PRESERVED BEHAVIORS
// =============================================================================

#[cfg(test)]
mod preserved_behaviors {
    use crate::analysis::clones::{
        classify_clone_type, is_generated_file, is_test_file, CloneType, ClonesOptions,
        NormalizationMode,
    };
    use std::path::Path;

    // -------------------------------------------------------------------------
    // is_test_file() must match same patterns as v1
    // -------------------------------------------------------------------------

    #[test]
    fn test_is_test_file_directory_patterns() {
        // Directory patterns that should match
        assert!(is_test_file(Path::new("project/tests/test_foo.py")));
        assert!(is_test_file(Path::new("project/test/helper.py")));
        assert!(is_test_file(Path::new("src/__tests__/component.test.js")));
        assert!(is_test_file(Path::new("spec/models/user_spec.rb")));
        assert!(is_test_file(Path::new("testing/integration.py")));
    }

    #[test]
    fn test_is_test_file_name_patterns() {
        // File name patterns that should match
        assert!(is_test_file(Path::new("test_utils.py")));
        assert!(is_test_file(Path::new("auth_test.py")));
        assert!(is_test_file(Path::new("handler_test.go")));
        assert!(is_test_file(Path::new("parser_test.rs")));
        assert!(is_test_file(Path::new("model_spec.rb")));
        assert!(is_test_file(Path::new("button.test.ts")));
        assert!(is_test_file(Path::new("button.test.js")));
        assert!(is_test_file(Path::new("api.spec.ts")));
        assert!(is_test_file(Path::new("api.spec.js")));
        assert!(is_test_file(Path::new("UserTest.java")));
        assert!(is_test_file(Path::new("UserTests.cs")));
    }

    #[test]
    fn test_is_test_file_non_test_files() {
        // These should NOT be detected as test files
        assert!(!is_test_file(Path::new("src/main.py")));
        assert!(!is_test_file(Path::new("src/utils.rs")));
        assert!(!is_test_file(Path::new("lib/handler.go")));
        assert!(!is_test_file(Path::new("app/models/user.py")));
    }

    // -------------------------------------------------------------------------
    // is_generated_file() must match same patterns as v1
    // -------------------------------------------------------------------------

    #[test]
    fn test_is_generated_file_directory_patterns() {
        assert!(is_generated_file(Path::new("vendor/lib/foo.py")));
        assert!(is_generated_file(Path::new("node_modules/pkg/index.js")));
        assert!(is_generated_file(Path::new("__pycache__/module.pyc")));
        assert!(is_generated_file(Path::new("dist/bundle.js")));
        assert!(is_generated_file(Path::new("build/output.js")));
        assert!(is_generated_file(Path::new("target/debug/main.rs")));
        assert!(is_generated_file(Path::new("gen/proto.go")));
        assert!(is_generated_file(Path::new("generated/types.ts")));
        assert!(is_generated_file(Path::new(".gen/schema.rs")));
        assert!(is_generated_file(Path::new("third_party/lib.go")));
        assert!(is_generated_file(Path::new("external/dep.rs")));
    }

    #[test]
    fn test_is_generated_file_suffix_patterns() {
        // Protobuf
        assert!(is_generated_file(Path::new("api.pb.go")));
        assert!(is_generated_file(Path::new("schema_pb2.py")));
        assert!(is_generated_file(Path::new("types.pb.ts")));
        assert!(is_generated_file(Path::new("types.pb.js")));
        assert!(is_generated_file(Path::new("types.pb.rs")));
        assert!(is_generated_file(Path::new("api_grpc.pb.go")));
        assert!(is_generated_file(Path::new("api_pb2_grpc.py")));

        // Codegen
        assert!(is_generated_file(Path::new("schema.generated.ts")));
        assert!(is_generated_file(Path::new("schema.generated.tsx")));
        assert!(is_generated_file(Path::new("schema.generated.js")));
        assert!(is_generated_file(Path::new("query.graphql.ts")));

        // General generated
        assert!(is_generated_file(Path::new("types_generated.go")));
        assert!(is_generated_file(Path::new("types_generated.ts")));
        assert!(is_generated_file(Path::new("types_generated.rs")));
        assert!(is_generated_file(Path::new("types_generated.py")));
        assert!(is_generated_file(Path::new("schema.gen.go")));
        assert!(is_generated_file(Path::new("schema.gen.ts")));
        assert!(is_generated_file(Path::new("schema.gen.rs")));

        // Mock
        assert!(is_generated_file(Path::new("client_mock.go")));
        assert!(is_generated_file(Path::new("service_mocks.go")));

        // Thrift
        assert!(is_generated_file(Path::new("service.thrift.go")));
    }

    #[test]
    fn test_is_generated_file_prefix_patterns() {
        assert!(is_generated_file(Path::new("generated_types.py")));
        assert!(is_generated_file(Path::new("auto_generated_schema.ts")));
        assert!(is_generated_file(Path::new("autogenerated_client.go")));
        assert!(is_generated_file(Path::new("mock_service.py")));
        assert!(is_generated_file(Path::new("mocks_handler.py")));

        // Case insensitive
        assert!(is_generated_file(Path::new("Generated_Types.py")));
        assert!(is_generated_file(Path::new("AUTO_GENERATED_SCHEMA.ts")));
    }

    #[test]
    fn test_is_generated_file_non_generated() {
        assert!(!is_generated_file(Path::new("src/main.py")));
        assert!(!is_generated_file(Path::new("lib/utils.ts")));
        assert!(!is_generated_file(Path::new("cmd/server.go")));
    }

    // -------------------------------------------------------------------------
    // ClonesOptions defaults must match spec
    // -------------------------------------------------------------------------

    #[test]
    fn test_clones_options_defaults() {
        let opts = ClonesOptions::default();

        assert_eq!(opts.min_tokens, 25, "Default min_tokens should be 25");
        assert_eq!(opts.min_lines, 5, "Default min_lines should be 5");
        assert!(
            (opts.threshold - 0.7).abs() < 1e-9,
            "Default threshold should be 0.7"
        );
        assert_eq!(opts.type_filter, None, "Default type_filter should be None");
        assert_eq!(
            opts.normalization,
            NormalizationMode::All,
            "Default normalization should be All"
        );
        assert_eq!(opts.language, None, "Default language should be None");
        assert!(!opts.show_classes, "Default show_classes should be false");
        assert!(
            !opts.include_within_file,
            "Default include_within_file should be false"
        );
        assert_eq!(opts.max_clones, 100, "Default max_clones should be 100");
        assert_eq!(opts.max_files, 1000, "Default max_files should be 1000");
        assert!(
            !opts.exclude_generated,
            "Default exclude_generated should be false"
        );
        assert!(!opts.exclude_tests, "Default exclude_tests should be false");
    }

    #[test]
    fn test_clones_options_new_equals_default() {
        let new = ClonesOptions::new();
        let default = ClonesOptions::default();

        assert_eq!(new.min_tokens, default.min_tokens);
        assert_eq!(new.min_lines, default.min_lines);
        assert!((new.threshold - default.threshold).abs() < 1e-9);
        assert_eq!(new.normalization, default.normalization);
        assert_eq!(new.max_clones, default.max_clones);
    }

    // -------------------------------------------------------------------------
    // classify_clone_type thresholds
    // -------------------------------------------------------------------------

    #[test]
    fn test_classify_clone_type_type1() {
        assert_eq!(classify_clone_type(1.0), CloneType::Type1);
        assert_eq!(classify_clone_type(0.9999999999), CloneType::Type1);
    }

    #[test]
    fn test_classify_clone_type_type2() {
        assert_eq!(classify_clone_type(0.95), CloneType::Type2);
        assert_eq!(classify_clone_type(0.9), CloneType::Type2);
        assert_eq!(classify_clone_type(0.9000000001), CloneType::Type2);
    }

    #[test]
    fn test_classify_clone_type_type3() {
        assert_eq!(classify_clone_type(0.89), CloneType::Type3);
        assert_eq!(classify_clone_type(0.7), CloneType::Type3);
        assert_eq!(classify_clone_type(0.5), CloneType::Type3);
    }

    // -------------------------------------------------------------------------
    // CloneType methods
    // -------------------------------------------------------------------------

    #[test]
    fn test_clone_type_as_str() {
        assert_eq!(CloneType::Type1.as_str(), "Type-1");
        assert_eq!(CloneType::Type2.as_str(), "Type-2");
        assert_eq!(CloneType::Type3.as_str(), "Type-3");
    }

    #[test]
    fn test_clone_type_min_similarity() {
        assert!((CloneType::Type1.min_similarity() - 1.0).abs() < 1e-9);
        assert!((CloneType::Type2.min_similarity() - 0.9).abs() < 1e-9);
        assert!((CloneType::Type3.min_similarity() - 0.7).abs() < 1e-9);
    }

    #[test]
    fn test_clone_type_display() {
        assert_eq!(format!("{}", CloneType::Type1), "Type-1");
        assert_eq!(format!("{}", CloneType::Type2), "Type-2");
        assert_eq!(format!("{}", CloneType::Type3), "Type-3");
    }

    // -------------------------------------------------------------------------
    // NormalizationMode methods
    // -------------------------------------------------------------------------

    #[test]
    fn test_normalization_mode_as_str() {
        assert_eq!(NormalizationMode::None.as_str(), "none");
        assert_eq!(NormalizationMode::Identifiers.as_str(), "identifiers");
        assert_eq!(NormalizationMode::Literals.as_str(), "literals");
        assert_eq!(NormalizationMode::All.as_str(), "all");
    }

    #[test]
    fn test_normalization_mode_from_str() {
        assert_eq!(
            NormalizationMode::parse("none"),
            Some(NormalizationMode::None)
        );
        assert_eq!(
            NormalizationMode::parse("identifiers"),
            Some(NormalizationMode::Identifiers)
        );
        assert_eq!(
            NormalizationMode::parse("literals"),
            Some(NormalizationMode::Literals)
        );
        assert_eq!(
            NormalizationMode::parse("all"),
            Some(NormalizationMode::All)
        );
        assert_eq!(NormalizationMode::parse("bogus"), None);
    }

    #[test]
    fn test_normalization_mode_flags() {
        assert!(!NormalizationMode::None.normalize_identifiers());
        assert!(!NormalizationMode::None.normalize_literals());

        assert!(NormalizationMode::Identifiers.normalize_identifiers());
        assert!(!NormalizationMode::Identifiers.normalize_literals());

        assert!(!NormalizationMode::Literals.normalize_identifiers());
        assert!(NormalizationMode::Literals.normalize_literals());

        assert!(NormalizationMode::All.normalize_identifiers());
        assert!(NormalizationMode::All.normalize_literals());
    }

    #[test]
    fn test_normalization_mode_default() {
        assert_eq!(NormalizationMode::default(), NormalizationMode::All);
    }
}

// =============================================================================
// 10. EDGE CASES AND INTEGRATION
// =============================================================================

#[cfg(test)]
mod edge_cases {
    use super::v2_fixtures::*;
    use crate::analysis::clones::{detect_clones, ClonesOptions};

    /// Test: Empty directory returns empty report (not an error).
    #[test]
    fn test_empty_directory_returns_empty_report() {
        let td = V2TestDir::new().unwrap();

        let opts = ClonesOptions::default();
        let report = detect_clones(td.path(), &opts).unwrap();

        assert_eq!(report.clone_pairs.len(), 0);
        assert_eq!(report.stats.files_analyzed, 0);
        assert_eq!(report.stats.clones_found, 0);
    }

    /// Test: Single file with include_within_file=false returns no pairs.
    #[test]
    fn test_single_file_no_within_file() {
        let td = V2TestDir::new().unwrap();
        td.write_file("src/only.py", PYTHON_LONG_FUNCTION_A)
            .unwrap();

        let opts = ClonesOptions {
            language: Some("python".to_string()),
            include_within_file: false,
            ..Default::default()
        };

        let report = detect_clones(td.path(), &opts).unwrap();

        assert_eq!(
            report.clone_pairs.len(),
            0,
            "Single file with include_within_file=false should have no pairs"
        );
    }

    /// Test: Files below min_tokens produce no fragments.
    #[test]
    fn test_file_below_min_tokens_no_fragments() {
        let td = V2TestDir::new().unwrap();
        // Very short functions with few tokens
        td.write_file("src/a.py", "def f(): pass\n").unwrap();
        td.write_file("src/b.py", "def f(): pass\n").unwrap();

        let opts = ClonesOptions {
            language: Some("python".to_string()),
            min_tokens: 25, // High threshold
            ..Default::default()
        };

        let report = detect_clones(td.path(), &opts).unwrap();

        assert_eq!(
            report.clone_pairs.len(),
            0,
            "Files with fewer tokens than min_tokens should produce no pairs"
        );
    }

    /// Test: max_clones limits the number of returned pairs.
    #[test]
    fn test_max_clones_limit() {
        let td = V2TestDir::new().unwrap();
        // Create multiple identical files to generate many clone pairs
        for i in 0..10 {
            td.write_file(&format!("src/file_{}.py", i), PYTHON_LONG_FUNCTION_A)
                .unwrap();
        }

        let mut opts = crate::analysis::clones::ClonesOptions { language: Some("python".to_string()), min_tokens: 10, min_lines: 3, ..Default::default() };
        opts.max_clones = 5;

        let report = detect_clones(td.path(), &opts).unwrap();

        assert!(
            report.clone_pairs.len() <= 5,
            "max_clones=5 should limit output to at most 5 pairs, got {}",
            report.clone_pairs.len()
        );
    }

    /// Test: Stats counts are consistent with clone_pairs.
    #[test]
    fn test_stats_consistency() {
        let td = V2TestDir::new().unwrap();
        td.write_file("src/a.py", PYTHON_LONG_FUNCTION_A).unwrap();
        td.write_file("src/b.py", PYTHON_LONG_FUNCTION_B).unwrap();

        let opts = crate::analysis::clones::ClonesOptions { language: Some("python".to_string()), min_tokens: 10, min_lines: 3, ..Default::default() };

        let report = detect_clones(td.path(), &opts).unwrap();

        let expected_total =
            report.stats.type1_count + report.stats.type2_count + report.stats.type3_count;

        assert_eq!(
            report.stats.clones_found, expected_total,
            "clones_found ({}) should equal type1 + type2 + type3 ({})",
            report.stats.clones_found, expected_total
        );
        assert_eq!(
            report.stats.clones_found,
            report.clone_pairs.len(),
            "clones_found ({}) should equal clone_pairs.len() ({})",
            report.stats.clones_found,
            report.clone_pairs.len()
        );
    }

    /// Test: Clone pair IDs are 1-indexed and sequential.
    #[test]
    fn test_clone_pair_ids_sequential() {
        let td = V2TestDir::new().unwrap();
        for i in 0..5 {
            td.write_file(&format!("src/file_{}.py", i), PYTHON_LONG_FUNCTION_A)
                .unwrap();
        }

        let opts = crate::analysis::clones::ClonesOptions { language: Some("python".to_string()), min_tokens: 10, min_lines: 3, ..Default::default() };

        let report = detect_clones(td.path(), &opts).unwrap();

        for (idx, pair) in report.clone_pairs.iter().enumerate() {
            assert_eq!(
                pair.id,
                idx + 1,
                "Clone pair ID should be 1-indexed sequential: expected {}, got {}",
                idx + 1,
                pair.id
            );
        }
    }

    /// Test: Canonical ordering -- fragment1.file <= fragment2.file.
    #[test]
    fn test_canonical_pair_ordering() {
        let td = V2TestDir::new().unwrap();
        td.write_file("src/z_file.py", PYTHON_LONG_FUNCTION_A)
            .unwrap();
        td.write_file("src/a_file.py", PYTHON_LONG_FUNCTION_B)
            .unwrap();

        let opts = crate::analysis::clones::ClonesOptions { language: Some("python".to_string()), min_tokens: 10, min_lines: 3, ..Default::default() };

        let report = detect_clones(td.path(), &opts).unwrap();

        for pair in &report.clone_pairs {
            if pair.fragment1.file != pair.fragment2.file {
                assert!(
                    pair.fragment1.file <= pair.fragment2.file,
                    "Canonical ordering violated: {:?} should come before {:?}",
                    pair.fragment1.file,
                    pair.fragment2.file
                );
            } else {
                // Same file: fragment1.start_line <= fragment2.start_line
                assert!(
                    pair.fragment1.start_line <= pair.fragment2.start_line,
                    "Same-file canonical ordering violated: start_line {} > {}",
                    pair.fragment1.start_line,
                    pair.fragment2.start_line
                );
            }
        }
    }

    /// Test: Report config snapshot reflects the options used.
    #[test]
    fn test_config_snapshot() {
        let td = V2TestDir::new().unwrap();
        td.write_file("src/a.py", PYTHON_LONG_FUNCTION_A).unwrap();

        let opts = ClonesOptions {
            language: Some("python".to_string()),
            min_tokens: 15,
            min_lines: 4,
            threshold: 0.8,
            ..Default::default()
        };

        let report = detect_clones(td.path(), &opts).unwrap();

        assert_eq!(report.config.min_tokens, 15);
        assert_eq!(report.config.min_lines, 4);
        assert!((report.config.similarity_threshold - 0.8).abs() < 1e-9);
    }

    /// Test: exclude_tests filters out test files.
    #[test]
    fn test_exclude_tests_option() {
        let td = V2TestDir::new().unwrap();
        td.write_file("src/main.py", PYTHON_LONG_FUNCTION_A)
            .unwrap();
        td.write_file("tests/test_main.py", PYTHON_LONG_FUNCTION_B)
            .unwrap();

        let mut opts = crate::analysis::clones::ClonesOptions { language: Some("python".to_string()), min_tokens: 10, min_lines: 3, ..Default::default() };
        opts.exclude_tests = true;

        let report = detect_clones(td.path(), &opts).unwrap();

        // test_main.py is in tests/ directory, should be excluded
        assert_eq!(
            report.clone_pairs.len(),
            0,
            "With exclude_tests=true, test files should be excluded"
        );
    }

    /// Test: exclude_generated filters out generated files.
    #[test]
    fn test_exclude_generated_option() {
        let td = V2TestDir::new().unwrap();
        td.write_file("src/main.py", PYTHON_LONG_FUNCTION_A)
            .unwrap();
        td.write_file("generated/types_generated.py", PYTHON_LONG_FUNCTION_B)
            .unwrap();

        let mut opts = crate::analysis::clones::ClonesOptions { language: Some("python".to_string()), min_tokens: 10, min_lines: 3, ..Default::default() };
        opts.exclude_generated = true;

        let report = detect_clones(td.path(), &opts).unwrap();

        assert_eq!(
            report.clone_pairs.len(),
            0,
            "With exclude_generated=true, generated files should be excluded"
        );
    }

    /// Test: detect_clones never panics on invalid/empty content.
    #[test]
    fn test_no_panic_on_empty_files() {
        let td = V2TestDir::new().unwrap();
        td.write_file("src/empty.py", "").unwrap();
        td.write_file("src/comment_only.py", "# just a comment\n")
            .unwrap();
        td.write_file("src/whitespace.py", "\n\n\n\n").unwrap();

        let opts = ClonesOptions {
            language: Some("python".to_string()),
            ..Default::default()
        };

        // This should not panic
        let result = detect_clones(td.path(), &opts);
        assert!(
            result.is_ok(),
            "detect_clones should not panic on empty/comment-only files"
        );
    }
}

// =============================================================================
// 10. MULTI-LANGUAGE FILE DISCOVERY (Bug 1: missing 8+ languages)
// =============================================================================

#[cfg(test)]
mod multi_language_discovery {
    use super::v2_fixtures::*;
    use crate::analysis::clones::filter::{discover_source_files, get_language_from_path};
    use std::path::Path;

    /// Test: C files (.c, .h) are discovered when language="c"
    #[test]
    fn test_discover_c_files() {
        let td = V2TestDir::new().unwrap();
        td.write_file("src/main.c", "int main() { return 0; }")
            .unwrap();
        td.write_file("src/util.h", "void util();").unwrap();

        let files = discover_source_files(td.path(), Some("c"), 100, false, false);
        assert!(
            files.len() >= 2,
            "Expected at least 2 C files (.c, .h), found {}",
            files.len()
        );
    }

    /// Test: C# files (.cs) are discovered when language="csharp"
    #[test]
    fn test_discover_csharp_files() {
        let td = V2TestDir::new().unwrap();
        td.write_file("src/Program.cs", "class Program { static void Main() {} }")
            .unwrap();

        let files = discover_source_files(td.path(), Some("csharp"), 100, false, false);
        assert_eq!(files.len(), 1, "Expected 1 C# file, found {}", files.len());
    }

    /// Test: Elixir files (.ex, .exs) are discovered when language="elixir"
    #[test]
    fn test_discover_elixir_files() {
        let td = V2TestDir::new().unwrap();
        td.write_file("lib/app.ex", "defmodule App do\nend")
            .unwrap();
        td.write_file("lib/app_helper.exs", "defmodule AppHelper do\nend")
            .unwrap();

        let files = discover_source_files(td.path(), Some("elixir"), 100, false, false);
        assert!(
            files.len() >= 2,
            "Expected at least 2 Elixir files (.ex, .exs), found {}",
            files.len()
        );
    }

    /// Test: Lua files (.lua) are discovered when language="lua"
    #[test]
    fn test_discover_lua_files() {
        let td = V2TestDir::new().unwrap();
        td.write_file("src/main.lua", "print('hello')").unwrap();

        let files = discover_source_files(td.path(), Some("lua"), 100, false, false);
        assert_eq!(files.len(), 1, "Expected 1 Lua file, found {}", files.len());
    }

    /// Test: OCaml files (.ml, .mli) are discovered when language="ocaml"
    #[test]
    fn test_discover_ocaml_files() {
        let td = V2TestDir::new().unwrap();
        td.write_file("src/main.ml", "let () = print_endline \"hello\"")
            .unwrap();
        td.write_file("src/main.mli", "val main : unit -> unit")
            .unwrap();

        let files = discover_source_files(td.path(), Some("ocaml"), 100, false, false);
        assert!(
            files.len() >= 2,
            "Expected at least 2 OCaml files (.ml, .mli), found {}",
            files.len()
        );
    }

    /// Test: PHP files (.php) are discovered when language="php"
    #[test]
    fn test_discover_php_files() {
        let td = V2TestDir::new().unwrap();
        td.write_file("src/index.php", "<?php echo 'hello'; ?>")
            .unwrap();

        let files = discover_source_files(td.path(), Some("php"), 100, false, false);
        assert_eq!(files.len(), 1, "Expected 1 PHP file, found {}", files.len());
    }

    /// Test: Ruby files (.rb) are discovered when language="ruby"
    #[test]
    fn test_discover_ruby_files() {
        let td = V2TestDir::new().unwrap();
        td.write_file("lib/app.rb", "puts 'hello'").unwrap();

        let files = discover_source_files(td.path(), Some("ruby"), 100, false, false);
        assert_eq!(
            files.len(),
            1,
            "Expected 1 Ruby file, found {}",
            files.len()
        );
    }

    /// Test: Scala files (.scala) are discovered when language="scala"
    #[test]
    fn test_discover_scala_files() {
        let td = V2TestDir::new().unwrap();
        td.write_file(
            "src/Main.scala",
            "object Main { def main(args: Array[String]) = {} }",
        )
        .unwrap();

        let files = discover_source_files(td.path(), Some("scala"), 100, false, false);
        assert_eq!(
            files.len(),
            1,
            "Expected 1 Scala file, found {}",
            files.len()
        );
    }

    /// Test: Swift files (.swift) are discovered when language="swift"
    #[test]
    fn test_discover_swift_files() {
        let td = V2TestDir::new().unwrap();
        td.write_file("Sources/main.swift", "print(\"hello\")")
            .unwrap();

        let files = discover_source_files(td.path(), Some("swift"), 100, false, false);
        assert_eq!(
            files.len(),
            1,
            "Expected 1 Swift file, found {}",
            files.len()
        );
    }

    /// Test: Kotlin files (.kt) are discovered when language="kotlin"
    #[test]
    fn test_discover_kotlin_files() {
        let td = V2TestDir::new().unwrap();
        td.write_file("src/Main.kt", "fun main() { println(\"hello\") }")
            .unwrap();

        let files = discover_source_files(td.path(), Some("kotlin"), 100, false, false);
        assert_eq!(
            files.len(),
            1,
            "Expected 1 Kotlin file, found {}",
            files.len()
        );
    }

    /// Test: Comprehensive check -- all 18 corpus languages have file extension support.
    #[test]
    fn test_discover_all_supported_extensions() {
        let td = V2TestDir::new().unwrap();

        // Create one file per language
        let language_files: Vec<(&str, &str, &str)> = vec![
            ("python", "a.py", "def f(): pass"),
            ("typescript", "a.ts", "function f() {}"),
            ("javascript", "a.js", "function f() {}"),
            ("go", "a.go", "package main\nfunc main() {}"),
            ("rust", "a.rs", "fn main() {}"),
            ("java", "A.java", "class A { void f() {} }"),
            ("c", "a.c", "int main() { return 0; }"),
            ("csharp", "a.cs", "class A { void F() {} }"),
            ("elixir", "a.ex", "defmodule A do\nend"),
            ("lua", "a.lua", "print('hello')"),
            ("ocaml", "a.ml", "let () = ()"),
            ("php", "a.php", "<?php echo 1; ?>"),
            ("ruby", "a.rb", "puts 'hello'"),
            ("scala", "a.scala", "object A {}"),
            ("swift", "a.swift", "print(\"hello\")"),
            ("kotlin", "a.kt", "fun main() {}"),
        ];

        for (lang, filename, content) in &language_files {
            td.write_file(&format!("src/{}", filename), content)
                .unwrap();
            let files = discover_source_files(td.path(), Some(lang), 100, false, false);
            assert!(
                !files.is_empty(),
                "Language '{}' with extension '{}' should discover at least 1 file, found 0",
                lang,
                filename
            );
        }
    }

    /// Test: get_language_from_path works for all new extensions
    #[test]
    fn test_get_language_from_path_all_languages() {
        let cases = vec![
            ("test.py", "python"),
            ("test.ts", "typescript"),
            ("test.js", "javascript"),
            ("test.go", "go"),
            ("test.rs", "rust"),
            ("test.java", "java"),
            ("test.c", "c"),
            ("test.h", "c"),
            ("test.cs", "csharp"),
            ("test.ex", "elixir"),
            ("test.exs", "elixir"),
            ("test.lua", "lua"),
            ("test.ml", "ocaml"),
            ("test.mli", "ocaml"),
            ("test.php", "php"),
            ("test.rb", "ruby"),
            ("test.scala", "scala"),
            ("test.swift", "swift"),
            ("test.kt", "kotlin"),
        ];

        for (path_str, expected_lang) in cases {
            let lang = get_language_from_path(Path::new(path_str));
            assert_eq!(
                lang,
                Some(expected_lang),
                "get_language_from_path('{}') should return Some('{}'), got {:?}",
                path_str,
                expected_lang,
                lang
            );
        }
    }
}

// =============================================================================
// 11. MULTI-LANGUAGE FUNCTION EXTRACTION (Bug 1: missing node types)
// =============================================================================

#[cfg(test)]
mod multi_language_function_extraction {
    use super::v2_fixtures::*;
    use crate::analysis::clones::detect_clones;

    /// Test: C functions are detected as clone pairs between identical files
    #[test]
    fn test_function_extraction_c() {
        let td = V2TestDir::new().unwrap();
        let c_source = r#"
#include <stdio.h>

int add(int a, int b) {
    int result = a + b;
    return result;
}

int multiply(int a, int b) {
    int result = a * b;
    return result;
}
"#;
        td.write_file("src/a.c", c_source).unwrap();
        td.write_file("src/b.c", c_source).unwrap();

        let opts = crate::analysis::clones::ClonesOptions { language: Some("c".to_string()), min_tokens: 5, min_lines: 3, ..Default::default() };

        let report = detect_clones(td.path(), &opts).unwrap();
        assert!(
            !report.clone_pairs.is_empty(),
            "Expected clone pairs between identical C files, found 0. \
             Likely missing C function extraction support."
        );
    }

    /// Test: Ruby methods are detected as clone pairs between identical files
    #[test]
    fn test_function_extraction_ruby() {
        let td = V2TestDir::new().unwrap();
        let ruby_source = r#"
def process_data(input)
  result = []
  input.each do |item|
    result << item.to_s
  end
  result
end

def transform_data(input)
  output = []
  input.each do |item|
    output << item.to_i
  end
  output
end
"#;
        td.write_file("lib/a.rb", ruby_source).unwrap();
        td.write_file("lib/b.rb", ruby_source).unwrap();

        let opts = crate::analysis::clones::ClonesOptions { language: Some("ruby".to_string()), min_tokens: 5, min_lines: 3, ..Default::default() };

        let report = detect_clones(td.path(), &opts).unwrap();
        assert!(
            !report.clone_pairs.is_empty(),
            "Expected clone pairs between identical Ruby files, found 0. \
             Likely missing Ruby method extraction support."
        );
    }

    /// Test: PHP functions are detected
    #[test]
    fn test_function_extraction_php() {
        let td = V2TestDir::new().unwrap();
        let php_source = r#"<?php
function processData($input) {
    $result = [];
    foreach ($input as $item) {
        $result[] = $item * 2;
    }
    return $result;
}

function transformData($input) {
    $result = [];
    foreach ($input as $item) {
        $result[] = $item + 1;
    }
    return $result;
}
"#;
        td.write_file("src/a.php", php_source).unwrap();
        td.write_file("src/b.php", php_source).unwrap();

        let opts = crate::analysis::clones::ClonesOptions { language: Some("php".to_string()), min_tokens: 5, min_lines: 3, ..Default::default() };

        let report = detect_clones(td.path(), &opts).unwrap();
        assert!(
            !report.clone_pairs.is_empty(),
            "Expected clone pairs between identical PHP files, found 0. \
             Likely missing PHP function extraction support."
        );
    }

    /// Test: Swift functions are detected
    #[test]
    fn test_function_extraction_swift() {
        let td = V2TestDir::new().unwrap();
        let swift_source = r#"
import Foundation

func processData(input: [Int]) -> [Int] {
    var result: [Int] = []
    for item in input {
        result.append(item * 2)
    }
    return result
}

func transformData(input: [Int]) -> [Int] {
    var result: [Int] = []
    for item in input {
        result.append(item + 1)
    }
    return result
}
"#;
        td.write_file("Sources/a.swift", swift_source).unwrap();
        td.write_file("Sources/b.swift", swift_source).unwrap();

        let opts = crate::analysis::clones::ClonesOptions { language: Some("swift".to_string()), min_tokens: 5, min_lines: 3, ..Default::default() };

        let report = detect_clones(td.path(), &opts).unwrap();
        assert!(
            !report.clone_pairs.is_empty(),
            "Expected clone pairs between identical Swift files, found 0. \
             Likely missing Swift function extraction support."
        );
    }

    /// Test: Kotlin functions are detected
    #[test]
    fn test_function_extraction_kotlin() {
        let td = V2TestDir::new().unwrap();
        let kotlin_source = r#"
fun processData(input: List<Int>): List<Int> {
    val result = mutableListOf<Int>()
    for (item in input) {
        result.add(item * 2)
    }
    return result
}

fun transformData(input: List<Int>): List<Int> {
    val result = mutableListOf<Int>()
    for (item in input) {
        result.add(item + 1)
    }
    return result
}
"#;
        td.write_file("src/a.kt", kotlin_source).unwrap();
        td.write_file("src/b.kt", kotlin_source).unwrap();

        let opts = crate::analysis::clones::ClonesOptions { language: Some("kotlin".to_string()), min_tokens: 5, min_lines: 3, ..Default::default() };

        let report = detect_clones(td.path(), &opts).unwrap();
        assert!(
            !report.clone_pairs.is_empty(),
            "Expected clone pairs between identical Kotlin files, found 0. \
             Likely missing Kotlin function extraction support."
        );
    }

    /// Test: Scala functions are detected
    #[test]
    fn test_function_extraction_scala() {
        let td = V2TestDir::new().unwrap();
        let scala_source = r#"
object DataProcessor {
  def processData(input: List[Int]): List[Int] = {
    val result = input.map(_ * 2)
    result.filter(_ > 0)
  }

  def transformData(input: List[Int]): List[Int] = {
    val result = input.map(_ + 1)
    result.filter(_ > 0)
  }
}
"#;
        td.write_file("src/a.scala", scala_source).unwrap();
        td.write_file("src/b.scala", scala_source).unwrap();

        let opts = crate::analysis::clones::ClonesOptions { language: Some("scala".to_string()), min_tokens: 5, min_lines: 3, ..Default::default() };

        let report = detect_clones(td.path(), &opts).unwrap();
        assert!(
            !report.clone_pairs.is_empty(),
            "Expected clone pairs between identical Scala files, found 0. \
             Likely missing Scala function extraction support."
        );
    }

    /// Test: C# methods are detected
    #[test]
    fn test_function_extraction_csharp() {
        let td = V2TestDir::new().unwrap();
        let csharp_source = r#"
using System;
using System.Collections.Generic;

public class DataProcessor {
    public List<int> ProcessData(List<int> input) {
        var result = new List<int>();
        foreach (var item in input) {
            result.Add(item * 2);
        }
        return result;
    }

    public List<int> TransformData(List<int> input) {
        var result = new List<int>();
        foreach (var item in input) {
            result.Add(item + 1);
        }
        return result;
    }
}
"#;
        td.write_file("src/a.cs", csharp_source).unwrap();
        td.write_file("src/b.cs", csharp_source).unwrap();

        let opts = crate::analysis::clones::ClonesOptions { language: Some("csharp".to_string()), min_tokens: 5, min_lines: 3, ..Default::default() };

        let report = detect_clones(td.path(), &opts).unwrap();
        assert!(
            !report.clone_pairs.is_empty(),
            "Expected clone pairs between identical C# files, found 0. \
             Likely missing C# method extraction support."
        );
    }

    /// Test: Lua functions are detected
    #[test]
    fn test_function_extraction_lua() {
        let td = V2TestDir::new().unwrap();
        let lua_source = r#"
function processData(input)
    local result = {}
    for i, item in ipairs(input) do
        result[i] = item * 2
    end
    return result
end

function transformData(input)
    local result = {}
    for i, item in ipairs(input) do
        result[i] = item + 1
    end
    return result
end
"#;
        td.write_file("src/a.lua", lua_source).unwrap();
        td.write_file("src/b.lua", lua_source).unwrap();

        let opts = crate::analysis::clones::ClonesOptions { language: Some("lua".to_string()), min_tokens: 5, min_lines: 3, ..Default::default() };

        let report = detect_clones(td.path(), &opts).unwrap();
        assert!(
            !report.clone_pairs.is_empty(),
            "Expected clone pairs between identical Lua files, found 0. \
             Likely missing Lua function extraction support."
        );
    }
}