pkgrank 0.4.0

Centrality analysis for dependency graphs and file-level import graphs
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
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
use anyhow::Result;
use petgraph::prelude::*;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::process::Command as ProcessCommand;

use super::*;

// ---------------------------------------------------------------------------
// CLI
// ---------------------------------------------------------------------------

#[derive(Parser, Debug, Clone)]
pub(crate) struct FilesArgs {
    /// Project root directory or GitHub URL (e.g. https://github.com/owner/repo).
    #[arg(default_value = ".")]
    pub path: String,

    /// Ecosystem (auto-detected if omitted).
    #[arg(long, value_enum)]
    pub ecosystem: Option<Ecosystem>,

    /// Include test files in the graph.
    #[arg(long, default_value_t = false)]
    pub include_tests: bool,

    /// Include all file roles (tests, benchmarks, examples, build scripts).
    #[arg(long, default_value_t = false)]
    pub include_all: bool,

    /// Centrality metric for sorting.
    #[arg(short, long, value_enum, default_value_t = Metric::Pagerank)]
    pub metric: Metric,

    /// Top-N rows.
    #[arg(short = 'n', long, default_value_t = 25)]
    pub top: usize,

    /// Output format.
    #[arg(long, value_enum, default_value_t = OutputFormat::Text)]
    pub format: OutputFormat,

    /// Aggregate results by directory instead of individual files.
    ///
    /// Useful for large codebases where file-level is too noisy.
    #[arg(long, default_value_t = false)]
    pub directory: bool,

    /// Focus on a specific file: show its imports, dependents, and co-changers.
    ///
    /// Accepts a partial path (e.g. "graph.rs" matches "src/hnsw/graph.rs").
    #[arg(long)]
    pub focus: Option<String>,

    /// Overlay git change history (change frequency + co-change coupling).
    ///
    /// When enabled, combines structural centrality with temporal signals
    /// to produce a hotspot score. Requires a git repository.
    #[arg(long, default_value_t = false)]
    pub git: bool,

    /// Cache analysis results. Invalidates when source files change.
    #[arg(long, default_value_t = false)]
    pub cache: bool,

    /// Git history window in days (default: 90).
    #[arg(long, default_value_t = 90)]
    pub git_days: u64,

    /// Persist results to SQLite database for cross-project queries (default: true).
    #[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
    pub store: bool,

    /// Exit with code 1 if layer violations or cycles are detected.
    ///
    /// Use in CI to enforce architectural rules.
    #[arg(long, default_value_t = false)]
    pub fail_on_violation: bool,

    /// Show files transitively affected by changes to the given files.
    ///
    /// Accepts comma-separated file paths (relative to project root).
    /// Outputs all files that transitively depend on the changed files.
    /// Useful for CI: only run tests for affected modules.
    #[arg(long, value_delimiter = ',')]
    pub affected: Option<Vec<String>>,
}

// ---------------------------------------------------------------------------
// File classification
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum FileRole {
    /// Library root (lib.rs, __init__.py, index.ts).
    LibRoot,
    /// Binary / CLI entry point (main.rs, __main__.py, main.go).
    BinEntry,
    /// Production source code.
    Source,
    /// Test file.
    Test,
    /// Benchmark file.
    Bench,
    /// Example file.
    Example,
    /// Build script (build.rs, setup.py).
    Build,
}

fn classify_rust_file(path: &Path, project_root: &Path) -> FileRole {
    let rel = path.strip_prefix(project_root).unwrap_or(path);
    let rel_str = rel.to_string_lossy();

    // build.rs at project root
    if rel_str == "build.rs" {
        return FileRole::Build;
    }

    // tests/ directory → integration tests
    if rel_str.starts_with("tests/") || rel_str.starts_with("tests\\") {
        return FileRole::Test;
    }

    // benches/ directory
    if rel_str.starts_with("benches/") || rel_str.starts_with("benches\\") {
        return FileRole::Bench;
    }

    // examples/ directory
    if rel_str.starts_with("examples/") || rel_str.starts_with("examples\\") {
        return FileRole::Example;
    }

    // src/main.rs or src/bin/*.rs
    if rel_str == "src/main.rs" || rel_str.starts_with("src/bin/") {
        return FileRole::BinEntry;
    }

    // src/lib.rs
    if rel_str == "src/lib.rs" {
        return FileRole::LibRoot;
    }

    FileRole::Source
}

fn classify_python_file(path: &Path, project_root: &Path) -> FileRole {
    let rel = path.strip_prefix(project_root).unwrap_or(path);
    let rel_str = rel.to_string_lossy();
    let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");

    if rel_str.starts_with("tests/")
        || rel_str.starts_with("test/")
        || file_name.starts_with("test_")
        || file_name.ends_with("_test.py")
        || file_name == "conftest.py"
    {
        return FileRole::Test;
    }

    if rel_str.starts_with("benchmarks/") || rel_str.starts_with("bench/") {
        return FileRole::Bench;
    }

    if rel_str.starts_with("examples/") {
        return FileRole::Example;
    }

    if file_name == "setup.py" || file_name == "setup.cfg" {
        return FileRole::Build;
    }

    if file_name == "__main__.py" {
        return FileRole::BinEntry;
    }

    if file_name == "__init__.py" {
        return FileRole::LibRoot;
    }

    FileRole::Source
}

fn classify_js_file(path: &Path, project_root: &Path) -> FileRole {
    let rel = path.strip_prefix(project_root).unwrap_or(path);
    let rel_str = rel.to_string_lossy();
    let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");

    if file_name.contains(".test.")
        || file_name.contains(".spec.")
        || rel_str.starts_with("__tests__/")
        || rel_str.contains("/__tests__/")
        || rel_str.starts_with("tests/")
        || rel_str.contains("/tests/")
        || rel_str.starts_with("test/")
        || rel_str.contains("/test/")
    {
        return FileRole::Test;
    }

    if rel_str.starts_with("examples/") || rel_str.starts_with("example/") {
        return FileRole::Example;
    }

    // Config files
    if file_name.contains("config.") || file_name.starts_with("webpack.") {
        return FileRole::Build;
    }

    if file_name == "index.ts"
        || file_name == "index.js"
        || file_name == "index.tsx"
        || file_name == "index.jsx"
    {
        return FileRole::LibRoot;
    }

    FileRole::Source
}

fn classify_go_file(path: &Path, project_root: &Path) -> FileRole {
    let rel = path.strip_prefix(project_root).unwrap_or(path);
    let rel_str = rel.to_string_lossy();
    let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");

    // Check bench before test -- _bench_test.go also ends with _test.go.
    if file_name.ends_with("_bench_test.go") {
        return FileRole::Bench;
    }

    if file_name.ends_with("_test.go") {
        return FileRole::Test;
    }

    if rel_str.starts_with("cmd/") && file_name == "main.go" {
        return FileRole::BinEntry;
    }

    if file_name == "main.go" {
        return FileRole::BinEntry;
    }

    if rel_str.starts_with("examples/") || rel_str.starts_with("example/") {
        return FileRole::Example;
    }

    FileRole::Source
}

fn classify_file(path: &Path, project_root: &Path, ecosystem: Ecosystem) -> FileRole {
    match ecosystem {
        Ecosystem::Rust => classify_rust_file(path, project_root),
        Ecosystem::Python => classify_python_file(path, project_root),
        Ecosystem::Js => classify_js_file(path, project_root),
        Ecosystem::Go => classify_go_file(path, project_root),
    }
}

fn should_include(role: FileRole, args: &FilesArgs) -> bool {
    match role {
        FileRole::LibRoot | FileRole::BinEntry | FileRole::Source => true,
        FileRole::Test => args.include_tests || args.include_all,
        FileRole::Bench | FileRole::Example | FileRole::Build => args.include_all,
    }
}

// ---------------------------------------------------------------------------
// Ecosystem auto-detection
// ---------------------------------------------------------------------------

#[allow(dead_code)]
pub(crate) fn detect_ecosystem(dir: &Path) -> Option<Ecosystem> {
    detect_all_ecosystems(dir).into_iter().next()
}

/// Detect all ecosystems present in a directory.
pub(crate) fn detect_all_ecosystems(dir: &Path) -> Vec<Ecosystem> {
    let mut ecosystems = Vec::new();
    if dir.join("Cargo.toml").exists() {
        ecosystems.push(Ecosystem::Rust);
    }
    if dir.join("go.mod").exists() {
        ecosystems.push(Ecosystem::Go);
    }
    if dir.join("pyproject.toml").exists()
        || dir.join("uv.lock").exists()
        || dir.join("setup.py").exists()
    {
        ecosystems.push(Ecosystem::Python);
    }
    if dir.join("package.json").exists()
        || dir.join("package-lock.json").exists()
        || dir.join("deno.json").exists()
        || dir.join("deno.jsonc").exists()
        || dir.join("import_map.json").exists()
    {
        ecosystems.push(Ecosystem::Js);
    }
    ecosystems
}

// ---------------------------------------------------------------------------
// File discovery
// ---------------------------------------------------------------------------

fn discover_files(root: &Path, ecosystem: Ecosystem) -> Vec<PathBuf> {
    let extensions: &[&str] = match ecosystem {
        Ecosystem::Rust => &["rs"],
        Ecosystem::Python => &["py"],
        Ecosystem::Js => &["ts", "tsx", "js", "jsx", "mjs", "svelte", "vue"],
        Ecosystem::Go => &["go"],
    };

    // Prefer `git ls-files` to respect .gitignore (skips generated/vendored files).
    if let Some(files) = discover_files_git(root, extensions) {
        if !files.is_empty() {
            return files;
        }
    }

    // Fallback: manual walk with heuristic excludes.
    let mut files = Vec::new();
    walk_dir(root, extensions, &mut files);
    files.sort();
    files
}

/// Use `git ls-files` to discover tracked source files (respects .gitignore).
fn discover_files_git(root: &Path, extensions: &[&str]) -> Option<Vec<PathBuf>> {
    let out = ProcessCommand::new("git")
        .args(["ls-files", "--cached", "--others", "--exclude-standard"])
        .current_dir(root)
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let stdout = String::from_utf8_lossy(&out.stdout);
    let files: Vec<PathBuf> = stdout
        .lines()
        .filter(|l| !l.is_empty())
        .filter(|l| {
            l.rsplit('.')
                .next()
                .map(|ext| extensions.contains(&ext))
                .unwrap_or(false)
        })
        .filter(|l| {
            // Skip files in directories that should be excluded.
            let skip_dirs = [
                "testdata/",
                "vendor/",
                "node_modules/",
                "dist/",
                "build/",
                "__pycache__/",
                ".git/",
                "target/",
                "fixtures/",
                "migrations/",
                "generated/",
                "gen/",
                "third_party/",
                "third-party/",
                "docs/",
                "doc/",
                "fuzz/",
                "locale/",
                "locales/",
                "translations/",
                "i18n/",
            ];
            !skip_dirs.iter().any(|d| l.contains(d))
        })
        .filter(|l| {
            // Skip generated files and type-only declaration files even if tracked.
            let fname = l.rsplit('/').next().unwrap_or(l);
            !fname.ends_with(".pb.go")
                && !fname.ends_with("_generated.go")
                && !fname.ends_with(".gen.go")
                && !fname.ends_with(".generated.ts")
                && !fname.ends_with(".generated.js")
                && !fname.ends_with("_pb2.py")
                && !fname.ends_with("_pb2_grpc.py")
                && !fname.starts_with("generated_")
                // TypeScript declaration files: ambient types, not module imports.
                && !fname.ends_with(".d.ts")
                && !fname.ends_with(".d.mts")
                && !fname.ends_with(".d.cts")
        })
        .map(|l| root.join(l))
        .collect();
    Some(files)
}

fn walk_dir(dir: &Path, extensions: &[&str], out: &mut Vec<PathBuf>) {
    let entries = match std::fs::read_dir(dir) {
        Ok(e) => e,
        Err(_) => return,
    };
    for entry in entries.flatten() {
        let path = entry.path();
        if path.is_dir() {
            let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
            // Skip common non-source directories.
            if matches!(
                name,
                "target"
                    | "node_modules"
                    | ".git"
                    | "__pycache__"
                    | ".mypy_cache"
                    | ".pytest_cache"
                    | "dist"
                    | "build"
                    | "out"
                    | ".next"
                    | ".vercel"
                    | ".nuxt"
                    | ".svelte-kit"
                    | ".angular"
                    | "coverage"
                    | "vendor"
                    | ".venv"
                    | "venv"
                    | ".tox"
                    | ".nox"
                    | "archive"
                    | ".eggs"
                    | "*.egg-info"
                    | "testdata"
                    | "fixtures"
                    | "migrations"
                    | "assets"
                    | "static"
                    | "public"
                    | "templates"
                    | "generated"
                    | "gen"
                    | "proto"
                    | "third_party"
                    | "third-party"
                    | "external"
                    | "docs"
                    | "doc"
                    | "site"
                    | ".cache"
                    | ".parcel-cache"
                    | ".turbo"
                    | "storybook-static"
            ) {
                continue;
            }
            walk_dir(&path, extensions, out);
        } else if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
            if extensions.contains(&ext) {
                let fname = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
                // Skip generated files.
                let is_generated = fname.ends_with(".pb.go")      // protobuf
                    || fname.ends_with("_generated.go")
                    || fname.ends_with(".gen.go")
                    || fname.ends_with(".generated.ts")
                    || fname.ends_with(".generated.js")
                    || fname.ends_with("_pb2.py")                 // protobuf Python
                    || fname.ends_with("_pb2_grpc.py")
                    || fname.starts_with("generated_")
                    // TypeScript declaration files: ambient types, not module imports.
                    || fname.ends_with(".d.ts")
                    || fname.ends_with(".d.mts")
                    || fname.ends_with(".d.cts");
                if !is_generated {
                    out.push(path);
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Import edge: source file → target file
// ---------------------------------------------------------------------------

#[derive(Debug, Clone)]
struct FileEdge {
    from: PathBuf,
    to: PathBuf,
}

/// Extract external dependency names from source files.
fn extract_external_deps(
    files: &[PathBuf],
    ecosystem: Ecosystem,
    internal_prefixes: &HashSet<String>,
) -> HashMap<PathBuf, Vec<String>> {
    let mut result: HashMap<PathBuf, Vec<String>> = HashMap::new();
    let std_prefixes: HashSet<&str> = match ecosystem {
        Ecosystem::Rust => ["std", "core", "alloc", "proc_macro", "test"]
            .iter()
            .copied()
            .collect(),
        Ecosystem::Python => [
            "abc",
            "argparse",
            "ast",
            "asyncio",
            "base64",
            "binascii",
            "bisect",
            "builtins",
            "calendar",
            "cgi",
            "cmd",
            "codecs",
            "collections",
            "colorsys",
            "concurrent",
            "configparser",
            "contextlib",
            "contextvars",
            "copy",
            "copyreg",
            "csv",
            "ctypes",
            "dataclasses",
            "datetime",
            "decimal",
            "difflib",
            "dis",
            "distutils",
            "doctest",
            "email",
            "encodings",
            "enum",
            "errno",
            "faulthandler",
            "filecmp",
            "fileinput",
            "fnmatch",
            "fractions",
            "ftplib",
            "functools",
            "gc",
            "getopt",
            "getpass",
            "gettext",
            "glob",
            "grp",
            "gzip",
            "hashlib",
            "heapq",
            "hmac",
            "html",
            "http",
            "idlelib",
            "imaplib",
            "importlib",
            "inspect",
            "io",
            "ipaddress",
            "itertools",
            "json",
            "keyword",
            "lib2to3",
            "linecache",
            "locale",
            "logging",
            "lzma",
            "mailbox",
            "math",
            "mimetypes",
            "mmap",
            "multiprocessing",
            "netrc",
            "numbers",
            "operator",
            "optparse",
            "os",
            "pathlib",
            "pdb",
            "pickle",
            "pickletools",
            "pipes",
            "pkgutil",
            "platform",
            "plistlib",
            "poplib",
            "posixpath",
            "pprint",
            "profile",
            "pstats",
            "pty",
            "pwd",
            "pydoc",
            "queue",
            "quopri",
            "random",
            "re",
            "readline",
            "reprlib",
            "resource",
            "rlcompleter",
            "runpy",
            "sched",
            "secrets",
            "select",
            "selectors",
            "shelve",
            "shlex",
            "shutil",
            "signal",
            "site",
            "smtplib",
            "sndhdr",
            "socket",
            "socketserver",
            "sqlite3",
            "ssl",
            "stat",
            "statistics",
            "string",
            "stringprep",
            "struct",
            "subprocess",
            "sunau",
            "symtable",
            "sys",
            "sysconfig",
            "syslog",
            "tabnanny",
            "tarfile",
            "telnetlib",
            "tempfile",
            "termios",
            "test",
            "textwrap",
            "threading",
            "time",
            "timeit",
            "tkinter",
            "token",
            "tokenize",
            "tomllib",
            "trace",
            "traceback",
            "tracemalloc",
            "tty",
            "turtle",
            "turtledemo",
            "types",
            "typing",
            "unicodedata",
            "unittest",
            "urllib",
            "uuid",
            "venv",
            "warnings",
            "wave",
            "weakref",
            "webbrowser",
            "winreg",
            "wsgiref",
            "xdrlib",
            "xml",
            "xmlrpc",
            "zipapp",
            "zipfile",
            "zipimport",
            "zlib",
            "_thread",
            "__future__",
            // Common false positives from Python syntax
            "name",
            "main",
            "file",
        ]
        .iter()
        .copied()
        .collect(),
        Ecosystem::Js => [
            // Node.js built-in modules (commonly imported without node: prefix)
            "assert",
            "async_hooks",
            "buffer",
            "child_process",
            "cluster",
            "console",
            "constants",
            "crypto",
            "dgram",
            "diagnostics_channel",
            "dns",
            "domain",
            "events",
            "fs",
            "http",
            "http2",
            "https",
            "inspector",
            "module",
            "net",
            "os",
            "path",
            "perf_hooks",
            "process",
            "punycode",
            "querystring",
            "readline",
            "repl",
            "stream",
            "string_decoder",
            "sys",
            "timers",
            "tls",
            "trace_events",
            "tty",
            "url",
            "util",
            "v8",
            "vm",
            "wasi",
            "worker_threads",
            "zlib",
        ]
        .iter()
        .copied()
        .collect(),
        Ecosystem::Go => HashSet::new(), // Go stdlib detected by absence of dots in import path
    };

    for file in files {
        let content = match std::fs::read_to_string(file) {
            Ok(c) => c,
            Err(_) => continue,
        };
        let mut deps: HashSet<String> = HashSet::new();

        for line in content.lines() {
            let line = line.trim();
            match ecosystem {
                Ecosystem::Rust => {
                    // `use foo::...` where foo is not crate/super/self/known
                    let use_part = strip_visibility(line)
                        .strip_prefix("use ")
                        .or_else(|| line.strip_prefix("use "));
                    if let Some(use_part) = use_part {
                        let use_part = use_part.trim_end_matches(';').trim();
                        if use_part.starts_with("crate::")
                            || use_part.starts_with("super::")
                            || use_part.starts_with("self::")
                        {
                            continue;
                        }
                        let first_seg = use_part.split("::").next().unwrap_or("");
                        if !first_seg.is_empty()
                            && !internal_prefixes.contains(first_seg)
                            && !std_prefixes.contains(first_seg)
                        {
                            deps.insert(first_seg.to_string());
                        }
                    }
                }
                Ecosystem::Python => {
                    if let Some(rest) = line.strip_prefix("import ") {
                        let mod_name = rest.split(' ').next().unwrap_or(rest);
                        let top = mod_name.split('.').next().unwrap_or(mod_name);
                        if !top.is_empty()
                            && !top.starts_with('.')
                            && !internal_prefixes.contains(top)
                            && !std_prefixes.contains(top)
                        {
                            deps.insert(top.to_string());
                        }
                    } else if let Some(rest) = line.strip_prefix("from ") {
                        if let Some((mod_part, _)) = rest.split_once(" import ") {
                            let mod_part = mod_part.trim();
                            if !mod_part.starts_with('.') {
                                let top = mod_part.split('.').next().unwrap_or(mod_part);
                                if !internal_prefixes.contains(top) && !std_prefixes.contains(top) {
                                    deps.insert(top.to_string());
                                }
                            }
                        }
                    }
                }
                Ecosystem::Js => {
                    for spec in extract_js_import_specifiers(line) {
                        // Skip node: prefixed imports
                        if spec.starts_with("node:") {
                            continue;
                        }
                        if !spec.starts_with('.') && !spec.starts_with('@') {
                            let pkg = spec.split('/').next().unwrap_or(&spec);
                            if !std_prefixes.contains(pkg) {
                                deps.insert(pkg.to_string());
                            }
                        } else if spec.starts_with("@") {
                            // Scoped package: @scope/pkg
                            let parts: Vec<&str> = spec.splitn(3, '/').collect();
                            if parts.len() >= 2 {
                                deps.insert(format!("{}/{}", parts[0], parts[1]));
                            }
                        }
                    }
                }
                Ecosystem::Go => {
                    if let Some(import_path) = extract_go_import(line) {
                        // Go stdlib has no dots in the first path segment (fmt, os, net/http).
                        // Third-party always has a domain (github.com/..., golang.org/x/...).
                        let first_seg = import_path.split('/').next().unwrap_or("");
                        let is_stdlib = !first_seg.contains('.');
                        if !is_stdlib
                            && !internal_prefixes
                                .iter()
                                .any(|p| import_path.starts_with(p.as_str()))
                        {
                            // Use the first three segments as the package identifier.
                            let parts: Vec<&str> = import_path.splitn(4, '/').collect();
                            if parts.len() >= 3 {
                                deps.insert(format!("{}/{}/{}", parts[0], parts[1], parts[2]));
                            }
                        }
                    }
                }
            }
        }

        if !deps.is_empty() {
            let mut sorted: Vec<String> = deps.into_iter().collect();
            sorted.sort();
            result.insert(file.clone(), sorted);
        }
    }

    result
}

// ---------------------------------------------------------------------------
// Rust import parser
// ---------------------------------------------------------------------------

fn parse_rust_imports(root: &Path, files: &[PathBuf]) -> Vec<FileEdge> {
    // Find all crate roots in the project (handles workspaces with nested crates).
    let crate_roots = find_rust_crate_roots(root);

    // Global maps across all crates.
    let mut mod_to_file: HashMap<String, PathBuf> = HashMap::new();
    let mut file_to_mod: HashMap<PathBuf, String> = HashMap::new();
    let mut file_to_crate: HashMap<PathBuf, String> = HashMap::new();
    let mut known_crates: HashSet<String> = HashSet::new();

    for (crate_dir, crate_name) in &crate_roots {
        known_crates.insert(crate_name.clone());
        // Standard layout: src/ under crate dir. Custom layout: source at crate dir itself.
        let src_dir = {
            let standard = crate_dir.join("src");
            if standard.is_dir() {
                standard
            } else {
                crate_dir.clone()
            }
        };
        for file in files {
            if !file.starts_with(&src_dir) {
                continue;
            }
            if let Some(mod_path) = rust_file_to_mod_path(file, &src_dir, crate_name) {
                mod_to_file.insert(mod_path.clone(), file.clone());
                file_to_mod.insert(file.clone(), mod_path);
                file_to_crate.insert(file.clone(), crate_name.clone());
            }
        }
    }

    let mut edges = Vec::new();

    for file in files {
        let content = match std::fs::read_to_string(file) {
            Ok(c) => c,
            Err(_) => continue,
        };

        let this_mod = file_to_mod.get(file).cloned().unwrap_or_default();
        let crate_name = file_to_crate
            .get(file)
            .cloned()
            .unwrap_or_else(|| "crate".to_string());

        let logical_lines = join_rust_logical_lines(&content);

        for line in &logical_lines {
            let line = line.trim();

            if let Some(mod_name) = parse_mod_declaration(line) {
                let child_mod = format!("{}::{}", this_mod, mod_name);
                if let Some(target) = mod_to_file.get(&child_mod) {
                    if target != file {
                        edges.push(FileEdge {
                            from: file.clone(),
                            to: target.clone(),
                        });
                    }
                }
            }

            if let Some(targets) =
                parse_use_statement(line, &this_mod, &crate_name, &known_crates, &mod_to_file)
            {
                for target in targets {
                    if target != *file {
                        edges.push(FileEdge {
                            from: file.clone(),
                            to: target,
                        });
                    }
                }
            }
        }
    }

    edges
}

/// Join multi-line `use` and `mod` statements into single logical lines.
/// Handles patterns like:
/// ```
/// use crate::{
///     foo,
///     bar,
/// };
/// ```
fn join_rust_logical_lines(content: &str) -> Vec<String> {
    let mut result = Vec::new();
    let mut accum = String::new();
    let mut in_use = false;
    let mut brace_depth: i32 = 0;

    for line in content.lines() {
        let trimmed = line.trim();

        if in_use {
            accum.push(' ');
            accum.push_str(trimmed);
            brace_depth += trimmed.chars().filter(|c| *c == '{').count() as i32;
            brace_depth -= trimmed.chars().filter(|c| *c == '}').count() as i32;
            if brace_depth <= 0 && trimmed.ends_with(';') {
                result.push(std::mem::take(&mut accum));
                in_use = false;
                brace_depth = 0;
            }
            continue;
        }

        // Detect start of multi-line use/pub use.
        let stripped = strip_visibility(trimmed);
        let is_use_start = stripped.starts_with("use ") || trimmed.starts_with("use ");
        if is_use_start && !trimmed.ends_with(';') {
            in_use = true;
            brace_depth = trimmed.chars().filter(|c| *c == '{').count() as i32;
            brace_depth -= trimmed.chars().filter(|c| *c == '}').count() as i32;
            accum = trimmed.to_string();
            continue;
        }

        result.push(trimmed.to_string());
    }

    // Flush any unterminated accumulator.
    if !accum.is_empty() {
        result.push(accum);
    }

    result
}

/// Join multi-line statements delimited by `(` `)` (Python, JS).
fn join_paren_lines(content: &str) -> Vec<String> {
    let mut result = Vec::new();
    let mut accum = String::new();
    let mut depth: i32 = 0;

    for line in content.lines() {
        let trimmed = line.trim();
        if depth > 0 {
            accum.push(' ');
            accum.push_str(trimmed);
            depth += trimmed.chars().filter(|c| *c == '(').count() as i32;
            depth -= trimmed.chars().filter(|c| *c == ')').count() as i32;
            if depth <= 0 {
                result.push(std::mem::take(&mut accum));
                depth = 0;
            }
            continue;
        }

        let opens = trimmed.chars().filter(|c| *c == '(').count() as i32;
        let closes = trimmed.chars().filter(|c| *c == ')').count() as i32;
        if opens > closes {
            depth = opens - closes;
            accum = trimmed.to_string();
            continue;
        }

        result.push(trimmed.to_string());
    }

    if !accum.is_empty() {
        result.push(accum);
    }

    result
}

/// Find all crate roots in a project: (crate_dir, crate_name).
/// Handles single crates, workspaces, and nested crates/ directories.
fn find_rust_crate_roots(root: &Path) -> Vec<(PathBuf, String)> {
    let mut roots = Vec::new();

    // Check if root itself is a crate.
    let root_cargo = root.join("Cargo.toml");
    if root_cargo.exists() {
        roots.push((root.to_path_buf(), read_rust_crate_name(root)));
        // Also check for custom binary paths (e.g., `path = "crates/core/main.rs"`).
        // These create a "virtual crate" whose source root is the directory containing the entry point.
        if let Ok(raw) = std::fs::read_to_string(&root_cargo) {
            if let Ok(val) = raw.parse::<toml::Value>() {
                let crate_name = read_rust_crate_name(root);
                if let Some(bins) = val.get("bin").and_then(|b| b.as_array()) {
                    for bin in bins {
                        if let Some(path) = bin.get("path").and_then(|p| p.as_str()) {
                            let full = root.join(path);
                            if let Some(dir) = full.parent() {
                                if dir.is_dir() && dir != root.join("src") && dir != root {
                                    roots.push((dir.to_path_buf(), crate_name.clone()));
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    // Walk for nested Cargo.toml files (workspace members).
    walk_for_cargo_tomls(root, &mut roots, 0);

    // Dedup by crate dir.
    roots.sort_by(|a, b| a.0.cmp(&b.0));
    roots.dedup_by(|a, b| a.0 == b.0);

    roots
}

fn walk_for_cargo_tomls(dir: &Path, roots: &mut Vec<(PathBuf, String)>, depth: usize) {
    if depth > 5 {
        return;
    }
    let entries = match std::fs::read_dir(dir) {
        Ok(e) => e,
        Err(_) => return,
    };
    for entry in entries.flatten() {
        let path = entry.path();
        if path.is_dir() {
            let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
            if matches!(name, "target" | ".git" | "node_modules" | "vendor") {
                continue;
            }
            let cargo_toml = path.join("Cargo.toml");
            let src_dir = path.join("src");
            if cargo_toml.exists() && src_dir.is_dir() {
                roots.push((path.clone(), read_rust_crate_name(&path)));
            }
            walk_for_cargo_tomls(&path, roots, depth + 1);
        }
    }
}

fn read_rust_crate_name(root: &Path) -> String {
    let cargo_toml = root.join("Cargo.toml");
    if let Ok(raw) = std::fs::read_to_string(&cargo_toml) {
        if let Ok(val) = raw.parse::<toml::Value>() {
            // Check [lib] name first, then [package] name.
            if let Some(name) = val
                .get("lib")
                .and_then(|l| l.get("name"))
                .and_then(|n| n.as_str())
            {
                return name.replace('-', "_");
            }
            if let Some(name) = val
                .get("package")
                .and_then(|p| p.get("name"))
                .and_then(|n| n.as_str())
            {
                return name.replace('-', "_");
            }
        }
    }
    // Fallback: directory name.
    root.file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("crate")
        .replace('-', "_")
}

fn rust_file_to_mod_path(file: &Path, src_dir: &Path, crate_name: &str) -> Option<String> {
    let rel = file.strip_prefix(src_dir).ok()?;
    let rel_str = rel.to_string_lossy().replace('\\', "/");

    // lib.rs or main.rs → "crate" (the crate root module)
    if rel_str == "lib.rs" || rel_str == "main.rs" {
        return Some(crate_name.to_string());
    }

    // foo.rs → "crate::foo"
    // foo/mod.rs → "crate::foo"
    // foo/bar.rs → "crate::foo::bar"
    // foo/bar/mod.rs → "crate::foo::bar"
    let rel_str = if rel_str.ends_with("/mod.rs") {
        rel_str.trim_end_matches("/mod.rs").to_string()
    } else {
        rel_str.trim_end_matches(".rs").to_string()
    };

    // bin/foo.rs → skip (handled separately)
    if rel_str.starts_with("bin/") {
        return Some(format!("bin::{}", rel_str.trim_start_matches("bin/")));
    }

    let mod_path = rel_str.replace('/', "::");
    Some(format!("{}::{}", crate_name, mod_path))
}

fn parse_mod_declaration(line: &str) -> Option<String> {
    // Match: `mod foo;` or `pub mod foo;` or `pub(crate) mod foo;`
    // Skip: `mod tests {`, `mod foo {` (inline modules, not file declarations)
    let line = line.trim();
    if !line.ends_with(';') {
        return None;
    }

    // Strip attributes like #[cfg(feature = "...")] -- these are on preceding lines,
    // but `mod foo;` on its own line is what we care about.
    let stripped = strip_visibility(line);
    let stripped = stripped.trim();

    if let Some(rest) = stripped.strip_prefix("mod ") {
        let name = rest.trim_end_matches(';').trim();
        // Validate it's a simple identifier.
        if name.chars().all(|c| c.is_alphanumeric() || c == '_') && !name.is_empty() {
            return Some(name.to_string());
        }
    }
    None
}

fn strip_visibility(line: &str) -> &str {
    if let Some(rest) = line.strip_prefix("pub(crate) ") {
        return rest;
    }
    if let Some(rest) = line.strip_prefix("pub(super) ") {
        return rest;
    }
    if let Some(rest) = line.strip_prefix("pub(self) ") {
        return rest;
    }
    // pub(in path) -- complex, just strip pub(...) prefix
    if line.starts_with("pub(") {
        if let Some(close) = line.find(") ") {
            return &line[close + 2..];
        }
    }
    if let Some(rest) = line.strip_prefix("pub ") {
        return rest;
    }
    line
}

fn parse_use_statement(
    line: &str,
    current_mod: &str,
    crate_name: &str,
    known_crates: &HashSet<String>,
    mod_to_file: &HashMap<String, PathBuf>,
) -> Option<Vec<PathBuf>> {
    let line = line.trim();
    let use_part = if let Some(rest) = strip_visibility(line).strip_prefix("use ") {
        rest
    } else if let Some(rest) = line.strip_prefix("use ") {
        rest
    } else {
        return None;
    };

    let use_part = use_part.trim_end_matches(';').trim();

    let (base_mod, _rest) = if use_part.starts_with("crate::") {
        let resolved = format!("{}{}", crate_name, &use_part["crate".len()..]);
        (resolved, "")
    } else if use_part.starts_with("super::") {
        // Handle chained super:: (e.g. super::super::foo).
        let mut base = current_mod.to_string();
        let mut rest = use_part;
        while let Some(after) = rest.strip_prefix("super::") {
            base = base
                .rsplit_once("::")
                .map(|(p, _)| p.to_string())
                .unwrap_or_default();
            rest = after;
        }
        let resolved = if rest.is_empty() || base.is_empty() {
            if base.is_empty() {
                rest.to_string()
            } else {
                base
            }
        } else {
            format!("{}::{}", base, rest)
        };
        (resolved, "")
    } else if use_part.starts_with("self::") {
        let relative = use_part.strip_prefix("self::").unwrap_or(use_part);
        (format!("{}::{}", current_mod, relative), "")
    } else {
        let first_seg = use_part.split("::").next().unwrap_or("");
        if known_crates.contains(first_seg) {
            // Cross-crate workspace import: `use other_crate::foo`.
            (use_part.to_string(), "")
        } else {
            // Try as bare sibling module: `use graph::Foo` → `current_mod::graph::Foo`.
            let sibling_mod = format!("{}::{}", current_mod, first_seg);
            let sibling_exists = mod_to_file.contains_key(&sibling_mod)
                || mod_to_file
                    .keys()
                    .any(|k| k.starts_with(&format!("{}::", sibling_mod)));
            if sibling_exists {
                (format!("{}::{}", current_mod, use_part), "")
            } else {
                return None;
            }
        }
    };

    // The base_mod might be "crate::foo::bar::Baz" or "crate::foo::{A, B}".
    // We need to find the longest prefix that matches a known module.
    let mut targets = Vec::new();
    resolve_use_path(&base_mod, mod_to_file, &mut targets);

    if targets.is_empty() {
        None
    } else {
        Some(targets)
    }
}

fn resolve_use_path(path: &str, mod_to_file: &HashMap<String, PathBuf>, out: &mut Vec<PathBuf>) {
    // Handle grouped imports: `crate::foo::{bar, baz}`
    if let Some(brace_start) = path.find('{') {
        let prefix = &path[..brace_start];
        let rest = &path[brace_start + 1..];
        let rest = rest.trim_end_matches('}');
        for item in rest.split(',') {
            let item = item.trim();
            if item.is_empty() {
                continue;
            }
            let full = format!("{}{}", prefix, item);
            resolve_use_path(&full, mod_to_file, out);
        }
        return;
    }

    // Try progressively shorter prefixes to find the owning module's file.
    let mut path_str = path.to_string();
    // Replace "crate::" with the actual crate name if present.
    // The mod_to_file keys use the crate name, not "crate".
    // Actually, we need to check both forms. The caller already resolved super/self,
    // but "crate::" → we stored as "crate_name::".
    // Let's check if any key starts with the first segment.

    loop {
        if let Some(file) = mod_to_file.get(&path_str) {
            out.push(file.clone());
            return;
        }
        // Strip last segment and try again.
        match path_str.rsplit_once("::") {
            Some((parent, _)) => path_str = parent.to_string(),
            None => break,
        }
    }
}

// ---------------------------------------------------------------------------
// Python import parser
// ---------------------------------------------------------------------------

fn parse_python_imports(root: &Path, files: &[PathBuf]) -> Vec<FileEdge> {
    let packages = detect_python_packages(root);

    // Map: module path (dot-separated) → file path.
    let mut mod_to_file: HashMap<String, PathBuf> = HashMap::new();
    let mut file_to_mod: HashMap<PathBuf, String> = HashMap::new();

    for (pkg_name, pkg_dir) in &packages {
        for file in files {
            if !file.starts_with(pkg_dir) {
                continue;
            }
            if let Some(mod_path) = python_file_to_mod_path(file, pkg_dir, pkg_name) {
                mod_to_file.insert(mod_path.clone(), file.clone());
                file_to_mod.insert(file.clone(), mod_path);
            }
        }
    }
    // Fallback: map any unmapped files against the first package.
    if let Some((pkg_name, pkg_dir)) = packages.first() {
        for file in files {
            if !file_to_mod.contains_key(file) {
                if let Some(mod_path) = python_file_to_mod_path(file, pkg_dir, pkg_name) {
                    mod_to_file.insert(mod_path.clone(), file.clone());
                    file_to_mod.insert(file.clone(), mod_path);
                }
            }
        }
    }
    let pkg_name = packages
        .first()
        .map(|(n, _)| n.clone())
        .unwrap_or_else(|| "pkg".to_string());

    let mut edges = Vec::new();

    for file in files {
        let content = match std::fs::read_to_string(file) {
            Ok(c) => c,
            Err(_) => continue,
        };

        let this_mod = file_to_mod.get(file).cloned().unwrap_or_default();

        // Join multi-line imports: `from pkg import (\n  A,\n  B\n)`
        let logical_lines = join_paren_lines(&content);

        for line in &logical_lines {
            let line = line.trim();

            if let Some(targets) =
                parse_python_from_import(line, &this_mod, &pkg_name, &mod_to_file)
            {
                for target in targets {
                    if target != *file {
                        edges.push(FileEdge {
                            from: file.clone(),
                            to: target,
                        });
                    }
                }
                continue;
            }

            if let Some(targets) = parse_python_import(line, &mod_to_file) {
                for target in targets {
                    if target != *file {
                        edges.push(FileEdge {
                            from: file.clone(),
                            to: target,
                        });
                    }
                }
            }
        }
    }

    edges
}

fn detect_python_packages(root: &Path) -> Vec<(String, PathBuf)> {
    let mut packages = Vec::new();

    // Check src/ layout first.
    let src = root.join("src");
    if src.is_dir() {
        if let Ok(entries) = std::fs::read_dir(&src) {
            for entry in entries.flatten() {
                let p = entry.path();
                if p.is_dir() && p.join("__init__.py").exists() {
                    let name = p
                        .file_name()
                        .and_then(|n| n.to_str())
                        .unwrap_or("pkg")
                        .to_string();
                    packages.push((name, p));
                }
            }
        }
    }

    // Check root-level package dirs.
    if let Ok(entries) = std::fs::read_dir(root) {
        for entry in entries.flatten() {
            let p = entry.path();
            if p.is_dir() && p.join("__init__.py").exists() {
                let name = p
                    .file_name()
                    .and_then(|n| n.to_str())
                    .unwrap_or("pkg")
                    .to_string();
                if !matches!(
                    name.as_str(),
                    "tests" | "test" | "docs" | "examples" | "benchmarks"
                ) && !packages.iter().any(|(n, _)| n == &name)
                {
                    packages.push((name, p));
                }
            }
        }
    }

    // Check pyproject.toml for project name and look for matching dir (namespace packages).
    if packages.is_empty() {
        if let Some(project_name) = read_pyproject_name(root) {
            let normalized = project_name.replace('-', "_");
            // Check common locations.
            for candidate in [root.join("src").join(&normalized), root.join(&normalized)] {
                if candidate.is_dir() {
                    packages.push((normalized.clone(), candidate));
                    break;
                }
            }
        }
    }

    // Fallback: treat root as the package.
    if packages.is_empty() {
        let name = root
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("pkg")
            .to_string();
        packages.push((name, root.to_path_buf()));
    }

    packages
}

/// Backward-compatible wrapper for single-package detection.
fn read_pyproject_name(root: &Path) -> Option<String> {
    let pyproject = root.join("pyproject.toml");
    let raw = std::fs::read_to_string(&pyproject).ok()?;
    let val: toml::Value = toml::from_str(&raw).ok()?;
    val.get("project")
        .and_then(|p| p.get("name"))
        .and_then(|n| n.as_str())
        .map(|s| s.to_string())
}

fn detect_python_package(root: &Path) -> (String, PathBuf) {
    detect_python_packages(root)
        .into_iter()
        .next()
        .unwrap_or_else(|| {
            let name = root
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("pkg")
                .to_string();
            (name, root.to_path_buf())
        })
}

fn python_file_to_mod_path(file: &Path, pkg_dir: &Path, pkg_name: &str) -> Option<String> {
    let rel = file.strip_prefix(pkg_dir).ok()?;
    let rel_str = rel.to_string_lossy().replace('\\', "/");

    if rel_str == "__init__.py" {
        return Some(pkg_name.to_string());
    }

    let rel_str = if rel_str.ends_with("/__init__.py") {
        rel_str.trim_end_matches("/__init__.py").to_string()
    } else {
        rel_str.trim_end_matches(".py").to_string()
    };

    let mod_path = rel_str.replace('/', ".");
    Some(format!("{}.{}", pkg_name, mod_path))
}

fn parse_python_from_import(
    line: &str,
    current_mod: &str,
    pkg_name: &str,
    mod_to_file: &HashMap<String, PathBuf>,
) -> Option<Vec<PathBuf>> {
    // `from .foo import bar` or `from ..foo import bar` or `from pkg.foo import bar`
    let rest = line.strip_prefix("from ")?;
    let (module_part, import_names) = rest.split_once(" import ")?;
    let module_part = module_part.trim();

    let resolved = if module_part.starts_with('.') {
        // Relative import.
        let dots = module_part.chars().take_while(|c| *c == '.').count();
        let relative = &module_part[dots..];

        // Go up `dots` levels from current module.
        let mut base = current_mod.to_string();
        for _ in 0..dots {
            base = base
                .rsplit_once('.')
                .map(|(p, _)| p.to_string())
                .unwrap_or_default();
        }

        if relative.is_empty() {
            base
        } else {
            format!("{}.{}", base, relative)
        }
    } else if module_part.starts_with(pkg_name) {
        // Absolute import within the package.
        module_part.to_string()
    } else {
        // External package.
        return None;
    };

    let mut targets = Vec::new();
    resolve_python_path(&resolved, mod_to_file, &mut targets);

    // Also try each imported name as a submodule:
    // `from pkg.utils import helpers` → try `pkg.utils.helpers` as a module.
    for name in import_names.split(',') {
        let name = name.trim().split(" as ").next().unwrap_or("").trim();
        if name.is_empty() || name == "*" {
            continue;
        }
        let submod = format!("{}.{}", resolved, name);
        resolve_python_path(&submod, mod_to_file, &mut targets);
    }

    if targets.is_empty() {
        None
    } else {
        Some(targets)
    }
}

fn parse_python_import(line: &str, mod_to_file: &HashMap<String, PathBuf>) -> Option<Vec<PathBuf>> {
    // `import pkg.foo.bar` or `import pkg.foo.bar as baz`
    let rest = line.strip_prefix("import ")?;
    // Skip `from ... import ...` (handled separately).
    if line.starts_with("from ") {
        return None;
    }

    let mut targets = Vec::new();
    for part in rest.split(',') {
        let part = part.trim();
        let mod_path = part.split(" as ").next().unwrap_or(part).trim();
        resolve_python_path(mod_path, mod_to_file, &mut targets);
    }

    if targets.is_empty() {
        None
    } else {
        Some(targets)
    }
}

fn resolve_python_path(path: &str, mod_to_file: &HashMap<String, PathBuf>, out: &mut Vec<PathBuf>) {
    let mut path_str = path.to_string();
    loop {
        if let Some(file) = mod_to_file.get(&path_str) {
            out.push(file.clone());
            return;
        }
        match path_str.rsplit_once('.') {
            Some((parent, _)) => path_str = parent.to_string(),
            None => break,
        }
    }
}

// ---------------------------------------------------------------------------
// JS/TS import parser
// ---------------------------------------------------------------------------

fn parse_js_imports(root: &Path, files: &[PathBuf]) -> Vec<FileEdge> {
    let mut edges = Vec::new();

    let file_set: HashSet<PathBuf> = files.iter().cloned().collect();
    let path_aliases = read_tsconfig_paths(root);

    for file in files {
        let content = match std::fs::read_to_string(file) {
            Ok(c) => c,
            Err(_) => continue,
        };

        let dir = file.parent().unwrap_or(root);

        // For Svelte/Vue files, only process imports inside <script> blocks.
        let ext = file.extension().and_then(|e| e.to_str()).unwrap_or("");
        let effective_content: std::borrow::Cow<str> = if ext == "svelte" || ext == "vue" {
            extract_script_block_content(&content).into()
        } else {
            std::borrow::Cow::Borrowed(&content)
        };

        for line in effective_content.lines() {
            let line = line.trim();

            for spec in extract_js_import_specifiers(line) {
                // Resolve the import to a filesystem path.
                let resolved = if spec.starts_with('.') {
                    resolve_js_import(dir, &spec, &file_set)
                } else {
                    // Try all alias candidates (bare package imports may resolve
                    // to src/ or the package root, whichever has the index file).
                    let candidates = resolve_alias_candidates(&spec, &path_aliases);
                    if candidates.is_empty() {
                        continue;
                    }
                    candidates.into_iter().find_map(|abs_path| {
                        let parent = abs_path.parent().unwrap_or(root).to_path_buf();
                        let fname = abs_path
                            .file_name()
                            .unwrap_or_default()
                            .to_string_lossy()
                            .to_string();
                        resolve_js_import(&parent, &format!("./{}", fname), &file_set)
                    })
                };

                if let Some(resolved) = resolved {
                    if resolved != *file {
                        edges.push(FileEdge {
                            from: file.clone(),
                            to: resolved,
                        });
                    }
                }
            }
        }
    }

    edges
}

/// Read path aliases from tsconfig.json / jsconfig.json.
/// Returns Vec<(prefix, replacement_dir)>, e.g. ("@/", "./src/").
fn read_tsconfig_paths(root: &Path) -> Vec<(String, PathBuf)> {
    let mut aliases = Vec::new();

    // Read tsconfig.json/jsconfig.json for path aliases.
    let candidates = ["tsconfig.json", "jsconfig.json"];
    for name in &candidates {
        let path = root.join(name);
        if let Ok(raw) = std::fs::read_to_string(&path) {
            let cleaned: String = raw
                .lines()
                .map(|l| {
                    if let Some(pos) = l.find("//") {
                        &l[..pos]
                    } else {
                        l
                    }
                })
                .collect::<Vec<_>>()
                .join("\n");
            if let Ok(val) = serde_json::from_str::<serde_json::Value>(&cleaned) {
                aliases = extract_path_aliases(&val, root);
                break;
            }
        }
    }

    // Always discover workspace packages (even without tsconfig).
    discover_workspace_packages(root, &mut aliases);

    // Fallback: @/ → root if nothing else matched.
    if aliases.is_empty() {
        aliases.push(("@/".to_string(), root.to_path_buf()));
    }

    aliases
}

fn extract_path_aliases(tsconfig: &serde_json::Value, root: &Path) -> Vec<(String, PathBuf)> {
    let mut aliases = Vec::new();

    let base_url = tsconfig
        .get("compilerOptions")
        .and_then(|c| c.get("baseUrl"))
        .and_then(|b| b.as_str())
        .unwrap_or(".");
    let base_dir = root.join(base_url);

    if let Some(paths) = tsconfig
        .get("compilerOptions")
        .and_then(|c| c.get("paths"))
        .and_then(|p| p.as_object())
    {
        for (pattern, targets) in paths {
            // Pattern like "@/*" → strip the wildcard.
            let prefix = pattern.trim_end_matches('*');
            if let Some(first_target) = targets.as_array().and_then(|a| a.first()) {
                if let Some(target_str) = first_target.as_str() {
                    let target_path = target_str.trim_end_matches('*');
                    let resolved = base_dir.join(target_path);
                    aliases.push((prefix.to_string(), resolved));
                }
            }
        }
    }

    // Discover npm/yarn/pnpm workspace packages.
    // Maps `@scope/pkg` or `pkg` → the package's directory.
    discover_workspace_packages(root, &mut aliases);

    aliases
}

/// Find all workspace packages by scanning for package.json files in common locations.
fn discover_workspace_packages(root: &Path, aliases: &mut Vec<(String, PathBuf)>) {
    // Read root package.json for workspace patterns.
    let root_pkg = root.join("package.json");
    if !root_pkg.exists() {
        return;
    }
    let raw = match std::fs::read_to_string(&root_pkg) {
        Ok(r) => r,
        Err(_) => return,
    };
    let val: serde_json::Value = match serde_json::from_str(&raw) {
        Ok(v) => v,
        Err(_) => return,
    };

    // Workspace dirs: from "workspaces" field (npm/yarn) or common patterns.
    let mut search_dirs: Vec<PathBuf> = Vec::new();
    if let Some(workspaces) = val.get("workspaces") {
        let patterns = if let Some(arr) = workspaces.as_array() {
            arr.iter()
                .filter_map(|v| v.as_str())
                .map(|s| s.to_string())
                .collect::<Vec<_>>()
        } else if let Some(obj) = workspaces.as_object() {
            // yarn workspaces: { "packages": ["packages/*"] }
            obj.get("packages")
                .and_then(|p| p.as_array())
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str())
                        .map(|s| s.to_string())
                        .collect::<Vec<_>>()
                })
                .unwrap_or_default()
        } else {
            Vec::new()
        };

        for pattern in patterns {
            let pattern = pattern.trim_end_matches("/*").trim_end_matches("/**");
            let dir = root.join(pattern);
            if dir.is_dir() {
                search_dirs.push(dir);
            }
        }
    }

    // Common fallback patterns.
    if search_dirs.is_empty() {
        for dir_name in ["packages", "apps", "libs", "modules"] {
            let d = root.join(dir_name);
            if d.is_dir() {
                search_dirs.push(d);
            }
        }
    }

    // Scan each workspace dir for package.json files.
    for dir in &search_dirs {
        let entries = match std::fs::read_dir(dir) {
            Ok(e) => e,
            Err(_) => continue,
        };
        for entry in entries.flatten() {
            let pkg_json = entry.path().join("package.json");
            if !pkg_json.exists() {
                continue;
            }
            let raw = match std::fs::read_to_string(&pkg_json) {
                Ok(r) => r,
                Err(_) => continue,
            };
            let pkg_val: serde_json::Value = match serde_json::from_str(&raw) {
                Ok(v) => v,
                Err(_) => continue,
            };
            if let Some(name) = pkg_val.get("name").and_then(|n| n.as_str()) {
                // Map "name/" → package directory.
                // For imports like `@calcom/lib/hooks/useLocale`,
                // the prefix `@calcom/lib/` maps to `packages/lib/`.
                let pkg_dir = entry.path();

                // Check for explicit "main" or "exports" to find src root.
                let has_src = pkg_dir.join("src").is_dir();
                let src_dir = if has_src {
                    pkg_dir.join("src")
                } else {
                    pkg_dir.clone()
                };

                aliases.push((format!("{}/", name), src_dir));
                // Also push the pkg root so bare imports like `import 'react'`
                // can resolve to `packages/react/index.js` when index.js is at
                // the root (not in src/).
                if has_src {
                    aliases.push((format!("{}/", name), pkg_dir.clone()));
                }
            }
        }
    }
}

/// Try all alias dirs for a bare package import and return candidates.
/// Used when a package may have index files in multiple locations (src/ vs root).
fn resolve_alias_candidates(spec: &str, aliases: &[(String, PathBuf)]) -> Vec<PathBuf> {
    let mut candidates = Vec::new();
    // Path imports.
    for (prefix, target_dir) in aliases {
        if let Some(rest) = spec.strip_prefix(prefix.as_str()) {
            candidates.push(target_dir.join(rest));
            return candidates; // Exact prefix match -- no ambiguity.
        }
    }
    // Bare package imports: collect all matching dirs.
    for (prefix, target_dir) in aliases {
        let bare = prefix.trim_end_matches('/');
        if spec == bare {
            candidates.push(target_dir.join("index"));
        }
    }
    candidates
}

/// Extract the content of `<script>` blocks from Svelte/Vue component files.
/// Returns only the text inside `<script ...>...</script>` tags, stripping the tags themselves.
/// Multiple script blocks are concatenated. Falls back to the full content if no script tags found.
fn extract_script_block_content(content: &str) -> String {
    let mut result = String::new();
    let mut remaining = content;

    while let Some(start) = remaining.find("<script") {
        // Find the end of the opening tag.
        let tag_body = &remaining[start..];
        if let Some(tag_end) = tag_body.find('>') {
            let script_content_start = start + tag_end + 1;
            let rest = &remaining[script_content_start..];
            if let Some(close) = rest.find("</script>") {
                result.push_str(&rest[..close]);
                result.push('\n');
                remaining = &rest[close + "</script>".len()..];
            } else {
                break;
            }
        } else {
            break;
        }
    }

    if result.is_empty() {
        // No script tags found; return full content (graceful fallback).
        content.to_string()
    } else {
        result
    }
}

fn extract_js_import_specifiers(line: &str) -> Vec<String> {
    let mut specs = Vec::new();

    // `import ... from '...'` or `import ... from "..."`
    if line.starts_with("import ") || line.starts_with("export ") {
        if let Some(spec) = extract_string_after(line, " from ") {
            specs.push(spec);
        } else if line.starts_with("import '") || line.starts_with("import \"") {
            // Side-effect import: `import './foo'`
            if let Some(spec) = extract_quoted_string(&line["import ".len()..]) {
                specs.push(spec);
            }
        }
    }

    // `require('...')` -- only at statement level (not inside a string).
    // Heuristic: require( must be preceded by start-of-line, `=`, `(`, or whitespace.
    if let Some(pos) = line.find("require(") {
        let before = if pos > 0 {
            line.as_bytes()[pos - 1]
        } else {
            b' '
        };
        if matches!(before, b' ' | b'=' | b'(' | b'\t' | b',') || pos == 0 {
            let after = &line[pos + "require(".len()..];
            if let Some(spec) = extract_quoted_string(after) {
                specs.push(spec);
            }
        }
    }

    specs
}

fn extract_string_after(line: &str, marker: &str) -> Option<String> {
    let pos = line.find(marker)?;
    let after = &line[pos + marker.len()..];
    extract_quoted_string(after)
}

fn extract_quoted_string(s: &str) -> Option<String> {
    let s = s.trim();
    let (quote, rest) = if let Some(rest) = s.strip_prefix('\'') {
        ('\'', rest)
    } else if let Some(rest) = s.strip_prefix('"') {
        ('"', rest)
    } else {
        return None;
    };
    let end = rest.find(quote)?;
    Some(rest[..end].to_string())
}

fn resolve_js_import(dir: &Path, spec: &str, file_set: &HashSet<PathBuf>) -> Option<PathBuf> {
    let base = dir.join(spec);

    // Try exact path, then with extensions, then as directory/index.
    let extensions = ["", ".ts", ".tsx", ".js", ".jsx", ".mjs", ".svelte", ".vue"];

    for ext in &extensions {
        let candidate = PathBuf::from(format!("{}{}", base.display(), ext));
        if let Ok(canonical) = candidate.canonicalize() {
            if file_set.contains(&canonical) {
                return Some(canonical);
            }
        }
        // Also try without canonicalize (symlinks, etc.)
        if file_set.contains(&candidate) {
            return Some(candidate);
        }
    }

    // Try as directory: spec/index.{ts,tsx,js,jsx,svelte}
    let dir_extensions = [
        "index.ts",
        "index.tsx",
        "index.js",
        "index.jsx",
        "index.svelte",
    ];
    for idx in &dir_extensions {
        let candidate = base.join(idx);
        if let Ok(canonical) = candidate.canonicalize() {
            if file_set.contains(&canonical) {
                return Some(canonical);
            }
        }
        if file_set.contains(&candidate) {
            return Some(candidate);
        }
    }

    None
}

// ---------------------------------------------------------------------------
// Go import parser
// ---------------------------------------------------------------------------

fn parse_go_imports(root: &Path, files: &[PathBuf]) -> Vec<FileEdge> {
    // Try `go list -json` for correct, build-tag-aware, alias-aware import resolution.
    // Requires Go toolchain + module download. Falls back to text parsing.
    if let Some(edges) = parse_go_imports_golist(root, files) {
        return edges;
    }
    parse_go_imports_text(root, files)
}

/// Use `go list -json ./...` for correct import resolution.
fn parse_go_imports_golist(root: &Path, files: &[PathBuf]) -> Option<Vec<FileEdge>> {
    // Ensure modules are available (shallow clones won't have them).
    let dl = ProcessCommand::new("go")
        .args(["mod", "download"])
        .current_dir(root)
        .stderr(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .status();
    if dl.map(|s| !s.success()).unwrap_or(true) {
        return None;
    }

    let out = ProcessCommand::new("go")
        .args(["list", "-e", "-json", "./..."])
        .current_dir(root)
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let stdout = String::from_utf8_lossy(&out.stdout);
    if stdout.trim().is_empty() {
        return None;
    }

    let module_name = read_go_module_name(root);
    if module_name.is_empty() {
        return None;
    }

    // Parse concatenated JSON objects (go list outputs one object per package, not an array).
    #[derive(Deserialize)]
    #[serde(rename_all = "PascalCase")]
    struct GoPackage {
        import_path: Option<String>,
        #[serde(default)]
        dir: String,
        #[serde(default)]
        go_files: Vec<String>,
        #[serde(default)]
        imports: Vec<String>,
    }

    let mut packages: Vec<GoPackage> = Vec::new();
    // Use serde_json StreamDeserializer for concatenated JSON.
    for result in serde_json::Deserializer::from_str(&stdout).into_iter::<GoPackage>() {
        match result {
            Ok(pkg) => packages.push(pkg),
            Err(_) => continue,
        }
    }

    // Need enough packages to be useful (go list may partially fail).
    if packages.len() < 2 {
        return None;
    }

    let file_set: HashSet<PathBuf> = files.iter().cloned().collect();

    // Map: import path → (canonical file, all files in package).
    let mut pkg_canonical: HashMap<String, PathBuf> = HashMap::new();
    let mut pkg_to_files: HashMap<String, Vec<PathBuf>> = HashMap::new();

    for pkg in &packages {
        let import_path = match &pkg.import_path {
            Some(ip) => ip.clone(),
            None => continue,
        };
        let pkg_dir = PathBuf::from(&pkg.dir);

        let go_files: Vec<PathBuf> = pkg
            .go_files
            .iter()
            .map(|f| pkg_dir.join(f))
            .filter(|f| file_set.contains(f))
            .collect();

        if let Some(canonical) = go_files.first().cloned() {
            pkg_canonical.insert(import_path.clone(), canonical);
        }
        if !go_files.is_empty() {
            pkg_to_files.insert(import_path, go_files);
        }
    }

    let mut edges = Vec::new();

    // Cross-package edges from resolved Imports.
    for pkg in &packages {
        let import_path = match &pkg.import_path {
            Some(ip) => ip,
            None => continue,
        };
        let from_files = match pkg_to_files.get(import_path.as_str()) {
            Some(f) => f,
            None => continue,
        };
        for imp in &pkg.imports {
            if !imp.starts_with(&module_name) {
                continue;
            }
            if let Some(target) = pkg_canonical.get(imp.as_str()) {
                for from_file in from_files {
                    if from_file != target {
                        edges.push(FileEdge {
                            from: from_file.clone(),
                            to: target.clone(),
                        });
                    }
                }
            }
        }
    }

    // Intra-package edges: files in the same package share a namespace.
    for (pkg_path, pkg_files) in &pkg_to_files {
        if let Some(canonical) = pkg_canonical.get(pkg_path.as_str()) {
            for f in pkg_files {
                if f != canonical {
                    edges.push(FileEdge {
                        from: f.clone(),
                        to: canonical.clone(),
                    });
                }
            }
        }
    }

    if edges.is_empty() {
        return None; // Fall back to text parser.
    }
    Some(edges)
}

/// Fallback: text-based Go import parsing (when Go toolchain is not available).
fn parse_go_imports_text(root: &Path, files: &[PathBuf]) -> Vec<FileEdge> {
    let module_name = read_go_module_name(root);

    let mut pkg_to_files: HashMap<String, Vec<PathBuf>> = HashMap::new();
    for file in files {
        if let Some(pkg_path) = go_file_to_pkg_path(file, root, &module_name) {
            pkg_to_files.entry(pkg_path).or_default().push(file.clone());
        }
    }

    let mut pkg_canonical: HashMap<String, PathBuf> = HashMap::new();
    for (pkg, pkg_files) in &mut pkg_to_files {
        pkg_files.sort();
        let pkg_leaf = pkg.rsplit('/').next().unwrap_or(pkg);
        let canonical = pkg_files
            .iter()
            .find(|f| {
                f.file_stem()
                    .and_then(|s| s.to_str())
                    .map(|s| s == pkg_leaf)
                    .unwrap_or(false)
            })
            .or_else(|| {
                pkg_files.iter().find(|f| {
                    f.file_name()
                        .and_then(|n| n.to_str())
                        .map(|n| n != "doc.go")
                        .unwrap_or(true)
                })
            })
            .or(pkg_files.first())
            .cloned();
        if let Some(c) = canonical {
            pkg_canonical.insert(pkg.clone(), c);
        }
    }

    let mut edges = Vec::new();

    for file in files {
        let content = match std::fs::read_to_string(file) {
            Ok(c) => c,
            Err(_) => continue,
        };
        for line in content.lines() {
            let line = line.trim();
            if let Some(import_path) = extract_go_import(line) {
                if !import_path.starts_with(&module_name) {
                    continue;
                }
                if let Some(target) = pkg_canonical.get(&import_path) {
                    if target != file {
                        edges.push(FileEdge {
                            from: file.clone(),
                            to: target.clone(),
                        });
                    }
                }
            }
        }
    }

    // Intra-package edges.
    for (pkg, canonical) in &pkg_canonical {
        if let Some(pkg_files) = pkg_to_files.get(pkg) {
            for f in pkg_files {
                if f != canonical {
                    edges.push(FileEdge {
                        from: f.clone(),
                        to: canonical.clone(),
                    });
                }
            }
        }
    }

    edges
}

fn read_go_module_name(root: &Path) -> String {
    let go_mod = root.join("go.mod");
    if let Ok(content) = std::fs::read_to_string(&go_mod) {
        for line in content.lines() {
            if let Some(rest) = line.strip_prefix("module ") {
                return rest.trim().to_string();
            }
        }
    }
    String::new()
}

fn go_file_to_pkg_path(file: &Path, root: &Path, module_name: &str) -> Option<String> {
    let dir = file.parent()?;
    let rel = dir.strip_prefix(root).ok()?;
    let rel_str = rel.to_string_lossy().replace('\\', "/");

    if rel_str.is_empty() {
        Some(module_name.to_string())
    } else {
        Some(format!("{}/{}", module_name, rel_str))
    }
}

fn extract_go_import(line: &str) -> Option<String> {
    // Match: `"some/import/path"` (possibly with alias prefix)
    let line = line.trim();
    // Skip `import (` and `)` lines, and the `import` keyword line.
    if line == "import (" || line == ")" || line == "import" {
        return None;
    }

    // Could be: `import "path"` or `_ "path"` or `alias "path"`
    extract_quoted_string(line).or_else(|| {
        // With alias: `foo "path"`
        let parts: Vec<&str> = line.splitn(2, ' ').collect();
        if parts.len() == 2 {
            extract_quoted_string(parts[1])
        } else {
            None
        }
    })
}

// ---------------------------------------------------------------------------
// Output row
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct FileRow {
    pub file: String,
    pub role: FileRole,
    pub in_degree: usize,
    pub out_degree: usize,
    pub dependents: usize,
    pub dependencies: usize,
    pub pagerank: f64,
    pub consumers_pagerank: f64,
    pub betweenness: f64,
    pub orphan: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cycle_id: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub commits: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub churn_risk: Option<f64>,
    /// Files that most frequently change in the same commit (temporal coupling).
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub co_changers: Vec<(String, usize)>,
    /// Instability: out_degree / (in_degree + out_degree). 0 = stable, 1 = unstable.
    pub instability: f64,
    /// Unique contributors in the git window (bus factor proxy).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub contributors: Option<usize>,
    /// Structural role + stability-volatility quadrant.
    pub structure: String,
    /// External packages this file imports (ecosystem-level deps).
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub external_deps: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct FilesResult {
    pub rows: Vec<FileRow>,
    pub nodes: usize,
    pub edges: usize,
    pub ecosystem: Ecosystem,
    pub orphan_count: usize,
    pub cycles: Vec<Vec<String>>,
    #[serde(skip)]
    pub direct_edges: Vec<(String, String)>,
}

#[derive(Debug, Clone, Serialize)]
pub(crate) struct LayerViolation {
    pub from: String,
    pub to: String,
    pub from_instability: f64,
    pub to_instability: f64,
}

/// Compute layer violations: stable files (low I) importing unstable files (high I).
pub(crate) fn compute_layer_violations(result: &FilesResult) -> Vec<LayerViolation> {
    let file_instability: HashMap<&str, f64> = result
        .rows
        .iter()
        .map(|r| (r.file.as_str(), r.instability))
        .collect();
    let mut violations = Vec::new();
    for (from, to) in &result.direct_edges {
        let from_i = file_instability.get(from.as_str()).copied().unwrap_or(0.5);
        let to_i = file_instability.get(to.as_str()).copied().unwrap_or(0.5);
        // Skip mod.rs/lib.rs/index.ts → sibling edges (module tree structure).
        let from_base = std::path::Path::new(from)
            .file_name()
            .and_then(|f| f.to_str())
            .unwrap_or("");
        let same_dir = std::path::Path::new(from).parent() == std::path::Path::new(to).parent();
        let is_mod_reexport = (from_base == "mod.rs"
            || from_base == "lib.rs"
            || from_base == "__init__.py"
            || from_base == "index.ts"
            || from_base == "index.js")
            && same_dir;
        if from_i < 0.3 && to_i > 0.7 && !is_mod_reexport {
            violations.push(LayerViolation {
                from: from.clone(),
                to: to.clone(),
                from_instability: from_i,
                to_instability: to_i,
            });
        }
    }
    violations.sort_by(|a, b| {
        (b.to_instability - b.from_instability).total_cmp(&(a.to_instability - a.from_instability))
    });
    violations
}

/// Compute transitively affected files from a set of changed files.
///
/// Does reverse BFS on the import graph: if A imports B and B changed,
/// A is affected (because its dependency changed).
pub(crate) fn compute_affected(result: &FilesResult, changed: &[String]) -> Vec<String> {
    // Build reverse adjacency list: to -> [from] (who imports this file).
    let mut reverse_adj: HashMap<&str, Vec<&str>> = HashMap::new();
    for (from, to) in &result.direct_edges {
        reverse_adj
            .entry(to.as_str())
            .or_default()
            .push(from.as_str());
    }

    // Normalize changed file paths: try matching by suffix against known files.
    let known_files: HashSet<&str> = result.rows.iter().map(|r| r.file.as_str()).collect();
    let mut seeds: HashSet<&str> = HashSet::new();
    for ch in changed {
        let ch = ch.trim();
        if known_files.contains(ch) {
            seeds.insert(ch);
        } else {
            // Try suffix match (user may pass "src/main.rs" when graph has "main.rs" or vice versa).
            for &f in &known_files {
                if f.ends_with(ch) || ch.ends_with(f) {
                    seeds.insert(f);
                }
            }
        }
    }

    // BFS from seeds through reverse edges.
    let mut visited: HashSet<&str> = seeds.clone();
    let mut queue: std::collections::VecDeque<&str> = seeds.iter().copied().collect();
    while let Some(node) = queue.pop_front() {
        if let Some(dependents) = reverse_adj.get(node) {
            for &dep in dependents {
                if visited.insert(dep) {
                    queue.push_back(dep);
                }
            }
        }
    }

    // Return affected files (excluding the seeds themselves).
    let mut affected: Vec<String> = visited
        .into_iter()
        .filter(|f| !seeds.contains(f))
        .map(|f| f.to_string())
        .collect();
    affected.sort();
    affected
}

// ---------------------------------------------------------------------------
// Architectural rules (.pkgrank.toml)
// ---------------------------------------------------------------------------

/// Project-level architectural rules loaded from `.pkgrank.toml`.
#[derive(Debug, Clone, Deserialize)]
pub(crate) struct ArchRules {
    /// Named layers mapping glob patterns to a layer name.
    #[serde(default)]
    pub layers: HashMap<String, Vec<String>>,
    /// Denied dependencies between layers.
    #[serde(default)]
    pub deny: Vec<DenyRule>,
    /// Allowed dependencies: layer may only import from listed layers.
    /// Stricter than deny -- any unlisted import is a violation.
    #[serde(default)]
    pub allow: Vec<AllowRule>,
}

#[derive(Debug, Clone, Deserialize)]
pub(crate) struct DenyRule {
    pub from: String,
    pub to: String,
}

#[derive(Debug, Clone, Deserialize)]
pub(crate) struct AllowRule {
    /// The layer being constrained.
    pub from: String,
    /// Layers this layer is allowed to import from.
    pub to: Vec<String>,
}

#[derive(Debug, Clone, Serialize)]
pub(crate) struct RuleViolation {
    pub rule_from: String,
    pub rule_to: String,
    pub file_from: String,
    pub file_to: String,
}

/// Load `.pkgrank.toml` from a directory. Returns None if not found.
pub(crate) fn load_arch_rules(dir: &Path) -> Option<ArchRules> {
    let path = dir.join(".pkgrank.toml");
    let raw = std::fs::read_to_string(&path).ok()?;
    toml::from_str(&raw).ok()
}

/// Check edges against user-defined architectural rules.
pub(crate) fn check_arch_rules(
    rules: &ArchRules,
    edges: &[(String, String)],
) -> Vec<RuleViolation> {
    // Build layer membership: file -> layer name.
    let mut file_layer: HashMap<&str, &str> = HashMap::new();

    // Pre-compile glob patterns per layer.
    let layer_patterns: Vec<(&str, Vec<glob::Pattern>)> = rules
        .layers
        .iter()
        .map(|(name, patterns)| {
            let compiled: Vec<glob::Pattern> = patterns
                .iter()
                .filter_map(|p| glob::Pattern::new(p).ok())
                .collect();
            (name.as_str(), compiled)
        })
        .collect();

    // Collect all file paths from edges.
    let mut all_files: HashSet<&str> = HashSet::new();
    for (from, to) in edges {
        all_files.insert(from.as_str());
        all_files.insert(to.as_str());
    }

    // Assign files to layers.
    for &file in &all_files {
        for (layer_name, patterns) in &layer_patterns {
            if patterns.iter().any(|p| p.matches(file)) {
                file_layer.insert(file, layer_name);
                break; // First matching layer wins.
            }
        }
    }

    // Build allow-set lookup: layer -> set of allowed target layers.
    let allow_sets: HashMap<&str, HashSet<&str>> = rules
        .allow
        .iter()
        .map(|r| {
            (
                r.from.as_str(),
                r.to.iter().map(|s| s.as_str()).collect::<HashSet<_>>(),
            )
        })
        .collect();

    // Check each edge against deny and allow rules.
    let mut violations = Vec::new();
    for (from, to) in edges {
        let from_layer = match file_layer.get(from.as_str()) {
            Some(l) => *l,
            None => continue,
        };
        let to_layer = match file_layer.get(to.as_str()) {
            Some(l) => *l,
            None => continue,
        };
        // Same-layer imports are always allowed.
        if from_layer == to_layer {
            continue;
        }
        // Check deny rules (explicit blocklist).
        for rule in &rules.deny {
            if rule.from == from_layer && rule.to == to_layer {
                violations.push(RuleViolation {
                    rule_from: rule.from.clone(),
                    rule_to: rule.to.clone(),
                    file_from: from.clone(),
                    file_to: to.clone(),
                });
            }
        }
        // Check allow rules (explicit allowlist -- anything not listed is denied).
        if let Some(allowed) = allow_sets.get(from_layer) {
            if !allowed.contains(to_layer) {
                violations.push(RuleViolation {
                    rule_from: from_layer.to_string(),
                    rule_to: format!("!{}", to_layer),
                    file_from: from.clone(),
                    file_to: to.clone(),
                });
            }
        }
    }
    violations
}

// ---------------------------------------------------------------------------
// Core analysis
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// Git history analysis
// ---------------------------------------------------------------------------

/// Parse git log to get per-file commit counts within a time window.
struct GitStats {
    counts: HashMap<String, usize>,
    co_changers: HashMap<String, Vec<(String, usize)>>,
    /// Unique contributors per file (bus factor proxy).
    contributors: HashMap<String, usize>,
}

fn git_file_stats(root: &Path, days: u64) -> GitStats {
    let since = format!("--since={} days ago", days);
    // Use %x00 as separator, include author email for contributor counting.
    let out = ProcessCommand::new("git")
        .args(["log", "--name-only", "--pretty=format:%x00%ae", &since])
        .current_dir(root)
        .output();
    let out = match out {
        Ok(o) if o.status.success() => o,
        _ => {
            return GitStats {
                counts: HashMap::new(),
                co_changers: HashMap::new(),
                contributors: HashMap::new(),
            }
        }
    };
    let stdout = String::from_utf8_lossy(&out.stdout);

    let mut counts: HashMap<String, usize> = HashMap::new();
    let mut pair_counts: HashMap<(String, String), usize> = HashMap::new();
    let mut file_authors: HashMap<String, HashSet<String>> = HashMap::new();

    // Split by commit separator. Format: \0author@email\nfile1\nfile2...
    for commit_block in stdout.split('\0') {
        let mut lines = commit_block
            .lines()
            .map(|l| l.trim())
            .filter(|l| !l.is_empty());
        let author = lines.next().unwrap_or("").to_string();
        let files: Vec<&str> = lines.collect();

        for &f in &files {
            *counts.entry(f.to_string()).or_insert(0) += 1;
            if !author.is_empty() {
                file_authors
                    .entry(f.to_string())
                    .or_default()
                    .insert(author.clone());
            }
        }

        // Co-change pairs (only for commits with 2-20 files to avoid noise).
        if files.len() >= 2 && files.len() <= 20 {
            for i in 0..files.len() {
                for j in (i + 1)..files.len() {
                    let (a, b) = if files[i] < files[j] {
                        (files[i].to_string(), files[j].to_string())
                    } else {
                        (files[j].to_string(), files[i].to_string())
                    };
                    *pair_counts.entry((a, b)).or_insert(0) += 1;
                }
            }
        }
    }

    // Build top co-changers per file (top 5).
    let mut co_changers: HashMap<String, Vec<(String, usize)>> = HashMap::new();
    for ((a, b), count) in &pair_counts {
        if *count >= 2 {
            co_changers
                .entry(a.clone())
                .or_default()
                .push((b.clone(), *count));
            co_changers
                .entry(b.clone())
                .or_default()
                .push((a.clone(), *count));
        }
    }
    for partners in co_changers.values_mut() {
        partners.sort_by(|a, b| b.1.cmp(&a.1));
        partners.truncate(5);
    }

    let contributors: HashMap<String, usize> = file_authors
        .into_iter()
        .map(|(f, authors)| (f, authors.len()))
        .collect();

    GitStats {
        counts,
        co_changers,
        contributors,
    }
}

/// Clone a git URL to a temp directory. Returns the path.
/// Contract a file-level graph into a directory-level graph.
/// Returns: (contracted graph, node labels, file count per directory).
fn contract_to_directories(
    graph: &DiGraph<PathBuf, f64>,
    root: &Path,
) -> (DiGraph<String, f64>, Vec<String>, HashMap<String, usize>) {
    let mut dir_indices: HashMap<String, NodeIndex> = HashMap::new();
    let mut contracted: DiGraph<String, f64> = DiGraph::new();
    let mut file_to_dir_idx: Vec<NodeIndex> = Vec::new();
    let mut file_counts: HashMap<String, usize> = HashMap::new();

    for n in graph.node_indices() {
        let file = graph.nw(n);
        let rel = file.strip_prefix(root).unwrap_or(file);
        let dir = rel
            .parent()
            .map(|p| p.to_string_lossy().to_string())
            .unwrap_or_else(|| ".".to_string());
        let dir = if dir.is_empty() { ".".to_string() } else { dir };

        *file_counts.entry(dir.clone()).or_insert(0) += 1;

        let dir_idx = *dir_indices
            .entry(dir.clone())
            .or_insert_with(|| contracted.add_node(dir));
        file_to_dir_idx.push(dir_idx);
    }

    // Add edges between directories (merge weights).
    for e in graph.edge_references() {
        let from_dir = file_to_dir_idx[e.source().index()];
        let to_dir = file_to_dir_idx[e.target().index()];
        if from_dir == to_dir {
            continue;
        }
        let cur = contracted
            .find_edge(from_dir, to_dir)
            .and_then(|ei| contracted.edge_weight(ei).copied())
            .unwrap_or(0.0);
        contracted.update_edge(from_dir, to_dir, cur + e.weight());
    }

    let labels: Vec<String> = contracted
        .node_indices()
        .map(|n| contracted.nw(n).clone())
        .collect();

    (contracted, labels, file_counts)
}

/// Detect cross-language seams: Python files importing Rust PyO3 modules.
/// Creates edges from Python files to the Rust lib.rs that defines the #[pymodule].
/// Detect cross-language FFI seams.
/// PyO3: Python files importing Rust #[pymodule] modules.
/// NAPI: JS/TS files importing Rust #[napi] modules.
fn detect_ffi_seams(root: &Path, files: &[PathBuf], ecosystems: &[Ecosystem]) -> Vec<FileEdge> {
    let mut edges = Vec::new();

    // Find Rust files with FFI export markers.
    let mut rust_modules: Vec<(String, PathBuf, &str)> = Vec::new(); // (name, file, kind)
    for file in files {
        if file.extension().and_then(|e| e.to_str()) != Some("rs") {
            continue;
        }
        if let Ok(content) = std::fs::read_to_string(file) {
            let crate_dir = file
                .ancestors()
                .find(|p| p.join("Cargo.toml").exists())
                .unwrap_or(root);
            let crate_name = read_rust_crate_name(crate_dir);

            if content.contains("#[pymodule]") || content.contains("#[pymodule(") {
                rust_modules.push((crate_name.clone(), file.clone(), "pyo3"));
            }
            if content.contains("#[napi]") || content.contains("#[napi(") {
                rust_modules.push((crate_name, file.clone(), "napi"));
            }
        }
    }

    if rust_modules.is_empty() {
        return edges;
    }

    let pyo3_names: HashSet<&str> = rust_modules
        .iter()
        .filter(|(_, _, k)| *k == "pyo3")
        .map(|(n, _, _)| n.as_str())
        .collect();
    let napi_names: HashSet<&str> = rust_modules
        .iter()
        .filter(|(_, _, k)| *k == "napi")
        .map(|(n, _, _)| n.as_str())
        .collect();

    for file in files {
        let ext = file.extension().and_then(|e| e.to_str()).unwrap_or("");

        // PyO3: Python -> Rust
        if ext == "py" && ecosystems.contains(&Ecosystem::Python) {
            if let Ok(content) = std::fs::read_to_string(file) {
                for line in content.lines() {
                    let line = line.trim();
                    if !line.starts_with("import ") && !line.starts_with("from ") {
                        continue;
                    }
                    for mod_name in &pyo3_names {
                        if line.contains(mod_name) {
                            for (name, rust_file, kind) in &rust_modules {
                                if *kind == "pyo3" && name == mod_name {
                                    edges.push(FileEdge {
                                        from: file.clone(),
                                        to: rust_file.clone(),
                                    });
                                }
                            }
                        }
                    }
                }
            }
        }

        // NAPI: JS/TS -> Rust
        if matches!(ext, "ts" | "tsx" | "js" | "jsx" | "mjs" | "svelte" | "vue")
            && ecosystems.contains(&Ecosystem::Js)
        {
            if let Ok(content) = std::fs::read_to_string(file) {
                for line in content.lines() {
                    let line = line.trim();
                    for mod_name in &napi_names {
                        if line.contains(mod_name)
                            && (line.starts_with("import ") || line.contains("require("))
                        {
                            for (name, rust_file, kind) in &rust_modules {
                                if *kind == "napi" && name == mod_name {
                                    edges.push(FileEdge {
                                        from: file.clone(),
                                        to: rust_file.clone(),
                                    });
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    edges
}

fn clone_repo_to_temp(url: &str) -> Result<PathBuf> {
    let tmp = std::env::temp_dir().join(format!("pkgrank-{:016x}", fnv1a64(url.as_bytes())));
    if tmp.exists() {
        // Reuse existing clone.
        return Ok(tmp);
    }
    eprintln!("cloning {} → {}", url, tmp.display());
    let out = ProcessCommand::new("git")
        .args(["clone", "--depth", "1", url])
        .arg(&tmp)
        .env_remove("GITHUB_TOKEN") // Avoid PAT auth failures on public repos
        .output()
        .map_err(|e| anyhow::anyhow!("git clone failed: {}", e))?;
    if !out.status.success() {
        let stderr = String::from_utf8_lossy(&out.stderr);
        return Err(anyhow::anyhow!("git clone failed: {}", stderr.trim()));
    }
    Ok(tmp)
}

fn is_url(s: &str) -> bool {
    s.starts_with("https://") || s.starts_with("http://") || s.starts_with("git@")
}

/// Expand shorthand like "owner/repo" to "https://github.com/owner/repo".
fn expand_uri(s: &str) -> String {
    if is_url(s) || PathBuf::from(s).exists() {
        return s.to_string();
    }
    // owner/repo pattern (exactly one slash, no spaces, doesn't look like a file path).
    let parts: Vec<&str> = s.split('/').collect();
    if parts.len() == 2 && parts.iter().all(|p| !p.is_empty() && !p.contains(' ')) {
        return format!("https://github.com/{}/{}", parts[0], parts[1]);
    }
    s.to_string()
}

/// Compute a cache key from file paths + mtimes + analysis args.
fn files_cache_key(files: &[PathBuf], args: &FilesArgs) -> u64 {
    let mut material = format!(
        "v={}\necosystem={:?}\ndir={}\ngit={}\ngit_days={}\ntests={}\nall={}\n",
        env!("CARGO_PKG_VERSION"),
        args.ecosystem,
        args.directory,
        args.git,
        args.git_days,
        args.include_tests,
        args.include_all,
    );
    for f in files {
        let mtime = f
            .metadata()
            .and_then(|m| m.modified())
            .ok()
            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
            .map(|d| d.as_secs())
            .unwrap_or(0);
        material.push_str(&format!("{}:{}\n", f.display(), mtime));
    }
    fnv1a64(material.as_bytes())
}

fn files_cache_read(cache_dir: &Path, key: u64) -> Option<FilesResult> {
    let path = cache_dir.join(format!("files_{:016x}.bin", key));
    let raw = std::fs::read(&path).ok()?;
    bincode::deserialize(&raw).ok()
}

fn files_cache_write(cache_dir: &Path, key: u64, result: &FilesResult) {
    let _ = std::fs::create_dir_all(cache_dir);
    let path = cache_dir.join(format!("files_{:016x}.bin", key));
    if let Ok(bytes) = bincode::serialize(result) {
        let _ = std::fs::write(&path, bytes);
    }
}

pub(crate) fn files_analyze(args: &FilesArgs) -> Result<FilesResult> {
    let uri = expand_uri(&args.path);
    let root = if is_url(&uri) {
        clone_repo_to_temp(&uri)?
    } else {
        let p = PathBuf::from(&uri);
        if p.is_file() {
            p.parent().unwrap_or(Path::new(".")).to_path_buf()
        } else {
            p
        }
    };

    // Determine ecosystem(s) to analyze.
    let ecosystems: Vec<Ecosystem> = if let Some(eco) = args.ecosystem {
        vec![eco]
    } else {
        let detected = detect_all_ecosystems(&root);
        if detected.is_empty() {
            return Err(anyhow::anyhow!(
                "Could not detect ecosystem in {}. Pass --ecosystem explicitly.",
                root.display()
            ));
        }
        detected
    };
    let ecosystem = ecosystems[0]; // Primary ecosystem for display.

    // Discover files across all detected ecosystems.
    let mut all_files = Vec::new();
    for eco in &ecosystems {
        all_files.extend(discover_files(&root, *eco));
    }
    all_files.sort();
    all_files.dedup();

    // Cache check: use file paths + mtimes as cache key.
    let cache_dir = root.join("evals/pkgrank/files_cache");
    if args.cache {
        let key = files_cache_key(&all_files, args);
        if let Some(cached) = files_cache_read(&cache_dir, key) {
            return Ok(cached);
        }
    }

    let mut included_files: Vec<PathBuf> = Vec::new();
    let mut file_roles: HashMap<PathBuf, FileRole> = HashMap::new();

    for file in &all_files {
        let role = classify_file(file, &root, ecosystem);
        if should_include(role, args) {
            included_files.push(file.clone());
            file_roles.insert(file.clone(), role);
        }
    }

    // Parse imports for each ecosystem and merge edges.
    let mut edges = Vec::new();
    for eco in &ecosystems {
        let eco_files: Vec<PathBuf> = included_files
            .iter()
            .filter(|f| {
                let ext = f.extension().and_then(|e| e.to_str()).unwrap_or("");
                match eco {
                    Ecosystem::Rust => ext == "rs",
                    Ecosystem::Python => ext == "py",
                    Ecosystem::Js => {
                        matches!(ext, "ts" | "tsx" | "js" | "jsx" | "mjs" | "svelte" | "vue")
                    }
                    Ecosystem::Go => ext == "go",
                }
            })
            .cloned()
            .collect();
        let eco_edges = match eco {
            Ecosystem::Rust => parse_rust_imports(&root, &eco_files),
            Ecosystem::Python => parse_python_imports(&root, &eco_files),
            Ecosystem::Js => parse_js_imports(&root, &eco_files),
            Ecosystem::Go => parse_go_imports(&root, &eco_files),
        };
        edges.extend(eco_edges);
    }

    // Cross-language seam edges (PyO3: Python -> Rust, NAPI: JS -> Rust).
    if ecosystems.contains(&Ecosystem::Rust) && ecosystems.len() > 1 {
        edges.extend(detect_ffi_seams(&root, &included_files, &ecosystems));
    }

    // Extract external dependency names per file.
    let mut internal_prefixes: HashSet<String> = HashSet::new();
    for eco in &ecosystems {
        match eco {
            Ecosystem::Rust => {
                let crate_roots = find_rust_crate_roots(&root);
                for (_, name) in &crate_roots {
                    internal_prefixes.insert(name.clone());
                }
                // Also add all known module names (from mod declarations) as internal.
                for file in &included_files {
                    if let Ok(content) = std::fs::read_to_string(file) {
                        for line in content.lines() {
                            if let Some(mod_name) = parse_mod_declaration(line.trim()) {
                                internal_prefixes.insert(mod_name);
                            }
                        }
                    }
                }
            }
            Ecosystem::Python => {
                let (pkg_name, _) = detect_python_package(&root);
                internal_prefixes.insert(pkg_name);
            }
            Ecosystem::Go => {
                let mod_name = read_go_module_name(&root);
                if !mod_name.is_empty() {
                    internal_prefixes.insert(mod_name);
                }
            }
            Ecosystem::Js => {} // JS doesn't have a simple internal prefix
        }
    }
    let external_deps_map = extract_external_deps(&included_files, ecosystem, &internal_prefixes);

    let mut graph: DiGraph<PathBuf, f64> = DiGraph::new();
    let mut node_map: HashMap<PathBuf, NodeIndex> = HashMap::new();

    for file in &included_files {
        let idx = graph.add_node(file.clone());
        node_map.insert(file.clone(), idx);
    }

    let mut seen_edges: HashSet<(usize, usize)> = HashSet::new();
    for edge in &edges {
        if let (Some(&from_idx), Some(&to_idx)) = (node_map.get(&edge.from), node_map.get(&edge.to))
        {
            let key = (from_idx.index(), to_idx.index());
            if seen_edges.insert(key) {
                graph.update_edge(from_idx, to_idx, 1.0);
            }
        }
    }

    // Compute labels and centrality.
    // Directory mode: contract to directory-level graph first.
    // File mode: compute directly on the PathBuf graph (avoids copying).
    // Precomputed analysis vectors.
    struct AnalysisVecs {
        labels: Vec<String>,
        pr: Vec<f64>,
        consumers_pr: Vec<f64>,
        bc: Vec<f64>,
        in_degrees: Vec<usize>,
        out_degrees: Vec<usize>,
        transitive_dependents: Vec<usize>,
        transitive_deps: Vec<usize>,
        scc_labels: Vec<usize>,
        direct_edges: Vec<(String, String)>,
        node_count: usize,
        edge_count: usize,
    }

    fn compute_analysis<N: Clone + std::fmt::Debug>(
        g: &DiGraph<N, f64>,
        labels: Vec<String>,
    ) -> AnalysisVecs {
        let pr = pagerank_auto(g);
        let consumers_pr = pagerank_auto(&reverse_graph(g));
        let bc = betweenness_centrality(g);
        let in_degrees: Vec<usize> = g
            .node_indices()
            .map(|n| g.neighbors_directed(n, Direction::Incoming).count())
            .collect();
        let out_degrees: Vec<usize> = g
            .node_indices()
            .map(|n| g.neighbors_directed(n, Direction::Outgoing).count())
            .collect();
        let mut ep: Vec<(usize, usize)> = Vec::new();
        for e in g.edge_references() {
            ep.push((e.source().index(), e.target().index()));
        }
        let (td, tdd) = reachability_counts_edges(g.node_count(), &ep);
        let scc = strongly_connected_components(g);
        let direct_edges: Vec<(String, String)> = g
            .edge_references()
            .map(|e| {
                (
                    labels[e.source().index()].clone(),
                    labels[e.target().index()].clone(),
                )
            })
            .collect();
        AnalysisVecs {
            labels,
            pr,
            consumers_pr,
            bc,
            in_degrees,
            out_degrees,
            transitive_dependents: td,
            transitive_deps: tdd,
            scc_labels: scc,
            direct_edges,
            node_count: g.node_count(),
            edge_count: g.edge_count(),
        }
    }

    let av = if args.directory {
        let (contracted, labels, _counts) = contract_to_directories(&graph, &root);
        compute_analysis(&contracted, labels)
    } else {
        let labels: Vec<String> = graph
            .node_indices()
            .map(|n| {
                graph
                    .nw(n)
                    .strip_prefix(&root)
                    .unwrap_or(graph.nw(n))
                    .to_string_lossy()
                    .to_string()
            })
            .collect();
        compute_analysis(&graph, labels)
    };
    let mut scc_sizes: HashMap<usize, usize> = HashMap::new();
    for &label in &av.scc_labels {
        *scc_sizes.entry(label).or_insert(0) += 1;
    }
    let mut cycles: Vec<Vec<String>> = Vec::new();
    let mut cycle_id_map: HashMap<usize, usize> = HashMap::new();
    {
        let mut cycle_labels: Vec<usize> = scc_sizes
            .iter()
            .filter(|(_, &size)| size > 1)
            .map(|(&label, _)| label)
            .collect();
        cycle_labels.sort();

        for (cycle_idx, &scc_label) in cycle_labels.iter().enumerate() {
            cycle_id_map.insert(scc_label, cycle_idx);
            let members: Vec<String> = (0..av.node_count)
                .filter(|&i| av.scc_labels[i] == scc_label)
                .map(|i| av.labels[i].clone())
                .collect();
            cycles.push(members);
        }
    }

    // Git history (optional).
    let git_stats = if args.git {
        git_file_stats(&root, args.git_days)
    } else {
        GitStats {
            counts: HashMap::new(),
            co_changers: HashMap::new(),
            contributors: HashMap::new(),
        }
    };
    let max_commits = git_stats.counts.values().copied().max().unwrap_or(1).max(1) as f64;

    let mut rows: Vec<FileRow> = (0..av.node_count)
        .map(|i| {
            let rel = av.labels[i].clone();
            let role = if args.directory {
                FileRole::Source
            } else {
                let full = root.join(&rel);
                file_roles.get(&full).copied().unwrap_or(FileRole::Source)
            };
            let in_degree = av.in_degrees[i];
            let out_degree = av.out_degrees[i];
            let cycle_id = cycle_id_map.get(&av.scc_labels[i]).copied();

            let commits = if args.git {
                if args.directory {
                    Some(
                        git_stats
                            .counts
                            .iter()
                            .filter(|(path, _)| {
                                Path::new(path)
                                    .parent()
                                    .map(|p| {
                                        p.to_string_lossy() == rel
                                            || (rel == "." && p == Path::new(""))
                                    })
                                    .unwrap_or(false)
                            })
                            .map(|(_, &c)| c)
                            .sum::<usize>(),
                    )
                } else {
                    Some(git_stats.counts.get(&rel).copied().unwrap_or(0))
                }
            } else {
                None
            };
            let churn_risk = commits.map(|c| av.pr[i] * (c as f64 / max_commits));
            let co_changers = if args.git {
                git_stats.co_changers.get(&rel).cloned().unwrap_or_default()
            } else {
                Vec::new()
            };
            let contributors = if args.git {
                Some(git_stats.contributors.get(&rel).copied().unwrap_or(0))
            } else {
                None
            };
            let ext_deps = if args.directory {
                Vec::new()
            } else {
                let full = root.join(&rel);
                external_deps_map.get(&full).cloned().unwrap_or_default()
            };

            FileRow {
                file: rel,
                role,
                in_degree,
                out_degree,
                dependents: av.transitive_dependents[i],
                dependencies: av.transitive_deps[i],
                pagerank: av.pr[i],
                consumers_pagerank: av.consumers_pr[i],
                betweenness: av.bc[i],
                orphan: in_degree == 0 && out_degree == 0,
                cycle_id,
                commits,
                churn_risk,
                co_changers,
                instability: if in_degree + out_degree > 0 {
                    out_degree as f64 / (in_degree + out_degree) as f64
                } else {
                    0.0
                },
                contributors,
                structure: String::new(), // filled below
                external_deps: ext_deps,
            }
        })
        .collect();

    // Compute structural roles based on median degree.
    let median_in = {
        let mut ins: Vec<usize> = rows.iter().map(|r| r.in_degree).collect();
        ins.sort();
        if ins.is_empty() {
            0
        } else {
            ins[ins.len() / 2]
        }
    };
    let median_out = {
        let mut outs: Vec<usize> = rows.iter().map(|r| r.out_degree).collect();
        outs.sort();
        if outs.is_empty() {
            0
        } else {
            outs[outs.len() / 2]
        }
    };
    // Stability-volatility quadrant (when git data available).
    let median_churn = if args.git {
        let mut churns: Vec<f64> = rows
            .iter()
            .filter_map(|r| r.churn_risk)
            .filter(|c| *c > 0.0)
            .collect();
        churns.sort_by(|a, b| a.total_cmp(b));
        if churns.is_empty() {
            0.0
        } else {
            churns[churns.len() / 2]
        }
    } else {
        0.0
    };

    for row in &mut rows {
        let base = match (row.in_degree > median_in, row.out_degree > median_out) {
            (true, false) => "foundation",
            (true, true) => "hub",
            (false, true) => "consumer",
            (false, false) => {
                if row.orphan {
                    "orphan"
                } else {
                    "leaf"
                }
            }
        };

        // When git data is available, overlay stability-volatility quadrant.
        if args.git && row.churn_risk.unwrap_or(0.0) > 0.0 {
            let is_volatile = row.churn_risk.unwrap_or(0.0) > median_churn;
            let is_central = row.in_degree > median_in;
            row.structure = match (is_central, is_volatile) {
                (true, true) => format!("{}!!", base), // danger zone
                (true, false) => base.to_string(),     // load-bearing (stable)
                (false, true) => format!("{}~", base), // volatile but low-risk
                (false, false) => base.to_string(),    // stable leaf
            };
        } else {
            row.structure = base.to_string();
        }
    }

    if args.git && matches!(args.metric, Metric::Pagerank) {
        rows.sort_by(|a, b| {
            b.churn_risk
                .unwrap_or(0.0)
                .total_cmp(&a.churn_risk.unwrap_or(0.0))
        });
    } else {
        rows.sort_by(|a, b| match args.metric {
            Metric::Pagerank => b.pagerank.total_cmp(&a.pagerank),
            Metric::ConsumersPagerank => b.consumers_pagerank.total_cmp(&a.consumers_pagerank),
            Metric::Betweenness => b.betweenness.total_cmp(&a.betweenness),
            Metric::Indegree => b.in_degree.cmp(&a.in_degree),
            Metric::Outdegree => b.out_degree.cmp(&a.out_degree),
        });
    }

    let orphan_count = rows.iter().filter(|r| r.orphan).count();

    let result = FilesResult {
        nodes: av.node_count,
        edges: av.edge_count,
        ecosystem,
        orphan_count,
        cycles,
        rows,
        direct_edges: av.direct_edges,
    };

    // Cache write.
    if args.cache {
        let key = files_cache_key(&all_files, args);
        files_cache_write(&cache_dir, key, &result);
    }

    Ok(result)
}

// ---------------------------------------------------------------------------
// Run + print
// ---------------------------------------------------------------------------

pub(crate) fn run_files(args: &FilesArgs) -> Result<()> {
    let result = files_analyze(args)?;

    let fmt = effective_format(args.format);
    match fmt {
        OutputFormat::Json => {
            let layer_violations = compute_layer_violations(&result);
            let project_dir = if is_url(&args.path) {
                PathBuf::from(".")
            } else {
                let p = PathBuf::from(&args.path);
                if p.is_file() {
                    p.parent().unwrap_or(Path::new(".")).to_path_buf()
                } else {
                    p
                }
            };
            let arch_rules = load_arch_rules(&project_dir);
            let rule_violations = arch_rules
                .as_ref()
                .map(|r| check_arch_rules(r, &result.direct_edges))
                .unwrap_or_default();

            #[derive(Serialize)]
            struct Out {
                schema_version: u32,
                ok: bool,
                command: &'static str,
                ecosystem: Ecosystem,
                nodes: usize,
                edges: usize,
                orphan_count: usize,
                cycle_count: usize,
                cycles: Vec<Vec<String>>,
                layer_violation_count: usize,
                layer_violations: Vec<LayerViolation>,
                rule_violation_count: usize,
                rule_violations: Vec<RuleViolation>,
                rows_total: usize,
                rows_returned: usize,
                rows: Vec<FileRow>,
            }
            let rows_total = result.rows.len();
            let rows: Vec<FileRow> = result.rows.iter().take(args.top).cloned().collect();
            let out = Out {
                schema_version: 1,
                ok: true,
                command: "files",
                ecosystem: result.ecosystem,
                nodes: result.nodes,
                edges: result.edges,
                orphan_count: result.orphan_count,
                cycle_count: result.cycles.len(),
                cycles: result.cycles.clone(),
                layer_violation_count: layer_violations.len(),
                layer_violations,
                rule_violation_count: rule_violations.len(),
                rule_violations,
                rows_total,
                rows_returned: rows.len(),
                rows,
            };
            println!("{}", serde_json::to_string_pretty(&out)?);
        }
        OutputFormat::Text => {
            let git_label = if args.git {
                format!("  git_days={}", args.git_days)
            } else {
                String::new()
            };
            println!(
                "pkgrank files  ecosystem={}  metric={:?}  include_tests={}{}\n",
                result.ecosystem, args.metric, args.include_tests, git_label
            );
            if args.git {
                println!(
                    "{:>4}  {:>8}  {:>5}  {:>10}  {:>5}  {:>3}  {:>3}  {:<10}  file",
                    "rank", "churn", "comms", "pr", "blast", "in", "out", "role"
                );
            } else {
                println!(
                    "{:>4}  {:>10}  {:>10}  {:>9}  {:>5}  {:>5}  {:>3}  {:>3}  {:<10}  file",
                    "rank", "pr", "cons_pr", "between", "blast", "deps", "in", "out", "role"
                );
            }
            println!("{:\u{2500}<110}", "");
            for (i, r) in result.rows.iter().take(args.top).enumerate() {
                let mut label = r.structure.clone();
                if r.cycle_id.is_some() {
                    label.push('*');
                }
                if args.git {
                    println!(
                        "{:>4}. {:>8.6} {:>5} {:>10.6} {:>5} {:>3} {:>3}  {:<10}  {}",
                        i + 1,
                        r.churn_risk.unwrap_or(0.0),
                        r.commits.unwrap_or(0),
                        r.pagerank,
                        r.dependents,
                        r.in_degree,
                        r.out_degree,
                        label,
                        r.file
                    );
                } else {
                    println!(
                        "{:>4}. {:>10.6} {:>10.6} {:>9.6} {:>5} {:>5} {:>3} {:>3}  {:<10}  {}",
                        i + 1,
                        r.pagerank,
                        r.consumers_pagerank,
                        r.betweenness,
                        r.dependents,
                        r.dependencies,
                        r.in_degree,
                        r.out_degree,
                        label,
                        r.file
                    );
                }
            }

            // Summary.
            let density = if result.nodes > 1 {
                result.edges as f64 / (result.nodes as f64 * (result.nodes as f64 - 1.0))
            } else {
                0.0
            };
            println!(
                "\n{} files, {} edges, density={:.4}, {} orphans, {} cycles",
                result.nodes,
                result.edges,
                density,
                result.orphan_count,
                result.cycles.len()
            );

            // Architectural insights.
            if result.nodes > 3 {
                // Hub files (top 3 by in-degree).
                let mut by_in: Vec<&FileRow> = result.rows.iter().collect();
                by_in.sort_by(|a, b| b.in_degree.cmp(&a.in_degree));
                println!("\nhubs (most depended-on):");
                for r in by_in.iter().take(3) {
                    println!(
                        "  {} ({} dependents, blast={}, {})",
                        r.file, r.in_degree, r.dependents, r.structure
                    );
                }

                // Structure distribution.
                let mut struct_counts: HashMap<&str, usize> = HashMap::new();
                for r in &result.rows {
                    // Take base structure (strip !! and ~ suffixes).
                    let base = r.structure.trim_end_matches('!').trim_end_matches('~');
                    *struct_counts.entry(base).or_insert(0) += 1;
                }
                let danger_count = result
                    .rows
                    .iter()
                    .filter(|r| r.structure.contains("!!"))
                    .count();
                if !struct_counts.is_empty() {
                    let parts: Vec<String> = struct_counts
                        .iter()
                        .map(|(k, v)| format!("{}: {}", k, v))
                        .collect();
                    println!("\nstructure: {}", parts.join(", "));
                    if danger_count > 0 {
                        println!(
                            "  {} files in danger zone (central + volatile)",
                            danger_count
                        );
                    }
                }

                // Layer violations: stable files importing from unstable files.
                let violations = compute_layer_violations(&result);
                if !violations.is_empty() {
                    println!(
                        "\nlayer violations ({}, stable -> unstable):",
                        violations.len()
                    );
                    for v in violations.iter().take(5) {
                        println!(
                            "  {} (I={:.2}) -> {} (I={:.2})",
                            v.from, v.from_instability, v.to, v.to_instability
                        );
                    }
                }

                // Leaves (highest out-degree, lowest in-degree) -- entry points/consumers.
                let mut consumers: Vec<&FileRow> = result
                    .rows
                    .iter()
                    .filter(|r| r.in_degree == 0 && r.out_degree > 0)
                    .collect();
                consumers.sort_by(|a, b| b.out_degree.cmp(&a.out_degree));
                if !consumers.is_empty() {
                    println!("\nentry points (no dependents, import others):");
                    for r in consumers.iter().take(3) {
                        println!("  {} (imports {})", r.file, r.out_degree);
                    }
                }
            }

            // External dependency summary.
            if !args.directory {
                let mut dep_usage: HashMap<&str, usize> = HashMap::new();
                for r in &result.rows {
                    for dep in &r.external_deps {
                        *dep_usage.entry(dep.as_str()).or_insert(0) += 1;
                    }
                }
                if !dep_usage.is_empty() {
                    let mut sorted_deps: Vec<(&&str, &usize)> = dep_usage.iter().collect();
                    sorted_deps.sort_by(|a, b| b.1.cmp(a.1));
                    println!(
                        "\nexternal deps ({} unique, top by file count):",
                        dep_usage.len()
                    );
                    for (dep, count) in sorted_deps.iter().take(5) {
                        println!("  {} ({} files)", dep, count);
                    }
                }
            }

            if !result.cycles.is_empty() {
                println!("\ncycles (* in table):");
                for (i, cycle) in result.cycles.iter().take(5).enumerate() {
                    let preview: Vec<&str> = cycle.iter().take(5).map(|s| s.as_str()).collect();
                    let suffix = if cycle.len() > 5 {
                        format!(", ... (+{})", cycle.len() - 5)
                    } else {
                        String::new()
                    };
                    println!(
                        "  cycle {}: {} files  [{}{}]",
                        i,
                        cycle.len(),
                        preview.join(", "),
                        suffix
                    );
                }
                if result.cycles.len() > 5 {
                    println!("  ... (+{} more cycles)", result.cycles.len() - 5);
                }
            }
        }
    }

    // Persist to SQLite if --store.
    if args.store {
        let db_path = crate::store::default_db_path();
        match crate::store::open_db(&db_path) {
            Ok(conn) => {
                let project_path = args.path.clone();
                match crate::store::store_snapshot(&conn, &project_path, &result) {
                    Ok(snap_id) => {
                        eprintln!("stored snapshot {} in {}", snap_id, db_path.display());
                    }
                    Err(e) => {
                        eprintln!("warning: failed to store snapshot: {}", e);
                    }
                }
            }
            Err(e) => {
                eprintln!("warning: failed to open db: {}", e);
            }
        }
    }

    // Focus mode: show detailed info about a specific file.
    if let Some(focus) = &args.focus {
        print_focus(focus, &result);
    }

    // Affected mode: show files transitively affected by changed files.
    if let Some(changed) = &args.affected {
        // If the only argument is "-", read file list from stdin (one per line).
        let changed = if changed.len() == 1 && changed[0] == "-" {
            use std::io::BufRead;
            std::io::stdin()
                .lock()
                .lines()
                .map_while(|l| l.ok())
                .map(|l| l.trim().to_string())
                .filter(|l| !l.is_empty())
                .collect()
        } else {
            changed.clone()
        };
        let affected = compute_affected(&result, &changed);
        if affected.is_empty() {
            eprintln!("no affected files found for: {}", changed.join(", "));
        } else {
            let fmt = effective_format(args.format);
            match fmt {
                OutputFormat::Json => {
                    #[derive(Serialize)]
                    struct AffectedOut {
                        changed: Vec<String>,
                        affected_count: usize,
                        affected: Vec<String>,
                    }
                    let out = AffectedOut {
                        changed: changed.clone(),
                        affected_count: affected.len(),
                        affected,
                    };
                    println!("{}", serde_json::to_string_pretty(&out)?);
                }
                OutputFormat::Text => {
                    println!(
                        "\naffected by [{}] ({} files):",
                        changed.join(", "),
                        affected.len()
                    );
                    for f in &affected {
                        println!("  {}", f);
                    }
                }
            }
        }
    }

    // Check user-defined architectural rules (.pkgrank.toml).
    let project_dir = if is_url(&args.path) {
        PathBuf::from(".")
    } else {
        let p = PathBuf::from(&args.path);
        if p.is_file() {
            p.parent().unwrap_or(Path::new(".")).to_path_buf()
        } else {
            p
        }
    };
    let arch_rules = load_arch_rules(&project_dir);
    let rule_violations = if let Some(ref rules) = arch_rules {
        let v = check_arch_rules(rules, &result.direct_edges);
        if !v.is_empty() {
            let fmt = effective_format(args.format);
            match fmt {
                OutputFormat::Json => {
                    // Will be included in fail-on-violation error below.
                }
                OutputFormat::Text => {
                    println!("\nrule violations ({}, from .pkgrank.toml):", v.len());
                    for rv in v.iter().take(10) {
                        println!(
                            "  {} -> {}  (rule: {} must not import {})",
                            rv.file_from, rv.file_to, rv.rule_from, rv.rule_to
                        );
                    }
                    if v.len() > 10 {
                        println!("  ... (+{} more)", v.len() - 10);
                    }
                }
            }
        }
        v
    } else {
        Vec::new()
    };

    // CI mode: fail if violations detected.
    if args.fail_on_violation {
        let layer_violations = compute_layer_violations(&result);
        let cycle_count = result.cycles.len();
        let rule_count = rule_violations.len();
        if !layer_violations.is_empty() || cycle_count > 0 || rule_count > 0 {
            let mut parts = Vec::new();
            if !layer_violations.is_empty() {
                parts.push(format!("{} layer violations", layer_violations.len()));
            }
            if cycle_count > 0 {
                parts.push(format!("{} cycles", cycle_count));
            }
            if rule_count > 0 {
                parts.push(format!("{} rule violations", rule_count));
            }
            return Err(anyhow::anyhow!(
                "architectural violations detected: {}",
                parts.join(", ")
            ));
        }
    }

    Ok(())
}

fn print_focus(query: &str, result: &FilesResult) {
    // Match the query against file paths (partial match).
    let matches: Vec<&FileRow> = result
        .rows
        .iter()
        .filter(|r| r.file.contains(query))
        .collect();

    if matches.is_empty() {
        eprintln!("no file matching '{}' found", query);
        return;
    }

    for row in &matches {
        println!("\n{:=<80}", "");
        println!("focus: {}", row.file);
        println!(
            "  role={:?}  pagerank={:.6}  betweenness={:.6}",
            row.role, row.pagerank, row.betweenness
        );
        println!(
            "  in_degree={}  out_degree={}  blast_radius={}  deps={}",
            row.in_degree, row.out_degree, row.dependents, row.dependencies
        );
        if let Some(c) = row.commits {
            println!(
                "  commits={}  churn_risk={:.6}",
                c,
                row.churn_risk.unwrap_or(0.0)
            );
        }
        if let Some(cid) = row.cycle_id {
            println!(
                "  cycle_id={} ({} files)",
                cid,
                result.cycles.get(cid).map(|c| c.len()).unwrap_or(0)
            );
        }

        // Co-changers (temporal coupling from git history).
        if !row.co_changers.is_empty() {
            println!("  co-changes with ({}):", row.co_changers.len());
            for (partner, count) in &row.co_changers {
                println!("    ~{} {}", count, partner);
            }
        }

        // Direct imports (this file depends on).
        let imports: Vec<&str> = result
            .direct_edges
            .iter()
            .filter(|(from, _)| from == &row.file)
            .map(|(_, to)| to.as_str())
            .collect();
        if !imports.is_empty() {
            println!("  imports ({}):", imports.len());
            for imp in &imports {
                println!("    -> {}", imp);
            }
        }

        // Direct dependents (files that import this one).
        let dependents: Vec<&str> = result
            .direct_edges
            .iter()
            .filter(|(_, to)| to == &row.file)
            .map(|(from, _)| from.as_str())
            .collect();
        if !dependents.is_empty() {
            println!("  imported by ({}):", dependents.len());
            for dep in dependents.iter().take(15) {
                println!("    <- {}", dep);
            }
            if dependents.len() > 15 {
                println!("    ... (+{} more)", dependents.len() - 15);
            }
        }
    }
}