agent-file-tools 0.42.0

Agent File Tools — tree-sitter powered code analysis for AI agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
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
//! Call graph engine: cross-file call resolution and forward traversal.
//!
//! Builds a lazy, worktree-scoped call graph that resolves calls across files
//! using import chains. Supports depth-limited forward traversal with cycle
//! detection.

use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::{LazyLock, RwLock};

use globset::{Glob, GlobSet, GlobSetBuilder};
use serde::Serialize;
use serde_json::Value;
use tree_sitter::{Node, Parser};

use crate::calls::{call_node_kinds, extract_callee_name, extract_calls_full, extract_full_callee};
use crate::edit::line_col_to_byte;
use crate::error::AftError;
use crate::imports::{self, ImportBlock};
use crate::parser::{detect_language, grammar_for, LangId};
use crate::symbols::{Range, Symbol, SymbolKind};

// ---------------------------------------------------------------------------
// Core types
// ---------------------------------------------------------------------------

type WorkspacePackageCache = HashMap<(PathBuf, String), Option<PathBuf>>;
type RustCrateInfoCache = HashMap<PathBuf, Option<RustCrateInfo>>;
type RustWorkspaceCrateCache = HashMap<PathBuf, HashMap<String, RustCrateInfo>>;

static WORKSPACE_PACKAGE_CACHE: LazyLock<RwLock<WorkspacePackageCache>> =
    LazyLock::new(|| RwLock::new(HashMap::new()));
static RUST_CRATE_INFO_CACHE: LazyLock<RwLock<RustCrateInfoCache>> =
    LazyLock::new(|| RwLock::new(HashMap::new()));
static RUST_WORKSPACE_CRATE_CACHE: LazyLock<RwLock<RustWorkspaceCrateCache>> =
    LazyLock::new(|| RwLock::new(HashMap::new()));

const TOP_LEVEL_SYMBOL: &str = "<top-level>";
const JS_TS_EXTENSIONS: &[&str] = &["ts", "tsx", "mts", "cts", "js", "jsx", "mjs", "cjs"];
const JS_TS_INDEX_FILES: &[&str] = &[
    "index.ts",
    "index.tsx",
    "index.mts",
    "index.cts",
    "index.js",
    "index.jsx",
    "index.mjs",
    "index.cjs",
];

fn symbol_identity(symbol: &Symbol) -> String {
    if symbol.scope_chain.is_empty() {
        symbol.name.clone()
    } else {
        format!("{}::{}", symbol.scope_chain.join("::"), symbol.name)
    }
}

fn symbol_unqualified_name(symbol: &str) -> &str {
    symbol.rsplit("::").next().unwrap_or(symbol)
}

pub(crate) fn is_bare_callee(full_callee: &str, short_name: &str) -> bool {
    full_callee == short_name || (!full_callee.contains('.') && !full_callee.contains("::"))
}

fn symbol_query_candidates(file_data: &FileCallData, symbol_name: &str) -> Vec<String> {
    let mut seen = HashSet::new();
    let mut candidates = Vec::new();
    let qualified_query = symbol_name.contains("::");

    let mut consider = |candidate: &str| {
        let matches = if qualified_query {
            candidate == symbol_name
        } else {
            candidate == symbol_name || symbol_unqualified_name(candidate) == symbol_name
        };

        if matches && seen.insert(candidate.to_string()) {
            candidates.push(candidate.to_string());
        }
    };

    for candidate in file_data.symbol_metadata.keys() {
        consider(candidate);
    }
    for candidate in file_data.calls_by_symbol.keys() {
        consider(candidate);
    }
    for candidate in &file_data.exported_symbols {
        consider(candidate);
    }

    candidates.sort();
    candidates
}

pub(crate) fn resolve_symbol_query_in_data(
    file_data: &FileCallData,
    file: &Path,
    symbol_name: &str,
) -> Result<String, AftError> {
    let candidates = symbol_query_candidates(file_data, symbol_name);
    match candidates.as_slice() {
        [candidate] => Ok(candidate.clone()),
        [] => Err(AftError::SymbolNotFound {
            name: symbol_name.to_string(),
            file: file.display().to_string(),
        }),
        _ => Err(AftError::AmbiguousSymbol {
            name: symbol_name.to_string(),
            candidates,
        }),
    }
}

/// A single call site within a function body.
#[derive(Debug, Clone)]
pub struct CallSite {
    /// The short callee name (last segment, e.g. "foo" for `utils.foo()`).
    pub callee_name: String,
    /// The full callee expression (e.g. "utils.foo" for `utils.foo()`).
    pub full_callee: String,
    /// 1-based line number of the call.
    pub line: u32,
    /// Byte range of the call expression in the source.
    pub byte_start: usize,
    pub byte_end: usize,
}

/// Per-symbol metadata for entry point detection (avoids re-parsing).
#[derive(Debug, Clone, Serialize)]
pub struct SymbolMeta {
    /// The kind of symbol (function, class, method, etc).
    pub kind: SymbolKind,
    /// Whether this symbol is exported.
    pub exported: bool,
    /// Function/method signature if available.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signature: Option<String>,
    /// 1-based start line of the symbol.
    pub line: u32,
    /// 0-based source range of the symbol.
    pub range: Range,
}

/// Per-file call data: call sites grouped by containing symbol, plus
/// exported symbol names and parsed imports.
#[derive(Debug, Clone)]
pub struct FileCallData {
    /// Map from symbol name → list of call sites within that symbol's body.
    pub calls_by_symbol: HashMap<String, Vec<CallSite>>,
    /// Names of exported symbols in this file.
    pub exported_symbols: Vec<String>,
    /// Per-symbol metadata (kind, exported, signature).
    pub symbol_metadata: HashMap<String, SymbolMeta>,
    /// Real or synthetic symbol name for this file's default export.
    pub default_export_symbol: Option<String>,
    /// Parsed import block for cross-file resolution.
    pub import_block: ImportBlock,
    /// Language of the file.
    pub lang: LangId,
}

impl FileCallData {
    /// Look up metadata for an exported symbol name.
    ///
    /// `exported_symbols` stores bare names (e.g. `total_disk_bytes`), but
    /// `symbol_metadata` is keyed by scoped identity (e.g.
    /// `BackupStore::total_disk_bytes` for impl methods, via
    /// [`symbol_identity`]). A bare-name `.get()` therefore misses scoped
    /// symbols and forces callers into degraded `unknown`/line-1 fallbacks.
    /// This resolves an exact key first, then falls back to the first entry
    /// whose unqualified name matches — recovering correct kind and line for
    /// methods. (Bare-name exports are already ambiguous across scopes, so
    /// first-match is the best available signal; this only affects displayed
    /// metadata, never liveness, which keys on the symbol name.)
    pub fn symbol_metadata_for(&self, name: &str) -> Option<&SymbolMeta> {
        if let Some(meta) = self.symbol_metadata.get(name) {
            return Some(meta);
        }
        self.symbol_metadata
            .iter()
            .find(|(key, _)| symbol_unqualified_name(key) == name)
            .map(|(_, meta)| meta)
    }
}

/// Result of resolving a cross-file call edge.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EdgeResolution {
    /// Successfully resolved to a specific file and symbol.
    Resolved { file: PathBuf, symbol: String },
    /// Could not resolve — callee name preserved for diagnostics.
    Unresolved { callee_name: String },
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct ResolvedSymbol {
    file: PathBuf,
    symbol: String,
}

#[derive(Debug, Clone)]
struct RustCrateInfo {
    lib_name: String,
    lib_root: Option<PathBuf>,
    main_root: Option<PathBuf>,
}

#[derive(Debug, Clone)]
struct RustModuleBase {
    src_dir: PathBuf,
    root_file: PathBuf,
}

#[derive(Debug, Clone)]
struct RustUseEntry {
    module_path: String,
    local_name: String,
    kind: RustUseKind,
}

#[derive(Debug, Clone)]
enum RustUseKind {
    Item { imported_name: String },
    Module,
}

/// A node in the forward call tree.
#[derive(Debug, Clone, Serialize)]
pub struct CallTreeNode {
    /// Symbol name.
    pub name: String,
    /// File path (relative to project root when possible).
    pub file: String,
    /// 1-based line number.
    pub line: u32,
    /// Function signature if available.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signature: Option<String>,
    /// Whether this edge was resolved cross-file.
    pub resolved: bool,
    /// Child calls (recursive).
    pub children: Vec<CallTreeNode>,
    /// Whether traversal below this node stopped at the requested depth.
    pub depth_limited: bool,
    /// Number of child call edges omitted because of the depth limit.
    pub truncated: usize,
}

// ---------------------------------------------------------------------------
// Entry point detection
// ---------------------------------------------------------------------------

/// Well-known main/init function names (case-insensitive exact match).
const MAIN_INIT_NAMES: &[&str] = &["main", "init", "setup", "bootstrap", "run"];

/// Determine whether a symbol is an entry point.
///
/// Entry points are:
/// - Exported standalone functions (not methods — methods are class members)
/// - Functions matching well-known main/init patterns (any language)
/// - Test functions matching language-specific patterns
pub fn is_entry_point(name: &str, kind: &SymbolKind, exported: bool, lang: LangId) -> bool {
    // Exported standalone functions
    if exported && *kind == SymbolKind::Function {
        return true;
    }

    // Main/init patterns (case-insensitive exact match, any kind)
    let lower = name.to_lowercase();
    if MAIN_INIT_NAMES.contains(&lower.as_str()) {
        return true;
    }

    // Test patterns by language
    match lang {
        LangId::TypeScript | LangId::JavaScript | LangId::Tsx => {
            // describe, it, test (exact), or starts with test/spec
            matches!(lower.as_str(), "describe" | "it" | "test")
                || lower.starts_with("test")
                || lower.starts_with("spec")
        }
        LangId::Python => {
            // starts with test_ or matches setUp/tearDown
            lower.starts_with("test_") || matches!(name, "setUp" | "tearDown")
        }
        LangId::Rust => {
            // starts with test_
            lower.starts_with("test_")
        }
        LangId::Go => {
            // starts with Test (case-sensitive)
            name.starts_with("Test")
        }
        LangId::C
        | LangId::Cpp
        | LangId::Zig
        | LangId::CSharp
        | LangId::Bash
        | LangId::Solidity
        | LangId::Scss
        | LangId::Vue
        | LangId::Json
        | LangId::Scala
        | LangId::Java
        | LangId::Ruby
        | LangId::Kotlin
        | LangId::Swift
        | LangId::Php
        | LangId::Lua
        | LangId::Perl
        | LangId::Html
        | LangId::Markdown
        | LangId::Yaml
        | LangId::Pascal
        | LangId::R => false,
    }
}

// ---------------------------------------------------------------------------
// Trace-to types
// ---------------------------------------------------------------------------

/// A single hop in a trace path.
#[derive(Debug, Clone, Serialize)]
pub struct TraceHop {
    /// Symbol name at this hop.
    pub symbol: String,
    /// File path (relative to project root).
    pub file: String,
    /// 1-based line number.
    pub line: u32,
    /// Function signature if available.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signature: Option<String>,
    /// Whether this hop is an entry point.
    pub is_entry_point: bool,
}

/// A complete path from an entry point to the target symbol (top-down).
#[derive(Debug, Clone, Serialize)]
pub struct TracePath {
    /// Hops from entry point (first) to target (last).
    pub hops: Vec<TraceHop>,
}

/// Result of a `trace_to` query.
#[derive(Debug, Clone, Serialize)]
pub struct TraceToResult {
    /// The target symbol that was traced.
    pub target_symbol: String,
    /// The target file (relative to project root).
    pub target_file: String,
    /// Complete paths from entry points to the target.
    pub paths: Vec<TracePath>,
    /// Total number of complete paths found.
    pub total_paths: usize,
    /// Number of distinct entry points found across all paths.
    pub entry_points_found: usize,
    /// Whether any path was cut short by the depth limit.
    pub max_depth_reached: bool,
    /// Number of paths that reached a dead end (no callers, not entry point).
    pub truncated_paths: usize,
}

/// A single hop in a `trace_to_symbol` path.
#[derive(Debug, Clone, Serialize)]
pub struct TraceToSymbolHop {
    /// Symbol name at this hop.
    pub symbol: String,
    /// File path (relative to project root).
    pub file: String,
    /// 1-based definition line number.
    pub line: u32,
}

/// Candidate target location for an ambiguous `trace_to_symbol` request.
#[derive(Debug, Clone, Serialize)]
pub struct TraceToSymbolCandidate {
    /// File path (relative to project root).
    pub file: String,
    /// 1-based definition line number.
    pub line: u32,
}

/// Result of a `trace_to_symbol` query.
#[derive(Debug, Clone, Serialize)]
pub struct TraceToSymbolResult {
    /// Shortest path from the origin symbol to the target symbol, if found.
    pub path: Option<Vec<TraceToSymbolHop>>,
    /// Whether traversal was complete within the requested depth.
    pub complete: bool,
    /// Machine-readable explanation when `path` is null.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

// ---------------------------------------------------------------------------
// Data flow tracking types
// ---------------------------------------------------------------------------

/// A single hop in a data flow trace.
#[derive(Debug, Clone, Serialize)]
pub struct DataFlowHop {
    /// File path (relative to project root).
    pub file: String,
    /// Symbol (function/method) containing this hop.
    pub symbol: String,
    /// Variable or parameter name being tracked at this hop.
    pub variable: String,
    /// 1-based line number.
    pub line: u32,
    /// Type of data flow: "assignment", "parameter", or "return".
    pub flow_type: String,
    /// Whether this hop is an approximation (destructuring, spread, unresolved).
    pub approximate: bool,
}

/// Result of a `trace_data` query — tracks how an expression flows through
/// variable assignments and function parameters.
#[derive(Debug, Clone, Serialize)]
pub struct TraceDataResult {
    /// The expression being tracked.
    pub expression: String,
    /// The file where tracking started.
    pub origin_file: String,
    /// The symbol where tracking started.
    pub origin_symbol: String,
    /// Hops through assignments and parameters.
    pub hops: Vec<DataFlowHop>,
    /// Whether tracking stopped due to depth limit.
    pub depth_limited: bool,
}

/// Extract parameter names from a function signature string.
///
/// Strips language-specific receivers (`self`, `&self`, `&mut self` for Rust,
/// `self` for Python) and type annotations / default values. Returns just
/// the parameter names.
pub fn extract_parameters(signature: &str, lang: LangId) -> Vec<String> {
    // Find the parameter list between parentheses
    let start = match signature.find('(') {
        Some(i) => i + 1,
        None => return Vec::new(),
    };
    let end = match signature[start..].find(')') {
        Some(i) => start + i,
        None => return Vec::new(),
    };

    let params_str = &signature[start..end].trim();
    if params_str.is_empty() {
        return Vec::new();
    }

    // Split on commas, respecting nested generics/brackets
    let parts = split_params(params_str);

    let mut result = Vec::new();
    for part in parts {
        let trimmed = part.trim();
        if trimmed.is_empty() {
            continue;
        }

        // Skip language-specific receivers
        match lang {
            LangId::Rust => {
                if trimmed == "self"
                    || trimmed == "mut self"
                    || trimmed.starts_with("&self")
                    || trimmed.starts_with("&mut self")
                {
                    continue;
                }
            }
            LangId::Python => {
                if trimmed == "self" || trimmed.starts_with("self:") {
                    continue;
                }
            }
            _ => {}
        }

        // Extract just the parameter name
        let name = extract_param_name(trimmed, lang);
        if !name.is_empty() {
            result.push(name);
        }
    }

    result
}

/// Split parameter string on commas, respecting nested brackets/generics.
fn split_params(s: &str) -> Vec<String> {
    let mut parts = Vec::new();
    let mut current = String::new();
    let mut depth = 0i32;

    for ch in s.chars() {
        match ch {
            '<' | '[' | '{' | '(' => {
                depth += 1;
                current.push(ch);
            }
            '>' | ']' | '}' | ')' => {
                depth -= 1;
                current.push(ch);
            }
            ',' if depth == 0 => {
                parts.push(current.clone());
                current.clear();
            }
            _ => {
                current.push(ch);
            }
        }
    }
    if !current.is_empty() {
        parts.push(current);
    }
    parts
}

/// Extract the parameter name from a single parameter declaration.
///
/// Handles:
/// - TS/JS: `name: Type`, `name = default`, `...name`, `name?: Type`
/// - Python: `name: Type`, `name=default`, `*args`, `**kwargs`
/// - Rust: `name: Type`, `mut name: Type`
/// - Go: `name Type`, `name, name2 Type`
fn extract_param_name(param: &str, lang: LangId) -> String {
    let trimmed = param.trim();

    // Handle rest/spread params
    let working = if trimmed.starts_with("...") {
        &trimmed[3..]
    } else if trimmed.starts_with("**") {
        &trimmed[2..]
    } else if trimmed.starts_with('*') && lang == LangId::Python {
        &trimmed[1..]
    } else {
        trimmed
    };

    // Rust: `mut name: Type` → strip `mut `
    let working = if lang == LangId::Rust && working.starts_with("mut ") {
        &working[4..]
    } else {
        working
    };

    // Strip type annotation (`: Type`) and default values (`= default`)
    // Take only the name part — everything before `:`, `=`, or `?`
    let name = working
        .split(|c: char| c == ':' || c == '=')
        .next()
        .unwrap_or("")
        .trim();

    // Strip trailing `?` (optional params in TS)
    let name = name.trim_end_matches('?');

    // For Go, the name might be just `name Type` — take the first word
    if lang == LangId::Go && !name.contains(' ') {
        return name.to_string();
    }
    if lang == LangId::Go {
        return name.split_whitespace().next().unwrap_or("").to_string();
    }

    name.to_string()
}

// ---------------------------------------------------------------------------
// CallGraph
// ---------------------------------------------------------------------------

/// Worktree-scoped call graph with lazy per-file construction.
///
/// Files are parsed and analyzed on first access, then cached. The graph
/// can resolve cross-file call edges using the import engine.
pub struct CallGraph {
    /// Cached per-file call data.
    data: HashMap<PathBuf, FileCallData>,
    /// Project root for relative path resolution.
    project_root: PathBuf,
}

impl CallGraph {
    /// Create a new call graph for a project.
    pub fn new(project_root: PathBuf) -> Self {
        clear_workspace_package_cache();
        Self {
            data: HashMap::new(),
            project_root,
        }
    }

    /// Get the project root directory.
    pub fn project_root(&self) -> &Path {
        &self.project_root
    }

    fn resolve_cross_file_edge_with_exports<F, D>(
        full_callee: &str,
        short_name: &str,
        caller_file: &Path,
        import_block: &ImportBlock,
        mut file_exports_symbol: F,
        mut file_default_export_symbol: D,
    ) -> EdgeResolution
    where
        F: FnMut(&Path, &str) -> bool,
        D: FnMut(&Path) -> Option<String>,
    {
        let caller_dir = caller_file.parent().unwrap_or(Path::new("."));

        // Rust uses `::` module paths rather than JS/TS specifiers. Keep this
        // branch gated to `.rs` callers so the existing JS/TS resolver below
        // remains unchanged.
        if is_rust_source_file(caller_file) {
            if let Some(target) = resolve_rust_cross_file_edge(
                full_callee,
                short_name,
                caller_file,
                import_block,
                &mut file_exports_symbol,
            ) {
                return EdgeResolution::Resolved {
                    file: target.file,
                    symbol: target.symbol,
                };
            }
        }

        // Check namespace imports: "utils.foo" where utils is a namespace import
        if full_callee.contains('.') {
            let parts: Vec<&str> = full_callee.splitn(2, '.').collect();
            if parts.len() == 2 {
                let namespace = parts[0];
                let member = parts[1];

                for imp in &import_block.imports {
                    if imp.namespace_import.as_deref() == Some(namespace) {
                        if let Some(resolved_path) =
                            resolve_module_path(caller_dir, &imp.module_path)
                        {
                            if let Some(target) = resolve_reexported_symbol(
                                &resolved_path,
                                member,
                                &mut file_exports_symbol,
                                &mut file_default_export_symbol,
                            ) {
                                return EdgeResolution::Resolved {
                                    file: target.file,
                                    symbol: target.symbol,
                                };
                            }
                        }
                    }
                }
            }
        }

        // Check named imports (direct and aliased)
        for imp in &import_block.imports {
            // Direct named import: import { foo } from './utils'
            if imp.names.iter().any(|name| name == short_name) {
                if let Some(resolved_path) = resolve_module_path(caller_dir, &imp.module_path) {
                    let target = resolve_reexported_symbol(
                        &resolved_path,
                        short_name,
                        &mut file_exports_symbol,
                        &mut file_default_export_symbol,
                    )
                    .unwrap_or(ResolvedSymbol {
                        file: resolved_path,
                        symbol: short_name.to_owned(),
                    });
                    return EdgeResolution::Resolved {
                        file: target.file,
                        symbol: target.symbol,
                    };
                }
            }

            // Default import: import foo from './utils'
            if imp.default_import.as_deref() == Some(short_name) {
                if let Some(resolved_path) = resolve_module_path(caller_dir, &imp.module_path) {
                    let target = resolve_reexported_symbol(
                        &resolved_path,
                        "default",
                        &mut file_exports_symbol,
                        &mut file_default_export_symbol,
                    )
                    .unwrap_or_else(|| ResolvedSymbol {
                        symbol: file_default_export_symbol(&resolved_path)
                            .unwrap_or_else(|| synthetic_default_symbol(&resolved_path)),
                        file: resolved_path,
                    });
                    return EdgeResolution::Resolved {
                        file: target.file,
                        symbol: target.symbol,
                    };
                }
            }
        }

        // Check aliased imports by examining the raw import text.
        // ImportStatement.names stores the original name (foo), but the local code
        // uses the alias (bar). We need to parse `import { foo as bar }` to find
        // that `bar` maps to `foo`.
        if let Some((original_name, resolved_path)) =
            resolve_aliased_import(short_name, import_block, caller_dir)
        {
            let target = resolve_reexported_symbol(
                &resolved_path,
                &original_name,
                &mut file_exports_symbol,
                &mut file_default_export_symbol,
            )
            .unwrap_or(ResolvedSymbol {
                file: resolved_path,
                symbol: original_name,
            });
            return EdgeResolution::Resolved {
                file: target.file,
                symbol: target.symbol,
            };
        }

        // Try barrel file re-exports: if any import points to an index file,
        // check if that file re-exports the symbol
        for imp in &import_block.imports {
            if let Some(resolved_path) = resolve_module_path(caller_dir, &imp.module_path) {
                // Check if the resolved path is a directory (barrel file)
                if resolved_path.is_dir() {
                    if let Some(index_path) = find_index_file(&resolved_path) {
                        // Check if the index file exports this symbol
                        if file_exports_symbol(&index_path, short_name) {
                            return EdgeResolution::Resolved {
                                file: index_path,
                                symbol: short_name.to_owned(),
                            };
                        }
                    }
                } else if file_exports_symbol(&resolved_path, short_name) {
                    return EdgeResolution::Resolved {
                        file: resolved_path,
                        symbol: short_name.to_owned(),
                    };
                }
            }
        }

        EdgeResolution::Unresolved {
            callee_name: short_name.to_owned(),
        }
    }

    /// Get or build the call data for a file.
    pub fn build_file(&mut self, path: &Path) -> Result<&FileCallData, AftError> {
        let canon = self.canonicalize(path)?;

        if !self.data.contains_key(&canon) {
            let file_data = build_file_data(&canon)?;
            self.data.insert(canon.clone(), file_data);
        }

        Ok(&self.data[&canon])
    }

    /// Resolve a user-provided symbol query to the unique scoped symbol identity
    /// used internally by the call graph.
    pub fn resolve_symbol_query(&mut self, file: &Path, symbol: &str) -> Result<String, AftError> {
        let canon = self.canonicalize(file)?;
        let file_data = self.build_file(&canon)?;
        resolve_symbol_query_in_data(file_data, &canon, symbol)
    }

    /// Resolve a cross-file call edge.
    ///
    /// Given a callee expression and the calling file's import block,
    /// determines which file and symbol the call targets.
    pub fn resolve_cross_file_edge(
        &mut self,
        full_callee: &str,
        short_name: &str,
        caller_file: &Path,
        import_block: &ImportBlock,
    ) -> EdgeResolution {
        let graph = RefCell::new(self);
        Self::resolve_cross_file_edge_with_exports(
            full_callee,
            short_name,
            caller_file,
            import_block,
            |path, symbol_name| graph.borrow_mut().file_exports_symbol(path, symbol_name),
            |path| graph.borrow_mut().file_default_export_symbol(path),
        )
    }

    /// Check if a file exports a given symbol name.
    fn file_exports_symbol(&mut self, path: &Path, symbol_name: &str) -> bool {
        match self.build_file(path) {
            Ok(data) => data.exported_symbols.iter().any(|name| name == symbol_name),
            Err(_) => false,
        }
    }

    fn file_default_export_symbol(&mut self, path: &Path) -> Option<String> {
        self.build_file(path)
            .ok()
            .and_then(|data| data.default_export_symbol.clone())
    }

    /// Invalidate a file by removing its cached call data.
    pub fn invalidate_file(&mut self, path: &Path) {
        // Remove from data cache (try both as-is and canonicalized)
        self.data.remove(path);
        if let Ok(canon) = self.canonicalize(path) {
            self.data.remove(&canon);
        }
        clear_workspace_package_cache();
    }

    /// Canonicalize a path, falling back to the original if canonicalization fails.
    fn canonicalize(&self, path: &Path) -> Result<PathBuf, AftError> {
        // If the path is relative, resolve it against project_root
        let full_path = if path.is_relative() {
            self.project_root.join(path)
        } else {
            path.to_path_buf()
        };

        // Try canonicalize, fall back to the full path
        Ok(std::fs::canonicalize(&full_path).unwrap_or(full_path))
    }
}

// ---------------------------------------------------------------------------
// File-level building
// ---------------------------------------------------------------------------

/// Build call data for a single file.
pub(crate) fn build_file_data(path: &Path) -> Result<FileCallData, AftError> {
    let lang = detect_language(path).ok_or_else(|| AftError::InvalidRequest {
        message: format!("unsupported file for call graph: {}", path.display()),
    })?;

    let source = std::fs::read_to_string(path).map_err(|e| AftError::FileNotFound {
        path: format!("{}: {}", path.display(), e),
    })?;

    build_file_data_from_source_with_lang(path, &source, lang)
}

pub(crate) fn build_file_data_from_source(
    path: &Path,
    source: &str,
) -> Result<FileCallData, AftError> {
    let lang = detect_language(path).ok_or_else(|| AftError::InvalidRequest {
        message: format!("unsupported file for call graph: {}", path.display()),
    })?;
    build_file_data_from_source_with_lang(path, source, lang)
}

fn build_file_data_from_source_with_lang(
    path: &Path,
    source: &str,
    lang: LangId,
) -> Result<FileCallData, AftError> {
    let grammar = grammar_for(lang);
    let mut parser = Parser::new();
    parser
        .set_language(&grammar)
        .map_err(|e| AftError::ParseError {
            message: format!("grammar init failed for {:?}: {}", lang, e),
        })?;

    let tree = parser
        .parse(&source, None)
        .ok_or_else(|| AftError::ParseError {
            message: format!("parse failed for {}", path.display()),
        })?;

    // Parse imports
    let import_block = imports::parse_imports(&source, &tree, lang);

    // Get symbols (for call site extraction and export detection)
    let symbols = crate::parser::extract_symbols_from_tree(&source, &tree, lang)?;

    // Build calls_by_symbol
    let mut calls_by_symbol: HashMap<String, Vec<CallSite>> = HashMap::new();
    let root = tree.root_node();

    for sym in &symbols {
        let byte_start = line_col_to_byte(&source, sym.range.start_line, sym.range.start_col);
        let byte_end = line_col_to_byte(&source, sym.range.end_line, sym.range.end_col);

        let raw_calls = extract_calls_full(&source, root, byte_start, byte_end, lang);

        let sites: Vec<CallSite> = raw_calls
            .into_iter()
            .map(
                |(full, short, line, call_byte_start, call_byte_end)| CallSite {
                    callee_name: short,
                    full_callee: full,
                    line,
                    byte_start: call_byte_start,
                    byte_end: call_byte_end,
                },
            )
            .collect();

        if !sites.is_empty() {
            calls_by_symbol.insert(symbol_identity(sym), sites);
        }
    }

    let symbol_ranges: Vec<(usize, usize)> = symbols
        .iter()
        .map(|sym| {
            (
                line_col_to_byte(&source, sym.range.start_line, sym.range.start_col),
                line_col_to_byte(&source, sym.range.end_line, sym.range.end_col),
            )
        })
        .collect();

    let top_level_sites: Vec<CallSite> =
        collect_calls_full_with_ranges(root, &source, 0, source.len(), lang)
            .into_iter()
            .filter(|site| {
                !symbol_ranges
                    .iter()
                    .any(|(start, end)| site.byte_start >= *start && site.byte_end <= *end)
            })
            .map(|site| CallSite {
                callee_name: site.short,
                full_callee: site.full,
                line: site.line,
                byte_start: site.byte_start,
                byte_end: site.byte_end,
            })
            .collect();

    if !top_level_sites.is_empty() {
        calls_by_symbol.insert(TOP_LEVEL_SYMBOL.to_string(), top_level_sites);
    }

    let default_export = find_default_export(&source, root, path, lang);

    if let Some(default_export) = &default_export {
        if default_export.synthetic {
            let byte_start = default_export.node.byte_range().start;
            let byte_end = default_export.node.byte_range().end;
            let raw_calls = extract_calls_full(&source, root, byte_start, byte_end, lang);
            let sites: Vec<CallSite> = raw_calls
                .into_iter()
                .filter(|(_, short, _, _, _)| *short != default_export.symbol)
                .map(
                    |(full, short, line, call_byte_start, call_byte_end)| CallSite {
                        callee_name: short,
                        full_callee: full,
                        line,
                        byte_start: call_byte_start,
                        byte_end: call_byte_end,
                    },
                )
                .collect();
            if !sites.is_empty() {
                calls_by_symbol.insert(default_export.symbol.clone(), sites);
            }
        }
    }

    // Collect exported symbol names
    let mut exported_symbols: Vec<String> = symbols
        .iter()
        .filter(|s| s.exported)
        .map(|s| s.name.clone())
        .collect();
    if let Some(default_export) = &default_export {
        if !exported_symbols
            .iter()
            .any(|name| name == &default_export.symbol)
        {
            exported_symbols.push(default_export.symbol.clone());
        }
    }

    // Build per-symbol metadata for entry point detection
    let mut symbol_metadata: HashMap<String, SymbolMeta> = symbols
        .iter()
        .map(|s| {
            (
                symbol_identity(s),
                SymbolMeta {
                    kind: s.kind.clone(),
                    exported: s.exported,
                    signature: s.signature.clone(),
                    line: s.range.start_line + 1,
                    range: s.range.clone(),
                },
            )
        })
        .collect();
    if let Some(default_export) = &default_export {
        symbol_metadata
            .entry(default_export.symbol.clone())
            .or_insert_with(|| SymbolMeta {
                kind: default_export.kind.clone(),
                exported: true,
                signature: Some(first_line_signature(&source, &default_export.node)),
                line: default_export.node.start_position().row as u32 + 1,
                range: crate::parser::node_range(&default_export.node),
            });
    }
    if calls_by_symbol.contains_key(TOP_LEVEL_SYMBOL) {
        symbol_metadata
            .entry(TOP_LEVEL_SYMBOL.to_string())
            .or_insert(SymbolMeta {
                kind: SymbolKind::Function,
                exported: false,
                signature: None,
                line: 1,
                range: Range {
                    start_line: 0,
                    start_col: 0,
                    end_line: 0,
                    end_col: 0,
                },
            });
    }

    Ok(FileCallData {
        calls_by_symbol,
        exported_symbols,
        symbol_metadata,
        default_export_symbol: default_export.map(|export| export.symbol),
        import_block,
        lang,
    })
}

#[derive(Debug, Clone)]
struct DefaultExport<'tree> {
    symbol: String,
    synthetic: bool,
    kind: SymbolKind,
    node: Node<'tree>,
}

fn find_default_export<'tree>(
    source: &str,
    root: Node<'tree>,
    path: &Path,
    lang: LangId,
) -> Option<DefaultExport<'tree>> {
    if !matches!(lang, LangId::TypeScript | LangId::Tsx | LangId::JavaScript) {
        return None;
    }
    find_default_export_inner(source, root, path)
}

fn find_default_export_inner<'tree>(
    source: &str,
    node: Node<'tree>,
    path: &Path,
) -> Option<DefaultExport<'tree>> {
    if node.kind() == "export_statement" {
        if let Some(default_export) = default_export_from_statement(source, node, path) {
            return Some(default_export);
        }
    }

    let mut cursor = node.walk();
    if !cursor.goto_first_child() {
        return None;
    }

    loop {
        let child = cursor.node();
        if let Some(default_export) = find_default_export_inner(source, child, path) {
            return Some(default_export);
        }
        if !cursor.goto_next_sibling() {
            break;
        }
    }

    None
}

fn default_export_from_statement<'tree>(
    source: &str,
    node: Node<'tree>,
    path: &Path,
) -> Option<DefaultExport<'tree>> {
    let mut cursor = node.walk();
    if !cursor.goto_first_child() {
        return None;
    }

    let mut saw_default = false;
    loop {
        let child = cursor.node();
        match child.kind() {
            "default" => saw_default = true,
            "function_declaration" | "generator_function_declaration" | "class_declaration"
                if saw_default =>
            {
                if let Some(name_node) = child.child_by_field_name("name") {
                    return Some(DefaultExport {
                        symbol: source[name_node.byte_range()].to_string(),
                        synthetic: false,
                        kind: default_export_kind(&child),
                        node: child,
                    });
                }
                return Some(DefaultExport {
                    symbol: synthetic_default_symbol(path),
                    synthetic: true,
                    kind: default_export_kind(&child),
                    node: child,
                });
            }
            "arrow_function"
            | "function"
            | "function_expression"
            | "class"
            | "class_expression"
                if saw_default =>
            {
                return Some(DefaultExport {
                    symbol: synthetic_default_symbol(path),
                    synthetic: true,
                    kind: default_export_kind(&child),
                    node: child,
                });
            }
            "identifier" | "type_identifier" | "property_identifier" if saw_default => {
                return Some(DefaultExport {
                    symbol: source[child.byte_range()].to_string(),
                    synthetic: false,
                    kind: SymbolKind::Function,
                    node: child,
                });
            }
            _ => {}
        }
        if !cursor.goto_next_sibling() {
            break;
        }
    }

    None
}

fn default_export_kind(node: &Node) -> SymbolKind {
    if node.kind().contains("class") {
        SymbolKind::Class
    } else {
        SymbolKind::Function
    }
}

fn synthetic_default_symbol(path: &Path) -> String {
    let file_name = path
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("unknown");
    format!("<default:{file_name}>")
}

fn first_line_signature(source: &str, node: &Node) -> String {
    let text = &source[node.byte_range()];
    let first_line = text.lines().next().unwrap_or(text);
    first_line
        .trim_end()
        .trim_end_matches('{')
        .trim_end()
        .to_string()
}

fn node_text(node: tree_sitter::Node, source: &str) -> String {
    source[node.start_byte()..node.end_byte()].to_string()
}

/// Find a direct child node by kind name.
fn find_child_by_kind<'a>(
    node: tree_sitter::Node<'a>,
    kind: &str,
) -> Option<tree_sitter::Node<'a>> {
    let mut cursor = node.walk();
    if cursor.goto_first_child() {
        loop {
            if cursor.node().kind() == kind {
                return Some(cursor.node());
            }
            if !cursor.goto_next_sibling() {
                break;
            }
        }
    }
    None
}

#[derive(Debug, Clone)]
struct CallSiteWithRange {
    full: String,
    short: String,
    line: u32,
    byte_start: usize,
    byte_end: usize,
}

fn collect_calls_full_with_ranges(
    root: tree_sitter::Node,
    source: &str,
    byte_start: usize,
    byte_end: usize,
    lang: LangId,
) -> Vec<CallSiteWithRange> {
    let mut results = Vec::new();
    let call_kinds = call_node_kinds(lang);
    collect_calls_full_with_ranges_inner(
        root,
        source,
        byte_start,
        byte_end,
        &call_kinds,
        &mut results,
    );
    results
}

fn collect_calls_full_with_ranges_inner(
    node: tree_sitter::Node,
    source: &str,
    byte_start: usize,
    byte_end: usize,
    call_kinds: &[&str],
    results: &mut Vec<CallSiteWithRange>,
) {
    let node_start = node.start_byte();
    let node_end = node.end_byte();

    if node_end <= byte_start || node_start >= byte_end {
        return;
    }

    if call_kinds.contains(&node.kind()) && node_start >= byte_start && node_end <= byte_end {
        if let (Some(full), Some(short)) = (
            extract_full_callee(&node, source),
            extract_callee_name(&node, source),
        ) {
            results.push(CallSiteWithRange {
                full,
                short,
                line: node.start_position().row as u32 + 1,
                byte_start: node_start,
                byte_end: node_end,
            });
        }
    }

    let mut cursor = node.walk();
    if cursor.goto_first_child() {
        loop {
            collect_calls_full_with_ranges_inner(
                cursor.node(),
                source,
                byte_start,
                byte_end,
                call_kinds,
                results,
            );
            if !cursor.goto_next_sibling() {
                break;
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Module path resolution
// ---------------------------------------------------------------------------

/// Resolve a module path (e.g. './utils') relative to a directory.
///
/// Tries common file extensions for TypeScript/JavaScript projects.
pub(crate) fn resolve_module_path(from_dir: &Path, module_path: &str) -> Option<PathBuf> {
    if module_path.starts_with('.') {
        return resolve_relative_module_path(from_dir, module_path);
    }

    if module_path.starts_with('/') {
        return None;
    }

    if let Some(path) = resolve_tsconfig_path(from_dir, module_path) {
        return Some(path);
    }

    resolve_workspace_module_path(from_dir, module_path)
}

fn resolve_relative_module_path(from_dir: &Path, module_path: &str) -> Option<PathBuf> {
    let base = from_dir.join(module_path);
    resolve_file_like_path(&base)
}

fn resolve_file_like_path(base: &Path) -> Option<PathBuf> {
    let base = base.to_path_buf();

    // Try exact path first
    if base.is_file() {
        return Some(std::fs::canonicalize(&base).unwrap_or(base));
    }

    // Try common extensions, including ESM/CJS TypeScript pairs used by workspaces.
    for ext in JS_TS_EXTENSIONS {
        let with_ext = base.with_extension(ext);
        if with_ext.is_file() {
            return Some(std::fs::canonicalize(&with_ext).unwrap_or(with_ext));
        }
    }

    // Try as directory with index file
    if base.is_dir() {
        if let Some(index) = find_index_file(&base) {
            return Some(index);
        }
    }

    None
}

fn resolve_workspace_module_path(from_dir: &Path, module_path: &str) -> Option<PathBuf> {
    let (package_name, subpath) = split_package_import(module_path)?;
    let package_root = find_package_root_for_import(from_dir, &package_name)?;
    resolve_package_entry(&package_root, &subpath)
}

fn is_rust_source_file(path: &Path) -> bool {
    path.extension().and_then(|ext| ext.to_str()) == Some("rs")
}

fn resolve_rust_cross_file_edge<F>(
    full_callee: &str,
    short_name: &str,
    caller_file: &Path,
    import_block: &ImportBlock,
    file_exports_symbol: &mut F,
) -> Option<ResolvedSymbol>
where
    F: FnMut(&Path, &str) -> bool,
{
    if let Some(target) = resolve_rust_qualified_call(caller_file, full_callee, file_exports_symbol)
    {
        return Some(target);
    }

    resolve_rust_imported_call(
        caller_file,
        full_callee,
        short_name,
        import_block,
        file_exports_symbol,
    )
}

fn resolve_rust_qualified_call<F>(
    caller_file: &Path,
    full_callee: &str,
    file_exports_symbol: &mut F,
) -> Option<ResolvedSymbol>
where
    F: FnMut(&Path, &str) -> bool,
{
    if !full_callee.contains("::") {
        return None;
    }

    let segments = rust_path_segments(full_callee)?;
    resolve_rust_call_segments(caller_file, &segments, file_exports_symbol)
}

fn resolve_rust_imported_call<F>(
    caller_file: &Path,
    full_callee: &str,
    short_name: &str,
    import_block: &ImportBlock,
    file_exports_symbol: &mut F,
) -> Option<ResolvedSymbol>
where
    F: FnMut(&Path, &str) -> bool,
{
    let call_segments = rust_path_segments(full_callee).unwrap_or_default();
    let bare_call_name = if call_segments.len() <= 1 {
        call_segments
            .first()
            .map(String::as_str)
            .unwrap_or(short_name)
    } else {
        short_name
    };

    for imp in &import_block.imports {
        for entry in rust_use_entries(imp) {
            match &entry.kind {
                RustUseKind::Item { imported_name } if call_segments.len() <= 1 => {
                    if entry.local_name != bare_call_name {
                        continue;
                    }
                    let Some(file) = resolve_rust_module_path(caller_file, &entry.module_path)
                    else {
                        continue;
                    };
                    if file_exports_symbol(&file, imported_name) {
                        return Some(ResolvedSymbol {
                            file,
                            symbol: imported_name.clone(),
                        });
                    }
                }
                RustUseKind::Module if call_segments.len() >= 2 => {
                    if call_segments.first().map(String::as_str) != Some(entry.local_name.as_str())
                    {
                        continue;
                    }
                    let symbol = call_segments.last()?.clone();
                    let mut module_path = entry.module_path.clone();
                    for segment in &call_segments[1..call_segments.len().saturating_sub(1)] {
                        module_path.push_str("::");
                        module_path.push_str(segment);
                    }
                    let Some(file) = resolve_rust_module_path(caller_file, &module_path) else {
                        continue;
                    };
                    if file_exports_symbol(&file, &symbol) {
                        return Some(ResolvedSymbol { file, symbol });
                    }
                }
                _ => {}
            }
        }
    }

    None
}

fn resolve_rust_call_segments<F>(
    caller_file: &Path,
    segments: &[String],
    file_exports_symbol: &mut F,
) -> Option<ResolvedSymbol>
where
    F: FnMut(&Path, &str) -> bool,
{
    if segments.len() < 2 {
        return None;
    }

    let symbol = segments.last()?.clone();
    let module_path = segments[..segments.len() - 1].join("::");
    let file = resolve_rust_module_path(caller_file, &module_path)?;
    if file_exports_symbol(&file, &symbol) {
        Some(ResolvedSymbol { file, symbol })
    } else {
        None
    }
}

fn resolve_rust_module_path(caller_file: &Path, module_path: &str) -> Option<PathBuf> {
    let segments = rust_path_segments(module_path)?;
    let first = segments.first()?.as_str();

    match first {
        "std" | "core" | "alloc" => None,
        "crate" => {
            let crate_root = find_rust_crate_root(caller_file)?;
            let crate_info = rust_crate_info(&crate_root)?;
            let base = rust_module_base_for_caller(&crate_info, caller_file)?;
            resolve_rust_module_segments(&base, &segments[1..])
        }
        "self" => {
            let crate_root = find_rust_crate_root(caller_file)?;
            let crate_info = rust_crate_info(&crate_root)?;
            let base = rust_module_base_for_caller(&crate_info, caller_file)?;
            if segments.len() == 1 {
                return Some(canonicalize_path(caller_file));
            }
            let mut target_segments = rust_module_segments_for_file(&base.src_dir, caller_file)?;
            target_segments.extend(segments[1..].iter().cloned());
            resolve_rust_module_segments(&base, &target_segments)
        }
        "super" => {
            let crate_root = find_rust_crate_root(caller_file)?;
            let crate_info = rust_crate_info(&crate_root)?;
            let base = rust_module_base_for_caller(&crate_info, caller_file)?;
            let mut target_segments = rust_module_segments_for_file(&base.src_dir, caller_file)?;
            target_segments.pop();
            target_segments.extend(segments[1..].iter().cloned());
            resolve_rust_module_segments(&base, &target_segments)
        }
        crate_name => {
            let caller_dir = caller_file.parent().unwrap_or_else(|| Path::new("."));
            let workspace_crates = rust_workspace_crates(caller_dir)?;
            let crate_info = workspace_crates.get(crate_name)?;
            let base = rust_lib_module_base(crate_info)?;
            resolve_rust_module_segments(&base, &segments[1..])
        }
    }
}

fn rust_use_entries(imp: &imports::ImportStatement) -> Vec<RustUseEntry> {
    let Some(body) = rust_use_body(&imp.raw_text) else {
        return Vec::new();
    };
    let mut entries = Vec::new();
    expand_rust_use_tree(body, &mut entries);
    entries
}

fn rust_use_body(raw: &str) -> Option<&str> {
    let use_pos = raw.find("use ")?;
    let body = raw[use_pos + 4..].trim();
    let body = body.strip_suffix(';').unwrap_or(body).trim();
    (!body.is_empty()).then_some(body)
}

fn expand_rust_use_tree(path: &str, entries: &mut Vec<RustUseEntry>) {
    let path = path.trim();
    if path.is_empty() {
        return;
    }

    if let Some((prefix, inner)) = split_rust_use_braces(path) {
        let prefix = prefix.trim().trim_end_matches("::").trim();
        for part in split_top_level_commas(inner) {
            let part = part.trim();
            if part.is_empty() {
                continue;
            }
            if part == "self" {
                if let Some(local_name) = rust_last_path_segment(prefix) {
                    entries.push(RustUseEntry {
                        module_path: prefix.to_string(),
                        local_name,
                        kind: RustUseKind::Module,
                    });
                }
                continue;
            }
            let combined = if prefix.is_empty() {
                part.to_string()
            } else {
                format!("{prefix}::{part}")
            };
            expand_rust_use_tree(&combined, entries);
        }
        return;
    }

    add_rust_use_leaf(path, entries);
}

fn split_rust_use_braces(path: &str) -> Option<(&str, &str)> {
    let mut depth = 0usize;
    let mut start = None;
    for (idx, ch) in path.char_indices() {
        match ch {
            '{' => {
                if depth == 0 {
                    start = Some(idx);
                }
                depth += 1;
            }
            '}' => {
                depth = depth.checked_sub(1)?;
                if depth == 0 {
                    let start = start?;
                    if !path[idx + ch.len_utf8()..].trim().is_empty() {
                        return None;
                    }
                    return Some((&path[..start], &path[start + 1..idx]));
                }
            }
            _ => {}
        }
    }
    None
}

fn split_top_level_commas(value: &str) -> Vec<&str> {
    let mut parts = Vec::new();
    let mut depth = 0usize;
    let mut start = 0usize;
    for (idx, ch) in value.char_indices() {
        match ch {
            '{' => depth += 1,
            '}' => depth = depth.saturating_sub(1),
            ',' if depth == 0 => {
                parts.push(&value[start..idx]);
                start = idx + ch.len_utf8();
            }
            _ => {}
        }
    }
    parts.push(&value[start..]);
    parts
}

fn add_rust_use_leaf(path: &str, entries: &mut Vec<RustUseEntry>) {
    let (path, alias) = split_rust_alias(path);
    let Some(segments) = rust_path_segments(path) else {
        return;
    };
    if segments.is_empty() || segments.last().map(String::as_str) == Some("*") {
        return;
    }

    let imported_name = segments.last().cloned().unwrap_or_default();
    let local_name = alias.unwrap_or(&imported_name).to_string();
    if segments.len() >= 2 {
        entries.push(RustUseEntry {
            module_path: segments[..segments.len() - 1].join("::"),
            local_name: local_name.clone(),
            kind: RustUseKind::Item {
                imported_name: imported_name.clone(),
            },
        });
    }

    entries.push(RustUseEntry {
        module_path: segments.join("::"),
        local_name,
        kind: RustUseKind::Module,
    });
}

fn split_rust_alias(path: &str) -> (&str, Option<&str>) {
    if let Some(idx) = path.rfind(" as ") {
        let original = path[..idx].trim();
        let alias = path[idx + 4..].trim();
        if !original.is_empty() && !alias.is_empty() {
            return (original, Some(alias));
        }
    }
    (path.trim(), None)
}

fn rust_path_segments(path: &str) -> Option<Vec<String>> {
    let path = path.trim().trim_end_matches(';').trim();
    if path.is_empty() || path.contains('{') || path.contains('}') {
        return None;
    }

    let mut segments = Vec::new();
    for raw_segment in path.split("::") {
        let segment = raw_segment.trim();
        if segment.is_empty() || segment == "*" || segment.chars().any(char::is_whitespace) {
            return None;
        }
        let segment = segment.strip_prefix("r#").unwrap_or(segment);
        if segment
            .chars()
            .any(|ch| !(ch == '_' || ch.is_ascii_alphanumeric()))
        {
            return None;
        }
        segments.push(segment.to_string());
    }

    (!segments.is_empty()).then_some(segments)
}

fn rust_last_path_segment(path: &str) -> Option<String> {
    rust_path_segments(path)?.last().cloned()
}

fn find_rust_crate_root(from: &Path) -> Option<PathBuf> {
    let mut current = if from.is_file() {
        from.parent()
    } else {
        Some(from)
    };
    while let Some(dir) = current {
        if dir.join("Cargo.toml").is_file() {
            return Some(canonicalize_path(dir));
        }
        current = dir.parent();
    }
    None
}

fn rust_crate_info(crate_root: &Path) -> Option<RustCrateInfo> {
    let root = canonicalize_path(crate_root);
    if let Some(cached) = RUST_CRATE_INFO_CACHE
        .read()
        .ok()
        .and_then(|cache| cache.get(&root).cloned())
    {
        return cached;
    }

    let resolved = read_rust_crate_info(&root);
    if let Ok(mut cache) = RUST_CRATE_INFO_CACHE.write() {
        cache.insert(root, resolved.clone());
    }
    resolved
}

fn read_rust_crate_info(crate_root: &Path) -> Option<RustCrateInfo> {
    let cargo = rust_manifest_value(&crate_root.join("Cargo.toml"))?;
    let package = cargo.get("package")?;
    let package_name = package.get("name")?.as_str()?;
    let lib_name = cargo
        .get("lib")
        .and_then(|lib| lib.get("name"))
        .and_then(|name| name.as_str())
        .map(ToOwned::to_owned)
        .unwrap_or_else(|| package_name.replace('-', "_"));

    let lib_root = cargo
        .get("lib")
        .and_then(|lib| lib.get("path"))
        .and_then(|path| path.as_str())
        .map(|path| crate_root.join(path))
        .unwrap_or_else(|| crate_root.join("src/lib.rs"));
    let lib_root = lib_root.is_file().then(|| canonicalize_path(&lib_root));

    let main_root = crate_root.join("src/main.rs");
    let main_root = main_root.is_file().then(|| canonicalize_path(&main_root));

    Some(RustCrateInfo {
        lib_name,
        lib_root,
        main_root,
    })
}

fn rust_manifest_value(path: &Path) -> Option<toml::Value> {
    let source = std::fs::read_to_string(path).ok()?;
    toml::from_str(&source).ok()
}

fn rust_module_base_for_caller(
    crate_info: &RustCrateInfo,
    caller_file: &Path,
) -> Option<RustModuleBase> {
    let caller = canonicalize_path(caller_file);
    if crate_info.main_root.as_ref() == Some(&caller) {
        return rust_main_module_base(crate_info);
    }
    rust_lib_module_base(crate_info).or_else(|| rust_main_module_base(crate_info))
}

fn rust_lib_module_base(crate_info: &RustCrateInfo) -> Option<RustModuleBase> {
    let root_file = crate_info.lib_root.clone()?;
    let src_dir = root_file.parent()?.to_path_buf();
    Some(RustModuleBase { src_dir, root_file })
}

fn rust_main_module_base(crate_info: &RustCrateInfo) -> Option<RustModuleBase> {
    let root_file = crate_info.main_root.clone()?;
    let src_dir = root_file.parent()?.to_path_buf();
    Some(RustModuleBase { src_dir, root_file })
}

fn resolve_rust_module_segments(base: &RustModuleBase, segments: &[String]) -> Option<PathBuf> {
    if segments.is_empty() {
        return Some(base.root_file.clone());
    }

    let module_base = segments
        .iter()
        .fold(base.src_dir.clone(), |path, segment| path.join(segment));
    let file_path = module_base.with_extension("rs");
    if file_path.is_file() {
        return Some(canonicalize_path(&file_path));
    }

    let mod_path = module_base.join("mod.rs");
    if mod_path.is_file() {
        return Some(canonicalize_path(&mod_path));
    }

    None
}

fn rust_module_segments_for_file(src_dir: &Path, file: &Path) -> Option<Vec<String>> {
    let src_dir = canonicalize_path(src_dir);
    let file = canonicalize_path(file);
    let rel = file.strip_prefix(&src_dir).ok()?;
    let mut parts: Vec<String> = rel
        .components()
        .filter_map(|component| component.as_os_str().to_str().map(ToOwned::to_owned))
        .collect();
    if parts.is_empty() {
        return None;
    }

    let last = parts.pop()?;
    if last == "lib.rs" || last == "main.rs" {
        return Some(Vec::new());
    }
    if last == "mod.rs" {
        return Some(parts);
    }
    let stem = Path::new(&last).file_stem()?.to_str()?.to_string();
    parts.push(stem);
    Some(parts)
}

fn rust_workspace_crates(from_dir: &Path) -> Option<HashMap<String, RustCrateInfo>> {
    let workspace_root =
        find_rust_workspace_root(from_dir).or_else(|| find_rust_crate_root(from_dir))?;
    let workspace_root = canonicalize_path(&workspace_root);

    if let Some(cached) = RUST_WORKSPACE_CRATE_CACHE
        .read()
        .ok()
        .and_then(|cache| cache.get(&workspace_root).cloned())
    {
        return Some(cached);
    }

    let mut crates = HashMap::new();
    for member in rust_workspace_member_dirs(&workspace_root) {
        if let Some(info) = rust_crate_info(&member) {
            if info.lib_root.is_some() {
                crates.insert(info.lib_name.clone(), info);
            }
        }
    }
    if let Some(info) = rust_crate_info(&workspace_root) {
        if info.lib_root.is_some() {
            crates.insert(info.lib_name.clone(), info);
        }
    }

    if let Ok(mut cache) = RUST_WORKSPACE_CRATE_CACHE.write() {
        cache.insert(workspace_root, crates.clone());
    }
    Some(crates)
}

fn find_rust_workspace_root(from_dir: &Path) -> Option<PathBuf> {
    let mut current = Some(from_dir);
    while let Some(dir) = current {
        let cargo = dir.join("Cargo.toml");
        if rust_manifest_value(&cargo)
            .and_then(|value| value.get("workspace").cloned())
            .is_some()
        {
            return Some(canonicalize_path(dir));
        }
        current = dir.parent();
    }
    None
}

fn rust_workspace_member_dirs(workspace_root: &Path) -> Vec<PathBuf> {
    let Some(cargo) = rust_manifest_value(&workspace_root.join("Cargo.toml")) else {
        return Vec::new();
    };
    let Some(members) = cargo
        .get("workspace")
        .and_then(|workspace| workspace.get("members"))
        .and_then(|members| members.as_array())
    else {
        return Vec::new();
    };

    let mut dirs = Vec::new();
    for member in members.iter().filter_map(|member| member.as_str()) {
        dirs.extend(expand_rust_workspace_member(workspace_root, member));
    }
    dirs.sort();
    dirs.dedup();
    dirs
}

fn expand_rust_workspace_member(workspace_root: &Path, member: &str) -> Vec<PathBuf> {
    let member = member.trim();
    if member.is_empty() {
        return Vec::new();
    }

    if member.contains('*') || member.contains('?') || member.contains('[') {
        let pattern = workspace_root.join(member).to_string_lossy().to_string();
        return glob::glob(&pattern)
            .ok()
            .into_iter()
            .flatten()
            .filter_map(Result::ok)
            .filter(|path| path.join("Cargo.toml").is_file())
            .map(|path| canonicalize_path(&path))
            .collect();
    }

    let path = workspace_root.join(member);
    if path.join("Cargo.toml").is_file() {
        vec![canonicalize_path(&path)]
    } else {
        Vec::new()
    }
}

fn canonicalize_path(path: &Path) -> PathBuf {
    std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
}

fn resolve_tsconfig_path(from_dir: &Path, module_path: &str) -> Option<PathBuf> {
    let tsconfig_dir = find_tsconfig_dir(from_dir)?;
    let tsconfig = package_json_like_value(&tsconfig_dir.join("tsconfig.json"))?;
    let compiler_options = tsconfig.get("compilerOptions")?;
    let paths = compiler_options.get("paths")?.as_object()?;
    let base_url = compiler_options
        .get("baseUrl")
        .and_then(Value::as_str)
        .unwrap_or(".");
    let base_dir = tsconfig_dir.join(base_url);

    for (alias, targets) in paths {
        let Some(capture) = ts_path_capture(alias, module_path) else {
            continue;
        };
        let Some(targets) = targets.as_array() else {
            continue;
        };
        for target in targets.iter().filter_map(Value::as_str) {
            let target = if target.contains('*') {
                target.replace('*', capture)
            } else {
                target.to_string()
            };
            if let Some(path) = resolve_file_like_path(&base_dir.join(target)) {
                return Some(path);
            }
        }
    }

    None
}

fn find_tsconfig_dir(from_dir: &Path) -> Option<PathBuf> {
    let mut current = Some(from_dir);
    while let Some(dir) = current {
        if dir.join("tsconfig.json").is_file() {
            return Some(dir.to_path_buf());
        }
        current = dir.parent();
    }
    None
}

fn ts_path_capture<'a>(alias: &str, module_path: &'a str) -> Option<&'a str> {
    if let Some(star_index) = alias.find('*') {
        let (prefix, suffix_with_star) = alias.split_at(star_index);
        let suffix = &suffix_with_star[1..];
        if module_path.starts_with(prefix) && module_path.ends_with(suffix) {
            return Some(&module_path[prefix.len()..module_path.len() - suffix.len()]);
        }
        return None;
    }

    (alias == module_path).then_some("")
}

fn split_package_import(module_path: &str) -> Option<(String, Option<String>)> {
    let mut parts = module_path.split('/');
    let first = parts.next()?;
    if first.is_empty() {
        return None;
    }

    if first.starts_with('@') {
        let second = parts.next()?;
        if second.is_empty() {
            return None;
        }
        let package_name = format!("{first}/{second}");
        let subpath = parts.collect::<Vec<_>>().join("/");
        let subpath = (!subpath.is_empty()).then_some(subpath);
        Some((package_name, subpath))
    } else {
        let package_name = first.to_string();
        let subpath = parts.collect::<Vec<_>>().join("/");
        let subpath = (!subpath.is_empty()).then_some(subpath);
        Some((package_name, subpath))
    }
}

fn find_package_root_for_import(from_dir: &Path, package_name: &str) -> Option<PathBuf> {
    let mut current = Some(from_dir);
    while let Some(dir) = current {
        if package_json_name(dir).as_deref() == Some(package_name) {
            return Some(std::fs::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf()));
        }
        current = dir.parent();
    }

    find_workspace_root(from_dir)
        .and_then(|workspace_root| resolve_workspace_package(&workspace_root, package_name))
}

fn find_workspace_root(from_dir: &Path) -> Option<PathBuf> {
    let mut current = Some(from_dir);
    while let Some(dir) = current {
        if is_workspace_root(dir) {
            return Some(std::fs::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf()));
        }
        current = dir.parent();
    }
    None
}

fn is_workspace_root(dir: &Path) -> bool {
    package_json_value(dir)
        .map(|value| !workspace_patterns(&value).is_empty())
        .unwrap_or(false)
        || !pnpm_workspace_patterns(dir).is_empty()
}

pub(crate) fn clear_workspace_package_cache() {
    if let Ok(mut cache) = WORKSPACE_PACKAGE_CACHE.write() {
        cache.clear();
    }
    if let Ok(mut cache) = RUST_CRATE_INFO_CACHE.write() {
        cache.clear();
    }
    if let Ok(mut cache) = RUST_WORKSPACE_CRATE_CACHE.write() {
        cache.clear();
    }
}

fn resolve_workspace_package(workspace_root: &Path, package_name: &str) -> Option<PathBuf> {
    let workspace_root =
        std::fs::canonicalize(workspace_root).unwrap_or_else(|_| workspace_root.to_path_buf());
    let cache_key = (workspace_root.clone(), package_name.to_string());

    if let Ok(cache) = WORKSPACE_PACKAGE_CACHE.read() {
        if let Some(cached) = cache.get(&cache_key) {
            return cached.clone();
        }
    }

    let resolved = workspace_member_dirs(&workspace_root)
        .into_iter()
        .find(|dir| package_json_name(dir).as_deref() == Some(package_name))
        .map(|dir| std::fs::canonicalize(&dir).unwrap_or(dir));

    if let Ok(mut cache) = WORKSPACE_PACKAGE_CACHE.write() {
        cache.insert(cache_key, resolved.clone());
    }

    resolved
}

fn workspace_member_dirs(workspace_root: &Path) -> Vec<PathBuf> {
    let mut patterns = package_json_value(workspace_root)
        .map(|package_json| workspace_patterns(&package_json))
        .unwrap_or_default();
    patterns.extend(pnpm_workspace_patterns(workspace_root));

    expand_workspace_patterns(workspace_root, &patterns)
}

fn workspace_patterns(package_json: &Value) -> Vec<String> {
    match package_json.get("workspaces") {
        Some(Value::Array(items)) => items
            .iter()
            .filter_map(non_empty_workspace_pattern)
            .collect(),
        Some(Value::Object(map)) => map
            .get("packages")
            .and_then(Value::as_array)
            .map(|items| {
                items
                    .iter()
                    .filter_map(non_empty_workspace_pattern)
                    .collect()
            })
            .unwrap_or_default(),
        _ => Vec::new(),
    }
}

fn non_empty_workspace_pattern(value: &Value) -> Option<String> {
    let pattern = value.as_str()?.trim();
    (!pattern.is_empty()).then(|| pattern.to_string())
}

fn pnpm_workspace_patterns(workspace_root: &Path) -> Vec<String> {
    let Ok(source) = std::fs::read_to_string(workspace_root.join("pnpm-workspace.yaml")) else {
        return Vec::new();
    };

    let mut patterns = Vec::new();
    let mut in_packages = false;
    for line in source.lines() {
        let without_comment = line.split('#').next().unwrap_or("").trim_end();
        let trimmed = without_comment.trim();
        if trimmed.is_empty() {
            continue;
        }
        if trimmed == "packages:" {
            in_packages = true;
            continue;
        }
        if !trimmed.starts_with('-') && !line.starts_with(' ') && !line.starts_with('\t') {
            in_packages = false;
        }
        if in_packages {
            if let Some(pattern) = trimmed.strip_prefix('-') {
                let pattern = pattern.trim().trim_matches('"').trim_matches('\'');
                if !pattern.is_empty() {
                    patterns.push(pattern.to_string());
                }
            }
        }
    }
    patterns
}

fn expand_workspace_patterns(workspace_root: &Path, patterns: &[String]) -> Vec<PathBuf> {
    let positive_patterns: Vec<&str> = patterns
        .iter()
        .map(|pattern| pattern.trim())
        .filter(|pattern| !pattern.is_empty() && !pattern.starts_with('!'))
        .collect();
    if positive_patterns.is_empty() {
        return Vec::new();
    }

    let positives = build_glob_set(&positive_patterns);
    let negative_patterns: Vec<&str> = patterns
        .iter()
        .map(|pattern| pattern.trim())
        .filter_map(|pattern| pattern.strip_prefix('!'))
        .map(str::trim)
        .filter(|pattern| !pattern.is_empty())
        .collect();
    let negatives = build_glob_set(&negative_patterns);

    let mut members = Vec::new();
    collect_workspace_member_dirs(
        workspace_root,
        workspace_root,
        &positives,
        &negatives,
        &mut members,
    );
    members
}

fn build_glob_set(patterns: &[&str]) -> GlobSet {
    let mut builder = GlobSetBuilder::new();
    for pattern in patterns {
        if let Ok(glob) = Glob::new(pattern) {
            builder.add(glob);
        }
    }
    builder
        .build()
        .unwrap_or_else(|_| GlobSetBuilder::new().build().unwrap())
}

fn collect_workspace_member_dirs(
    workspace_root: &Path,
    dir: &Path,
    positives: &GlobSet,
    negatives: &GlobSet,
    members: &mut Vec<PathBuf>,
) {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };

    for entry in entries.filter_map(Result::ok) {
        let path = entry.path();
        let Ok(file_type) = entry.file_type() else {
            continue;
        };
        if !file_type.is_dir() {
            continue;
        }
        let name = entry.file_name();
        let name = name.to_string_lossy();
        if matches!(
            name.as_ref(),
            "node_modules" | ".git" | "target" | "dist" | "build"
        ) {
            continue;
        }

        if path.join("package.json").is_file() {
            if let Ok(rel) = path.strip_prefix(workspace_root) {
                let rel = rel.to_string_lossy().replace('\\', "/");
                if positives.is_match(&rel) && !negatives.is_match(&rel) {
                    members.push(path.clone());
                }
            }
        }

        collect_workspace_member_dirs(workspace_root, &path, positives, negatives, members);
    }
}

fn package_json_value(dir: &Path) -> Option<Value> {
    package_json_like_value(&dir.join("package.json"))
}

fn package_json_like_value(path: &Path) -> Option<Value> {
    let json = std::fs::read_to_string(path).ok()?;
    serde_json::from_str(&json).ok()
}

fn package_json_name(dir: &Path) -> Option<String> {
    package_json_value(dir)?
        .get("name")?
        .as_str()
        .map(ToOwned::to_owned)
}

fn resolve_package_entry(package_root: &Path, subpath: &Option<String>) -> Option<PathBuf> {
    let package_json = package_json_value(package_root).unwrap_or(Value::Null);

    if let Some(exports) = package_json.get("exports") {
        if let Some(target) = export_target_for_subpath(exports, subpath.as_deref()) {
            if let Some(path) = resolve_package_target(package_root, &target) {
                return Some(path);
            }
        }
    }

    if subpath.is_none() {
        for field in ["module", "main"] {
            if let Some(target) = package_json.get(field).and_then(Value::as_str) {
                if let Some(path) = resolve_package_target(package_root, target) {
                    return Some(path);
                }
            }
        }
    }

    resolve_package_fallback(package_root, subpath.as_deref())
}

fn export_target_for_subpath(exports: &Value, subpath: Option<&str>) -> Option<String> {
    let key = subpath
        .map(|value| format!("./{value}"))
        .unwrap_or_else(|| ".".to_string());

    match exports {
        Value::String(target) if key == "." => Some(target.clone()),
        Value::Object(map) => {
            if let Some(target) = map.get(&key).and_then(export_condition_target) {
                return Some(target);
            }

            if let Some(target) = wildcard_export_target(map, &key) {
                return Some(target);
            }

            if key == "." && !map.contains_key(".") && !map.keys().any(|k| k.starts_with("./")) {
                return export_condition_target(exports);
            }

            None
        }
        _ => None,
    }
}

fn wildcard_export_target(map: &serde_json::Map<String, Value>, key: &str) -> Option<String> {
    for (pattern, target) in map {
        let Some(star_index) = pattern.find('*') else {
            continue;
        };
        let (prefix, suffix_with_star) = pattern.split_at(star_index);
        let suffix = &suffix_with_star[1..];
        if !key.starts_with(prefix) || !key.ends_with(suffix) {
            continue;
        }
        let matched = &key[prefix.len()..key.len() - suffix.len()];
        if let Some(target_pattern) = export_condition_target(target) {
            return Some(target_pattern.replace('*', matched));
        }
    }
    None
}

fn export_condition_target(value: &Value) -> Option<String> {
    match value {
        Value::String(target) => Some(target.clone()),
        Value::Object(map) => ["source", "import", "module", "default", "types"]
            .into_iter()
            .find_map(|field| map.get(field).and_then(export_condition_target)),
        _ => None,
    }
}

fn resolve_package_target(package_root: &Path, target: &str) -> Option<PathBuf> {
    let target = target.strip_prefix("./").unwrap_or(target);
    // Prefer source over compiled bundle when both exist: the callgraph
    // walks source files and cannot extract symbols from a built JS bundle.
    if let Some(src_relative) = target.strip_prefix("dist/") {
        if let Some(path) = resolve_file_like_path(&package_root.join("src").join(src_relative)) {
            return Some(path);
        }
    }

    resolve_file_like_path(&package_root.join(target))
}

fn resolve_package_fallback(package_root: &Path, subpath: Option<&str>) -> Option<PathBuf> {
    match subpath {
        Some(subpath) => resolve_file_like_path(&package_root.join(subpath))
            .or_else(|| resolve_file_like_path(&package_root.join("src").join(subpath))),
        None => resolve_file_like_path(&package_root.join("src").join("index"))
            .or_else(|| resolve_file_like_path(&package_root.join("index"))),
    }
}

pub(crate) fn resolve_reexported_symbol_target<F, D>(
    file: &Path,
    symbol_name: &str,
    file_exports_symbol: &mut F,
    file_default_export_symbol: &mut D,
) -> Option<(PathBuf, String)>
where
    F: FnMut(&Path, &str) -> bool,
    D: FnMut(&Path) -> Option<String>,
{
    resolve_reexported_symbol(
        file,
        symbol_name,
        file_exports_symbol,
        file_default_export_symbol,
    )
    .map(|target| (target.file, target.symbol))
}

fn resolve_reexported_symbol<F, D>(
    file: &Path,
    symbol_name: &str,
    file_exports_symbol: &mut F,
    file_default_export_symbol: &mut D,
) -> Option<ResolvedSymbol>
where
    F: FnMut(&Path, &str) -> bool,
    D: FnMut(&Path) -> Option<String>,
{
    let mut visited = HashSet::new();
    resolve_reexported_symbol_inner(
        file,
        symbol_name,
        file_exports_symbol,
        file_default_export_symbol,
        &mut visited,
    )
}

fn resolve_reexported_symbol_inner<F, D>(
    file: &Path,
    symbol_name: &str,
    file_exports_symbol: &mut F,
    file_default_export_symbol: &mut D,
    visited: &mut HashSet<(PathBuf, String)>,
) -> Option<ResolvedSymbol>
where
    F: FnMut(&Path, &str) -> bool,
    D: FnMut(&Path) -> Option<String>,
{
    let canon = std::fs::canonicalize(file).unwrap_or_else(|_| file.to_path_buf());
    if !visited.insert((canon.clone(), symbol_name.to_string())) {
        return None;
    }

    let source = std::fs::read_to_string(&canon).ok()?;
    let lang = detect_language(&canon)?;
    if !matches!(lang, LangId::TypeScript | LangId::Tsx | LangId::JavaScript) {
        if symbol_name == "default" {
            return file_default_export_symbol(&canon).map(|symbol| ResolvedSymbol {
                file: canon,
                symbol,
            });
        }
        return file_exports_symbol(&canon, symbol_name).then(|| ResolvedSymbol {
            file: canon,
            symbol: symbol_name.to_string(),
        });
    }

    let grammar = grammar_for(lang);
    let mut parser = Parser::new();
    parser.set_language(&grammar).ok()?;
    let tree = parser.parse(&source, None)?;
    let from_dir = canon.parent().unwrap_or_else(|| Path::new("."));

    let mut cursor = tree.root_node().walk();
    if !cursor.goto_first_child() {
        return None;
    }

    loop {
        let node = cursor.node();
        if node.kind() == "export_statement" {
            if let Some(target) = resolve_reexport_statement(
                &source,
                node,
                from_dir,
                symbol_name,
                file_exports_symbol,
                file_default_export_symbol,
                visited,
            ) {
                return Some(target);
            }
        }

        if !cursor.goto_next_sibling() {
            break;
        }
    }

    if symbol_name == "default" {
        if let Some(symbol) = file_default_export_symbol(&canon) {
            return Some(ResolvedSymbol {
                file: canon,
                symbol,
            });
        }
    }

    if let Some(symbol) = resolve_local_export_alias(&source, &canon, symbol_name) {
        return Some(ResolvedSymbol {
            file: canon,
            symbol,
        });
    }

    if file_exports_symbol(&canon, symbol_name) {
        let symbol = symbol_name.to_string();
        return Some(ResolvedSymbol {
            file: canon,
            symbol,
        });
    }

    None
}

fn resolve_reexport_statement<F, D>(
    source: &str,
    node: tree_sitter::Node,
    from_dir: &Path,
    symbol_name: &str,
    file_exports_symbol: &mut F,
    file_default_export_symbol: &mut D,
    visited: &mut HashSet<(PathBuf, String)>,
) -> Option<ResolvedSymbol>
where
    F: FnMut(&Path, &str) -> bool,
    D: FnMut(&Path) -> Option<String>,
{
    let source_node = node
        .child_by_field_name("source")
        .or_else(|| find_child_by_kind(node, "string"))?;
    let module_path = string_literal_content(source, source_node)?;
    let target_file = resolve_module_path(from_dir, &module_path)?;
    let raw_export = node_text(node, source);

    if let Some(source_symbol) = reexport_clause_source_symbol(&raw_export, symbol_name) {
        return resolve_reexported_symbol_inner(
            &target_file,
            &source_symbol,
            file_exports_symbol,
            file_default_export_symbol,
            visited,
        )
        .or(Some(ResolvedSymbol {
            file: target_file,
            symbol: source_symbol,
        }));
    }

    if raw_export.contains('*') {
        return resolve_reexported_symbol_inner(
            &target_file,
            symbol_name,
            file_exports_symbol,
            file_default_export_symbol,
            visited,
        );
    }

    None
}

fn resolve_local_export_alias(source: &str, file: &Path, requested_export: &str) -> Option<String> {
    let lang = detect_language(file)?;
    let grammar = grammar_for(lang);
    let mut parser = Parser::new();
    parser.set_language(&grammar).ok()?;
    let tree = parser.parse(source, None)?;

    let mut cursor = tree.root_node().walk();
    if !cursor.goto_first_child() {
        return None;
    }

    loop {
        let node = cursor.node();
        if node.kind() == "export_statement" && node.child_by_field_name("source").is_none() {
            let raw_export = node_text(node, source);
            if let Some(source_symbol) =
                reexport_clause_source_symbol(&raw_export, requested_export)
            {
                return Some(source_symbol);
            }
        }

        if !cursor.goto_next_sibling() {
            break;
        }
    }

    None
}

fn reexport_clause_source_symbol(raw_export: &str, requested_export: &str) -> Option<String> {
    let start = raw_export.find('{')? + 1;
    let end = raw_export[start..].find('}')? + start;
    for specifier in raw_export[start..end].split(',') {
        let specifier = specifier.trim();
        if specifier.is_empty() {
            continue;
        }
        let specifier = specifier.strip_prefix("type ").unwrap_or(specifier).trim();
        if let Some((imported, exported)) = specifier.split_once(" as ") {
            if exported.trim() == requested_export {
                return Some(imported.trim().to_string());
            }
        } else if specifier == requested_export {
            return Some(requested_export.to_string());
        }
    }
    None
}

fn string_literal_content(source: &str, node: tree_sitter::Node) -> Option<String> {
    let raw = source[node.byte_range()].trim();
    let quote = raw.chars().next()?;
    if quote != '\'' && quote != '"' {
        return None;
    }
    raw.strip_prefix(quote)
        .and_then(|value| value.strip_suffix(quote))
        .map(ToOwned::to_owned)
}

/// Find an index file in a directory.
fn find_index_file(dir: &Path) -> Option<PathBuf> {
    for name in JS_TS_INDEX_FILES {
        let p = dir.join(name);
        if p.is_file() {
            return Some(std::fs::canonicalize(&p).unwrap_or(p));
        }
    }
    None
}

/// Resolve an aliased import: `import { foo as bar } from './utils'`
/// where `local_name` is "bar". Returns `(original_name, resolved_file_path)`.
fn resolve_aliased_import(
    local_name: &str,
    import_block: &ImportBlock,
    caller_dir: &Path,
) -> Option<(String, PathBuf)> {
    for imp in &import_block.imports {
        // Parse the raw text to find "as <alias>" patterns
        // This handles: import { foo as bar, baz as qux } from './mod'
        if let Some(original) = find_alias_original(&imp.raw_text, local_name) {
            if let Some(resolved_path) = resolve_module_path(caller_dir, &imp.module_path) {
                return Some((original, resolved_path));
            }
        }
    }
    None
}

/// Parse import raw text to find the original name for an alias.
/// Given raw text like `import { foo as bar, baz } from './utils'` and
/// local_name "bar", returns Some("foo").
fn find_alias_original(raw_import: &str, local_name: &str) -> Option<String> {
    // Look for pattern: <original> as <alias>
    // This is a simple text-based search; handles the common TS/JS pattern
    let search = format!(" as {}", local_name);
    if let Some(pos) = raw_import.find(&search) {
        // Walk backwards from `pos` to find the original name
        let before = &raw_import[..pos];
        // The original name is the last word-like token before " as "
        let original = before
            .rsplit(|c: char| c == '{' || c == ',' || c.is_whitespace())
            .find(|s| !s.is_empty())?;
        return Some(original.to_string());
    }
    None
}

// ---------------------------------------------------------------------------
// Worktree file discovery
// ---------------------------------------------------------------------------

/// Walk project files respecting .gitignore, excluding common non-source dirs.
///
/// Returns an iterator of file paths for supported source file types.
pub fn walk_project_files(root: &Path) -> impl Iterator<Item = PathBuf> {
    use ignore::WalkBuilder;

    let walker = WalkBuilder::new(root)
        .hidden(true)         // skip hidden files/dirs
        .git_ignore(true)     // respect .gitignore
        .git_global(true)     // respect global gitignore
        .git_exclude(true)    // respect .git/info/exclude
        .add_custom_ignore_filename(".aftignore") // AFT-specific ignores (e.g. submodules)
        .filter_entry(|entry| {
            let name = entry.file_name().to_string_lossy();
            // Always exclude these directories regardless of .gitignore
            if entry.file_type().map_or(false, |ft| ft.is_dir()) {
                return !matches!(
                    name.as_ref(),
                    "node_modules" | "target" | "venv" | ".venv" | ".git" | "__pycache__"
                        | ".tox" | "dist" | "build"
                );
            }
            true
        })
        .build();

    walker
        .filter_map(|entry| entry.ok())
        .filter(|entry| entry.file_type().map_or(false, |ft| ft.is_file()))
        .filter(|entry| detect_language(entry.path()).is_some())
        .map(|entry| entry.into_path())
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn symbol_metadata_for_recovers_scoped_method_by_bare_name() {
        // exported_symbols carries the bare name; symbol_metadata is keyed by
        // scoped identity (impl method). A plain .get(bare) misses and would
        // force the degraded unknown/line-1 fallback. symbol_metadata_for must
        // recover the scoped entry via unqualified-name match.
        let mut symbol_metadata = HashMap::new();
        symbol_metadata.insert(
            "BackupStore::total_disk_bytes".to_string(),
            SymbolMeta {
                kind: SymbolKind::Method,
                exported: true,
                signature: None,
                line: 703,
                range: Range {
                    start_line: 702,
                    start_col: 0,
                    end_line: 705,
                    end_col: 0,
                },
            },
        );
        let file_data = FileCallData {
            calls_by_symbol: HashMap::new(),
            exported_symbols: vec!["total_disk_bytes".to_string()],
            symbol_metadata,
            default_export_symbol: None,
            import_block: ImportBlock::empty(),
            lang: LangId::Rust,
        };

        let meta = file_data
            .symbol_metadata_for("total_disk_bytes")
            .expect("scoped method recovered by bare name");
        assert_eq!(meta.kind, SymbolKind::Method);
        assert_eq!(
            meta.line, 703,
            "real declaration line, not the line-1 fallback"
        );

        // A genuinely-absent symbol still returns None (no false recovery).
        assert!(file_data.symbol_metadata_for("does_not_exist").is_none());
    }

    /// Create a temp directory with TypeScript files for testing.
    fn setup_ts_project() -> TempDir {
        let dir = TempDir::new().unwrap();

        // main.ts: imports from utils and calls functions
        fs::write(
            dir.path().join("main.ts"),
            r#"import { helper, compute } from './utils';
import * as math from './math';

export function main() {
    const a = helper(1);
    const b = compute(a, 2);
    const c = math.add(a, b);
    return c;
}
"#,
        )
        .unwrap();

        // utils.ts: defines helper and compute, imports from helpers
        fs::write(
            dir.path().join("utils.ts"),
            r#"import { double } from './helpers';

export function helper(x: number): number {
    return double(x);
}

export function compute(a: number, b: number): number {
    return a + b;
}
"#,
        )
        .unwrap();

        // helpers.ts: defines double
        fs::write(
            dir.path().join("helpers.ts"),
            r#"export function double(x: number): number {
    return x * 2;
}

export function triple(x: number): number {
    return x * 3;
}
"#,
        )
        .unwrap();

        // math.ts: defines add (for namespace import test)
        fs::write(
            dir.path().join("math.ts"),
            r#"export function add(a: number, b: number): number {
    return a + b;
}

export function subtract(a: number, b: number): number {
    return a - b;
}
"#,
        )
        .unwrap();

        dir
    }

    /// Create a project with import aliasing.
    fn setup_alias_project() -> TempDir {
        let dir = TempDir::new().unwrap();

        fs::write(
            dir.path().join("main.ts"),
            r#"import { helper as h } from './utils';

export function main() {
    return h(42);
}
"#,
        )
        .unwrap();

        fs::write(
            dir.path().join("utils.ts"),
            r#"export function helper(x: number): number {
    return x + 1;
}
"#,
        )
        .unwrap();

        dir
    }

    // --- Single-file call extraction ---

    #[test]
    fn callgraph_single_file_call_extraction() {
        let dir = setup_ts_project();
        let mut graph = CallGraph::new(dir.path().to_path_buf());

        let file_data = graph.build_file(&dir.path().join("main.ts")).unwrap();
        let main_calls = &file_data.calls_by_symbol["main"];

        let callee_names: Vec<&str> = main_calls.iter().map(|c| c.callee_name.as_str()).collect();
        assert!(
            callee_names.contains(&"helper"),
            "main should call helper, got: {:?}",
            callee_names
        );
        assert!(
            callee_names.contains(&"compute"),
            "main should call compute, got: {:?}",
            callee_names
        );
        assert!(
            callee_names.contains(&"add"),
            "main should call math.add (short name: add), got: {:?}",
            callee_names
        );
    }

    #[test]
    fn callgraph_file_data_has_exports() {
        let dir = setup_ts_project();
        let mut graph = CallGraph::new(dir.path().to_path_buf());

        let file_data = graph.build_file(&dir.path().join("utils.ts")).unwrap();
        assert!(
            file_data.exported_symbols.contains(&"helper".to_string()),
            "utils.ts should export helper, got: {:?}",
            file_data.exported_symbols
        );
        assert!(
            file_data.exported_symbols.contains(&"compute".to_string()),
            "utils.ts should export compute, got: {:?}",
            file_data.exported_symbols
        );
    }

    // --- Cross-file resolution ---

    #[test]
    fn callgraph_resolve_direct_import() {
        let dir = setup_ts_project();
        let mut graph = CallGraph::new(dir.path().to_path_buf());

        let main_path = dir.path().join("main.ts");
        let file_data = graph.build_file(&main_path).unwrap();
        let import_block = file_data.import_block.clone();

        let edge = graph.resolve_cross_file_edge("helper", "helper", &main_path, &import_block);
        match edge {
            EdgeResolution::Resolved { file, symbol } => {
                assert!(
                    file.ends_with("utils.ts"),
                    "helper should resolve to utils.ts, got: {:?}",
                    file
                );
                assert_eq!(symbol, "helper");
            }
            EdgeResolution::Unresolved { callee_name } => {
                panic!("Expected resolved, got unresolved: {}", callee_name);
            }
        }
    }

    #[test]
    fn callgraph_resolve_namespace_import() {
        let dir = setup_ts_project();
        let mut graph = CallGraph::new(dir.path().to_path_buf());

        let main_path = dir.path().join("main.ts");
        let file_data = graph.build_file(&main_path).unwrap();
        let import_block = file_data.import_block.clone();

        let edge = graph.resolve_cross_file_edge("math.add", "add", &main_path, &import_block);
        match edge {
            EdgeResolution::Resolved { file, symbol } => {
                assert!(
                    file.ends_with("math.ts"),
                    "math.add should resolve to math.ts, got: {:?}",
                    file
                );
                assert_eq!(symbol, "add");
            }
            EdgeResolution::Unresolved { callee_name } => {
                panic!("Expected resolved, got unresolved: {}", callee_name);
            }
        }
    }

    #[test]
    fn callgraph_resolve_aliased_import() {
        let dir = setup_alias_project();
        let mut graph = CallGraph::new(dir.path().to_path_buf());

        let main_path = dir.path().join("main.ts");
        let file_data = graph.build_file(&main_path).unwrap();
        let import_block = file_data.import_block.clone();

        let edge = graph.resolve_cross_file_edge("h", "h", &main_path, &import_block);
        match edge {
            EdgeResolution::Resolved { file, symbol } => {
                assert!(
                    file.ends_with("utils.ts"),
                    "h (alias for helper) should resolve to utils.ts, got: {:?}",
                    file
                );
                assert_eq!(symbol, "helper");
            }
            EdgeResolution::Unresolved { callee_name } => {
                panic!("Expected resolved, got unresolved: {}", callee_name);
            }
        }
    }

    #[test]
    fn callgraph_unresolved_edge_marked() {
        let dir = setup_ts_project();
        let mut graph = CallGraph::new(dir.path().to_path_buf());

        let main_path = dir.path().join("main.ts");
        let file_data = graph.build_file(&main_path).unwrap();
        let import_block = file_data.import_block.clone();

        let edge =
            graph.resolve_cross_file_edge("unknownFunc", "unknownFunc", &main_path, &import_block);
        assert_eq!(
            edge,
            EdgeResolution::Unresolved {
                callee_name: "unknownFunc".to_string()
            },
            "Unknown callee should be unresolved"
        );
    }

    // --- Worktree walker ---

    #[test]
    fn callgraph_walker_excludes_gitignored() {
        let dir = TempDir::new().unwrap();

        // Create a .gitignore
        fs::write(dir.path().join(".gitignore"), "ignored_dir/\n").unwrap();

        // Create files
        fs::write(dir.path().join("main.ts"), "export function main() {}").unwrap();
        fs::create_dir(dir.path().join("ignored_dir")).unwrap();
        fs::write(
            dir.path().join("ignored_dir").join("secret.ts"),
            "export function secret() {}",
        )
        .unwrap();

        // Also create node_modules (should always be excluded)
        fs::create_dir(dir.path().join("node_modules")).unwrap();
        fs::write(
            dir.path().join("node_modules").join("dep.ts"),
            "export function dep() {}",
        )
        .unwrap();

        // Init git repo for .gitignore to work
        std::process::Command::new("git")
            .args(["init"])
            .current_dir(dir.path())
            .output()
            .unwrap();

        let files: Vec<PathBuf> = walk_project_files(dir.path()).collect();
        let file_names: Vec<String> = files
            .iter()
            .map(|f| f.file_name().unwrap().to_string_lossy().to_string())
            .collect();

        assert!(
            file_names.contains(&"main.ts".to_string()),
            "Should include main.ts, got: {:?}",
            file_names
        );
        assert!(
            !file_names.contains(&"secret.ts".to_string()),
            "Should exclude gitignored secret.ts, got: {:?}",
            file_names
        );
        assert!(
            !file_names.contains(&"dep.ts".to_string()),
            "Should exclude node_modules, got: {:?}",
            file_names
        );
    }

    #[test]
    fn callgraph_walker_excludes_aftignored() {
        let dir = TempDir::new().unwrap();

        // .aftignore is honored without a git repo (custom ignore file).
        fs::write(dir.path().join(".aftignore"), "vendored/\n").unwrap();
        fs::write(dir.path().join("main.ts"), "export function main() {}").unwrap();
        fs::create_dir(dir.path().join("vendored")).unwrap();
        fs::write(
            dir.path().join("vendored").join("sub.ts"),
            "export function sub() {}",
        )
        .unwrap();

        let files: Vec<PathBuf> = walk_project_files(dir.path()).collect();
        let file_names: Vec<String> = files
            .iter()
            .map(|f| f.file_name().unwrap().to_string_lossy().to_string())
            .collect();

        assert!(
            file_names.contains(&"main.ts".to_string()),
            "Should include main.ts, got: {:?}",
            file_names
        );
        assert!(
            !file_names.contains(&"sub.ts".to_string()),
            "Should exclude .aftignored sub.ts, got: {:?}",
            file_names
        );
    }

    #[test]
    fn callgraph_walker_only_source_files() {
        let dir = TempDir::new().unwrap();

        fs::write(dir.path().join("main.ts"), "export function main() {}").unwrap();
        fs::write(dir.path().join("module.mts"), "export function esm() {}").unwrap();
        fs::write(dir.path().join("common.cts"), "export function cjs() {}").unwrap();
        fs::write(
            dir.path().join("runtime.mjs"),
            "export function runtime() {}",
        )
        .unwrap();
        fs::write(
            dir.path().join("legacy.cjs"),
            "exports.legacy = function() {};",
        )
        .unwrap();
        fs::write(dir.path().join("types.pyi"), "def typed() -> None: ...").unwrap();
        fs::write(dir.path().join("readme.md"), "# Hello").unwrap();
        fs::write(dir.path().join("data.json"), "{}").unwrap();

        let files: Vec<PathBuf> = walk_project_files(dir.path()).collect();
        let file_names: Vec<String> = files
            .iter()
            .map(|f| f.file_name().unwrap().to_string_lossy().to_string())
            .collect();

        assert!(file_names.contains(&"main.ts".to_string()));
        for modern_ext_file in [
            "module.mts",
            "common.cts",
            "runtime.mjs",
            "legacy.cjs",
            "types.pyi",
        ] {
            assert!(
                file_names.contains(&modern_ext_file.to_string()),
                "walker should include {modern_ext_file}, got: {:?}",
                file_names
            );
        }
        assert!(
            file_names.contains(&"readme.md".to_string()),
            "Markdown is now a supported source language"
        );
        assert!(
            file_names.contains(&"data.json".to_string()),
            "JSON is now a supported source language"
        );
    }

    // --- find_alias_original ---

    #[test]
    fn callgraph_find_alias_original_simple() {
        let raw = "import { foo as bar } from './utils';";
        assert_eq!(find_alias_original(raw, "bar"), Some("foo".to_string()));
    }

    #[test]
    fn callgraph_find_alias_original_multiple() {
        let raw = "import { foo as bar, baz as qux } from './utils';";
        assert_eq!(find_alias_original(raw, "bar"), Some("foo".to_string()));
        assert_eq!(find_alias_original(raw, "qux"), Some("baz".to_string()));
    }

    #[test]
    fn callgraph_find_alias_no_match() {
        let raw = "import { foo } from './utils';";
        assert_eq!(find_alias_original(raw, "foo"), None);
    }

    // --- Reverse callers ---

    #[test]
    fn is_entry_point_exported_function() {
        assert!(is_entry_point(
            "handleRequest",
            &SymbolKind::Function,
            true,
            LangId::TypeScript
        ));
    }

    #[test]
    fn is_entry_point_exported_method_is_not_entry() {
        // Methods are class members, not standalone entry points
        assert!(!is_entry_point(
            "handleRequest",
            &SymbolKind::Method,
            true,
            LangId::TypeScript
        ));
    }

    #[test]
    fn is_entry_point_main_init_patterns() {
        for name in &["main", "Main", "MAIN", "init", "setup", "bootstrap", "run"] {
            assert!(
                is_entry_point(name, &SymbolKind::Function, false, LangId::TypeScript),
                "{} should be an entry point",
                name
            );
        }
    }

    #[test]
    fn is_entry_point_test_patterns_ts() {
        assert!(is_entry_point(
            "describe",
            &SymbolKind::Function,
            false,
            LangId::TypeScript
        ));
        assert!(is_entry_point(
            "it",
            &SymbolKind::Function,
            false,
            LangId::TypeScript
        ));
        assert!(is_entry_point(
            "test",
            &SymbolKind::Function,
            false,
            LangId::TypeScript
        ));
        assert!(is_entry_point(
            "testValidation",
            &SymbolKind::Function,
            false,
            LangId::TypeScript
        ));
        assert!(is_entry_point(
            "specHelper",
            &SymbolKind::Function,
            false,
            LangId::TypeScript
        ));
    }

    #[test]
    fn is_entry_point_test_patterns_python() {
        assert!(is_entry_point(
            "test_login",
            &SymbolKind::Function,
            false,
            LangId::Python
        ));
        assert!(is_entry_point(
            "setUp",
            &SymbolKind::Function,
            false,
            LangId::Python
        ));
        assert!(is_entry_point(
            "tearDown",
            &SymbolKind::Function,
            false,
            LangId::Python
        ));
        // "testSomething" should NOT match Python (needs test_ prefix)
        assert!(!is_entry_point(
            "testSomething",
            &SymbolKind::Function,
            false,
            LangId::Python
        ));
    }

    #[test]
    fn is_entry_point_test_patterns_rust() {
        assert!(is_entry_point(
            "test_parse",
            &SymbolKind::Function,
            false,
            LangId::Rust
        ));
        assert!(!is_entry_point(
            "TestSomething",
            &SymbolKind::Function,
            false,
            LangId::Rust
        ));
    }

    #[test]
    fn is_entry_point_test_patterns_go() {
        assert!(is_entry_point(
            "TestParsing",
            &SymbolKind::Function,
            false,
            LangId::Go
        ));
        // lowercase test should NOT match Go (needs uppercase Test prefix)
        assert!(!is_entry_point(
            "testParsing",
            &SymbolKind::Function,
            false,
            LangId::Go
        ));
    }

    #[test]
    fn is_entry_point_non_exported_non_main_is_not_entry() {
        assert!(!is_entry_point(
            "helperUtil",
            &SymbolKind::Function,
            false,
            LangId::TypeScript
        ));
    }

    // --- symbol_metadata ---

    #[test]
    fn callgraph_symbol_metadata_populated() {
        let dir = setup_ts_project();
        let mut graph = CallGraph::new(dir.path().to_path_buf());

        let file_data = graph.build_file(&dir.path().join("utils.ts")).unwrap();
        assert!(
            file_data.symbol_metadata.contains_key("helper"),
            "symbol_metadata should contain helper"
        );
        let meta = &file_data.symbol_metadata["helper"];
        assert_eq!(meta.kind, SymbolKind::Function);
        assert!(meta.exported, "helper should be exported");
    }

    #[test]
    fn namespace_import_follows_barrel_reexport_and_rejects_private_member() {
        let dir = TempDir::new().unwrap();
        fs::write(
            dir.path().join("main.ts"),
            r#"import * as lib from './index';

export function main() {
    lib.helper();
    lib.hidden();
}
"#,
        )
        .unwrap();
        fs::write(
            dir.path().join("index.ts"),
            "export { helper } from './utils';\n",
        )
        .unwrap();
        fs::write(
            dir.path().join("utils.ts"),
            r#"export function helper() {}
function hidden() {}
"#,
        )
        .unwrap();

        let mut graph = CallGraph::new(dir.path().to_path_buf());
        let main_path = dir.path().join("main.ts");
        let import_block = graph.build_file(&main_path).unwrap().import_block.clone();

        let helper =
            graph.resolve_cross_file_edge("lib.helper", "helper", &main_path, &import_block);
        match helper {
            EdgeResolution::Resolved { file, symbol } => {
                assert!(
                    file.ends_with("utils.ts"),
                    "helper should resolve through barrel: {file:?}"
                );
                assert_eq!(symbol, "helper");
            }
            other => panic!("expected helper to resolve through barrel, got {other:?}"),
        }

        let hidden =
            graph.resolve_cross_file_edge("lib.hidden", "hidden", &main_path, &import_block);
        assert_eq!(
            hidden,
            EdgeResolution::Unresolved {
                callee_name: "hidden".to_string()
            }
        );
    }

    #[test]
    fn workspace_package_resolution_prefers_modern_ts_source_extensions() {
        let dir = TempDir::new().unwrap();
        fs::write(
            dir.path().join("package.json"),
            r#"{"workspaces":["packages/*"]}"#,
        )
        .unwrap();
        let package_dir = dir.path().join("packages/lib");
        fs::create_dir_all(package_dir.join("src")).unwrap();
        fs::create_dir_all(package_dir.join("dist")).unwrap();
        fs::write(
            package_dir.join("package.json"),
            r#"{"name":"@scope/lib","exports":{".":"./dist/index.mjs"}}"#,
        )
        .unwrap();
        fs::write(
            package_dir.join("src/index.mts"),
            "export function helper() {}\n",
        )
        .unwrap();
        fs::write(package_dir.join("dist/index.mjs"), "export{};\n").unwrap();

        let resolved = resolve_module_path(dir.path(), "@scope/lib").unwrap();
        assert!(
            resolved.ends_with("src/index.mts"),
            "dist/index.mjs should map to src/index.mts, got {resolved:?}"
        );
    }

    #[test]
    fn same_named_methods_use_scoped_symbol_identity() {
        let dir = TempDir::new().unwrap();
        fs::write(
            dir.path().join("classes.ts"),
            r#"class A {
    run() { helperA(); }
}

class B {
    run() { helperB(); }
}

function helperA() {}
function helperB() {}
"#,
        )
        .unwrap();

        let mut graph = CallGraph::new(dir.path().to_path_buf());
        let path = dir.path().join("classes.ts");
        let data = graph.build_file(&path).unwrap();

        assert!(
            data.symbol_metadata.contains_key("A::run"),
            "A::run metadata missing"
        );
        assert!(
            data.symbol_metadata.contains_key("B::run"),
            "B::run metadata missing"
        );
        assert!(
            data.calls_by_symbol["A::run"]
                .iter()
                .any(|call| call.callee_name == "helperA"),
            "A::run calls should not be overwritten"
        );
        assert!(
            data.calls_by_symbol["B::run"]
                .iter()
                .any(|call| call.callee_name == "helperB"),
            "B::run calls should not be overwritten"
        );

        assert!(matches!(
            graph.resolve_symbol_query(&path, "run"),
            Err(AftError::AmbiguousSymbol { .. })
        ));
        assert_eq!(
            graph.resolve_symbol_query(&path, "A::run").unwrap(),
            "A::run"
        );
    }

    // --- extract_parameters ---

    #[test]
    fn extract_parameters_typescript() {
        let params = extract_parameters(
            "function processData(input: string, count: number): void",
            LangId::TypeScript,
        );
        assert_eq!(params, vec!["input", "count"]);
    }

    #[test]
    fn extract_parameters_typescript_optional() {
        let params = extract_parameters(
            "function fetch(url: string, options?: RequestInit): Promise<Response>",
            LangId::TypeScript,
        );
        assert_eq!(params, vec!["url", "options"]);
    }

    #[test]
    fn extract_parameters_typescript_defaults() {
        let params = extract_parameters(
            "function greet(name: string, greeting: string = \"hello\"): string",
            LangId::TypeScript,
        );
        assert_eq!(params, vec!["name", "greeting"]);
    }

    #[test]
    fn extract_parameters_typescript_rest() {
        let params = extract_parameters(
            "function sum(...numbers: number[]): number",
            LangId::TypeScript,
        );
        assert_eq!(params, vec!["numbers"]);
    }

    #[test]
    fn extract_parameters_python_self_skipped() {
        let params = extract_parameters(
            "def process(self, data: str, count: int) -> bool",
            LangId::Python,
        );
        assert_eq!(params, vec!["data", "count"]);
    }

    #[test]
    fn extract_parameters_python_no_self() {
        let params = extract_parameters("def validate(input: str) -> bool", LangId::Python);
        assert_eq!(params, vec!["input"]);
    }

    #[test]
    fn extract_parameters_python_star_args() {
        let params = extract_parameters("def func(*args, **kwargs)", LangId::Python);
        assert_eq!(params, vec!["args", "kwargs"]);
    }

    #[test]
    fn extract_parameters_rust_self_skipped() {
        let params = extract_parameters(
            "fn process(&self, data: &str, count: usize) -> bool",
            LangId::Rust,
        );
        assert_eq!(params, vec!["data", "count"]);
    }

    #[test]
    fn extract_parameters_rust_mut_self_skipped() {
        let params = extract_parameters("fn update(&mut self, value: i32)", LangId::Rust);
        assert_eq!(params, vec!["value"]);
    }

    #[test]
    fn extract_parameters_rust_no_self() {
        let params = extract_parameters("fn validate(input: &str) -> bool", LangId::Rust);
        assert_eq!(params, vec!["input"]);
    }

    #[test]
    fn extract_parameters_rust_mut_param() {
        let params = extract_parameters("fn process(mut buf: Vec<u8>, len: usize)", LangId::Rust);
        assert_eq!(params, vec!["buf", "len"]);
    }

    #[test]
    fn extract_parameters_go() {
        let params = extract_parameters(
            "func ProcessData(input string, count int) error",
            LangId::Go,
        );
        assert_eq!(params, vec!["input", "count"]);
    }

    #[test]
    fn extract_parameters_empty() {
        let params = extract_parameters("function noArgs(): void", LangId::TypeScript);
        assert!(
            params.is_empty(),
            "no-arg function should return empty params"
        );
    }

    #[test]
    fn extract_parameters_no_parens() {
        let params = extract_parameters("const x = 42", LangId::TypeScript);
        assert!(params.is_empty(), "no parens should return empty params");
    }

    #[test]
    fn extract_parameters_javascript() {
        let params = extract_parameters("function handleClick(event, target)", LangId::JavaScript);
        assert_eq!(params, vec!["event", "target"]);
    }
}