cargo-coupling 0.3.7

A coupling analysis tool for Rust projects - measuring the 'right distance' in your code
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
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
//! Rust AST analysis for coupling detection.
//!
//! This module converts source files and workspace metadata into `ProjectMetrics`,
//! giving the balance layer structural evidence about imports, type usage,
//! calls, visibility, and item-level dependencies.

use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::{Path, PathBuf};

use rayon::prelude::*;
use syn::visit::Visit;
use syn::{
    Expr, ExprCall, ExprField, ExprMethodCall, ExprStruct, File, FnArg, ItemFn, ItemImpl, ItemMod,
    ItemStruct, ItemTrait, ItemUse, ReturnType, Signature, Type, UseTree,
};
use thiserror::Error;

use crate::config::CompiledConfig;
use crate::discovery::{
    DiscoveredWorkspaceFile, canonical_file_key, discover_module_tree, file_path_to_module_path,
    normalize_exclude_path, rs_files, rs_files_excluding_nested_packages,
};
use crate::metrics::coupling::CouplingMetrics;
use crate::metrics::dimensions::{IntegrationStrength, Visibility};
use crate::metrics::module::ModuleMetrics;
use crate::metrics::project::ProjectMetrics;
use crate::volatility::Volatility;
use crate::workspace::{WorkspaceError, WorkspaceInfo, resolve_crate_from_path};

// ===== Syntax Helpers =====

/// Convert syn's Visibility to our Visibility enum
fn convert_visibility(vis: &syn::Visibility) -> Visibility {
    match vis {
        syn::Visibility::Public(_) => Visibility::Public,
        syn::Visibility::Restricted(restricted) => {
            // Check the path to determine the restriction type
            let path_str = restricted
                .path
                .segments
                .iter()
                .map(|s| s.ident.to_string())
                .collect::<Vec<_>>()
                .join("::");

            match path_str.as_str() {
                "crate" => Visibility::PubCrate,
                "super" => Visibility::PubSuper,
                "self" => Visibility::Private, // pub(self) is effectively private
                _ => Visibility::PubIn,        // pub(in path)
            }
        }
        syn::Visibility::Inherited => Visibility::Private,
    }
}

/// Check if an item has the #[test] attribute
fn has_test_attribute(attrs: &[syn::Attribute]) -> bool {
    attrs.iter().any(|attr| attr.path().is_ident("test"))
}

/// Check if an item has #[cfg(test)] attribute
fn has_cfg_test_attribute(attrs: &[syn::Attribute]) -> bool {
    attrs.iter().any(|attr| {
        if attr.path().is_ident("cfg") {
            // Try to parse the attribute content
            if let Ok(meta) = attr.meta.require_list() {
                let tokens = meta.tokens.to_string();
                return tokens.contains("test");
            }
        }
        false
    })
}

/// Check if a module is a test module (named "tests" or has #[cfg(test)])
fn is_test_module(item: &ItemMod) -> bool {
    item.ident == "tests" || has_cfg_test_attribute(&item.attrs)
}

// ===== Public Analysis Model =====

/// Errors that can occur during analysis
#[derive(Error, Debug)]
pub enum AnalyzerError {
    #[error("Failed to read file: {0}")]
    IoError(#[from] std::io::Error),

    #[error("Failed to parse Rust file: {0}")]
    ParseError(String),

    #[error("Invalid path: {0}")]
    InvalidPath(String),

    #[error("Workspace error: {0}")]
    WorkspaceError(#[from] WorkspaceError),
}

/// Represents a detected dependency
#[derive(Debug, Clone)]
pub struct Dependency {
    /// Full path of the dependency (e.g., "crate::models::user")
    pub path: String,
    /// Type of dependency
    pub kind: DependencyKind,
    /// Line number where the dependency is declared
    pub line: usize,
    /// Usage context for more accurate strength determination
    pub usage: UsageContext,
}

/// Kind of dependency
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DependencyKind {
    /// use crate::xxx or use super::xxx
    InternalUse,
    /// use external_crate::xxx
    ExternalUse,
    /// impl Trait for Type
    TraitImpl,
    /// impl Type
    InherentImpl,
    /// Type reference in struct fields, function params, etc.
    TypeRef,
}

/// Context of how a dependency is used - determines Integration Strength
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum UsageContext {
    /// Just imported, usage unknown
    Import,
    /// Used as a trait bound or trait impl
    TraitBound,
    /// Field access: `foo.bar`
    FieldAccess,
    /// Method call: `foo.method()`
    MethodCall,
    /// Function call: `Foo::new()` or `foo()`
    FunctionCall,
    /// Struct construction: `Foo { field: value }`
    StructConstruction,
    /// Type parameter: `Vec<Foo>`
    TypeParameter,
    /// Function parameter type
    FunctionParameter,
    /// Return type
    ReturnType,
    /// Inherent impl block
    InherentImplBlock,
}

impl UsageContext {
    /// Convert usage context to integration strength
    pub fn to_strength(&self) -> IntegrationStrength {
        match self {
            // Intrusive: implementation-level access, or unknown data access.
            UsageContext::FieldAccess => IntegrationStrength::Intrusive,
            UsageContext::StructConstruction => IntegrationStrength::Intrusive,
            UsageContext::InherentImplBlock => IntegrationStrength::Intrusive,

            // Functional: Depends on function signatures
            UsageContext::MethodCall => IntegrationStrength::Functional,
            UsageContext::FunctionCall => IntegrationStrength::Functional,
            UsageContext::FunctionParameter => IntegrationStrength::Functional,
            UsageContext::ReturnType => IntegrationStrength::Functional,

            // Model: Uses data types
            UsageContext::TypeParameter => IntegrationStrength::Model,
            UsageContext::Import => IntegrationStrength::Model,

            // Contract: Uses traits/interfaces
            UsageContext::TraitBound => IntegrationStrength::Contract,
        }
    }
}

impl DependencyKind {
    /// Convert coarse dependency kind to its default integration strength.
    pub fn to_strength(&self) -> IntegrationStrength {
        match self {
            DependencyKind::TraitImpl => IntegrationStrength::Contract,
            DependencyKind::InternalUse => IntegrationStrength::Model,
            DependencyKind::ExternalUse => IntegrationStrength::Model,
            DependencyKind::TypeRef => IntegrationStrength::Model,
            DependencyKind::InherentImpl => IntegrationStrength::Intrusive,
        }
    }
}

/// AST visitor for coupling analysis
#[derive(Debug)]
pub struct CouplingAnalyzer {
    /// Current module being analyzed
    pub current_module: String,
    /// File path
    pub file_path: std::path::PathBuf,
    /// Collected metrics
    pub metrics: ModuleMetrics,
    /// Detected dependencies
    pub dependencies: Vec<Dependency>,
    /// Defined types in this module
    pub defined_types: HashSet<String>,
    /// Defined traits in this module
    pub defined_traits: HashSet<String>,
    /// Defined functions in this module (name -> visibility)
    pub defined_functions: HashMap<String, Visibility>,
    /// Imported types (name -> full path)
    imported_types: HashMap<String, String>,
    /// Track unique dependencies to avoid duplicates
    seen_dependencies: HashSet<(String, UsageContext)>,
    /// Counts of each usage type for statistics
    pub usage_counts: UsageCounts,
    /// Type visibility map: type name -> visibility
    pub type_visibility: HashMap<String, Visibility>,
    /// Current item being analyzed (function name, struct name, etc.)
    current_item: Option<(String, ItemKind)>,
    /// Item-level dependencies (detailed tracking)
    pub item_dependencies: Vec<ItemDependency>,
}

/// Statistics about usage patterns
#[derive(Debug, Default, Clone)]
pub struct UsageCounts {
    /// Number of detected field access expressions.
    pub field_accesses: usize,
    /// Number of detected method calls.
    pub method_calls: usize,
    /// Number of detected associated or free function calls.
    pub function_calls: usize,
    /// Number of detected struct construction expressions.
    pub struct_constructions: usize,
    /// Number of trait bounds or trait implementations.
    pub trait_bounds: usize,
    /// Number of type parameter or field type usages.
    pub type_parameters: usize,
}

/// Detailed dependency at the item level (function, struct, etc.)
#[derive(Debug, Clone)]
pub struct ItemDependency {
    /// Source item (e.g., "fn analyze_project")
    pub source_item: String,
    /// Source item kind
    pub source_kind: ItemKind,
    /// Target (e.g., "ProjectMetrics" or "analyze_file")
    pub target: String,
    /// Target module (if known)
    pub target_module: Option<String>,
    /// Type of dependency
    pub dep_type: ItemDepType,
    /// Line number in source
    pub line: usize,
    /// The actual expression/code (e.g., "config.thresholds" or "self.couplings")
    pub expression: Option<String>,
}

/// Kind of source item
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ItemKind {
    Function,
    Method,
    Struct,
    Enum,
    Trait,
    Impl,
    Module,
}

/// Type of item-level dependency
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ItemDepType {
    /// Calls a function: foo()
    FunctionCall,
    /// Calls a method: x.foo()
    MethodCall,
    /// Uses a type: Vec<Foo>
    TypeUsage,
    /// Accesses a field: x.field
    FieldAccess,
    /// Constructs a struct: Foo { ... }
    StructConstruction,
    /// Implements a trait: impl Trait for Type
    TraitImpl,
    /// Uses a trait bound: T: Trait
    TraitBound,
    /// Imports: use foo::Bar
    Import,
}

// ===== AST Visitor =====

impl CouplingAnalyzer {
    /// Create a new analyzer for a module
    pub fn new(module_name: String, path: std::path::PathBuf) -> Self {
        Self {
            current_module: module_name.clone(),
            file_path: path.clone(),
            metrics: ModuleMetrics::new(path, module_name),
            dependencies: Vec::new(),
            defined_types: HashSet::new(),
            defined_traits: HashSet::new(),
            defined_functions: HashMap::new(),
            imported_types: HashMap::new(),
            seen_dependencies: HashSet::new(),
            usage_counts: UsageCounts::default(),
            type_visibility: HashMap::new(),
            current_item: None,
            item_dependencies: Vec::new(),
        }
    }

    /// Analyze a Rust source file
    pub fn analyze_file(&mut self, content: &str) -> Result<(), AnalyzerError> {
        let syntax: File =
            syn::parse_file(content).map_err(|e| AnalyzerError::ParseError(e.to_string()))?;

        self.visit_file(&syntax);

        Ok(())
    }

    /// Add a dependency with deduplication
    fn add_dependency(&mut self, path: String, kind: DependencyKind, usage: UsageContext) {
        let key = (path.clone(), usage);
        if self.seen_dependencies.contains(&key) {
            return;
        }
        self.seen_dependencies.insert(key);

        self.dependencies.push(Dependency {
            path,
            kind,
            line: 0,
            usage,
        });
    }

    /// Record an item-level dependency with detailed tracking
    fn add_item_dependency(
        &mut self,
        target: String,
        dep_type: ItemDepType,
        line: usize,
        expression: Option<String>,
    ) {
        if let Some((ref source_item, source_kind)) = self.current_item {
            // Determine target module
            let target_module = self.imported_types.get(&target).cloned().or_else(|| {
                if self.defined_types.contains(&target)
                    || self.defined_functions.contains_key(&target)
                {
                    Some(self.current_module.clone())
                } else {
                    None
                }
            });

            self.item_dependencies.push(ItemDependency {
                source_item: source_item.clone(),
                source_kind,
                target,
                target_module,
                dep_type,
                line,
                expression,
            });
        }
    }

    /// Extract full path from UseTree recursively
    fn extract_use_paths(&self, tree: &UseTree, prefix: &str) -> Vec<(String, DependencyKind)> {
        let mut paths = Vec::new();

        match tree {
            UseTree::Path(path) => {
                let new_prefix = if prefix.is_empty() {
                    path.ident.to_string()
                } else {
                    format!("{}::{}", prefix, path.ident)
                };
                paths.extend(self.extract_use_paths(&path.tree, &new_prefix));
            }
            UseTree::Name(name) => {
                let full_path = if prefix.is_empty() {
                    name.ident.to_string()
                } else {
                    format!("{}::{}", prefix, name.ident)
                };
                let kind = if prefix.starts_with("crate") || prefix.starts_with("super") {
                    DependencyKind::InternalUse
                } else {
                    DependencyKind::ExternalUse
                };
                paths.push((full_path, kind));
            }
            UseTree::Rename(rename) => {
                let full_path = if prefix.is_empty() {
                    rename.ident.to_string()
                } else {
                    format!("{}::{}", prefix, rename.ident)
                };
                let kind = if prefix.starts_with("crate") || prefix.starts_with("super") {
                    DependencyKind::InternalUse
                } else {
                    DependencyKind::ExternalUse
                };
                paths.push((full_path, kind));
            }
            UseTree::Glob(_) => {
                let full_path = format!("{}::*", prefix);
                let kind = if prefix.starts_with("crate") || prefix.starts_with("super") {
                    DependencyKind::InternalUse
                } else {
                    DependencyKind::ExternalUse
                };
                paths.push((full_path, kind));
            }
            UseTree::Group(group) => {
                for item in &group.items {
                    paths.extend(self.extract_use_paths(item, prefix));
                }
            }
        }

        paths
    }

    /// Extract type name from a Type
    fn extract_type_name(&self, ty: &Type) -> Option<String> {
        match ty {
            Type::Path(type_path) => {
                let segments: Vec<_> = type_path
                    .path
                    .segments
                    .iter()
                    .map(|s| s.ident.to_string())
                    .collect();
                Some(segments.join("::"))
            }
            Type::Reference(ref_type) => self.extract_type_name(&ref_type.elem),
            Type::Slice(slice_type) => self.extract_type_name(&slice_type.elem),
            Type::Array(array_type) => self.extract_type_name(&array_type.elem),
            Type::Ptr(ptr_type) => self.extract_type_name(&ptr_type.elem),
            Type::Paren(paren_type) => self.extract_type_name(&paren_type.elem),
            Type::Group(group_type) => self.extract_type_name(&group_type.elem),
            _ => None,
        }
    }

    /// Analyze function signature for dependencies
    fn analyze_signature(&mut self, sig: &Signature) {
        // Analyze parameters
        for arg in &sig.inputs {
            if let FnArg::Typed(pat_type) = arg
                && let Some(type_name) = self.extract_type_name(&pat_type.ty)
                && !self.is_primitive_type(&type_name)
            {
                self.add_dependency(
                    type_name,
                    DependencyKind::TypeRef,
                    UsageContext::FunctionParameter,
                );
            }
        }

        // Analyze return type
        if let ReturnType::Type(_, ty) = &sig.output
            && let Some(type_name) = self.extract_type_name(ty)
            && !self.is_primitive_type(&type_name)
        {
            self.add_dependency(type_name, DependencyKind::TypeRef, UsageContext::ReturnType);
        }
    }

    /// Check if a type should be ignored (primitives, self, or short variable names)
    fn is_primitive_type(&self, type_name: &str) -> bool {
        // Primitive types
        if matches!(
            type_name,
            "bool"
                | "char"
                | "str"
                | "u8"
                | "u16"
                | "u32"
                | "u64"
                | "u128"
                | "usize"
                | "i8"
                | "i16"
                | "i32"
                | "i64"
                | "i128"
                | "isize"
                | "f32"
                | "f64"
                | "String"
                | "Self"
                | "()"
                | "Option"
                | "Result"
                | "Vec"
                | "Box"
                | "Rc"
                | "Arc"
                | "RefCell"
                | "Cell"
                | "Mutex"
                | "RwLock"
        ) {
            return true;
        }

        // Short variable names (likely local variables, not types)
        // Type names in Rust are typically PascalCase and longer
        if type_name.len() <= 3 && type_name.chars().all(|c| c.is_lowercase()) {
            return true;
        }

        // Self-references or obviously local
        if type_name.starts_with("self") || type_name == "self" {
            return true;
        }

        false
    }
}

impl<'ast> Visit<'ast> for CouplingAnalyzer {
    fn visit_item_use(&mut self, node: &'ast ItemUse) {
        let paths = self.extract_use_paths(&node.tree, "");

        for (path, kind) in paths {
            // Skip self references
            if path == "self" || path.starts_with("self::") {
                continue;
            }

            // Track imported types for later resolution
            if let Some(type_name) = path.split("::").last() {
                self.imported_types
                    .insert(type_name.to_string(), path.clone());
            }

            self.add_dependency(path.clone(), kind, UsageContext::Import);

            // Update metrics
            if kind == DependencyKind::InternalUse {
                if !self.metrics.internal_deps.contains(&path) {
                    self.metrics.internal_deps.push(path.clone());
                }
            } else if kind == DependencyKind::ExternalUse {
                // Extract crate name
                let crate_name = path.split("::").next().unwrap_or(&path).to_string();
                if !self.metrics.external_deps.contains(&crate_name) {
                    self.metrics.external_deps.push(crate_name);
                }
            }
        }

        syn::visit::visit_item_use(self, node);
    }

    fn visit_item_impl(&mut self, node: &'ast ItemImpl) {
        if let Some((_, trait_path, _)) = &node.trait_ {
            // Trait implementation = Contract coupling
            self.metrics.trait_impl_count += 1;

            // Extract trait path
            let trait_name: String = trait_path
                .segments
                .iter()
                .map(|s| s.ident.to_string())
                .collect::<Vec<_>>()
                .join("::");

            self.add_dependency(
                trait_name,
                DependencyKind::TraitImpl,
                UsageContext::TraitBound,
            );
            self.usage_counts.trait_bounds += 1;
        } else {
            // Inherent implementation of another module's type is implementation-level coupling.
            self.metrics.inherent_impl_count += 1;

            // Get the type being implemented
            if let Some(type_name) = self.extract_type_name(&node.self_ty)
                && !self.defined_types.contains(&type_name)
            {
                self.add_dependency(
                    type_name,
                    DependencyKind::InherentImpl,
                    UsageContext::InherentImplBlock,
                );
            }
        }
        syn::visit::visit_item_impl(self, node);
    }

    fn visit_item_fn(&mut self, node: &'ast ItemFn) {
        // Record function definition
        let fn_name = node.sig.ident.to_string();
        let visibility = convert_visibility(&node.vis);
        self.defined_functions.insert(fn_name.clone(), visibility);

        // Check if this is a test function
        if has_test_attribute(&node.attrs) {
            self.metrics.test_function_count += 1;
        }

        // Analyze parameters for primitive obsession detection
        let mut param_count = 0;
        let mut primitive_param_count = 0;
        let mut param_types = Vec::new();

        for arg in &node.sig.inputs {
            if let FnArg::Typed(pat_type) = arg {
                param_count += 1;
                if let Some(type_name) = self.extract_type_name(&pat_type.ty) {
                    param_types.push(type_name.clone());
                    if self.is_primitive_type(&type_name) {
                        primitive_param_count += 1;
                    }
                }
            }
        }

        // Register in module metrics with full details
        self.metrics.add_function_definition_full(
            fn_name.clone(),
            visibility,
            param_count,
            primitive_param_count,
            param_types,
        );

        // Set current item context for dependency tracking
        let previous_item = self.current_item.take();
        self.current_item = Some((fn_name, ItemKind::Function));

        // Analyze function signature
        self.analyze_signature(&node.sig);
        syn::visit::visit_item_fn(self, node);

        // Restore previous context
        self.current_item = previous_item;
    }

    fn visit_item_struct(&mut self, node: &'ast ItemStruct) {
        let name = node.ident.to_string();
        let visibility = convert_visibility(&node.vis);

        self.defined_types.insert(name.clone());
        self.type_visibility.insert(name.clone(), visibility);

        // Detect newtype pattern: single-field tuple struct
        let (is_newtype, inner_type) = match &node.fields {
            syn::Fields::Unnamed(fields) if fields.unnamed.len() == 1 => {
                let inner = fields
                    .unnamed
                    .first()
                    .and_then(|f| self.extract_type_name(&f.ty));
                (true, inner)
            }
            _ => (false, None),
        };

        // Check for serde derives
        let has_serde_derive = node.attrs.iter().any(|attr| {
            if attr.path().is_ident("derive")
                && let Ok(nested) = attr.parse_args_with(
                    syn::punctuated::Punctuated::<syn::Path, syn::Token![,]>::parse_terminated,
                )
            {
                return nested.iter().any(|path| {
                    let path_str = path
                        .segments
                        .iter()
                        .map(|s| s.ident.to_string())
                        .collect::<Vec<_>>()
                        .join("::");
                    path_str == "Serialize"
                        || path_str == "Deserialize"
                        || path_str == "serde::Serialize"
                        || path_str == "serde::Deserialize"
                });
            }
            false
        });

        // Count fields and public fields
        let (total_field_count, public_field_count) = match &node.fields {
            syn::Fields::Named(fields) => {
                let total = fields.named.len();
                let public = fields
                    .named
                    .iter()
                    .filter(|f| matches!(f.vis, syn::Visibility::Public(_)))
                    .count();
                (total, public)
            }
            syn::Fields::Unnamed(fields) => {
                let total = fields.unnamed.len();
                let public = fields
                    .unnamed
                    .iter()
                    .filter(|f| matches!(f.vis, syn::Visibility::Public(_)))
                    .count();
                (total, public)
            }
            syn::Fields::Unit => (0, 0),
        };

        // Register in module metrics with full details
        self.metrics.add_type_definition_full(
            name,
            visibility,
            false, // is_trait
            is_newtype,
            inner_type,
            has_serde_derive,
            public_field_count,
            total_field_count,
        );

        // Analyze struct fields for type dependencies
        match &node.fields {
            syn::Fields::Named(fields) => {
                self.metrics.type_usage_count += fields.named.len();
                for field in &fields.named {
                    if let Some(type_name) = self.extract_type_name(&field.ty)
                        && !self.is_primitive_type(&type_name)
                    {
                        self.add_dependency(
                            type_name,
                            DependencyKind::TypeRef,
                            UsageContext::TypeParameter,
                        );
                        self.usage_counts.type_parameters += 1;
                    }
                }
            }
            syn::Fields::Unnamed(fields) => {
                for field in &fields.unnamed {
                    if let Some(type_name) = self.extract_type_name(&field.ty)
                        && !self.is_primitive_type(&type_name)
                    {
                        self.add_dependency(
                            type_name,
                            DependencyKind::TypeRef,
                            UsageContext::TypeParameter,
                        );
                    }
                }
            }
            syn::Fields::Unit => {}
        }
        syn::visit::visit_item_struct(self, node);
    }

    fn visit_item_enum(&mut self, node: &'ast syn::ItemEnum) {
        let name = node.ident.to_string();
        let visibility = convert_visibility(&node.vis);

        self.defined_types.insert(name.clone());
        self.type_visibility.insert(name.clone(), visibility);

        // Register in module metrics with visibility
        self.metrics.add_type_definition(name, visibility, false);

        // Analyze enum variants for type dependencies
        for variant in &node.variants {
            match &variant.fields {
                syn::Fields::Named(fields) => {
                    for field in &fields.named {
                        if let Some(type_name) = self.extract_type_name(&field.ty)
                            && !self.is_primitive_type(&type_name)
                        {
                            self.add_dependency(
                                type_name,
                                DependencyKind::TypeRef,
                                UsageContext::TypeParameter,
                            );
                        }
                    }
                }
                syn::Fields::Unnamed(fields) => {
                    for field in &fields.unnamed {
                        if let Some(type_name) = self.extract_type_name(&field.ty)
                            && !self.is_primitive_type(&type_name)
                        {
                            self.add_dependency(
                                type_name,
                                DependencyKind::TypeRef,
                                UsageContext::TypeParameter,
                            );
                        }
                    }
                }
                syn::Fields::Unit => {}
            }
        }
        syn::visit::visit_item_enum(self, node);
    }

    fn visit_item_trait(&mut self, node: &'ast ItemTrait) {
        let name = node.ident.to_string();
        let visibility = convert_visibility(&node.vis);

        self.defined_traits.insert(name.clone());
        self.type_visibility.insert(name.clone(), visibility);

        // Register in module metrics with visibility (is_trait = true)
        self.metrics.add_type_definition(name, visibility, true);

        self.metrics.trait_impl_count += 1;
        syn::visit::visit_item_trait(self, node);
    }

    fn visit_item_mod(&mut self, node: &'ast ItemMod) {
        // Check if this is a test module (named "tests" or has #[cfg(test)])
        if is_test_module(node) {
            self.metrics.is_test_module = true;
        }

        if node.content.is_some() {
            self.metrics.internal_deps.push(node.ident.to_string());
        }
        syn::visit::visit_item_mod(self, node);
    }

    // Detect field access: `foo.bar`
    fn visit_expr_field(&mut self, node: &'ast ExprField) {
        let field_name = match &node.member {
            syn::Member::Named(ident) => ident.to_string(),
            syn::Member::Unnamed(idx) => format!("{}", idx.index),
        };

        // Cross-module field access is classified later using target type visibility.
        if let Expr::Path(path_expr) = &*node.base {
            let base_name = path_expr
                .path
                .segments
                .iter()
                .map(|s| s.ident.to_string())
                .collect::<Vec<_>>()
                .join("::");

            // Resolve to full path if imported
            let full_path = self
                .imported_types
                .get(&base_name)
                .cloned()
                .unwrap_or(base_name.clone());

            if !self.is_primitive_type(&full_path) && !self.defined_types.contains(&full_path) {
                self.add_dependency(
                    full_path.clone(),
                    DependencyKind::TypeRef,
                    UsageContext::FieldAccess,
                );
                self.usage_counts.field_accesses += 1;
            }

            // Record item-level dependency with field name
            let expr = format!("{}.{}", base_name, field_name);
            self.add_item_dependency(
                format!("{}.{}", full_path, field_name),
                ItemDepType::FieldAccess,
                0,
                Some(expr),
            );
        }
        syn::visit::visit_expr_field(self, node);
    }

    // Detect method calls: `foo.method()`
    fn visit_expr_method_call(&mut self, node: &'ast ExprMethodCall) {
        let method_name = node.method.to_string();

        // This is a method call - Functional coupling
        if let Expr::Path(path_expr) = &*node.receiver {
            let receiver_name = path_expr
                .path
                .segments
                .iter()
                .map(|s| s.ident.to_string())
                .collect::<Vec<_>>()
                .join("::");

            let full_path = self
                .imported_types
                .get(&receiver_name)
                .cloned()
                .unwrap_or(receiver_name.clone());

            if !self.is_primitive_type(&full_path) && !self.defined_types.contains(&full_path) {
                self.add_dependency(
                    full_path.clone(),
                    DependencyKind::TypeRef,
                    UsageContext::MethodCall,
                );
                self.usage_counts.method_calls += 1;
            }

            // Record item-level dependency
            let expr = format!("{}.{}()", receiver_name, method_name);
            self.add_item_dependency(
                format!("{}::{}", full_path, method_name),
                ItemDepType::MethodCall,
                0, // TODO: get line number from span
                Some(expr),
            );
        }
        syn::visit::visit_expr_method_call(self, node);
    }

    // Detect function calls: `Foo::new()` or `foo()`
    fn visit_expr_call(&mut self, node: &'ast ExprCall) {
        if let Expr::Path(path_expr) = &*node.func {
            let path_str = path_expr
                .path
                .segments
                .iter()
                .map(|s| s.ident.to_string())
                .collect::<Vec<_>>()
                .join("::");

            // Check if this is a constructor or associated function call
            if path_str.contains("::") || path_str.chars().next().is_some_and(|c| c.is_uppercase())
            {
                let full_path = self
                    .imported_types
                    .get(&path_str)
                    .cloned()
                    .unwrap_or(path_str.clone());

                if !self.is_primitive_type(&full_path) && !self.defined_types.contains(&full_path) {
                    self.add_dependency(
                        full_path.clone(),
                        DependencyKind::TypeRef,
                        UsageContext::FunctionCall,
                    );
                    self.usage_counts.function_calls += 1;
                }

                // Record item-level dependency
                self.add_item_dependency(
                    full_path,
                    ItemDepType::FunctionCall,
                    0,
                    Some(format!("{}()", path_str)),
                );
            } else {
                // Simple function call like foo()
                self.add_item_dependency(
                    path_str.clone(),
                    ItemDepType::FunctionCall,
                    0,
                    Some(format!("{}()", path_str)),
                );
            }
        }
        syn::visit::visit_expr_call(self, node);
    }

    // Detect struct construction: `Foo { field: value }`
    fn visit_expr_struct(&mut self, node: &'ast ExprStruct) {
        let struct_name = node
            .path
            .segments
            .iter()
            .map(|s| s.ident.to_string())
            .collect::<Vec<_>>()
            .join("::");

        // Skip Self and self constructions
        if struct_name == "Self" || struct_name.starts_with("Self::") {
            syn::visit::visit_expr_struct(self, node);
            return;
        }

        let full_path = self
            .imported_types
            .get(&struct_name)
            .cloned()
            .unwrap_or(struct_name.clone());

        if !self.defined_types.contains(&full_path) && !self.is_primitive_type(&struct_name) {
            self.add_dependency(
                full_path,
                DependencyKind::TypeRef,
                UsageContext::StructConstruction,
            );
            self.usage_counts.struct_constructions += 1;
        }
        syn::visit::visit_expr_struct(self, node);
    }
}

// ===== Project Analysis Pipeline =====

/// Analyzed file data
#[derive(Debug, Clone)]
struct AnalyzedFile {
    module_name: String,
    #[allow(dead_code)]
    file_path: PathBuf,
    metrics: ModuleMetrics,
    dependencies: Vec<Dependency>,
    /// Type visibility information from this file
    type_visibility: HashMap<String, Visibility>,
    /// Item-level dependencies (function calls, field access, etc.)
    item_dependencies: Vec<ItemDependency>,
}

/// Analyze an entire project (parallel version)
pub fn analyze_project(path: &Path) -> Result<ProjectMetrics, AnalyzerError> {
    analyze_project_parallel(path)
}

/// Check whether a file path should be excluded according to `[analysis].exclude` patterns.
///
/// Patterns are evaluated relative to the directory that contained `.coupling.toml`
/// when known; otherwise they fall back to the analysis root. Paths are normalized
/// to forward slashes for consistent glob matching on Windows.
fn is_path_excluded(file_path: &Path, exclude_base: &Path, config: &CompiledConfig) -> bool {
    let normalized_file = normalize_exclude_path(file_path);
    let normalized_base = normalize_exclude_path(exclude_base);
    let relative = normalized_file
        .strip_prefix(&normalized_base)
        .unwrap_or(&normalized_file);
    let relative_str = relative.to_string_lossy().replace('\\', "/");
    config.should_exclude(&relative_str)
}

/// Convert a source path into the same normalized, config-root-relative form used by glob config.
fn path_for_config_matching(file_path: &Path, config: &CompiledConfig) -> String {
    let normalized_file = normalize_exclude_path(file_path);
    let path = config
        .config_root()
        .map(normalize_exclude_path)
        .and_then(|base| {
            normalized_file
                .strip_prefix(base)
                .ok()
                .map(Path::to_path_buf)
        })
        .unwrap_or(normalized_file);

    path.to_string_lossy().replace('\\', "/")
}

/// Analyze a project using parallel processing with Rayon
///
/// Automatically scales to available CPU cores. The parallel processing
/// uses work-stealing for optimal load balancing across cores.
pub fn analyze_project_parallel(path: &Path) -> Result<ProjectMetrics, AnalyzerError> {
    analyze_project_parallel_with_config(path, &CompiledConfig::empty())
}

/// Analyze a project in parallel, honoring `[analysis].exclude` patterns from config.
pub fn analyze_project_parallel_with_config(
    path: &Path,
    config: &CompiledConfig,
) -> Result<ProjectMetrics, AnalyzerError> {
    if !path.exists() {
        return Err(AnalyzerError::InvalidPath(path.display().to_string()));
    }

    let exclude_base = config.config_root().unwrap_or(path);

    // Collect all .rs file paths first (sequential, but fast), applying exclude patterns.
    let file_paths: Vec<PathBuf> = rs_files(path)
        .filter(|fp| !is_path_excluded(fp, exclude_base, config))
        .collect();

    // Calculate optimal chunk size based on file count and available parallelism
    // Smaller chunks = better load balancing, but more overhead
    // Larger chunks = less overhead, but potential load imbalance
    let num_threads = rayon::current_num_threads();
    let file_count = file_paths.len();

    // Use smaller chunks for better load balancing with work-stealing
    // Minimum chunk size of 1, maximum of file_count / (num_threads * 4)
    let chunk_size = if file_count < num_threads * 2 {
        1 // Small projects: process one file at a time
    } else {
        // Larger projects: balance between parallelism and overhead
        // Use ~4 chunks per thread for good work-stealing behavior
        (file_count / (num_threads * 4)).max(1)
    };

    // Parallel file analysis with optimized chunking
    let analyzed_results: Vec<_> = file_paths
        .par_chunks(chunk_size)
        .flat_map(|chunk| {
            chunk
                .iter()
                .filter_map(|file_path| match analyze_rust_file_full(file_path) {
                    Ok(result) => {
                        // Use full module path instead of just file stem (Issue #14)
                        let module_path = file_path_to_module_path(file_path, path);
                        let original_module_name = result.metrics.name.clone();
                        let module_name = if module_path.is_empty() {
                            // Crate root (lib.rs/main.rs) - use the original name
                            original_module_name.clone()
                        } else {
                            module_path
                        };

                        // Update target_module in item_dependencies if it referenced the old name
                        let item_dependencies = result
                            .item_dependencies
                            .into_iter()
                            .map(|mut dep| {
                                if dep.target_module.as_ref() == Some(&original_module_name) {
                                    dep.target_module = Some(module_name.clone());
                                }
                                dep
                            })
                            .collect();

                        Some(AnalyzedFile {
                            module_name: module_name.clone(),
                            file_path: file_path.clone(),
                            metrics: {
                                let mut module_metrics = result.metrics;
                                module_metrics.name = module_name;
                                module_metrics
                            },
                            dependencies: result.dependencies,
                            type_visibility: result.type_visibility,
                            item_dependencies,
                        })
                    }
                    Err(e) => {
                        eprintln!("Warning: Failed to analyze {}: {}", file_path.display(), e);
                        None
                    }
                })
                .collect::<Vec<_>>()
        })
        .collect();

    // Build module names set
    let module_names: HashSet<String> = analyzed_results
        .iter()
        .map(|a| a.module_name.clone())
        .collect();

    // Build project metrics (sequential, but fast)
    let mut project = ProjectMetrics::new();
    project.total_files = analyzed_results.len();
    project.parse_failures = file_paths.len().saturating_sub(analyzed_results.len());
    // Discovered (pre-parse) files: a pattern matching only a parse-failing file is
    // covered by the parse-failure note, not drift.
    let candidate_config_paths = file_paths
        .iter()
        .map(|file_path| path_for_config_matching(file_path, config))
        .collect::<Vec<_>>();

    // First pass: register all types with their visibility
    for analyzed in &analyzed_results {
        for (type_name, visibility) in &analyzed.type_visibility {
            project.register_type(type_name.clone(), analyzed.module_name.clone(), *visibility);
        }
    }

    // Second pass: add modules and couplings
    for analyzed in &analyzed_results {
        // Clone metrics and add item_dependencies
        let mut metrics = analyzed.metrics.clone();
        metrics.item_dependencies = analyzed.item_dependencies.clone();
        metrics.subdomain =
            config.get_subdomain(&path_for_config_matching(&analyzed.file_path, config));
        project.add_module(metrics);

        for dep in &analyzed.dependencies {
            // Skip invalid dependency paths (local variables, Self, etc.)
            if !is_valid_dependency_path(&dep.path) {
                continue;
            }

            // Determine if this is an internal coupling
            let target_module =
                resolve_target_module(&dep.path, &analyzed.module_name, &module_names, &project);
            let target_is_known_internal_module = module_names.contains(&target_module);

            // Skip if target module looks invalid (but allow known module names)
            if !target_is_known_internal_module && !is_valid_dependency_path(&target_module) {
                continue;
            }

            // Calculate structural distance after resolving the target module.
            let distance = calculate_distance(
                &analyzed.module_name,
                &target_module,
                target_is_known_internal_module,
            );

            let target_type = target_type_name(&dep.path);
            let target_visibility = target_type.and_then(|name| project.get_type_visibility(name));
            let strength = strength_for_dependency(dep, target_visibility);

            // Default volatility
            let volatility = Volatility::Low;

            let visibility = visibility_for_dependency(dep, target_visibility);

            // Create coupling metric with location
            let coupling = CouplingMetrics::with_location(
                analyzed.module_name.clone(),
                target_module.clone(),
                strength,
                distance,
                volatility,
                visibility,
                analyzed.file_path.clone(),
                dep.line,
            );

            project.add_coupling(coupling);
        }
    }

    // Update any remaining coupling visibility information
    project.update_coupling_visibility();
    project.dead_config_patterns =
        format_dead_config_patterns(config, &candidate_config_paths, path);

    Ok(project)
}

/// Analyze a workspace using cargo metadata for better accuracy
pub fn analyze_workspace(path: &Path) -> Result<ProjectMetrics, AnalyzerError> {
    analyze_workspace_with_config(path, &CompiledConfig::empty())
}

/// Analyze a workspace, honoring `[analysis].exclude` patterns from config.
pub fn analyze_workspace_with_config(
    path: &Path,
    config: &CompiledConfig,
) -> Result<ProjectMetrics, AnalyzerError> {
    // Try to get workspace info
    let workspace = match WorkspaceInfo::from_path(path) {
        Ok(ws) => Some(ws),
        Err(e) => {
            eprintln!("Note: Could not load workspace metadata: {}", e);
            eprintln!("Falling back to basic analysis...");
            None
        }
    };

    if let Some(ws) = workspace {
        analyze_with_workspace(path, &ws, config)
    } else {
        // Fall back to basic analysis
        analyze_project_parallel_with_config(path, config)
    }
}

/// Analyze project with workspace information (parallel version)
fn analyze_with_workspace(
    _project_root: &Path,
    workspace: &WorkspaceInfo,
    config: &CompiledConfig,
) -> Result<ProjectMetrics, AnalyzerError> {
    // Exclude patterns are rooted at the config file when known. Otherwise fall back
    // to the workspace root returned by `cargo metadata`.
    let exclude_base = config.config_root().unwrap_or(workspace.root.as_path());

    let mut project = ProjectMetrics::new();

    // Store workspace info for the report
    project.workspace_name = Some(
        workspace
            .root
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("workspace")
            .to_string(),
    );
    project.workspace_members = workspace.members.clone();

    // Collect file paths and names; module-tree parsing only runs for members using `#[path]`.
    let mut discovered_files: Vec<DiscoveredWorkspaceFile> = Vec::new();

    for member_name in &workspace.members {
        if let Some(crate_info) = workspace.get_crate(member_name) {
            let mut member_files: HashMap<PathBuf, DiscoveredWorkspaceFile> = HashMap::new();
            let mut source_contents = HashMap::new();

            for source_root in &crate_info.source_roots {
                if !source_root.exists() {
                    continue;
                }

                for file_path in
                    rs_files_excluding_nested_packages(source_root, &crate_info.manifest_path)
                {
                    if is_path_excluded(&file_path, exclude_base, config) {
                        continue;
                    }
                    let file_key = canonical_file_key(&file_path);
                    member_files
                        .entry(file_key)
                        .or_insert_with(|| DiscoveredWorkspaceFile {
                            file_path: file_path.to_path_buf(),
                            crate_name: member_name.clone(),
                            source_root: source_root.clone(),
                            module_name: None,
                        });
                }
            }

            let has_path_attribute = member_files
                .keys()
                .any(|file_key| cache_file_and_scan_path_attribute(file_key, &mut source_contents));

            if has_path_attribute {
                let mut visited = HashSet::new();

                // Module-tree resolution only ADDS files the directory walk could not see
                // (e.g. `#[path]` modules outside the source roots). Files the walk already
                // found keep their walk-based names so existing layouts are named as before.
                for crate_root in &crate_info.crate_roots {
                    let discovery = discover_module_tree(
                        crate_root,
                        &workspace.root,
                        &crate_info.manifest_path,
                        &mut visited,
                        &mut source_contents,
                    );
                    project.boundary_skipped_files += discovery.boundary_skipped_files;

                    for module_file in discovery.files {
                        if is_path_excluded(&module_file.file_path, exclude_base, config) {
                            continue;
                        }
                        let file_key = canonical_file_key(&module_file.file_path);
                        member_files
                            .entry(file_key)
                            .or_insert_with(|| DiscoveredWorkspaceFile {
                                file_path: module_file.file_path.clone(),
                                crate_name: member_name.clone(),
                                source_root: module_file
                                    .file_path
                                    .parent()
                                    .map(Path::to_path_buf)
                                    .unwrap_or_default(),
                                module_name: Some(module_file.module_name),
                            });
                    }
                }
            }

            if member_files.is_empty() {
                project.skipped_crates.push(member_name.clone());
            } else {
                discovered_files.extend(member_files.into_values());
            }
        }
    }

    // Calculate optimal chunk size for parallel processing
    let num_threads = rayon::current_num_threads();
    let file_count = discovered_files.len();
    let chunk_size = if file_count < num_threads * 2 {
        1
    } else {
        (file_count / (num_threads * 4)).max(1)
    };

    // Parallel file analysis with optimized chunking
    let analyzed_files: Vec<AnalyzedFileWithCrate> = discovered_files
        .par_chunks(chunk_size)
        .flat_map(|chunk| {
            chunk
                .iter()
                .filter_map(|discovered| {
                    match analyze_rust_file_full(&discovered.file_path) {
                        Ok(result) => {
                            // Use full module path instead of just file stem (Issue #14)
                            let module_path = discovered.module_name.clone().unwrap_or_else(|| {
                                file_path_to_module_path(
                                    &discovered.file_path,
                                    &discovered.source_root,
                                )
                            });
                            let original_module_name = result.metrics.name.clone();
                            let module_name = if module_path.is_empty() {
                                // Crate root (lib.rs/main.rs) - use the original name
                                original_module_name.clone()
                            } else {
                                module_path
                            };

                            // Update target_module in item_dependencies if it referenced the old name
                            let item_dependencies = result
                                .item_dependencies
                                .into_iter()
                                .map(|mut dep| {
                                    if dep.target_module.as_ref() == Some(&original_module_name) {
                                        dep.target_module = Some(module_name.clone());
                                    }
                                    dep
                                })
                                .collect();

                            Some(AnalyzedFileWithCrate {
                                module_name: module_name.clone(),
                                crate_name: discovered.crate_name.clone(),
                                file_path: discovered.file_path.clone(),
                                metrics: {
                                    let mut module_metrics = result.metrics;
                                    module_metrics.name = module_name;
                                    module_metrics
                                },
                                dependencies: result.dependencies,
                                type_visibility: result.type_visibility,
                                item_dependencies,
                            })
                        }
                        Err(e) => {
                            eprintln!(
                                "Warning: Failed to analyze {}: {}",
                                discovered.file_path.display(),
                                e
                            );
                            None
                        }
                    }
                })
                .collect::<Vec<_>>()
        })
        .collect();

    project.total_files = analyzed_files.len();
    project.parse_failures = discovered_files.len().saturating_sub(analyzed_files.len());
    // Discovered (pre-parse) files: a pattern matching only a parse-failing file is
    // covered by the parse-failure note, not drift.
    let candidate_config_paths = discovered_files
        .iter()
        .map(|discovered| path_for_config_matching(&discovered.file_path, config))
        .collect::<Vec<_>>();

    // Build set of known module names for validation
    let module_names: HashSet<String> = analyzed_files
        .iter()
        .map(|a| a.module_name.clone())
        .collect();

    // First pass: register all types with their visibility before resolving dependencies.
    for analyzed in &analyzed_files {
        for (type_name, visibility) in &analyzed.type_visibility {
            project.register_type(type_name.clone(), analyzed.module_name.clone(), *visibility);
        }
    }

    // Second pass: build coupling relationships with workspace context
    for analyzed in &analyzed_files {
        // Clone metrics and add item_dependencies
        let mut metrics = analyzed.metrics.clone();
        metrics.item_dependencies = analyzed.item_dependencies.clone();
        metrics.subdomain =
            config.get_subdomain(&path_for_config_matching(&analyzed.file_path, config));
        project.add_module(metrics);

        for dep in &analyzed.dependencies {
            // Skip invalid dependency paths (local variables, Self, etc.)
            if !is_valid_dependency_path(&dep.path) {
                continue;
            }

            // Resolve the target crate using workspace info
            let resolved_crate =
                resolve_crate_from_path(&dep.path, &analyzed.crate_name, workspace);

            let target_module =
                resolve_target_module(&dep.path, &analyzed.module_name, &module_names, &project);
            let target_is_known_internal_module = module_names.contains(&target_module);
            let resolved_crate = if resolved_crate.is_none() && target_is_known_internal_module {
                Some(analyzed.crate_name.clone())
            } else {
                resolved_crate
            };

            // Skip if target module looks invalid (but allow known module names)
            if !target_is_known_internal_module && !is_valid_dependency_path(&target_module) {
                continue;
            }

            // Calculate structural distance with workspace awareness.
            let distance = calculate_distance_with_workspace(
                &analyzed.module_name,
                &target_module,
                target_is_known_internal_module,
                &analyzed.crate_name,
                resolved_crate.as_deref(),
                workspace,
            );

            let target_type = target_type_name(&dep.path);
            let target_visibility = target_type.and_then(|name| project.get_type_visibility(name));
            let strength = strength_for_dependency(dep, target_visibility);

            // Default volatility
            let volatility = Volatility::Low;

            // Create coupling metric with location info
            let mut coupling = CouplingMetrics::with_location(
                format!("{}::{}", analyzed.crate_name, analyzed.module_name),
                if let Some(ref crate_name) = resolved_crate {
                    format!("{}::{}", crate_name, target_module)
                } else {
                    target_module.clone()
                },
                strength,
                distance,
                volatility,
                visibility_for_dependency(dep, target_visibility),
                analyzed.file_path.clone(),
                dep.line,
            );

            // Add crate-level info
            coupling.source_crate = Some(analyzed.crate_name.clone());
            coupling.target_crate = resolved_crate;

            project.add_coupling(coupling);
        }
    }

    // Add crate-level dependency information
    for (crate_name, deps) in &workspace.dependency_graph {
        if workspace.is_workspace_member(crate_name) {
            for dep in deps {
                // Track crate-level dependencies
                project
                    .crate_dependencies
                    .entry(crate_name.clone())
                    .or_default()
                    .push(dep.clone());
            }
        }
    }

    project.dead_config_patterns =
        format_dead_config_patterns(config, &candidate_config_paths, &workspace.root);

    Ok(project)
}

/// Dead scoring-affecting config patterns for this run, as "section: pattern" strings.
///
/// Precision guards (a false "config is rotted" note erodes trust):
/// - no loaded config file (`config_root` unknown) → no drift claims;
/// - candidates must be the DISCOVERED (post-exclusion, pre-parse) files, so a pattern
///   whose only match fails to parse stays attributed to the parse-failure note;
/// - patterns whose literal prefix is not fully covered by the analyzed scope are
///   skipped: a partial-scope run (one crate of a monorepo, a subdirectory) says
///   nothing about patterns aimed at sibling trees.
fn format_dead_config_patterns(
    config: &CompiledConfig,
    candidate_paths: &[String],
    analysis_scope: &Path,
) -> Vec<String> {
    let Some(config_root) = config.config_root() else {
        return Vec::new();
    };
    if !config.has_subdomain_config() && !config.has_volatility_overrides() {
        return Vec::new();
    }

    let normalized_scope = normalize_exclude_path(analysis_scope);
    let normalized_root = normalize_exclude_path(config_root);
    let scope = match normalized_scope.strip_prefix(&normalized_root) {
        Ok(rel) => rel.to_string_lossy().replace('\\', "/"),
        // The scope contains the config root (or a lookup quirk): everything the
        // config describes is in scope.
        Err(_) if normalized_root.starts_with(&normalized_scope) => String::new(),
        // Disjoint trees: this run cannot judge the config at all.
        Err(_) => return Vec::new(),
    };

    config
        .dead_patterns(candidate_paths)
        .into_iter()
        .filter(|dead| pattern_within_scope(&dead.pattern, &scope))
        .map(|dead| format!("{}: {}", dead.section, dead.pattern))
        .collect()
}

/// Whether everything a glob pattern could match lies inside the analyzed scope
/// (both config-root-relative). Judged via the pattern's literal (meta-free) prefix;
/// when the scope only partially covers the pattern, this run cannot prove drift.
fn pattern_within_scope(pattern: &str, scope: &str) -> bool {
    if scope.is_empty() {
        return true;
    }
    let (literal, had_meta) = match pattern.find(['*', '?', '[']) {
        Some(idx) => (&pattern[..idx], true),
        None => (pattern, false),
    };
    // A metacharacter can extend the final component ("src/bal*"), so only fully
    // literal components count.
    let literal = if had_meta {
        match literal.rfind('/') {
            Some(idx) => &literal[..idx],
            None => "",
        }
    } else {
        literal
    };
    let literal_components: Vec<&str> = literal.split('/').filter(|c| !c.is_empty()).collect();
    let scope_components: Vec<&str> = scope.split('/').filter(|c| !c.is_empty()).collect();
    literal_components.len() >= scope_components.len()
        && literal_components[..scope_components.len()] == scope_components[..]
}

fn cache_file_and_scan_path_attribute(
    file_key: &Path,
    source_contents: &mut HashMap<PathBuf, String>,
) -> bool {
    if let Some(content) = source_contents.get(file_key) {
        return content.contains("#[path");
    }

    let Ok(bytes) = fs::read(file_key) else {
        return false;
    };
    let has_path_attribute = bytes
        .windows(b"#[path".len())
        .any(|window| window == b"#[path");

    if let Ok(content) = String::from_utf8(bytes) {
        source_contents.insert(file_key.to_path_buf(), content);
    }

    has_path_attribute
}

// ===== Dependency Resolution (extracted to `classification`) =====
pub(crate) use crate::classification::{
    calculate_distance, calculate_distance_with_workspace, is_valid_dependency_path,
    resolve_target_module, strength_for_dependency, target_type_name, visibility_for_dependency,
};

/// Analyzed file with crate information
#[derive(Debug, Clone)]
struct AnalyzedFileWithCrate {
    module_name: String,
    crate_name: String,
    #[allow(dead_code)]
    file_path: PathBuf,
    metrics: ModuleMetrics,
    dependencies: Vec<Dependency>,
    /// Type visibility information from this file
    type_visibility: HashMap<String, Visibility>,
    /// Item-level dependencies (function calls, field access, etc.)
    item_dependencies: Vec<ItemDependency>,
}

/// Full result of analyzing a single Rust file.
pub struct AnalyzedFileResult {
    /// Module metrics collected from definitions and usage patterns.
    pub metrics: ModuleMetrics,
    /// File-level dependencies detected by the AST visitor.
    pub dependencies: Vec<Dependency>,
    /// Type name to visibility map collected from this file.
    pub type_visibility: HashMap<String, Visibility>,
    /// Item-level dependency edges collected within function/type contexts.
    pub item_dependencies: Vec<ItemDependency>,
}

/// Analyze one Rust file and return module metrics plus file-level dependencies.
pub fn analyze_rust_file(path: &Path) -> Result<(ModuleMetrics, Vec<Dependency>), AnalyzerError> {
    let result = analyze_rust_file_full(path)?;
    Ok((result.metrics, result.dependencies))
}

/// Analyze a Rust file and return full results including visibility
pub fn analyze_rust_file_full(path: &Path) -> Result<AnalyzedFileResult, AnalyzerError> {
    let content = fs::read_to_string(path)?;

    let module_name = path
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("unknown")
        .to_string();

    let mut analyzer = CouplingAnalyzer::new(module_name, path.to_path_buf());
    analyzer.analyze_file(&content)?;

    Ok(AnalyzedFileResult {
        metrics: analyzer.metrics,
        dependencies: analyzer.dependencies,
        type_visibility: analyzer.type_visibility,
        item_dependencies: analyzer.item_dependencies,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::classification::extract_target_module;
    use crate::metrics::dimensions::Distance;

    fn resolve_target_module_for_test(
        path: &str,
        source_module: &str,
        known_modules: &HashSet<String>,
    ) -> String {
        resolve_target_module(path, source_module, known_modules, &ProjectMetrics::new())
    }

    #[test]
    fn pattern_within_scope_requires_full_coverage() {
        // Empty scope (analysis covers the whole config tree) judges everything.
        assert!(pattern_within_scope("other/**", ""));
        // Pattern inside the scope: judged.
        assert!(pattern_within_scope("src/balance/**", "src"));
        assert!(pattern_within_scope("src/broken.rs", "src"));
        // Sibling trees: not judged.
        assert!(!pattern_within_scope("other/**", "src"));
        assert!(!pattern_within_scope("src/broken.rs", "src/web"));
        // Pattern broader than the scope: this run cannot prove drift.
        assert!(!pattern_within_scope("src/**", "src/web"));
        // Metacharacter can extend the final literal component.
        assert!(!pattern_within_scope("src/bal*", "src/balance"));
        assert!(pattern_within_scope("src/balance/mod*", "src/balance"));
        // Leading-glob patterns can match anywhere: never judged under a narrowed scope.
        assert!(!pattern_within_scope("**/generated/**", "src"));
    }

    #[test]
    fn test_analyzer_creation() {
        let analyzer = CouplingAnalyzer::new(
            "test_module".to_string(),
            std::path::PathBuf::from("test.rs"),
        );
        assert_eq!(analyzer.current_module, "test_module");
    }

    #[test]
    fn test_analyze_simple_file() {
        let mut analyzer =
            CouplingAnalyzer::new("test".to_string(), std::path::PathBuf::from("test.rs"));

        let code = r#"
            pub struct User {
                name: String,
                email: String,
            }

            impl User {
                pub fn new(name: String, email: String) -> Self {
                    Self { name, email }
                }
            }
        "#;

        let result = analyzer.analyze_file(code);
        assert!(result.is_ok());
        assert_eq!(analyzer.metrics.inherent_impl_count, 1);
    }

    #[test]
    fn test_item_dependencies() {
        let mut analyzer =
            CouplingAnalyzer::new("test".to_string(), std::path::PathBuf::from("test.rs"));

        let code = r#"
            pub struct Config {
                pub value: i32,
            }

            pub fn process(config: Config) -> i32 {
                let x = config.value;
                helper(x)
            }

            fn helper(n: i32) -> i32 {
                n * 2
            }
        "#;

        let result = analyzer.analyze_file(code);
        assert!(result.is_ok());

        // Check that functions are recorded
        assert!(analyzer.defined_functions.contains_key("process"));
        assert!(analyzer.defined_functions.contains_key("helper"));

        // Check item dependencies - process should have deps
        println!(
            "Item dependencies count: {}",
            analyzer.item_dependencies.len()
        );
        for dep in &analyzer.item_dependencies {
            println!(
                "  {} -> {} ({:?})",
                dep.source_item, dep.target, dep.dep_type
            );
        }

        // process function should have dependencies
        let process_deps: Vec<_> = analyzer
            .item_dependencies
            .iter()
            .filter(|d| d.source_item == "process")
            .collect();

        assert!(
            !process_deps.is_empty(),
            "process function should have item dependencies"
        );
    }

    #[test]
    fn test_analyze_trait_impl() {
        let mut analyzer =
            CouplingAnalyzer::new("test".to_string(), std::path::PathBuf::from("test.rs"));

        let code = r#"
            trait Printable {
                fn print(&self);
            }

            struct Document;

            impl Printable for Document {
                fn print(&self) {}
            }
        "#;

        let result = analyzer.analyze_file(code);
        assert!(result.is_ok());
        assert!(analyzer.metrics.trait_impl_count >= 1);
    }

    #[test]
    fn test_analyze_use_statements() {
        let mut analyzer =
            CouplingAnalyzer::new("test".to_string(), std::path::PathBuf::from("test.rs"));

        let code = r#"
            use std::collections::HashMap;
            use serde::Serialize;
            use crate::utils;
            use crate::models::{User, Post};
        "#;

        let result = analyzer.analyze_file(code);
        assert!(result.is_ok());
        assert!(analyzer.metrics.external_deps.contains(&"std".to_string()));
        assert!(
            analyzer
                .metrics
                .external_deps
                .contains(&"serde".to_string())
        );
        assert!(!analyzer.dependencies.is_empty());

        // Check internal dependencies
        let internal_deps: Vec<_> = analyzer
            .dependencies
            .iter()
            .filter(|d| d.kind == DependencyKind::InternalUse)
            .collect();
        assert!(!internal_deps.is_empty());
    }

    #[test]
    fn test_extract_use_paths() {
        let analyzer =
            CouplingAnalyzer::new("test".to_string(), std::path::PathBuf::from("test.rs"));

        // Test simple path
        let tree: UseTree = syn::parse_quote!(std::collections::HashMap);
        let paths = analyzer.extract_use_paths(&tree, "");
        assert_eq!(paths.len(), 1);
        assert_eq!(paths[0].0, "std::collections::HashMap");

        // Test grouped path
        let tree: UseTree = syn::parse_quote!(crate::models::{User, Post});
        let paths = analyzer.extract_use_paths(&tree, "");
        assert_eq!(paths.len(), 2);
    }

    #[test]
    fn test_extract_target_module() {
        assert_eq!(extract_target_module("crate::models::user"), "models");
        assert_eq!(extract_target_module("super::utils"), "utils");
        assert_eq!(extract_target_module("std::collections"), "std");
    }

    #[test]
    fn test_resolve_target_module_prefers_longest_known_module() {
        let known = HashSet::from([
            "balance".to_string(),
            "balance::issues".to_string(),
            "balance::score".to_string(),
        ]);

        assert_eq!(
            resolve_target_module_for_test(
                "crate::balance::issues::CouplingIssue",
                "report",
                &known
            ),
            "balance::issues"
        );
        assert_eq!(
            resolve_target_module_for_test("super::issues::IssueType", "balance::coupling", &known),
            "balance::issues"
        );
        assert_eq!(
            resolve_target_module_for_test(
                "std::collections::HashMap",
                "balance::coupling",
                &known
            ),
            "std"
        );
    }

    #[test]
    fn test_reexported_type_name_resolves_to_defining_module() {
        let known = HashSet::from(["a".to_string(), "a::b".to_string(), "consumer".to_string()]);
        let mut project = ProjectMetrics::new();
        project.register_type(
            "SomeType".to_string(),
            "a::b".to_string(),
            Visibility::Public,
        );

        let target = resolve_target_module("crate::SomeType", "a", &known, &project);

        assert_eq!(target, "a::b");
        assert_eq!(
            calculate_distance("a", &target, known.contains(&target)),
            Distance::SameModule
        );
    }

    #[test]
    fn test_unknown_reexported_type_name_keeps_external_fallback() {
        let known = HashSet::from(["a::b".to_string(), "consumer".to_string()]);
        let project = ProjectMetrics::new();

        let target = resolve_target_module("crate::UnknownType", "consumer", &known, &project);

        assert_eq!(target, "UnknownType");
        assert_eq!(
            calculate_distance("consumer", &target, known.contains(&target)),
            Distance::DifferentCrate
        );
    }

    #[test]
    fn test_type_registry_ambiguity_prefers_public_then_lexicographic_module() {
        let mut project = ProjectMetrics::new();
        project.register_type(
            "Shared".to_string(),
            "z::private".to_string(),
            Visibility::Private,
        );
        project.register_type(
            "Shared".to_string(),
            "m::public".to_string(),
            Visibility::Public,
        );
        project.register_type(
            "Shared".to_string(),
            "a::public".to_string(),
            Visibility::Public,
        );

        assert_eq!(project.get_type_module("Shared"), Some("a::public"));
        assert_eq!(
            project.get_type_visibility("Shared"),
            Some(Visibility::Public)
        );
    }

    #[test]
    fn test_strength_mapping_uses_public_model_for_data_access_only() {
        let public_field = Dependency {
            path: "crate::PublicType".to_string(),
            kind: DependencyKind::TypeRef,
            line: 0,
            usage: UsageContext::FieldAccess,
        };
        let public_struct = Dependency {
            path: "crate::PublicType".to_string(),
            kind: DependencyKind::TypeRef,
            line: 0,
            usage: UsageContext::StructConstruction,
        };
        let crate_field = Dependency {
            path: "crate::CrateType".to_string(),
            kind: DependencyKind::TypeRef,
            line: 0,
            usage: UsageContext::FieldAccess,
        };
        let unknown_struct = Dependency {
            path: "crate::UnknownType".to_string(),
            kind: DependencyKind::TypeRef,
            line: 0,
            usage: UsageContext::StructConstruction,
        };
        let inherent_impl = Dependency {
            path: "crate::PublicType".to_string(),
            kind: DependencyKind::InherentImpl,
            line: 0,
            usage: UsageContext::InherentImplBlock,
        };

        assert_eq!(
            strength_for_dependency(&public_field, Some(Visibility::Public)),
            IntegrationStrength::Model
        );
        assert_eq!(
            strength_for_dependency(&public_struct, Some(Visibility::Public)),
            IntegrationStrength::Model
        );
        assert_eq!(
            strength_for_dependency(&crate_field, Some(Visibility::PubCrate)),
            IntegrationStrength::Intrusive
        );
        assert_eq!(
            strength_for_dependency(&unknown_struct, None),
            IntegrationStrength::Intrusive
        );
        assert_eq!(
            strength_for_dependency(&inherent_impl, Some(Visibility::Public)),
            IntegrationStrength::Intrusive
        );
    }

    #[test]
    fn test_structural_distance_same_file_is_same_module() {
        assert_eq!(
            calculate_distance("balance::grade", "balance::grade", true),
            Distance::SameModule
        );
    }

    #[test]
    fn test_structural_distance_siblings_are_same_module_when_parent_is_not_root() {
        let known = HashSet::from([
            "balance::grade".to_string(),
            "balance::rationale".to_string(),
        ]);

        let super_target = resolve_target_module_for_test(
            "super::rationale::GradeRationale",
            "balance::grade",
            &known,
        );
        let crate_target = resolve_target_module(
            "crate::balance::rationale::GradeRationale",
            "balance::grade",
            &known,
            &ProjectMetrics::new(),
        );

        assert_eq!(super_target, "balance::rationale");
        assert_eq!(crate_target, "balance::rationale");
        assert_eq!(
            calculate_distance(
                "balance::grade",
                &super_target,
                known.contains(&super_target)
            ),
            Distance::SameModule
        );
        assert_eq!(
            calculate_distance(
                "balance::grade",
                &crate_target,
                known.contains(&crate_target)
            ),
            Distance::SameModule
        );
    }

    #[test]
    fn test_structural_distance_parent_child_is_same_module() {
        assert_eq!(
            calculate_distance("balance", "balance::grade", true),
            Distance::SameModule
        );
        assert_eq!(
            calculate_distance("balance::grade", "balance", true),
            Distance::SameModule
        );
        assert_eq!(
            calculate_distance("web", "web::server::internal", true),
            Distance::SameModule
        );
        assert_eq!(
            calculate_distance("web::server::internal", "web", true),
            Distance::SameModule
        );
    }

    #[test]
    fn test_structural_distance_cousins_are_different_module() {
        assert_eq!(
            calculate_distance("web::a", "web::b::c", true),
            Distance::DifferentModule
        );
    }

    #[test]
    fn test_structural_distance_root_level_siblings_are_different_module() {
        assert_eq!(
            calculate_distance("diff", "analyzer", true),
            Distance::DifferentModule
        );
        assert_eq!(
            calculate_distance("diff", "balance::issue", true),
            Distance::DifferentModule
        );
    }

    #[test]
    fn test_structural_distance_crate_syntax_does_not_make_far_module_close() {
        let known = HashSet::from(["far::away".to_string()]);
        let target = resolve_target_module_for_test("crate::far::away::X", "diff", &known);

        assert_eq!(target, "far::away");
        assert_eq!(
            calculate_distance("diff", &target, known.contains(&target)),
            Distance::DifferentModule
        );
    }

    #[test]
    fn test_structural_distance_workspace_member_and_external_crate() {
        let workspace = WorkspaceInfo {
            root: PathBuf::new(),
            crates: HashMap::new(),
            members: vec!["app".to_string(), "domain".to_string()],
            dependency_graph: HashMap::new(),
            reverse_deps: HashMap::new(),
        };

        assert_eq!(
            calculate_distance_with_workspace(
                "app_module",
                "serde",
                false,
                "app",
                Some("serde"),
                &workspace,
            ),
            Distance::DifferentCrate
        );
        assert_eq!(
            calculate_distance_with_workspace(
                "app_module",
                "domain_module",
                false,
                "app",
                Some("domain"),
                &workspace,
            ),
            Distance::DifferentModule
        );
    }

    #[test]
    fn test_field_access_detection() {
        let mut analyzer =
            CouplingAnalyzer::new("test".to_string(), std::path::PathBuf::from("test.rs"));

        let code = r#"
            use crate::models::User;

            fn get_name(user: &User) -> String {
                user.name.clone()
            }
        "#;

        let result = analyzer.analyze_file(code);
        assert!(result.is_ok());

        // Should detect User as a dependency with field access
        let _field_deps: Vec<_> = analyzer
            .dependencies
            .iter()
            .filter(|d| d.usage == UsageContext::FieldAccess)
            .collect();
        // Note: This may not detect field access on function parameters
        // as the type info isn't fully available without type inference
    }

    #[test]
    fn test_method_call_detection() {
        let mut analyzer =
            CouplingAnalyzer::new("test".to_string(), std::path::PathBuf::from("test.rs"));

        let code = r#"
            fn process() {
                let data = String::new();
                data.push_str("hello");
            }
        "#;

        let result = analyzer.analyze_file(code);
        assert!(result.is_ok());
        // Method calls on local variables are detected
    }

    #[test]
    fn test_struct_construction_detection() {
        let mut analyzer =
            CouplingAnalyzer::new("test".to_string(), std::path::PathBuf::from("test.rs"));

        let code = r#"
            use crate::config::Config;

            fn create_config() {
                let c = Config { value: 42 };
            }
        "#;

        let result = analyzer.analyze_file(code);
        assert!(result.is_ok());

        // Should detect Config struct construction
        let struct_deps: Vec<_> = analyzer
            .dependencies
            .iter()
            .filter(|d| d.usage == UsageContext::StructConstruction)
            .collect();
        assert!(!struct_deps.is_empty());
    }

    #[test]
    fn test_usage_context_to_strength() {
        assert_eq!(
            UsageContext::FieldAccess.to_strength(),
            IntegrationStrength::Intrusive
        );
        assert_eq!(
            UsageContext::MethodCall.to_strength(),
            IntegrationStrength::Functional
        );
        assert_eq!(
            UsageContext::TypeParameter.to_strength(),
            IntegrationStrength::Model
        );
        assert_eq!(
            UsageContext::TraitBound.to_strength(),
            IntegrationStrength::Contract
        );
    }

    #[test]
    fn test_has_test_attribute_with_test() {
        let code = r#"
            #[test]
            fn my_test() {}
        "#;
        let syntax: syn::File = syn::parse_str(code).unwrap();
        if let syn::Item::Fn(func) = &syntax.items[0] {
            assert!(has_test_attribute(&func.attrs));
        } else {
            panic!("Expected function");
        }
    }

    #[test]
    fn test_has_test_attribute_without_test() {
        let code = r#"
            fn regular_fn() {}
        "#;
        let syntax: syn::File = syn::parse_str(code).unwrap();
        if let syn::Item::Fn(func) = &syntax.items[0] {
            assert!(!has_test_attribute(&func.attrs));
        } else {
            panic!("Expected function");
        }
    }

    #[test]
    fn test_has_cfg_test_attribute_with_cfg_test() {
        let code = r#"
            #[cfg(test)]
            mod tests {}
        "#;
        let syntax: syn::File = syn::parse_str(code).unwrap();
        if let syn::Item::Mod(module) = &syntax.items[0] {
            assert!(has_cfg_test_attribute(&module.attrs));
        } else {
            panic!("Expected module");
        }
    }

    #[test]
    fn test_has_cfg_test_attribute_without_cfg_test() {
        let code = r#"
            mod regular_mod {}
        "#;
        let syntax: syn::File = syn::parse_str(code).unwrap();
        if let syn::Item::Mod(module) = &syntax.items[0] {
            assert!(!has_cfg_test_attribute(&module.attrs));
        } else {
            panic!("Expected module");
        }
    }

    #[test]
    fn test_has_cfg_test_attribute_with_other_cfg() {
        let code = r#"
            #[cfg(feature = "foo")]
            mod feature_mod {}
        "#;
        let syntax: syn::File = syn::parse_str(code).unwrap();
        if let syn::Item::Mod(module) = &syntax.items[0] {
            assert!(!has_cfg_test_attribute(&module.attrs));
        } else {
            panic!("Expected module");
        }
    }

    #[test]
    fn test_is_test_module_named_tests() {
        let code = r#"
            mod tests {}
        "#;
        let syntax: syn::File = syn::parse_str(code).unwrap();
        if let syn::Item::Mod(module) = &syntax.items[0] {
            assert!(is_test_module(module));
        } else {
            panic!("Expected module");
        }
    }

    #[test]
    fn test_is_test_module_with_cfg_test() {
        let code = r#"
            #[cfg(test)]
            mod my_tests {}
        "#;
        let syntax: syn::File = syn::parse_str(code).unwrap();
        if let syn::Item::Mod(module) = &syntax.items[0] {
            assert!(is_test_module(module));
        } else {
            panic!("Expected module");
        }
    }

    #[test]
    fn test_is_test_module_regular_module() {
        let code = r#"
            mod utils {}
        "#;
        let syntax: syn::File = syn::parse_str(code).unwrap();
        if let syn::Item::Mod(module) = &syntax.items[0] {
            assert!(!is_test_module(module));
        } else {
            panic!("Expected module");
        }
    }

    /// Regression test for Issue #39: `[analysis].exclude` patterns must be applied during analysis.
    ///
    /// We assert on module names (not just `total_files`) so the test distinguishes
    /// "excluded by config" from "silently dropped due to parse failure".
    /// Both `src/generated/*` and `src/generated/**` are kept to mirror the reporter's repro.
    #[test]
    fn test_analyze_project_parallel_applies_exclude_patterns() {
        use crate::config::{CompiledConfig, CouplingConfig};

        let tmp = tempfile::tempdir().expect("create tempdir");
        let root = tmp.path();
        let src = root.join("src");
        let generated = src.join("generated");
        std::fs::create_dir_all(&generated).expect("create generated dir");
        std::fs::write(src.join("lib.rs"), "pub mod generated;\npub fn call() {}\n")
            .expect("write lib.rs");
        std::fs::write(generated.join("mod.rs"), "pub fn helper() {}\n")
            .expect("write generated/mod.rs");

        // Baseline: with empty config both files are analyzed, including the generated module.
        let baseline = analyze_project_parallel_with_config(root, &CompiledConfig::empty())
            .expect("baseline analysis");
        assert_eq!(baseline.total_files, 2, "both files should be analyzed");
        assert!(
            baseline.modules.keys().any(|k| k.contains("generated")),
            "baseline must include the generated module; saw {:?}",
            baseline.modules.keys().collect::<Vec<_>>()
        );

        // With exclude patterns the generated file is filtered out by config.
        let toml = r#"
            [analysis]
            exclude = ["src/generated/*", "src/generated/**"]
        "#;
        let config: CouplingConfig = toml::from_str(toml).expect("parse toml");
        let compiled = CompiledConfig::from_config(config).expect("compile config");
        let filtered =
            analyze_project_parallel_with_config(root, &compiled).expect("filtered analysis");
        assert_eq!(
            filtered.total_files, 1,
            "generated file should be excluded from analysis"
        );
        assert!(
            !filtered.modules.keys().any(|k| k.contains("generated")),
            "no generated module should remain; saw {:?}",
            filtered.modules.keys().collect::<Vec<_>>()
        );
    }

    /// Regression test for Issue #39 on the CLI/workspace path:
    /// a relative `./src`-style path must still apply `[analysis].exclude`.
    #[test]
    fn test_analyze_workspace_applies_exclude_patterns_from_relative_src_path() {
        use crate::config::{CompiledConfig, load_compiled_config};

        let current_dir = std::env::current_dir().expect("get current dir");
        let target_dir = current_dir.join("target");
        let tmp = tempfile::Builder::new()
            .prefix("issue39-workspace-")
            .tempdir_in(&target_dir)
            .expect("create tempdir in target");
        let root = tmp.path();
        let src = root.join("src");
        let generated = src.join("generated");
        std::fs::create_dir_all(&generated).expect("create generated dir");
        std::fs::write(
            root.join("Cargo.toml"),
            r#"[package]
name = "coupling-fixture-exclude"
version = "0.1.0"
edition = "2024"
"#,
        )
        .expect("write Cargo.toml");
        std::fs::write(
            root.join(".coupling.toml"),
            "[analysis]\nexclude = [\"src/generated/*\", \"src/generated/**\"]\n",
        )
        .expect("write .coupling.toml");
        std::fs::write(
            src.join("lib.rs"),
            "pub mod generated;\npub fn call() { generated::helper(); }\n",
        )
        .expect("write lib.rs");
        std::fs::write(generated.join("mod.rs"), "pub fn helper() {}\n")
            .expect("write generated/mod.rs");

        let relative_src = src
            .strip_prefix(&current_dir)
            .expect("temp crate should be under current dir");

        let baseline = analyze_workspace_with_config(relative_src, &CompiledConfig::empty())
            .expect("baseline workspace analysis");
        assert_eq!(baseline.total_files, 2, "both files should be analyzed");
        assert!(
            baseline.modules.keys().any(|k| k.contains("generated")),
            "baseline must include the generated module; saw {:?}",
            baseline.modules.keys().collect::<Vec<_>>()
        );

        let compiled = load_compiled_config(relative_src).expect("load compiled config");
        let filtered = analyze_workspace_with_config(relative_src, &compiled)
            .expect("filtered workspace analysis");
        assert_eq!(
            filtered.total_files, 1,
            "generated file should be excluded from workspace analysis"
        );
        assert!(
            !filtered.modules.keys().any(|k| k.contains("generated")),
            "no generated module should remain; saw {:?}",
            filtered.modules.keys().collect::<Vec<_>>()
        );
    }

    /// Regression test for the non-workspace fallback path:
    /// when analyzing `./src`, exclude patterns must still be rooted at the config file.
    #[test]
    fn test_basic_analysis_fallback_applies_exclude_patterns_from_config_root() {
        use crate::config::{CompiledConfig, load_compiled_config};

        let tmp = tempfile::tempdir().expect("create tempdir");
        let root = tmp.path();
        let src = root.join("src");
        let generated = src.join("generated");
        std::fs::create_dir_all(&generated).expect("create generated dir");
        std::fs::write(
            root.join(".coupling.toml"),
            "[analysis]\nexclude = [\"src/generated/*\", \"src/generated/**\"]\n",
        )
        .expect("write .coupling.toml");
        std::fs::write(
            src.join("lib.rs"),
            "pub mod generated;\npub fn call() { generated::helper(); }\n",
        )
        .expect("write lib.rs");
        std::fs::write(generated.join("mod.rs"), "pub fn helper() {}\n")
            .expect("write generated/mod.rs");

        let baseline = analyze_workspace_with_config(&src, &CompiledConfig::empty())
            .expect("baseline analysis");
        assert_eq!(baseline.total_files, 2, "both files should be analyzed");
        assert!(
            baseline.modules.keys().any(|k| k.contains("generated")),
            "baseline must include the generated module; saw {:?}",
            baseline.modules.keys().collect::<Vec<_>>()
        );

        let compiled = load_compiled_config(&src).expect("load compiled config");
        let filtered = analyze_workspace_with_config(&src, &compiled).expect("filtered analysis");
        assert_eq!(
            filtered.total_files, 1,
            "generated file should be excluded from fallback analysis"
        );
        assert!(
            !filtered.modules.keys().any(|k| k.contains("generated")),
            "no generated module should remain; saw {:?}",
            filtered.modules.keys().collect::<Vec<_>>()
        );
    }
}