gid-core 0.2.0

Graph-Indexed Development core library — graph-based project management and 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
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
//! Code Graph Extraction — extract code dependencies from source files
//!
//! Multi-language support with tree-sitter AST parsing for Python, Rust, and TypeScript.
//! Builds a code structure graph:
//! - Nodes: files, classes/structs/traits, functions/methods
//! - Edges: imports, calls, inherits, defined_in
//!
//! Rust extraction handles: structs, enums, traits, impl blocks (with method-type association),
//! functions, modules, type aliases, const/static items, and macros.
//!
//! TypeScript/JavaScript extraction handles: classes, interfaces, functions, arrow functions,
//! enums, type aliases, namespaces, and export statements.

use std::collections::{BinaryHeap, HashMap, HashSet, VecDeque};
use std::path::Path;
use serde::{Deserialize, Serialize};
use regex::Regex;
use walkdir::WalkDir;
use tree_sitter::Parser;

// ═══ Graph Types ═══

/// A code dependency graph extracted from source files.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CodeGraph {
    pub nodes: Vec<CodeNode>,
    pub edges: Vec<CodeEdge>,
    /// Adjacency list: node_id → indices into self.edges (outgoing)
    #[serde(skip)]
    pub outgoing: HashMap<String, Vec<usize>>,
    /// Reverse adjacency list: node_id → indices into self.edges (incoming)
    #[serde(skip)]
    pub incoming: HashMap<String, Vec<usize>>,
    /// Node lookup: node_id → index into self.nodes
    #[serde(skip)]
    pub node_index: HashMap<String, usize>,
}

/// A node in the code graph (file, class, function).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CodeNode {
    pub id: String,
    pub kind: NodeKind,
    pub name: String,
    pub file_path: String,
    pub line: Option<usize>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub decorators: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub signature: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub docstring: Option<String>,
    #[serde(default)]
    pub line_count: usize,
    #[serde(default)]
    pub is_test: bool,
}

impl CodeNode {
    pub fn new_file(path: &str) -> Self {
        Self {
            id: format!("file:{}", path),
            kind: NodeKind::File,
            name: path.rsplit('/').next().unwrap_or(path).to_string(),
            file_path: path.to_string(),
            line: None,
            decorators: Vec::new(),
            signature: None,
            docstring: None,
            line_count: 0,
            is_test: path.contains("/test") || path.contains("_test."),
        }
    }

    pub fn new_class(path: &str, name: &str, line: usize) -> Self {
        Self {
            id: format!("class:{}:{}", path, name),
            kind: NodeKind::Class,
            name: name.to_string(),
            file_path: path.to_string(),
            line: Some(line),
            decorators: Vec::new(),
            signature: None,
            docstring: None,
            line_count: 0,
            is_test: name.starts_with("Test") || path.contains("/test"),
        }
    }

    pub fn new_function(path: &str, name: &str, line: usize, is_method: bool) -> Self {
        let prefix = if is_method { "method" } else { "func" };
        Self {
            id: format!("{}:{}:{}", prefix, path, name),
            kind: NodeKind::Function,
            name: name.to_string(),
            file_path: path.to_string(),
            line: Some(line),
            decorators: Vec::new(),
            signature: None,
            docstring: None,
            line_count: 0,
            is_test: name.starts_with("test_") || name.starts_with("Test") || path.contains("/test"),
        }
    }
}

/// Kind of code node.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum NodeKind {
    File,
    Class,
    Function,
    Module,
}

/// An edge in the code graph.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CodeEdge {
    pub from: String,
    pub to: String,
    pub relation: EdgeRelation,
    #[serde(default)]
    pub weight: f32,
    #[serde(default)]
    pub call_count: u32,
    #[serde(default)]
    pub in_error_path: bool,
    #[serde(default)]
    pub confidence: f32,
}

impl CodeEdge {
    pub fn new(from: &str, to: &str, relation: EdgeRelation) -> Self {
        Self {
            from: from.to_string(),
            to: to.to_string(),
            relation,
            weight: 0.5,
            call_count: 1,
            in_error_path: false,
            confidence: 1.0,
        }
    }

    pub fn imports(from: &str, to: &str) -> Self {
        Self::new(from, to, EdgeRelation::Imports)
    }

    pub fn calls(from: &str, to: &str) -> Self {
        Self::new(from, to, EdgeRelation::Calls)
    }

    pub fn inherits(from: &str, to: &str) -> Self {
        Self::new(from, to, EdgeRelation::Inherits)
    }

    pub fn defined_in(from: &str, to: &str) -> Self {
        Self::new(from, to, EdgeRelation::DefinedIn)
    }

    /// Compute composite weight from call_count, in_error_path, and confidence.
    pub fn compute_weight(&mut self) {
        if self.relation == EdgeRelation::Calls {
            let count_norm = (self.call_count as f32 / 10.0).min(1.0);
            let error_factor = if self.in_error_path { 0.8 } else { 0.5 };
            self.weight = 0.4 * count_norm + 0.3 * error_factor + 0.3 * self.confidence;
        } else {
            self.weight = 0.7; // Default for non-call edges
        }
    }
}

/// Edge relationship type.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EdgeRelation {
    /// File imports module
    Imports,
    /// Class inherits from parent
    Inherits,
    /// Entity is defined in file/class
    DefinedIn,
    /// Function calls another function
    Calls,
    /// Test file tests source file
    TestsFor,
    /// Method overrides parent method
    Overrides,
}

impl std::fmt::Display for EdgeRelation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            EdgeRelation::Imports => write!(f, "imports"),
            EdgeRelation::Inherits => write!(f, "inherits"),
            EdgeRelation::DefinedIn => write!(f, "defined_in"),
            EdgeRelation::Calls => write!(f, "calls"),
            EdgeRelation::TestsFor => write!(f, "tests_for"),
            EdgeRelation::Overrides => write!(f, "overrides"),
        }
    }
}

// ═══ Impact Analysis Types ═══

/// Result of impact analysis — what's affected by a change
#[derive(Debug)]
pub struct ImpactReport<'a> {
    pub affected_source: Vec<&'a CodeNode>,
    pub affected_tests: Vec<&'a CodeNode>,
}

/// A causal chain from symptom to potential root cause
#[derive(Debug, Clone)]
pub struct CausalChain {
    pub symptom_node_id: String,
    pub chain: Vec<ChainNode>,
}

#[derive(Debug, Clone)]
pub struct ChainNode {
    pub node_id: String,
    pub node_name: String,
    pub file_path: String,
    pub line: Option<usize>,
    pub edge_to_next: Option<String>,
}

// ═══ Language Detection ═══

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Language {
    Rust,
    TypeScript,
    Python,
    Unknown,
}

impl Language {
    pub fn from_path(path: &Path) -> Self {
        let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
        match ext {
            "rs" => Language::Rust,
            "ts" | "tsx" => Language::TypeScript,
            "js" | "jsx" => Language::TypeScript, // JS uses same patterns
            "py" => Language::Python,
            _ => Language::Unknown,
        }
    }
}

// ═══ Extraction ═══

impl CodeGraph {
    /// Extract with per-repo cache. Cache key = repo_name + base_commit.
    /// If a cached graph exists on disk, returns it instantly.
    /// Otherwise extracts fresh and saves to cache.
    pub fn extract_cached(repo_dir: &Path, repo_name: &str, base_commit: &str) -> Self {
        let cache_dir = repo_dir.parent().unwrap_or(repo_dir).join(".graph-cache");
        let _ = std::fs::create_dir_all(&cache_dir);

        // Cache key: sanitized repo name + first 8 chars of commit
        let safe_repo = repo_name.replace('/', "__");
        let short_commit = &base_commit[..base_commit.len().min(8)];
        let cache_file = cache_dir.join(format!("{}__{}.json", safe_repo, short_commit));

        // Try to load from cache
        if cache_file.exists() {
            if let Ok(data) = std::fs::read_to_string(&cache_file) {
                if let Ok(mut graph) = serde_json::from_str::<CodeGraph>(&data) {
                    graph.build_indexes();
                    tracing::info!(
                        "Loaded code graph from cache: {} ({} nodes, {} edges)",
                        cache_file.display(),
                        graph.nodes.len(),
                        graph.edges.len()
                    );
                    return graph;
                }
            }
            // Cache corrupt, delete and re-extract
            let _ = std::fs::remove_file(&cache_file);
        }

        // Extract fresh
        let graph = Self::extract_from_dir(repo_dir);

        // Save to cache (best-effort, don't fail if write fails)
        if let Ok(json) = serde_json::to_string(&graph) {
            let _ = std::fs::write(&cache_file, json);
            tracing::info!(
                "Saved code graph to cache: {} ({} nodes, {} edges)",
                cache_file.display(),
                graph.nodes.len(),
                graph.edges.len()
            );
        }

        graph
    }

    /// Extract code graph from a directory.
    pub fn extract_from_dir(dir: &Path) -> Self {
        let mut nodes = Vec::new();
        let mut edges = Vec::new();

        // Maps for resolving references
        let mut class_map: HashMap<String, String> = HashMap::new();
        let mut func_map: HashMap<String, Vec<String>> = HashMap::new();
        let mut module_map: HashMap<String, String> = HashMap::new();

        // Method to class mapping for scoped self.method() resolution
        let mut method_to_class: HashMap<String, String> = HashMap::new();
        let mut class_methods: HashMap<String, Vec<String>> = HashMap::new();

        // Class inheritance map for parent method resolution
        let mut class_parents: HashMap<String, Vec<String>> = HashMap::new();

        // File → imported function/module names
        let mut file_imported_names: HashMap<String, HashSet<String>> = HashMap::new();

        // Collect file entries first
        let mut file_entries: Vec<(String, String, Language)> = Vec::new();

        for entry in WalkDir::new(dir)
            .follow_links(false)
            .max_depth(20)
            .into_iter()
            .filter_entry(|e| {
                let name = e.file_name().to_str().unwrap_or("");
                !name.starts_with('.')
                    && name != "node_modules"
                    && name != "__pycache__"
                    && name != "target"
                    && name != "build"
                    && name != "dist"
                    && name != ".git"
                    && name != ".eggs"
                    && name != ".tox"
            })
        {
            let entry = match entry {
                Ok(e) => e,
                Err(_) => continue,
            };

            if !entry.file_type().is_file() {
                continue;
            }

            let path = entry.path();
            let lang = Language::from_path(path);
            if lang == Language::Unknown {
                continue;
            }

            let rel_path = path
                .strip_prefix(dir)
                .unwrap_or(path)
                .to_string_lossy()
                .to_string();

            // Skip certain files
            if rel_path == "setup.py" || rel_path == "conftest.py" || rel_path.contains("__pycache__") {
                continue;
            }

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

            // Build module path
            let module_path = rel_path
                .replace('/', ".")
                .trim_end_matches(".py")
                .trim_end_matches(".rs")
                .trim_end_matches(".ts")
                .trim_end_matches(".tsx")
                .trim_end_matches(".js")
                .trim_end_matches(".jsx")
                .to_string();

            let file_id = format!("file:{}", rel_path);
            module_map.insert(module_path.clone(), file_id.clone());

            // Also map partial paths
            let parts: Vec<&str> = module_path.split('.').collect();
            for start in 1..parts.len() {
                let partial = parts[start..].join(".");
                module_map.entry(partial).or_insert_with(|| file_id.clone());
            }

            file_entries.push((rel_path, content, lang));
        }

        // Second pass: parse each file
        let mut parser = Parser::new();
        let python_language = tree_sitter_python::LANGUAGE;
        parser.set_language(&python_language.into()).ok();

        for (rel_path, content, lang) in &file_entries {
            let _file_id = format!("file:{}", rel_path);

            let (file_nodes, file_edges, imports) = match lang {
                Language::Python => {
                    extract_python_tree_sitter(
                        rel_path,
                        content,
                        &mut parser,
                        &mut class_map,
                    )
                }
                Language::Rust => {
                    extract_rust_tree_sitter(
                        rel_path,
                        content,
                        &mut parser,
                        &mut class_map,
                    )
                }
                Language::TypeScript => {
                    let ext = rel_path.rsplit('.').next().unwrap_or("ts");
                    extract_typescript_tree_sitter(
                        rel_path,
                        content,
                        &mut parser,
                        &mut class_map,
                        ext,
                    )
                }
                Language::Unknown => continue,
            };

            // Update maps
            for node in &file_nodes {
                if node.kind == NodeKind::Class {
                    class_map.insert(node.name.clone(), node.id.clone());
                } else if node.kind == NodeKind::Function {
                    func_map
                        .entry(node.name.clone())
                        .or_default()
                        .push(node.id.clone());
                }
            }

            // Track method→class and class→methods relationships
            for edge in &file_edges {
                if edge.relation == EdgeRelation::DefinedIn {
                    if edge.from.starts_with("method:") && edge.to.starts_with("class:") {
                        method_to_class.insert(edge.from.clone(), edge.to.clone());
                        class_methods
                            .entry(edge.to.clone())
                            .or_default()
                            .push(edge.from.clone());
                    }
                }
                if edge.relation == EdgeRelation::Inherits {
                    if let Some(parent_id) = class_map.get(
                        edge.to.strip_prefix("class_ref:").unwrap_or(&edge.to),
                    ) {
                        class_parents
                            .entry(edge.from.clone())
                            .or_default()
                            .push(parent_id.clone());
                    }
                }
            }

            // Store imported names
            if !imports.is_empty() {
                file_imported_names.insert(rel_path.clone(), imports);
            }

            // Add file node if we found entities
            if !file_nodes.is_empty() {
                nodes.push(CodeNode::new_file(rel_path));
            }

            nodes.extend(file_nodes);
            edges.extend(file_edges);
        }

        // Build class_init_map for constructor resolution
        let class_init_map: HashMap<String, Vec<(String, String)>> = {
            let mut map: HashMap<String, Vec<(String, String)>> = HashMap::new();
            for node in &nodes {
                if node.kind == NodeKind::Function && node.name == "__init__" && !node.is_test {
                    if let Some(class_id) = method_to_class.get(&node.id) {
                        if let Some(class_name) = class_id.rsplit(':').next() {
                            map.entry(class_name.to_string())
                                .or_default()
                                .push((node.file_path.clone(), node.id.clone()));
                        }
                    }
                }
            }
            map
        };

        // Build node_pkg_map for package-scoped resolution
        let node_pkg_map: HashMap<String, String> = nodes
            .iter()
            .map(|n| {
                let pkg = n.file_path.rsplitn(2, '/').nth(1).unwrap_or("").to_string();
                (n.id.clone(), pkg)
            })
            .collect();

        // Third pass: extract call edges (only for Python with tree-sitter)
        for (rel_path, content, lang) in &file_entries {
            if *lang != Language::Python {
                continue;
            }

            let file_func_ids: HashSet<String> = nodes
                .iter()
                .filter(|n| n.file_path == *rel_path && n.kind == NodeKind::Function)
                .map(|n| n.id.clone())
                .collect();

            let package_dir = rel_path.rsplitn(2, '/').nth(1).unwrap_or("");

            if let Some(tree) = parser.parse(content, None) {
                let source = content.as_bytes();
                let root = tree.root_node();

                extract_calls_from_tree(
                    root,
                    source,
                    rel_path,
                    &func_map,
                    &method_to_class,
                    &class_parents,
                    &file_func_ids,
                    &file_imported_names,
                    package_dir,
                    &class_init_map,
                    &node_pkg_map,
                    &mut edges,
                );
            }

            // Test-to-source mapping
            let is_test_file = rel_path.contains("/tests/") || rel_path.contains("/test_");
            if is_test_file {
                let file_id = format!("file:{}", rel_path);
                let re_from_import = Regex::new(r"^from\s+([\w.]+)\s+import").unwrap();

                for line in content.lines() {
                    if let Some(cap) = re_from_import.captures(line) {
                        let module = cap[1].to_string();
                        if let Some(source_file_id) = module_map.get(&module) {
                            edges.push(CodeEdge {
                                from: file_id.clone(),
                                to: source_file_id.clone(),
                                relation: EdgeRelation::TestsFor,
                                weight: 0.5,
                                call_count: 1,
                                in_error_path: false,
                                confidence: 1.0,
                            });
                        }
                    }
                }
            }
        }

        // Resolve placeholder references
        let mut resolved_edges = Vec::new();
        for edge in edges {
            if edge.to.starts_with("class_ref:") {
                let class_name = &edge.to["class_ref:".len()..];
                if let Some(class_id) = class_map.get(class_name) {
                    resolved_edges.push(CodeEdge {
                        from: edge.from,
                        to: class_id.clone(),
                        relation: edge.relation,
                        weight: edge.weight,
                        call_count: edge.call_count,
                        in_error_path: edge.in_error_path,
                        confidence: edge.confidence,
                    });
                }
            } else if edge.to.starts_with("module_ref:") {
                let module = &edge.to["module_ref:".len()..];
                if let Some(file_id) = module_map.get(module) {
                    resolved_edges.push(CodeEdge {
                        from: edge.from,
                        to: file_id.clone(),
                        relation: edge.relation,
                        weight: edge.weight,
                        call_count: edge.call_count,
                        in_error_path: edge.in_error_path,
                        confidence: edge.confidence,
                    });
                }
            } else if edge.to.starts_with("func_ref:") {
                let func_name = &edge.to["func_ref:".len()..];
                if let Some(func_ids) = func_map.get(func_name) {
                    if let Some(func_id) = func_ids.first() {
                        resolved_edges.push(CodeEdge {
                            from: edge.from,
                            to: func_id.clone(),
                            relation: edge.relation,
                            weight: edge.weight,
                            call_count: edge.call_count,
                            in_error_path: edge.in_error_path,
                            confidence: edge.confidence,
                        });
                    }
                }
            } else {
                resolved_edges.push(edge);
            }
        }

        // Deduplicate call edges and compute call_count
        let mut edge_map: HashMap<(String, String), CodeEdge> = HashMap::new();
        let mut other_edges: Vec<CodeEdge> = Vec::new();

        for edge in resolved_edges {
            if edge.relation == EdgeRelation::Calls {
                let key = (edge.from.clone(), edge.to.clone());
                let entry = edge_map.entry(key).or_insert_with(|| {
                    let mut e = edge.clone();
                    e.call_count = 0;
                    e
                });
                entry.call_count += 1;
                if edge.confidence > entry.confidence {
                    entry.confidence = edge.confidence;
                }
                if edge.in_error_path {
                    entry.in_error_path = true;
                }
            } else {
                other_edges.push(edge);
            }
        }

        let mut final_edges: Vec<CodeEdge> = edge_map.into_values().collect();
        final_edges.extend(other_edges);

        // Compute weights for all edges
        for edge in &mut final_edges {
            edge.compute_weight();
        }

        // Add override edges
        add_override_edges(&nodes, &mut final_edges);

        let mut graph = CodeGraph {
            nodes,
            edges: final_edges,
            outgoing: HashMap::new(),
            incoming: HashMap::new(),
            node_index: HashMap::new(),
        };
        graph.build_indexes();
        graph
    }

    /// Build adjacency indexes for O(1) lookups.
    pub fn build_indexes(&mut self) {
        self.node_index.clear();
        self.outgoing.clear();
        self.incoming.clear();

        for (i, node) in self.nodes.iter().enumerate() {
            self.node_index.insert(node.id.clone(), i);
        }

        for (i, edge) in self.edges.iter().enumerate() {
            self.outgoing.entry(edge.from.clone()).or_default().push(i);
            self.incoming.entry(edge.to.clone()).or_default().push(i);
        }
    }

    // ═══ Query Methods ═══

    /// Get outgoing edges from a node.
    #[inline]
    pub fn outgoing_edges(&self, node_id: &str) -> impl Iterator<Item = &CodeEdge> {
        self.outgoing
            .get(node_id)
            .map(|indices| indices.as_slice())
            .unwrap_or(&[])
            .iter()
            .map(move |&i| &self.edges[i])
    }

    /// Get incoming edges to a node.
    #[inline]
    pub fn incoming_edges(&self, node_id: &str) -> impl Iterator<Item = &CodeEdge> {
        self.incoming
            .get(node_id)
            .map(|indices| indices.as_slice())
            .unwrap_or(&[])
            .iter()
            .map(move |&i| &self.edges[i])
    }

    /// Find node by id.
    #[inline]
    pub fn node_by_id(&self, node_id: &str) -> Option<&CodeNode> {
        self.node_index.get(node_id).map(|&i| &self.nodes[i])
    }

    /// Get all callers of a function/method.
    pub fn get_callers(&self, node_id: &str) -> Vec<&CodeNode> {
        self.incoming_edges(node_id)
            .filter(|e| e.relation == EdgeRelation::Calls)
            .filter_map(|e| self.node_by_id(&e.from))
            .collect()
    }

    /// Get all callees of a function/method.
    pub fn get_callees(&self, node_id: &str) -> Vec<&CodeNode> {
        self.outgoing_edges(node_id)
            .filter(|e| e.relation == EdgeRelation::Calls)
            .filter_map(|e| self.node_by_id(&e.to))
            .collect()
    }

    /// Get dependencies of a node (what it depends on)
    pub fn get_dependencies(&self, node_id: &str) -> Vec<&CodeNode> {
        self.outgoing_edges(node_id)
            .filter_map(|e| self.node_by_id(&e.to))
            .collect()
    }

    /// Get nodes that depend on this node (impact analysis).
    pub fn get_impact(&self, node_id: &str) -> Vec<&CodeNode> {
        let mut impacted = Vec::new();
        let mut visited = HashSet::new();
        self.collect_dependents(node_id, &mut impacted, &mut visited);
        impacted
    }

    fn collect_dependents<'a>(
        &'a self,
        node_id: &str,
        result: &mut Vec<&'a CodeNode>,
        visited: &mut HashSet<String>,
    ) {
        if !visited.insert(node_id.to_string()) {
            return;
        }

        for edge in self.incoming_edges(node_id) {
            if let Some(node) = self.node_by_id(&edge.from) {
                result.push(node);
                self.collect_dependents(&edge.from, result, visited);
            }
        }
    }

    /// Find nodes matching keywords in name or path.
    pub fn find_relevant_nodes(&self, keywords: &[&str]) -> Vec<&CodeNode> {
        let mut scored: Vec<(usize, &CodeNode)> = self
            .nodes
            .iter()
            .map(|n| {
                let score: usize = keywords
                    .iter()
                    .filter(|kw| {
                        let kw_lower = kw.to_lowercase();
                        let name_lower = n.name.to_lowercase();
                        let path_lower = n.file_path.to_lowercase();
                        name_lower.contains(&kw_lower)
                            || path_lower.contains(&kw_lower)
                            || (name_lower.len() >= 5
                                && kw_lower.contains(name_lower.trim_start_matches('_')))
                    })
                    .count();
                (score, n)
            })
            .filter(|(score, _)| *score > 0)
            .collect();

        scored.sort_by(|a, b| b.0.cmp(&a.0));
        let mut results: Vec<&CodeNode> = scored.into_iter().map(|(_, n)| n).collect();

        // Same-file expansion
        let relevant_files: HashSet<String> = results.iter().map(|n| n.file_path.clone()).collect();

        for node in &self.nodes {
            if relevant_files.contains(&node.file_path) && !results.iter().any(|r| r.id == node.id) {
                results.push(node);
            }
        }

        // Inheritance chain expansion
        let mut inheritance_additions: Vec<&CodeNode> = Vec::new();
        let result_ids: HashSet<String> = results.iter().map(|n| n.id.clone()).collect();

        for node in &results {
            if node.kind == NodeKind::Class {
                let chain = self.get_inheritance_chain(&node.id);
                for ancestor_id in &chain {
                    if !result_ids.contains(ancestor_id) {
                        if let Some(ancestor) = self.node_by_id(ancestor_id) {
                            inheritance_additions.push(ancestor);
                        }
                    }
                }
                for edge in self.incoming_edges(&node.id) {
                    if edge.relation == EdgeRelation::Inherits && !result_ids.contains(&edge.from) {
                        if let Some(child) = self.node_by_id(&edge.from) {
                            inheritance_additions.push(child);
                        }
                    }
                }
            }
        }

        let mut extra_files: HashSet<String> = HashSet::new();
        for node in &inheritance_additions {
            if !results.iter().any(|r| r.id == node.id) {
                extra_files.insert(node.file_path.clone());
                results.push(node);
            }
        }
        for node in &self.nodes {
            if extra_files.contains(&node.file_path) && !results.iter().any(|r| r.id == node.id) {
                results.push(node);
            }
        }

        // Import chain expansion: for relevant files, follow their imports to find related files
        // Only expand one level deep to avoid pulling in the entire codebase
        let mut import_additions: Vec<&CodeNode> = Vec::new();
        let current_ids: HashSet<String> = results.iter().map(|n| n.id.clone()).collect();

        for node in &results {
            if node.kind == NodeKind::File {
                for edge in self.outgoing_edges(&node.id) {
                    if edge.relation == EdgeRelation::Imports {
                        if !current_ids.contains(&edge.to) {
                            if let Some(imported) = self.node_by_id(&edge.to) {
                                import_additions.push(imported);
                            }
                        }
                    }
                }
            }
        }

        // Only add import expansions for files that have classes/functions matching keywords
        for node in &import_additions {
            if node.kind == NodeKind::File {
                let has_keyword_match = self
                    .nodes
                    .iter()
                    .filter(|n| n.file_path == node.file_path && n.kind != NodeKind::File)
                    .any(|n| {
                        let name_lower = n.name.to_lowercase();
                        keywords.iter().any(|kw| {
                            let kw_lower = kw.to_lowercase();
                            name_lower.contains(&kw_lower) || kw_lower.contains(&name_lower)
                        })
                    });
                if has_keyword_match && !results.iter().any(|r| r.id == node.id) {
                    results.push(node);
                    // Also add entities from that file
                    for entity in &self.nodes {
                        if entity.file_path == node.file_path
                            && !results.iter().any(|r| r.id == entity.id)
                        {
                            results.push(entity);
                        }
                    }
                }
            }
        }

        results
    }

    /// Full impact analysis: given nodes to change, return affected nodes + tests
    pub fn impact_analysis(&self, changed_node_ids: &[&str]) -> ImpactReport<'_> {
        let mut affected_nodes = Vec::new();
        let mut affected_tests = Vec::new();
        let mut seen = HashSet::new();

        for node_id in changed_node_ids {
            let impacted = self.get_impact(node_id);
            for node in impacted {
                if seen.insert(node.id.clone()) {
                    if node.file_path.contains("/tests/") || node.file_path.contains("/test_") {
                        affected_tests.push(node);
                    } else {
                        affected_nodes.push(node);
                    }
                }
            }
        }

        let related_tests = self.find_related_tests(changed_node_ids);
        for test in related_tests {
            if seen.insert(test.id.clone()) {
                affected_tests.push(test);
            }
        }

        ImpactReport {
            affected_source: affected_nodes,
            affected_tests,
        }
    }

    /// Find test files/functions related to given source nodes.
    pub fn find_related_tests(&self, source_node_ids: &[&str]) -> Vec<&CodeNode> {
        let mut test_nodes = Vec::new();
        let mut seen = HashSet::new();

        let source_files: HashSet<String> = source_node_ids
            .iter()
            .filter_map(|id| self.node_by_id(id))
            .map(|n| n.file_path.clone())
            .collect();

        let source_file_ids: HashSet<String> = source_files.iter().map(|f| format!("file:{}", f)).collect();

        // Find tests via TestsFor edges
        for source_fid in &source_file_ids {
            for edge in self.incoming_edges(source_fid.as_str()) {
                if edge.relation == EdgeRelation::TestsFor {
                    if let Some(test_node) = self.node_by_id(&edge.from) {
                        if seen.insert(test_node.id.clone()) {
                            test_nodes.push(test_node);
                        }
                        for node in &self.nodes {
                            if node.file_path == test_node.file_path
                                && node.kind != NodeKind::File
                                && seen.insert(node.id.clone())
                            {
                                test_nodes.push(node);
                            }
                        }
                    }
                }
            }
        }

        // Find tests via Calls edges
        for source_id in source_node_ids.iter() {
            for edge in self.incoming_edges(source_id) {
                if edge.relation == EdgeRelation::Calls {
                    if let Some(caller) = self.node_by_id(&edge.from) {
                        if caller.file_path.contains("/tests/") || caller.file_path.contains("/test_") {
                            if seen.insert(caller.id.clone()) {
                                test_nodes.push(caller);
                            }
                        }
                    }
                }
            }
        }

        test_nodes
    }

    /// Format impact analysis as context string for LLM
    pub fn format_impact_for_llm(&self, changed_node_ids: &[&str], repo_dir: &Path) -> String {
        let report = self.impact_analysis(changed_node_ids);
        let mut result = String::new();

        if !report.affected_source.is_empty() {
            result.push_str("**⚠️ Impact Analysis — Code affected by your change:**\n");
            for node in &report.affected_source {
                let prefix = match node.kind {
                    NodeKind::File => "📄",
                    NodeKind::Class => "🔷",
                    NodeKind::Function => "🔹",
                    NodeKind::Module => "📦",
                };
                result.push_str(&format!("{} {} (`{}`)\n", prefix, node.name, node.file_path));
            }
            result.push('\n');
        }

        if !report.affected_tests.is_empty() {
            result.push_str("**🧪 Tests that exercise the code you're changing:**\n");
            result.push_str("DO NOT break these tests! Make minimal changes.\n\n");

            let mut test_files: HashSet<String> = HashSet::new();
            for node in &report.affected_tests {
                test_files.insert(node.file_path.clone());
            }

            for test_file in &test_files {
                result.push_str(&format!("📋 `{}`\n", test_file));
                let funcs: Vec<&str> = report
                    .affected_tests
                    .iter()
                    .filter(|n| n.file_path == *test_file && n.kind == NodeKind::Function)
                    .map(|n| n.name.as_str())
                    .collect();
                if !funcs.is_empty() {
                    for func in funcs.iter().take(10) {
                        result.push_str(&format!("  - {}\n", func));
                    }
                    if funcs.len() > 10 {
                        result.push_str(&format!("  ... and {} more\n", funcs.len() - 10));
                    }
                }
            }
            result.push('\n');

            let test_nodes_refs: Vec<&CodeNode> = report
                .affected_tests
                .iter()
                .filter(|n| n.kind == NodeKind::Function)
                .take(10)
                .copied()
                .collect();

            if !test_nodes_refs.is_empty() {
                let test_snippets = self.extract_snippets(&test_nodes_refs, repo_dir, 30);
                if !test_snippets.is_empty() {
                    result.push_str("**Key test code (DO NOT break these):**\n```python\n");
                    for (node_id, snippet) in test_snippets.iter().take(5) {
                        let name = self.node_name(node_id);
                        result.push_str(&format!("# --- {} ---\n{}\n\n", name, snippet));
                    }
                    result.push_str("```\n");
                }
            }
        }

        result
    }

    /// Trace causal chains from symptom nodes to potential root causes.
    pub fn trace_causal_chains_from_symptoms(
        &self,
        symptom_node_ids: &[&str],
        max_depth: usize,
        max_chains: usize,
    ) -> Vec<CausalChain> {
        #[derive(Clone)]
        struct WeightedPath {
            node_id: String,
            accumulated_weight: f32,
            chain: Vec<ChainNode>,
        }

        impl PartialEq for WeightedPath {
            fn eq(&self, other: &Self) -> bool {
                self.accumulated_weight
                    .total_cmp(&other.accumulated_weight)
                    == std::cmp::Ordering::Equal
            }
        }
        impl Eq for WeightedPath {}
        impl PartialOrd for WeightedPath {
            fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
                Some(self.cmp(other))
            }
        }
        impl Ord for WeightedPath {
            fn cmp(&self, other: &Self) -> std::cmp::Ordering {
                self.accumulated_weight.total_cmp(&other.accumulated_weight)
            }
        }

        let mut all_chains: Vec<CausalChain> = Vec::new();

        for symptom_id in symptom_node_ids {
            let symptom_node = match self.node_by_id(symptom_id) {
                Some(n) => n,
                None => continue,
            };

            // Forward search
            {
                let mut heap: BinaryHeap<WeightedPath> = BinaryHeap::new();
                let mut visited = HashSet::new();
                visited.insert(symptom_id.to_string());

                let start_chain_node = ChainNode {
                    node_id: symptom_id.to_string(),
                    node_name: symptom_node.name.clone(),
                    file_path: symptom_node.file_path.clone(),
                    line: symptom_node.line,
                    edge_to_next: None,
                };
                heap.push(WeightedPath {
                    node_id: symptom_id.to_string(),
                    accumulated_weight: 1.0,
                    chain: vec![start_chain_node],
                });

                while let Some(current) = heap.pop() {
                    if current.chain.len() > max_depth {
                        continue;
                    }

                    for edge in self.outgoing_edges(&current.node_id) {
                        let (target_id, edge_label) = match edge.relation {
                            EdgeRelation::Calls => (&edge.to, "calls"),
                            EdgeRelation::Inherits => (&edge.to, "inherits"),
                            EdgeRelation::Imports => (&edge.to, "imports"),
                            EdgeRelation::Overrides => (&edge.to, "overrides"),
                            EdgeRelation::TestsFor => (&edge.to, "tests"),
                            _ => continue,
                        };
                        if visited.contains(target_id) {
                            continue;
                        }
                        if let Some(target_node) = self.node_by_id(target_id) {
                            visited.insert(target_node.id.clone());
                            let new_weight = current.accumulated_weight * edge.weight;

                            let mut new_chain = current.chain.clone();
                            if let Some(last) = new_chain.last_mut() {
                                last.edge_to_next = Some(edge_label.to_string());
                            }
                            new_chain.push(ChainNode {
                                node_id: target_node.id.clone(),
                                node_name: target_node.name.clone(),
                                file_path: target_node.file_path.clone(),
                                line: target_node.line,
                                edge_to_next: None,
                            });

                            if new_chain.len() >= 2 {
                                all_chains.push(CausalChain {
                                    symptom_node_id: symptom_id.to_string(),
                                    chain: new_chain.clone(),
                                });
                            }

                            if new_chain.len() < max_depth {
                                heap.push(WeightedPath {
                                    node_id: target_node.id.clone(),
                                    accumulated_weight: new_weight,
                                    chain: new_chain,
                                });
                            }
                        }
                    }
                }
            }

            // Reverse search
            {
                let mut heap: BinaryHeap<WeightedPath> = BinaryHeap::new();
                let mut visited = HashSet::new();
                visited.insert(symptom_id.to_string());

                let start_chain_node = ChainNode {
                    node_id: symptom_id.to_string(),
                    node_name: symptom_node.name.clone(),
                    file_path: symptom_node.file_path.clone(),
                    line: symptom_node.line,
                    edge_to_next: None,
                };
                heap.push(WeightedPath {
                    node_id: symptom_id.to_string(),
                    accumulated_weight: 1.0,
                    chain: vec![start_chain_node],
                });

                while let Some(current) = heap.pop() {
                    if current.chain.len() > max_depth {
                        continue;
                    }

                    for edge in self.incoming_edges(&current.node_id) {
                        if edge.relation != EdgeRelation::Calls
                            && edge.relation != EdgeRelation::Imports
                            && edge.relation != EdgeRelation::Overrides
                        {
                            continue;
                        }
                        if visited.contains(&edge.from) {
                            continue;
                        }
                        if let Some(caller) = self.node_by_id(&edge.from) {
                            if caller.file_path.contains("/tests/")
                                || caller.file_path.contains("/test_")
                            {
                                continue;
                            }
                            visited.insert(caller.id.clone());
                            let new_weight = current.accumulated_weight * edge.weight;

                            let edge_label = match edge.relation {
                                EdgeRelation::Imports => "imported_by",
                                EdgeRelation::Overrides => "overridden_by",
                                _ => "called_by",
                            };
                            let mut new_chain = current.chain.clone();
                            if let Some(last) = new_chain.last_mut() {
                                last.edge_to_next = Some(edge_label.to_string());
                            }
                            new_chain.push(ChainNode {
                                node_id: caller.id.clone(),
                                node_name: caller.name.clone(),
                                file_path: caller.file_path.clone(),
                                line: caller.line,
                                edge_to_next: None,
                            });

                            if new_chain.len() >= 2 {
                                all_chains.push(CausalChain {
                                    symptom_node_id: symptom_id.to_string(),
                                    chain: new_chain.clone(),
                                });
                            }

                            if new_chain.len() < max_depth {
                                heap.push(WeightedPath {
                                    node_id: caller.id.clone(),
                                    accumulated_weight: new_weight,
                                    chain: new_chain,
                                });
                            }
                        }
                    }
                }
            }
        }

        // Sort and deduplicate
        all_chains.sort_by(|a, b| {
            let len_cmp = a.chain.len().cmp(&b.chain.len());
            if len_cmp != std::cmp::Ordering::Equal {
                return len_cmp;
            }
            let a_source = a
                .chain
                .iter()
                .filter(|n| !n.file_path.contains("/tests/") && !n.file_path.contains("/test_"))
                .count();
            let b_source = b
                .chain
                .iter()
                .filter(|n| !n.file_path.contains("/tests/") && !n.file_path.contains("/test_"))
                .count();
            b_source.cmp(&a_source)
        });

        let mut deduped: Vec<CausalChain> = Vec::new();
        for chain in &all_chains {
            let is_prefix = deduped.iter().any(|existing| {
                existing.chain.len() > chain.chain.len()
                    && chain
                        .chain
                        .iter()
                        .zip(existing.chain.iter())
                        .all(|(a, b)| a.node_id == b.node_id)
            });
            if is_prefix {
                continue;
            }
            deduped.retain(|existing| {
                !(existing.chain.len() < chain.chain.len()
                    && existing
                        .chain
                        .iter()
                        .zip(chain.chain.iter())
                        .all(|(a, b)| a.node_id == b.node_id))
            });
            deduped.push(chain.clone());
        }

        deduped.truncate(max_chains);
        deduped
    }

    /// Trace causal chains from changed nodes to failed tests.
    pub fn trace_causal_chains(
        &self,
        changed_node_ids: &[&str],
        failed_p2p_tests: &[String],
        failed_f2p_tests: &[String],
    ) -> String {
        if failed_p2p_tests.is_empty() && failed_f2p_tests.is_empty() {
            return String::new();
        }

        let mut result = String::new();

        if !failed_p2p_tests.is_empty() {
            result.push_str("## 🚨 CAUSAL ANALYSIS — Why Your Fix Broke Existing Tests\n\n");
            result.push_str(
                "These tests PASSED before your change and now FAIL. You MUST fix these regressions.\n\n",
            );

            for test_name in failed_p2p_tests {
                let short_name = test_name.split("::").last().unwrap_or(test_name);
                result.push_str(&format!("### ❌ REGRESSION: `{}`\n", short_name));

                let test_node = self.nodes.iter().find(|n| {
                    n.name == short_name
                        || n.name.ends_with(short_name)
                        || (n.file_path.contains("/test") && n.name == short_name)
                });

                if let Some(test) = test_node {
                    let chains = self.find_paths_to_test(changed_node_ids, &test.id);

                    if !chains.is_empty() {
                        result.push_str("**Causal chain(s):**\n");
                        for chain in chains.iter().take(3) {
                            let chain_str: Vec<String> = chain
                                .iter()
                                .map(|id| {
                                    self.nodes
                                        .iter()
                                        .find(|n| n.id == *id)
                                        .map(|n| format!("`{}` ({})", n.name, n.file_path))
                                        .unwrap_or_else(|| id.to_string())
                                })
                                .collect();
                            result.push_str(&format!("  🔗 {}\n", chain_str.join("")));
                        }
                        result.push_str("\n**What this means:** Your change propagated through the dependency chain above and broke this test.\n");
                        result.push_str("**How to fix:** Make your change more surgical — ensure the modified function's behavior is backward-compatible for the callers in this chain.\n\n");
                    } else {
                        // No direct graph path — check file-level connection
                        let changed_files: HashSet<String> = changed_node_ids
                            .iter()
                            .filter_map(|id| self.node_by_id(id))
                            .map(|n| n.file_path.clone())
                            .collect();

                        if changed_files
                            .iter()
                            .any(|f| test.file_path.contains(f.as_str()))
                            || self.shares_import(&test.id, changed_node_ids)
                        {
                            result.push_str("**Connection:** Indirect — test imports or uses a module you changed.\n");
                            result.push_str("**How to fix:** Check that your change doesn't alter the public API or default behavior of the module.\n\n");
                        } else {
                            result.push_str("**Connection:** Could not trace via graph (may be via dynamic dispatch, monkey-patching, or shared global state).\n");
                            result.push_str("**How to fix:** Read the test's assertion error carefully — it will tell you what behavior changed.\n\n");
                        }
                    }
                } else {
                    result.push_str(
                        "**Note:** Test not found in code graph. Read the error output to understand what broke.\n\n",
                    );
                }
            }

            result.push_str("### 🎯 Overall Regression Fix Strategy\n");
            result.push_str(
                "1. **Don't change your approach** — your bug fix logic is likely correct\n",
            );
            result.push_str("2. **Narrow the scope** — guard your change with a condition so it only applies to the bug case\n");
            result.push_str("3. **Add backward compatibility** — if you changed a return type/value, ensure callers still get what they expect\n");
            result.push_str("4. **Check default parameters** — if you changed defaults, existing callers rely on the old defaults\n\n");
        }

        if !failed_f2p_tests.is_empty() {
            result.push_str("## ⚠️ Original Bug Not Fixed\n");
            result.push_str("These tests still fail — your fix is incomplete or incorrect:\n");
            for test_name in failed_f2p_tests {
                let short_name = test_name.split("::").last().unwrap_or(test_name);
                result.push_str(&format!("- `{}`\n", short_name));
            }
            result.push('\n');
        }

        result
    }

    fn find_paths_to_test(&self, changed_node_ids: &[&str], test_node_id: &str) -> Vec<Vec<String>> {
        let mut paths = Vec::new();

        for changed_id in changed_node_ids {
            if let Some(path) = self.bfs_path(test_node_id, changed_id, 5) {
                let mut p = path;
                p.reverse();
                paths.push(p);
            }
        }

        paths
    }

    /// BFS shortest path from `from` to `to`.
    pub fn bfs_path(&self, from: &str, to: &str, max_depth: usize) -> Option<Vec<String>> {
        let mut queue: VecDeque<(String, Vec<String>)> = VecDeque::new();
        let mut visited = HashSet::new();

        queue.push_back((from.to_string(), vec![from.to_string()]));
        visited.insert(from.to_string());

        while let Some((current, path)) = queue.pop_front() {
            if path.len() > max_depth {
                continue;
            }

            for edge in self.outgoing_edges(&current) {
                if edge.to == to {
                    let mut final_path = path.clone();
                    final_path.push(edge.to.clone());
                    return Some(final_path);
                }
                if !visited.contains(&edge.to) {
                    visited.insert(edge.to.clone());
                    let mut new_path = path.clone();
                    new_path.push(edge.to.clone());
                    queue.push_back((edge.to.clone(), new_path));
                }
            }
        }
        None
    }

    /// Get a summary of a node: name, file, line, and first 15 lines of code.
    pub fn get_node_summary(&self, node_id: &str, repo_dir: &Path) -> String {
        let node = match self.node_by_id(node_id) {
            Some(n) => n,
            None => return format!("[unknown node: {}]", node_id),
        };

        let mut result = format!(
            "{} ({}:{})",
            node.name,
            node.file_path,
            node.line.map(|l| l.to_string()).unwrap_or_else(|| "?".to_string()),
        );

        let full_path = repo_dir.join(&node.file_path);
        if let Ok(content) = std::fs::read_to_string(&full_path) {
            let lines: Vec<&str> = content.lines().collect();
            if let Some(start_line) = node.line {
                if start_line > 0 && start_line <= lines.len() {
                    let start_idx = start_line - 1;
                    let end_idx = (start_idx + 15).min(lines.len());
                    let preview: String = lines[start_idx..end_idx]
                        .iter()
                        .map(|l| *l)
                        .collect::<Vec<_>>()
                        .join("\n");
                    result.push('\n');
                    result.push_str(&preview);
                }
            }
        }

        result
    }

    /// Extract code snippets for nodes.
    pub fn extract_snippets(
        &self,
        nodes: &[&CodeNode],
        repo_dir: &Path,
        max_lines: usize,
    ) -> HashMap<String, String> {
        let mut snippets = HashMap::new();
        let mut file_cache: HashMap<String, Vec<String>> = HashMap::new();

        for node in nodes {
            if node.kind == NodeKind::File {
                continue;
            }

            let file_path = repo_dir.join(&node.file_path);
            let lines = file_cache.entry(node.file_path.clone()).or_insert_with(|| {
                std::fs::read_to_string(&file_path)
                    .unwrap_or_default()
                    .lines()
                    .map(|l| l.to_string())
                    .collect()
            });

            if let Some(start_line) = node.line {
                if start_line == 0 || start_line > lines.len() {
                    continue;
                }
                let start_idx = start_line - 1;

                let base_indent = lines[start_idx]
                    .chars()
                    .take_while(|c| c.is_whitespace())
                    .count();

                let mut end_idx = start_idx + 1;
                while end_idx < lines.len() && end_idx < start_idx + max_lines {
                    let line = &lines[end_idx];
                    if line.trim().is_empty() {
                        end_idx += 1;
                        continue;
                    }
                    let indent = line.chars().take_while(|c| c.is_whitespace()).count();
                    if indent <= base_indent && !line.trim().is_empty() {
                        break;
                    }
                    end_idx += 1;
                }

                let snippet: String = lines[start_idx..end_idx.min(lines.len())]
                    .iter()
                    .map(|l| l.as_str())
                    .collect::<Vec<_>>()
                    .join("\n");

                if !snippet.trim().is_empty() {
                    snippets.insert(node.id.clone(), snippet);
                }
            }
        }

        snippets
    }

    /// Format graph for LLM context.
    pub fn format_for_llm(&self, keywords: &[&str], max_chars: usize) -> String {
        let relevant = self.find_relevant_nodes(keywords);

        if relevant.is_empty() {
            return self.format_file_summary(max_chars);
        }

        let mut result = String::from("**Code structure (relevant to issue):**\n");

        result.push_str("\nRelevant files/classes/functions:\n");
        let relevant_ids: HashSet<&str> = relevant.iter().map(|n| n.id.as_str()).collect();

        for node in relevant.iter().take(20) {
            let prefix = match node.kind {
                NodeKind::File => "📄",
                NodeKind::Class => "🔷",
                NodeKind::Function => "🔹",
                NodeKind::Module => "📦",
            };
            let line_info = node.line.map(|l| format!(" (line {})", l)).unwrap_or_default();
            result.push_str(&format!(
                "{} {} — `{}`{}\n",
                prefix, node.name, node.file_path, line_info
            ));

            if result.len() > max_chars / 2 {
                break;
            }
        }

        let relevant_edges: Vec<&CodeEdge> = self
            .edges
            .iter()
            .filter(|e| {
                relevant_ids.contains(e.from.as_str()) || relevant_ids.contains(e.to.as_str())
            })
            .filter(|e| e.relation != EdgeRelation::DefinedIn)
            .collect();

        if !relevant_edges.is_empty() {
            result.push_str("\nRelationships:\n");
            for edge in relevant_edges.iter().take(15) {
                let from_name = self.node_name(&edge.from);
                let to_name = self.node_name(&edge.to);
                result.push_str(&format!(
                    "  {} --[{}]--> {}\n",
                    from_name, edge.relation, to_name
                ));

                if result.len() > max_chars {
                    break;
                }
            }
        }

        let relevant_classes: Vec<&&CodeNode> = relevant
            .iter()
            .filter(|n| n.kind == NodeKind::Class)
            .collect();

        if !relevant_classes.is_empty() {
            result.push_str("\nInheritance:\n");
            for cls in relevant_classes.iter().take(5) {
                let chain = self.get_inheritance_chain(&cls.id);
                if chain.len() > 1 {
                    let names: Vec<String> =
                        chain.iter().map(|id| self.node_name(id)).collect();
                    result.push_str(&format!("  {} \n", names.join("")));
                }
            }
        }

        let file_count = self.nodes.iter().filter(|n| n.kind == NodeKind::File).count();
        let class_count = self.nodes.iter().filter(|n| n.kind == NodeKind::Class).count();
        let import_count = self
            .edges
            .iter()
            .filter(|e| e.relation == EdgeRelation::Imports)
            .count();
        let inherit_count = self
            .edges
            .iter()
            .filter(|e| e.relation == EdgeRelation::Inherits)
            .count();

        result.push_str(&format!(
            "\nGraph: {} files, {} classes, {} imports, {} inheritance edges\n",
            file_count, class_count, import_count, inherit_count
        ));

        if result.len() > max_chars {
            result.truncate(max_chars);
            result.push_str("\n...[truncated]\n");
        }

        result
    }

    fn format_file_summary(&self, max_chars: usize) -> String {
        let mut result = String::from("**Repository files:**\n");

        let files: Vec<&CodeNode> = self
            .nodes
            .iter()
            .filter(|n| n.kind == NodeKind::File)
            .collect();

        for file in &files {
            let classes: Vec<String> = self
                .nodes
                .iter()
                .filter(|n| n.kind == NodeKind::Class && n.file_path == file.file_path)
                .map(|n| n.name.clone())
                .collect();

            let mut line = format!("- `{}`", file.file_path);
            if !classes.is_empty() {
                line.push_str(&format!("{}", classes.join(", ")));
            }
            line.push('\n');

            if result.len() + line.len() > max_chars {
                result.push_str(&format!("... and {} more files\n", files.len()));
                break;
            }
            result.push_str(&line);
        }

        result
    }

    fn node_name(&self, id: &str) -> String {
        self.nodes
            .iter()
            .find(|n| n.id == id)
            .map(|n| n.name.clone())
            .unwrap_or_else(|| id.to_string())
    }

    fn get_inheritance_chain(&self, class_id: &str) -> Vec<String> {
        let mut chain = vec![class_id.to_string()];
        let mut current = class_id.to_string();

        for _ in 0..10 {
            let parent = self
                .edges
                .iter()
                .find(|e| e.from == current && e.relation == EdgeRelation::Inherits);
            match parent {
                Some(edge) => {
                    chain.push(edge.to.clone());
                    current = edge.to.clone();
                }
                None => break,
            }
        }

        chain
    }

    /// Check if a test node shares imports with any of the changed nodes.
    /// Returns true if the test imports a file/module that contains a changed node.
    fn shares_import(&self, test_node_id: &str, changed_node_ids: &[&str]) -> bool {
        let test_imports: HashSet<String> = self
            .edges
            .iter()
            .filter(|e| e.from == test_node_id && e.relation == EdgeRelation::Imports)
            .map(|e| e.to.clone())
            .collect();

        let changed_files: HashSet<String> = changed_node_ids
            .iter()
            .filter_map(|id| self.node_by_id(id))
            .flat_map(|n| {
                let file_id = format!("file:{}", n.file_path);
                vec![n.id.clone(), file_id]
            })
            .collect();

        test_imports.intersection(&changed_files).next().is_some()
    }

    /// Search for identifiers in repo via grep
    pub fn grep_for_identifiers(&self, repo_dir: &Path, identifiers: &[&str]) -> Vec<CodeNode> {
        let mut found_nodes = Vec::new();
        let existing_names: HashSet<String> = self.nodes.iter().map(|n| n.name.clone()).collect();

        for ident in identifiers {
            if existing_names.contains(*ident) {
                continue;
            }

            let patterns = [
                format!("class {}[:(]", ident),
                format!("def {}[(]", ident),
                format!("class {}\\b", ident),
            ];

            for pattern in &patterns {
                if let Ok(output) = std::process::Command::new("grep")
                    .args(["-rn", pattern, "--include=*.py", "-l"])
                    .current_dir(repo_dir)
                    .output()
                {
                    let stdout = String::from_utf8_lossy(&output.stdout);
                    for file_path in stdout.lines().take(3) {
                        let file_path = file_path.trim();
                        if file_path.is_empty()
                            || file_path.contains("/tests/")
                            || file_path.contains("/test_")
                        {
                            continue;
                        }

                        if let Ok(line_output) = std::process::Command::new("grep")
                            .args(["-n", pattern, file_path])
                            .current_dir(repo_dir)
                            .output()
                        {
                            let line_stdout = String::from_utf8_lossy(&line_output.stdout);
                            if let Some(first_line) = line_stdout.lines().next() {
                                let line_num: usize = first_line
                                    .split(':')
                                    .next()
                                    .unwrap_or("0")
                                    .parse()
                                    .unwrap_or(0);

                                let is_class = first_line.contains("class ");
                                found_nodes.push(CodeNode {
                                    id: format!("grep:{}:{}", file_path, ident),
                                    kind: if is_class {
                                        NodeKind::Class
                                    } else {
                                        NodeKind::Function
                                    },
                                    name: ident.to_string(),
                                    file_path: file_path.to_string(),
                                    line: if line_num > 0 { Some(line_num) } else { None },
                                    decorators: Vec::new(),
                                    signature: None,
                                    docstring: None,
                                    line_count: 0,
                                    is_test: false,
                                });
                                break;
                            }
                        }
                    }
                }
                if found_nodes.iter().any(|n| n.name == *ident) {
                    break;
                }
            }
        }

        found_nodes
    }

    /// Extract keywords from a problem statement
    pub fn extract_keywords(problem_statement: &str) -> Vec<&str> {
        let mut keywords = Vec::new();

        for word in
            problem_statement.split(|c: char| !c.is_alphanumeric() && c != '_' && c != '.')
        {
            let trimmed = word.trim();
            if trimmed.len() < 3 {
                continue;
            }
            let lower = trimmed.to_lowercase();
            if [
                "the", "and", "for", "that", "this", "with", "from", "not", "but", "are", "was",
                "has", "have", "can", "should", "would", "when", "what", "how", "does", "bug",
                "fix", "issue", "error", "problem", "description",
            ]
            .contains(&lower.as_str())
            {
                continue;
            }
            if trimmed.contains('_')
                || trimmed.contains('.')
                || trimmed.chars().any(|c| c.is_uppercase())
                || trimmed.ends_with(".py")
            {
                keywords.push(trimmed);
            }
        }

        keywords.dedup();
        keywords.truncate(20);
        keywords
    }

    /// Check if graph has a node with given file and name
    pub fn has_node(&self, file_path: &str, name: &str) -> bool {
        let needle = file_path.strip_prefix("./").unwrap_or(file_path);
        self.nodes.iter().any(|n| {
            let hay = n.file_path.strip_prefix("./").unwrap_or(&n.file_path);
            hay == needle && n.name == name
        })
    }

    /// Find a node by file and name
    pub fn find_node(&self, file_path: &str, name: &str) -> Option<&CodeNode> {
        let needle = file_path.strip_prefix("./").unwrap_or(file_path);
        self.nodes.iter().find(|n| {
            let hay = n.file_path.strip_prefix("./").unwrap_or(&n.file_path);
            hay == needle && n.name == name
        })
    }

    /// Add nodes from a specific file
    pub fn add_file_nodes(
        &mut self,
        repo_dir: &Path,
        file_path: &Path,
        target_names: Option<&[String]>,
    ) -> anyhow::Result<()> {
        use anyhow::Context;

        let full_path = repo_dir.join(file_path);
        if !full_path.exists() {
            anyhow::bail!("File not found: {:?}", full_path);
        }

        let source = std::fs::read_to_string(&full_path)
            .context(format!("Failed to read {:?}", full_path))?;

        let mut parser = Parser::new();
        let language = tree_sitter_python::LANGUAGE;
        parser
            .set_language(&language.into())
            .context("Failed to set Python language")?;

        let tree = parser
            .parse(&source, None)
            .context("Failed to parse Python file")?;

        let file_path_str = file_path.to_string_lossy().to_string();

        let root = tree.root_node();

        fn extract_from_node(
            node: tree_sitter::Node,
            source: &str,
            file_path: &str,
            nodes: &mut Vec<CodeNode>,
            target_names: Option<&[String]>,
        ) {
            if node.kind() == "function_definition" {
                if let Some(name_node) = node.child_by_field_name("name") {
                    let name = &source[name_node.byte_range()];
                    let matched =
                        target_names.map_or(true, |targets| targets.iter().any(|t| t == name));
                    if matched {
                        let line = name_node.start_position().row + 1;
                        let id = format!("func:{}:{}", file_path, name);
                        nodes.push(CodeNode {
                            id,
                            kind: NodeKind::Function,
                            name: name.to_string(),
                            file_path: file_path.to_string(),
                            line: Some(line),
                            decorators: vec![],
                            signature: None,
                            docstring: None,
                            line_count: 0,
                            is_test: false,
                        });
                    }
                }
            } else if node.kind() == "class_definition" {
                if let Some(name_node) = node.child_by_field_name("name") {
                    let name = &source[name_node.byte_range()];
                    let matched =
                        target_names.map_or(true, |targets| targets.iter().any(|t| t == name));
                    if matched {
                        let line = name_node.start_position().row + 1;
                        let id = format!("class:{}:{}", file_path, name);
                        nodes.push(CodeNode {
                            id,
                            kind: NodeKind::Class,
                            name: name.to_string(),
                            file_path: file_path.to_string(),
                            line: Some(line),
                            decorators: vec![],
                            signature: None,
                            docstring: None,
                            line_count: 0,
                            is_test: false,
                        });
                    }
                }
            }

            for child in node.children(&mut node.walk()) {
                extract_from_node(child, source, file_path, nodes, target_names);
            }
        }

        extract_from_node(root, &source, &file_path_str, &mut self.nodes, target_names);
        self.build_indexes();

        Ok(())
    }

    /// Return graph schema information
    pub fn get_schema(&self) -> String {
        let node_kinds: HashSet<&str> = self.nodes.iter().map(|n| match n.kind {
            NodeKind::File => "File",
            NodeKind::Class => "Class",
            NodeKind::Function => "Function",
            NodeKind::Module => "Module",
        }).collect();

        let edge_relations: HashSet<&str> = self.edges.iter().map(|e| match e.relation {
            EdgeRelation::Imports => "imports",
            EdgeRelation::Inherits => "inherits",
            EdgeRelation::DefinedIn => "defined_in",
            EdgeRelation::Calls => "calls",
            EdgeRelation::TestsFor => "tests_for",
            EdgeRelation::Overrides => "overrides",
        }).collect();

        format!(
            "Schema:\n  Node kinds: {:?}\n  Edge relations: {:?}\n  Total nodes: {}\n  Total edges: {}",
            node_kinds,
            edge_relations,
            self.nodes.len(),
            self.edges.len()
        )
    }

    /// Get file-level summary
    pub fn get_file_summary(&self, file_path: &str) -> String {
        let file_nodes: Vec<&CodeNode> = self.nodes.iter()
            .filter(|n| n.file_path == file_path)
            .collect();

        if file_nodes.is_empty() {
            return format!("No nodes found for file: {}", file_path);
        }

        let classes: Vec<&str> = file_nodes.iter()
            .filter(|n| n.kind == NodeKind::Class)
            .map(|n| n.name.as_str())
            .collect();

        let functions: Vec<&str> = file_nodes.iter()
            .filter(|n| n.kind == NodeKind::Function)
            .map(|n| n.name.as_str())
            .collect();

        format!(
            "File: {}\n  Classes ({}): {}\n  Functions ({}): {}",
            file_path,
            classes.len(),
            classes.join(", "),
            functions.len(),
            functions.join(", ")
        )
    }

    // ═══ Failure Analysis ═══

    /// Analyze test failures using graph structure.
    /// Given changed nodes and failed test names, trace call chains and explain WHY tests failed.
    pub fn analyze_test_failures(
        &self,
        changed_node_ids: &[&str],
        failed_test_names: &[String],
        _repo_dir: &Path,
    ) -> String {
        let mut analysis = String::new();
        analysis.push_str("## 🔍 Graph-based Failure Analysis\n\n");

        // Map changed node IDs to names for readable output
        let changed_names: Vec<String> = changed_node_ids.iter()
            .filter_map(|id| self.node_by_id(id))
            .map(|n| n.name.clone())
            .collect();

        let changed_files: HashSet<String> = changed_node_ids.iter()
            .filter_map(|id| self.node_by_id(id))
            .map(|n| n.file_path.clone())
            .collect();

        // For each failed test, trace the connection to our changes
        for test_name in failed_test_names {
            // Extract the short function name from test ID
            // e.g., "tests/test_foo.py::test_bar" → "test_bar"
            let short_name = test_name.split("::").last().unwrap_or(test_name);
            
            // Find this test in the graph
            let test_node = self.nodes.iter().find(|n| {
                n.name == short_name
                    || n.name.ends_with(short_name)
                    || (n.file_path.contains("/test") && n.name == short_name)
            });

            analysis.push_str(&format!("### ❌ {}\n", short_name));

            if let Some(test) = test_node {
                // Trace: what does this test call that we changed?
                let callees = self.get_callees(&test.id);
                let mut found_connection = false;

                for callee in &callees {
                    if changed_node_ids.contains(&callee.id.as_str())
                        || changed_names.contains(&callee.name)
                    {
                        analysis.push_str(&format!(
                            "**Direct call chain:** `{}` → `{}` (YOU CHANGED THIS)\n",
                            short_name, callee.name
                        ));
                        found_connection = true;

                        // Show other callers of the changed function
                        let other_callers = self.get_callers(&callee.id);
                        let other_caller_names: Vec<&str> = other_callers.iter()
                            .filter(|c| c.id != test.id)
                            .map(|c| c.name.as_str())
                            .take(5)
                            .collect();
                        if !other_caller_names.is_empty() {
                            analysis.push_str(&format!(
                                "**Other callers of `{}`:** {}\n",
                                callee.name,
                                other_caller_names.join(", ")
                            ));
                        }
                    }
                }

                // If no direct connection, check indirect (2-hop)
                if !found_connection {
                    for callee in &callees {
                        let sub_callees = self.get_callees(&callee.id);
                        for sub in &sub_callees {
                            if changed_node_ids.contains(&sub.id.as_str())
                                || changed_names.contains(&sub.name)
                            {
                                analysis.push_str(&format!(
                                    "**Indirect chain:** `{}` → `{}` → `{}` (YOU CHANGED THIS)\n",
                                    short_name, callee.name, sub.name
                                ));
                                found_connection = true;
                                break;
                            }
                        }
                        if found_connection { break; }
                    }
                }

                // If still no connection, check file-level TestsFor edges
                if !found_connection {
                    let test_file = &test.file_path;
                    let test_file_id = format!("file:{}", test_file);
                    
                    for edge in self.outgoing_edges(&test_file_id) {
                        if edge.relation == EdgeRelation::TestsFor {
                            if let Some(target) = self.node_by_id(&edge.to) {
                                if changed_files.contains(&target.file_path) {
                                    analysis.push_str(&format!(
                                        "**File-level connection:** test file `{}` tests `{}` which you modified\n",
                                        test_file, target.file_path
                                    ));
                                    found_connection = true;
                                    break;
                                }
                            }
                        }
                    }
                }

                if !found_connection {
                    analysis.push_str("**Connection:** Could not trace via graph (may be indirect import)\n");
                }
            } else {
                analysis.push_str("**Note:** Test not found in code graph\n");
            }
            analysis.push('\n');
        }

        // Summary
        if !changed_names.is_empty() {
            analysis.push_str("### Summary\n");
            analysis.push_str(&format!("**You changed:** {}\n", changed_names.join(", ")));
            
            let total_callers: usize = changed_node_ids.iter()
                .map(|id| self.get_callers(id).len())
                .sum();
            analysis.push_str(&format!(
                "**Total callers of changed code:** {}\n",
                total_callers
            ));
            analysis.push_str("**Repair strategy:** Keep the fix but make it backward-compatible with all callers.\n");
        }

        analysis
    }

    /// Find symptom nodes from test names and issue text.
    ///
    /// Parses test names (JSON array or newline-separated), finds matching test nodes.
    /// Also finds nodes mentioned in issue text (functions/classes in error messages/tracebacks).
    /// Returns combined list, tests first.
    pub fn find_symptom_nodes(&self, problem_statement: &str, test_names: &str) -> Vec<&CodeNode> {
        let mut result: Vec<&CodeNode> = Vec::new();
        let mut seen = HashSet::new();

        // 1. Parse test names (try JSON first, then newline-separated)
        let test_list: Vec<String> = serde_json::from_str(test_names)
            .unwrap_or_else(|_| {
                test_names.lines()
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty())
                    .collect()
            });

        for test_id in &test_list {
            // Extract short test function name from various formats:
            // "tests/test_foo.py::TestClass::test_method" → "test_method"
            // "test_method (module.TestClass)" → "test_method"
            let short_name = if test_id.contains("::") {
                test_id.split("::").last().unwrap_or(test_id)
            } else if test_id.contains(" (") {
                test_id.split(" (").next().unwrap_or(test_id).trim()
            } else {
                test_id.as_str()
            };

            // Find matching test node in graph
            for node in &self.nodes {
                if node.kind == NodeKind::Function
                    && (node.name == short_name || node.name.ends_with(short_name))
                    && (node.file_path.contains("/tests/")
                        || node.file_path.contains("/test_")
                        || node.name.starts_with("test_"))
                {
                    if seen.insert(node.id.clone()) {
                        result.push(node);
                    }
                }
            }
        }

        // 2. Find nodes mentioned in issue text (functions/classes in tracebacks)
        for line in problem_statement.lines() {
            let trimmed = line.trim();

            // Python traceback: "File \"path\", line N, in <function_name>"
            if trimmed.contains(", in ") {
                if let Some(func_part) = trimmed.rsplit(", in ").next() {
                    let func_name = func_part.trim().trim_start_matches('<').trim_end_matches('>');
                    if func_name.len() >= 3 && func_name.chars().all(|c| c.is_alphanumeric() || c == '_') {
                        for node in &self.nodes {
                            if node.name == func_name && node.kind == NodeKind::Function {
                                if seen.insert(node.id.clone()) {
                                    result.push(node);
                                }
                            }
                        }
                    }
                }
            }

            // Look for quoted identifiers
            for quote in &['\'', '"', '`'] {
                let parts: Vec<&str> = trimmed.split(*quote).collect();
                for i in (1..parts.len()).step_by(2) {
                    let word = parts[i].trim();
                    if word.len() >= 3
                        && word.len() <= 60
                        && word.chars().all(|c| c.is_alphanumeric() || c == '_')
                    {
                        for node in &self.nodes {
                            if node.name == word && (node.kind == NodeKind::Function || node.kind == NodeKind::Class) {
                                if seen.insert(node.id.clone()) {
                                    result.push(node);
                                }
                            }
                        }
                    }
                }
            }
        }

        // 3. Match CamelCase class names from issue text
        for word in problem_statement.split(|c: char| c.is_whitespace() || c == ',' || c == '(' || c == ')' || c == '\'' || c == '"' || c == '`') {
            let word = word.trim_matches(|c: char| c == '.' || c == ':' || c == ';');
            if word.len() < 4 { continue; }
            let has_upper = word.chars().filter(|c| c.is_uppercase()).count() >= 2;
            let has_lower = word.chars().any(|c| c.is_lowercase());
            let is_ident = word.chars().all(|c| c.is_alphanumeric() || c == '_');
            if has_upper && has_lower && is_ident {
                for node in &self.nodes {
                    if node.name == word && node.kind == NodeKind::Class {
                        if seen.insert(node.id.clone()) {
                            result.push(node);
                        }
                    }
                }
            }
        }

        // 4. Fuzzy keyword matching from test names if we found nothing
        if result.is_empty() {
            for test_id in &test_list {
                let short_name = if test_id.contains("::") {
                    test_id.split("::").last().unwrap_or(test_id)
                } else if test_id.contains(" (") {
                    test_id.split(" (").next().unwrap_or(test_id).trim()
                } else {
                    test_id.as_str()
                };
                
                // Extract keywords: test_fast_delete_all → ["fast", "delete"]
                let kws: Vec<&str> = short_name.split('_')
                    .filter(|w| w.len() >= 3 && *w != "test" && *w != "tests")
                    .collect();
                if kws.is_empty() { continue; }
                
                // Find source (non-test) nodes that match keywords
                for node in &self.nodes {
                    if node.file_path.contains("/tests/") || node.file_path.contains("/test_") {
                        continue;
                    }
                    let name_lower = node.name.to_lowercase();
                    let match_count = kws.iter()
                        .filter(|kw| name_lower.contains(&kw.to_lowercase()))
                        .count();
                    if match_count >= 2 || (match_count >= 1 && kws.len() == 1) {
                        if seen.insert(node.id.clone()) {
                            result.push(node);
                        }
                    }
                }

                // Also try matching the test class name to find the test file → source imports
                // "test_method (module.tests.TestClass)" → "TestClass" → find the test file
                if test_id.contains(" (") {
                    let class_part = test_id
                        .split(" (")
                        .nth(1)
                        .unwrap_or("")
                        .trim_end_matches(')');
                    let class_name = class_part.rsplit('.').next().unwrap_or("");
                    if !class_name.is_empty() {
                        for node in &self.nodes {
                            if node.kind == NodeKind::Class && node.name == class_name {
                                let file_id = format!("file:{}", node.file_path);
                                for edge in self.outgoing_edges(&file_id) {
                                    if edge.relation == EdgeRelation::TestsFor {
                                        if let Some(target) = self.node_by_id(&edge.to) {
                                            if target.kind != NodeKind::File {
                                                if seen.insert(target.id.clone()) {
                                                    result.push(target);
                                                }
                                            }
                                        }
                                        for src_node in &self.nodes {
                                            if format!("file:{}", src_node.file_path) == edge.to
                                                && src_node.kind != NodeKind::File
                                            {
                                                if seen.insert(src_node.id.clone()) {
                                                    result.push(src_node);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        result
    }

    /// Build a unified graph combining code nodes with task structure.
    /// Returns a simplified representation suitable for task planning.
    pub fn build_unified_graph(
        &self,
        relevant_nodes: &[&CodeNode],
        snippets: &HashMap<String, String>,
        issue_id: &str,
        issue_description: &str,
    ) -> UnifiedGraphResult {
        let relevant_ids: HashSet<&str> = relevant_nodes.iter()
            .map(|n| n.id.as_str())
            .collect();

        // Build nodes
        let mut nodes: Vec<UnifiedNode> = Vec::new();
        for code_node in relevant_nodes {
            let node_id = code_node.name.replace(|c: char| !c.is_alphanumeric() && c != '_', "_");
            
            let (node_type, layer) = match code_node.kind {
                NodeKind::File => ("File".to_string(), "infrastructure"),
                NodeKind::Class => ("Component".to_string(), "domain"),
                NodeKind::Function | NodeKind::Module => ("Component".to_string(), "application"),
            };
            
            let snippet = snippets.get(&code_node.id).cloned();
            
            nodes.push(UnifiedNode {
                id: node_id,
                node_type,
                layer: layer.to_string(),
                description: format!("{} in {}", code_node.name, code_node.file_path),
                path: Some(code_node.file_path.clone()),
                line: code_node.line,
                code: snippet,
            });
        }

        // Build edges using adjacency indexes
        let mut edges: Vec<UnifiedEdge> = Vec::new();
        let mut seen_keys: HashSet<(String, String, String)> = HashSet::new();
        
        for rel_id in &relevant_ids {
            for edge in self.outgoing_edges(rel_id) {
                if let (Some(from), Some(to)) = (self.node_by_id(&edge.from), self.node_by_id(&edge.to)) {
                    let from_id = from.name.replace(|c: char| !c.is_alphanumeric() && c != '_', "_");
                    let to_id = to.name.replace(|c: char| !c.is_alphanumeric() && c != '_', "_");
                    let rel = edge.relation.to_string();
                    let key = (from_id.clone(), to_id.clone(), rel.clone());
                    
                    if nodes.iter().any(|n| n.id == from_id) 
                        && nodes.iter().any(|n| n.id == to_id)
                        && seen_keys.insert(key)
                    {
                        edges.push(UnifiedEdge {
                            from: from_id,
                            to: to_id,
                            relation: rel,
                        });
                    }
                }
            }
        }

        let description = if issue_description.len() > 100 {
            let mut end = 100;
            while end > 0 && !issue_description.is_char_boundary(end) { end -= 1; }
            format!("{}...", &issue_description[..end])
        } else {
            issue_description.to_string()
        };

        UnifiedGraphResult {
            issue_id: issue_id.to_string(),
            description,
            nodes,
            edges,
        }
    }
}

/// Result of build_unified_graph — a simplified graph structure for task planning
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UnifiedGraphResult {
    pub issue_id: String,
    pub description: String,
    pub nodes: Vec<UnifiedNode>,
    pub edges: Vec<UnifiedEdge>,
}

/// A node in the unified graph
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UnifiedNode {
    pub id: String,
    pub node_type: String,
    pub layer: String,
    pub description: String,
    pub path: Option<String>,
    pub line: Option<usize>,
    pub code: Option<String>,
}

/// An edge in the unified graph
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UnifiedEdge {
    pub from: String,
    pub to: String,
    pub relation: String,
}

// ═══ Tree-sitter extraction helpers ═══

fn collect_decorators(node: tree_sitter::Node, source: &[u8]) -> Vec<String> {
    let mut decorators = Vec::new();
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "decorator" {
            let dec_text = child.utf8_text(source).unwrap_or("").trim().to_string();
            let name = dec_text.trim_start_matches('@');
            let name = name.split('(').next().unwrap_or(name).trim();
            if !name.is_empty() {
                decorators.push(name.to_string());
            }
        }
    }
    decorators
}

fn extract_docstring(node: tree_sitter::Node, source: &str) -> Option<String> {
    let body = node.child_by_field_name("body")?;
    let mut cursor = body.walk();
    for child in body.children(&mut cursor) {
        if child.kind() == "comment" {
            continue;
        }
        if child.kind() == "expression_statement" {
            if let Some(str_node) = child.child(0) {
                if str_node.kind() == "string" || str_node.kind() == "concatenated_string" {
                    if str_node.start_byte() < source.len() && str_node.end_byte() <= source.len() {
                        let doc_text = &source[str_node.start_byte()..str_node.end_byte()];
                        let doc_clean = doc_text
                            .trim_start_matches("\"\"\"")
                            .trim_end_matches("\"\"\"")
                            .trim_start_matches("'''")
                            .trim_end_matches("'''")
                            .trim_start_matches('"')
                            .trim_end_matches('"')
                            .trim_start_matches('\'')
                            .trim_end_matches('\'')
                            .trim();
                        let first_line = doc_clean.lines().find(|l| !l.trim().is_empty()).unwrap_or("");
                        if first_line.is_empty() {
                            return None;
                        }
                        let truncated = if first_line.len() > 100 {
                            let mut end = 100;
                            while end > 0 && !first_line.is_char_boundary(end) {
                                end -= 1;
                            }
                            &first_line[..end]
                        } else {
                            first_line
                        };
                        return Some(truncated.to_string());
                    }
                }
            }
        }
        break;
    }
    None
}

fn is_in_error_path(node: &tree_sitter::Node, source: &[u8]) -> bool {
    let source_str = std::str::from_utf8(source).unwrap_or("");
    let mut current = node.parent();
    let mut levels = 0;
    while let Some(parent) = current {
        levels += 1;
        if levels > 10 {
            break;
        }
        match parent.kind() {
            "except_clause" | "raise_statement" => return true,
            "try_statement" => return true,
            "if_statement" => {
                if let Some(cond) = parent.child_by_field_name("condition") {
                    if cond.start_byte() < source_str.len() && cond.end_byte() <= source_str.len() {
                        let cond_text = &source_str[cond.start_byte()..cond.end_byte()];
                        let lower = cond_text.to_lowercase();
                        if lower.contains("error")
                            || lower.contains("exception")
                            || lower.contains("err")
                            || lower.contains("fail")
                            || lower.contains("none")
                        {
                            return true;
                        }
                    }
                }
            }
            _ => {}
        }
        current = parent.parent();
    }
    false
}

/// Extract Python code using tree-sitter AST parsing
fn extract_python_tree_sitter(
    path: &str,
    content: &str,
    parser: &mut Parser,
    class_id_map: &mut HashMap<String, String>,
) -> (Vec<CodeNode>, Vec<CodeEdge>, HashSet<String>) {
    let mut nodes = Vec::new();
    let mut edges = Vec::new();
    let mut imports = HashSet::new();

    let tree = match parser.parse(content, None) {
        Some(t) => t,
        None => return (nodes, edges, imports),
    };

    let file_id = format!("file:{}", path);
    let source = content.as_bytes();
    let root = tree.root_node();

    let text = |node: tree_sitter::Node| -> String {
        node.utf8_text(source).unwrap_or("").to_string()
    };

    let mut cursor = root.walk();
    for child in root.children(&mut cursor) {
        match child.kind() {
            "class_definition" => {
                extract_class_node(
                    child,
                    source,
                    content,
                    path,
                    &file_id,
                    &[],
                    &mut nodes,
                    &mut edges,
                    class_id_map,
                );
            }
            "function_definition" => {
                extract_function_node(child, source, content, path, &file_id, &[], &mut nodes, &mut edges);
            }
            "decorated_definition" => {
                let decorators = collect_decorators(child, source);
                let mut inner_cursor = child.walk();
                for inner in child.children(&mut inner_cursor) {
                    match inner.kind() {
                        "class_definition" => {
                            extract_class_node(
                                inner,
                                source,
                                content,
                                path,
                                &file_id,
                                &decorators,
                                &mut nodes,
                                &mut edges,
                                class_id_map,
                            );
                        }
                        "function_definition" => {
                            extract_function_node(
                                inner, source, content, path, &file_id, &decorators, &mut nodes, &mut edges,
                            );
                        }
                        _ => {}
                    }
                }
            }
            "import_statement" => {
                let import_text = text(child);
                let re_import = Regex::new(r"import\s+([\w.]+)").unwrap();
                if let Some(cap) = re_import.captures(&import_text) {
                    let module = cap[1].to_string();
                    if !is_stdlib(&module) {
                        edges.push(CodeEdge {
                            from: file_id.clone(),
                            to: format!("module_ref:{}", module),
                            relation: EdgeRelation::Imports,
                            weight: 0.5,
                            call_count: 1,
                            in_error_path: false,
                            confidence: 1.0,
                        });
                    }
                }
            }
            "import_from_statement" => {
                let mut mod_cursor = child.walk();
                for mod_child in child.children(&mut mod_cursor) {
                    if mod_child.kind() == "dotted_name" {
                        let module = text(mod_child);
                        if !is_stdlib(&module) {
                            edges.push(CodeEdge {
                                from: file_id.clone(),
                                to: format!("module_ref:{}", module),
                                relation: EdgeRelation::Imports,
                                weight: 0.5,
                                call_count: 1,
                                in_error_path: false,
                                confidence: 1.0,
                            });
                        }
                        break;
                    }
                    if mod_child.kind() == "relative_import" {
                        let rel_import_text = text(mod_child);
                        let trimmed = rel_import_text.trim_start_matches('.');
                        if !trimmed.is_empty() && !is_stdlib(trimmed) {
                            edges.push(CodeEdge {
                                from: file_id.clone(),
                                to: format!("module_ref:{}", trimmed),
                                relation: EdgeRelation::Imports,
                                weight: 0.5,
                                call_count: 1,
                                in_error_path: false,
                                confidence: 1.0,
                            });
                        }
                        break;
                    }
                }

                // Extract imported names
                let import_text = child.utf8_text(source).unwrap_or("");
                if let Some(after_import) = import_text.split(" import ").nth(1) {
                    for name in after_import.split(',') {
                        let clean = name.trim().split(" as ").next().unwrap_or("").trim();
                        if !clean.is_empty() && clean != "*" && clean != "(" && clean != ")" {
                            imports.insert(clean.to_string());
                        }
                    }
                }
            }
            _ => {}
        }
    }

    (nodes, edges, imports)
}

fn extract_class_node(
    node: tree_sitter::Node,
    source: &[u8],
    source_str: &str,
    path: &str,
    file_id: &str,
    decorators: &[String],
    nodes: &mut Vec<CodeNode>,
    edges: &mut Vec<CodeEdge>,
    class_id_map: &mut HashMap<String, String>,
) {
    let class_name = node
        .child_by_field_name("name")
        .and_then(|n| n.utf8_text(source).ok())
        .unwrap_or("")
        .to_string();

    if class_name.is_empty() {
        return;
    }

    let line_num = node.start_position().row + 1;
    let class_id = format!("class:{}:{}", path, class_name);

    let class_sig = {
        let sig_text = &source_str[node.start_byte()..];
        let sig_end = sig_text
            .find(":\n")
            .or_else(|| sig_text.find(":\r"))
            .unwrap_or(sig_text.len().min(200));
        Some(sig_text[..sig_end].trim().to_string())
    };

    let class_docstring = extract_docstring(node, source_str);
    let class_line_count = node.end_position().row - node.start_position().row + 1;
    let class_is_test =
        path.contains("/tests/") || path.contains("/test_") || class_name.starts_with("Test");

    nodes.push(CodeNode {
        id: class_id.clone(),
        kind: NodeKind::Class,
        name: class_name.clone(),
        file_path: path.to_string(),
        line: Some(line_num),
        decorators: decorators.to_vec(),
        signature: class_sig,
        docstring: class_docstring,
        line_count: class_line_count,
        is_test: class_is_test,
    });

    edges.push(CodeEdge {
        from: class_id.clone(),
        to: file_id.to_string(),
        relation: EdgeRelation::DefinedIn,
        weight: 0.5,
        call_count: 1,
        in_error_path: false,
        confidence: 1.0,
    });

    class_id_map.insert(class_name.clone(), class_id.clone());

    // Inheritance
    if let Some(superclasses) = node.child_by_field_name("superclasses") {
        let mut sc_cursor = superclasses.walk();
        for sc_child in superclasses.children(&mut sc_cursor) {
            let kind = sc_child.kind();
            if kind == "identifier" || kind == "attribute" {
                let parent_text = sc_child.utf8_text(source).unwrap_or("");
                let parent_name = parent_text.split('.').last().unwrap_or("").trim();
                if !parent_name.is_empty() && parent_name != "object" {
                    edges.push(CodeEdge {
                        from: class_id.clone(),
                        to: format!("class_ref:{}", parent_name),
                        relation: EdgeRelation::Inherits,
                        weight: 0.5,
                        call_count: 1,
                        in_error_path: false,
                        confidence: 1.0,
                    });
                }
            }
        }
    }

    // Extract methods
    if let Some(body) = node.child_by_field_name("body") {
        let mut body_cursor = body.walk();
        for body_child in body.children(&mut body_cursor) {
            match body_child.kind() {
                "function_definition" => {
                    extract_method_node(body_child, source, source_str, path, &class_id, &[], nodes, edges);
                }
                "decorated_definition" => {
                    let method_decorators = collect_decorators(body_child, source);
                    let mut inner_cursor = body_child.walk();
                    for inner in body_child.children(&mut inner_cursor) {
                        if inner.kind() == "function_definition" {
                            extract_method_node(
                                inner,
                                source,
                                source_str,
                                path,
                                &class_id,
                                &method_decorators,
                                nodes,
                                edges,
                            );
                        }
                    }
                }
                _ => {}
            }
        }
    }
}

fn extract_method_node(
    node: tree_sitter::Node,
    source: &[u8],
    source_str: &str,
    path: &str,
    class_id: &str,
    decorators: &[String],
    nodes: &mut Vec<CodeNode>,
    edges: &mut Vec<CodeEdge>,
) {
    let func_name = node
        .child_by_field_name("name")
        .and_then(|n| n.utf8_text(source).ok())
        .unwrap_or("")
        .to_string();

    if func_name.is_empty() {
        return;
    }

    let line_num = node.start_position().row + 1;
    let method_id = format!("method:{}:{}", path, func_name);

    let signature = {
        let sig_text = &source_str[node.start_byte()..];
        let sig_end = sig_text
            .find(":\n")
            .or_else(|| sig_text.find(":\r"))
            .unwrap_or(sig_text.len().min(200));
        Some(sig_text[..sig_end].trim().to_string())
    };
    let docstring = extract_docstring(node, source_str);
    let line_count = node.end_position().row - node.start_position().row + 1;
    let is_test = path.contains("/tests/")
        || path.contains("/test_")
        || func_name.starts_with("test_")
        || func_name.starts_with("Test");

    nodes.push(CodeNode {
        id: method_id.clone(),
        kind: NodeKind::Function,
        name: func_name,
        file_path: path.to_string(),
        line: Some(line_num),
        decorators: decorators.to_vec(),
        signature,
        docstring,
        line_count,
        is_test,
    });

    edges.push(CodeEdge {
        from: method_id,
        to: class_id.to_string(),
        relation: EdgeRelation::DefinedIn,
        weight: 0.5,
        call_count: 1,
        in_error_path: false,
        confidence: 1.0,
    });
}

fn extract_function_node(
    node: tree_sitter::Node,
    source: &[u8],
    source_str: &str,
    path: &str,
    file_id: &str,
    decorators: &[String],
    nodes: &mut Vec<CodeNode>,
    edges: &mut Vec<CodeEdge>,
) {
    let func_name = node
        .child_by_field_name("name")
        .and_then(|n| n.utf8_text(source).ok())
        .unwrap_or("")
        .to_string();

    if func_name.is_empty() {
        return;
    }

    let line_num = node.start_position().row + 1;
    let func_id = format!("func:{}:{}", path, func_name);

    let signature = {
        let sig_text = &source_str[node.start_byte()..];
        let sig_end = sig_text
            .find(":\n")
            .or_else(|| sig_text.find(":\r"))
            .unwrap_or(sig_text.len().min(200));
        Some(sig_text[..sig_end].trim().to_string())
    };
    let docstring = extract_docstring(node, source_str);
    let line_count = node.end_position().row - node.start_position().row + 1;
    let is_test = path.contains("/tests/")
        || path.contains("/test_")
        || func_name.starts_with("test_")
        || func_name.starts_with("Test");

    nodes.push(CodeNode {
        id: func_id.clone(),
        kind: NodeKind::Function,
        name: func_name,
        file_path: path.to_string(),
        line: Some(line_num),
        decorators: decorators.to_vec(),
        signature,
        docstring,
        line_count,
        is_test,
    });

    edges.push(CodeEdge {
        from: func_id,
        to: file_id.to_string(),
        relation: EdgeRelation::DefinedIn,
        weight: 0.5,
        call_count: 1,
        in_error_path: false,
        confidence: 1.0,
    });
}

/// Extract call edges from tree-sitter AST
fn extract_calls_from_tree(
    root: tree_sitter::Node,
    source: &[u8],
    rel_path: &str,
    func_name_map: &HashMap<String, Vec<String>>,
    method_to_class: &HashMap<String, String>,
    class_parents: &HashMap<String, Vec<String>>,
    file_func_ids: &HashSet<String>,
    file_imported_names: &HashMap<String, HashSet<String>>,
    package_dir: &str,
    class_init_map: &HashMap<String, Vec<(String, String)>>,
    node_pkg_map: &HashMap<String, String>,
    edges: &mut Vec<CodeEdge>,
) {
    // Build scope map
    let mut scope_map: Vec<(usize, usize, String, Option<String>)> = Vec::new();
    build_scope_map(root, source, rel_path, &mut scope_map);

    // Walk tree looking for calls
    let mut stack = vec![root];
    while let Some(node) = stack.pop() {
        if node.kind() == "string"
            || node.kind() == "comment"
            || node.kind() == "string_content"
            || node.kind() == "concatenated_string"
        {
            continue;
        }

        if node.kind() == "call" {
            let call_line = node.start_position().row + 1;
            let error_path = is_in_error_path(&node, source);

            let scope = scope_map
                .iter()
                .filter(|(start, end, _, _)| call_line >= *start && call_line <= *end)
                .max_by_key(|(start, _, _, _)| *start);

            if let Some((_start, _end, caller_id, caller_class)) = scope {
                if let Some(function_node) = node.child_by_field_name("function") {
                    let edges_before = edges.len();
                    match function_node.kind() {
                        "identifier" => {
                            let callee_name = function_node.utf8_text(source).unwrap_or("");
                            if !callee_name.is_empty() && !is_python_builtin(callee_name) {
                                resolve_and_add_call_edge(
                                    caller_id,
                                    callee_name,
                                    func_name_map,
                                    file_func_ids,
                                    file_imported_names,
                                    rel_path,
                                    package_dir,
                                    class_init_map,
                                    node_pkg_map,
                                    false,
                                    edges,
                                );
                            }
                        }
                        "attribute" => {
                            let obj_node = function_node.child_by_field_name("object");
                            let attr_node = function_node.child_by_field_name("attribute");

                            if let (Some(obj), Some(attr)) = (obj_node, attr_node) {
                                let obj_text = obj.utf8_text(source).unwrap_or("");
                                let method_name = attr.utf8_text(source).unwrap_or("");

                                if (obj_text == "self" || obj_text == "cls") && !method_name.is_empty() {
                                    resolve_self_method_call(
                                        caller_id,
                                        method_name,
                                        caller_class.as_deref(),
                                        func_name_map,
                                        method_to_class,
                                        class_parents,
                                        file_func_ids,
                                        edges,
                                    );
                                } else if !method_name.is_empty() && !is_python_builtin(method_name) {
                                    resolve_and_add_call_edge(
                                        caller_id,
                                        method_name,
                                        func_name_map,
                                        file_func_ids,
                                        file_imported_names,
                                        rel_path,
                                        package_dir,
                                        class_init_map,
                                        node_pkg_map,
                                        true,
                                        edges,
                                    );
                                }
                            }
                        }
                        _ => {}
                    }
                    if error_path {
                        for edge in edges[edges_before..].iter_mut() {
                            edge.in_error_path = true;
                        }
                    }
                }
            }
        }

        let child_count = node.child_count();
        for i in (0..child_count).rev() {
            if let Some(child) = node.child(i) {
                stack.push(child);
            }
        }
    }
}

fn build_scope_map(
    node: tree_sitter::Node,
    source: &[u8],
    rel_path: &str,
    scope_map: &mut Vec<(usize, usize, String, Option<String>)>,
) {
    let mut stack: Vec<(tree_sitter::Node, Option<String>)> = vec![(node, None)];

    while let Some((current, class_ctx)) = stack.pop() {
        match current.kind() {
            "class_definition" => {
                let class_name = current
                    .child_by_field_name("name")
                    .and_then(|n| n.utf8_text(source).ok())
                    .unwrap_or("");
                let class_id = if !class_name.is_empty() {
                    Some(format!("class:{}:{}", rel_path, class_name))
                } else {
                    class_ctx.clone()
                };

                let child_count = current.child_count();
                for i in (0..child_count).rev() {
                    if let Some(child) = current.child(i) {
                        stack.push((child, class_id.clone()));
                    }
                }
            }
            "function_definition" => {
                let func_name = current
                    .child_by_field_name("name")
                    .and_then(|n| n.utf8_text(source).ok())
                    .unwrap_or("");

                if !func_name.is_empty() {
                    let start_line = current.start_position().row + 1;
                    let end_line = current.end_position().row + 1;

                    let func_id = if class_ctx.is_some() {
                        format!("method:{}:{}", rel_path, func_name)
                    } else {
                        format!("func:{}:{}", rel_path, func_name)
                    };

                    scope_map.push((start_line, end_line, func_id, class_ctx.clone()));
                }

                let child_count = current.child_count();
                for i in (0..child_count).rev() {
                    if let Some(child) = current.child(i) {
                        stack.push((child, class_ctx.clone()));
                    }
                }
            }
            "decorated_definition" => {
                let child_count = current.child_count();
                for i in (0..child_count).rev() {
                    if let Some(child) = current.child(i) {
                        stack.push((child, class_ctx.clone()));
                    }
                }
            }
            _ => {
                let child_count = current.child_count();
                for i in (0..child_count).rev() {
                    if let Some(child) = current.child(i) {
                        stack.push((child, class_ctx.clone()));
                    }
                }
            }
        }
    }
}

fn is_common_dunder(name: &str) -> bool {
    matches!(
        name,
        "__init__"
            | "__str__"
            | "__repr__"
            | "__eq__"
            | "__ne__"
            | "__hash__"
            | "__len__"
            | "__iter__"
            | "__next__"
            | "__getitem__"
            | "__setitem__"
            | "__delitem__"
            | "__contains__"
            | "__call__"
            | "__enter__"
            | "__exit__"
            | "__get__"
            | "__set__"
            | "__delete__"
            | "__getattr__"
            | "__setattr__"
            | "__bool__"
            | "__lt__"
            | "__le__"
            | "__gt__"
            | "__ge__"
            | "__add__"
            | "__sub__"
            | "__mul__"
            | "__new__"
            | "__del__"
            | "__format__"
            | "get"
            | "set"
            | "update"
            | "delete"
            | "save"
            | "clean"
            | "run"
            | "setup"
            | "teardown"
    )
}

fn resolve_and_add_call_edge(
    caller_id: &str,
    callee_name: &str,
    func_name_map: &HashMap<String, Vec<String>>,
    file_func_ids: &HashSet<String>,
    file_imported_names: &HashMap<String, HashSet<String>>,
    rel_path: &str,
    package_dir: &str,
    class_init_map: &HashMap<String, Vec<(String, String)>>,
    node_pkg_map: &HashMap<String, String>,
    is_attribute_call: bool,
    edges: &mut Vec<CodeEdge>,
) {
    if let Some(callee_ids) = func_name_map.get(callee_name) {
        let same_file: Vec<&String> = callee_ids
            .iter()
            .filter(|id| file_func_ids.contains(*id))
            .collect();
        let imported: Vec<&String> = callee_ids
            .iter()
            .filter(|_id| {
                file_imported_names
                    .get(rel_path)
                    .map(|names| names.contains(callee_name))
                    .unwrap_or(false)
            })
            .collect();
        let same_pkg: Vec<&String> = callee_ids
            .iter()
            .filter(|id| {
                node_pkg_map
                    .get(id.as_str())
                    .map(|pkg| pkg == package_dir)
                    .unwrap_or(false)
            })
            .collect();

        let global_limit = if is_attribute_call && !is_common_dunder(callee_name) {
            20
        } else {
            3
        };

        let confidence = if !same_file.is_empty() {
            0.8_f32
        } else if !imported.is_empty() {
            0.8
        } else if !same_pkg.is_empty() {
            0.7
        } else if is_attribute_call {
            0.3
        } else {
            0.5
        };

        let weight = if !same_file.is_empty() || !imported.is_empty() || !same_pkg.is_empty() {
            0.5
        } else if is_attribute_call {
            0.8
        } else {
            0.5
        };

        let targets = if !same_file.is_empty() {
            same_file
        } else if !imported.is_empty() {
            imported
        } else if !same_pkg.is_empty() {
            same_pkg
        } else if callee_ids.len() <= global_limit {
            callee_ids.iter().collect()
        } else {
            vec![]
        };

        for callee_id in targets {
            if callee_id != caller_id {
                edges.push(CodeEdge {
                    from: caller_id.to_string(),
                    to: callee_id.clone(),
                    relation: EdgeRelation::Calls,
                    weight,
                    call_count: 1,
                    in_error_path: false,
                    confidence,
                });
            }
        }
    } else if callee_name
        .chars()
        .next()
        .map(|c| c.is_uppercase())
        .unwrap_or(false)
    {
        // Constructor call
        if let Some(init_entries) = class_init_map.get(callee_name) {
            let same_file: Vec<&str> = init_entries
                .iter()
                .filter(|(fp, _)| fp == rel_path)
                .map(|(_, id)| id.as_str())
                .collect();
            let is_imported = file_imported_names
                .get(rel_path)
                .map(|names| names.contains(callee_name))
                .unwrap_or(false);
            let imported: Vec<&str> = if is_imported {
                init_entries.iter().map(|(_, id)| id.as_str()).collect()
            } else {
                vec![]
            };
            let same_pkg: Vec<&str> = init_entries
                .iter()
                .filter(|(fp, _)| fp.rsplitn(2, '/').nth(1).unwrap_or("") == package_dir)
                .map(|(_, id)| id.as_str())
                .collect();

            let (targets, confidence): (Vec<&str>, f32) = if !same_file.is_empty() {
                (same_file, 0.8)
            } else if !imported.is_empty() {
                (imported, 0.7)
            } else if !same_pkg.is_empty() {
                (same_pkg, 0.6)
            } else if init_entries.len() <= 3 {
                (init_entries.iter().map(|(_, id)| id.as_str()).collect(), 0.5)
            } else {
                (vec![], 0.0)
            };

            for init_id in targets {
                if init_id != caller_id {
                    edges.push(CodeEdge {
                        from: caller_id.to_string(),
                        to: init_id.to_string(),
                        relation: EdgeRelation::Calls,
                        weight: 0.5,
                        call_count: 1,
                        in_error_path: false,
                        confidence,
                    });
                }
            }
        }
    }
}

fn resolve_self_method_call(
    caller_id: &str,
    method_name: &str,
    caller_class: Option<&str>,
    func_name_map: &HashMap<String, Vec<String>>,
    method_to_class: &HashMap<String, String>,
    class_parents: &HashMap<String, Vec<String>>,
    file_func_ids: &HashSet<String>,
    edges: &mut Vec<CodeEdge>,
) {
    if let Some(callee_ids) = func_name_map.get(method_name) {
        if let Some(class_id) = caller_class {
            let mut valid_classes = vec![class_id.to_string()];
            if let Some(parents) = class_parents.get(class_id) {
                valid_classes.extend(parents.iter().cloned());
            }

            let scoped: Vec<&String> = callee_ids
                .iter()
                .filter(|id| {
                    method_to_class
                        .get(*id)
                        .map(|cls| valid_classes.contains(cls))
                        .unwrap_or(false)
                })
                .collect();

            let targets = if !scoped.is_empty() {
                scoped
            } else if callee_ids.len() <= 3 {
                callee_ids.iter().collect()
            } else {
                callee_ids
                    .iter()
                    .filter(|id| file_func_ids.contains(*id))
                    .collect()
            };

            for callee_id in targets {
                if callee_id != caller_id {
                    edges.push(CodeEdge {
                        from: caller_id.to_string(),
                        to: callee_id.clone(),
                        relation: EdgeRelation::Calls,
                        weight: 0.5,
                        call_count: 1,
                        in_error_path: false,
                        confidence: 0.9,
                    });
                }
            }
        } else {
            for callee_id in callee_ids {
                if callee_id != caller_id && file_func_ids.contains(callee_id) {
                    edges.push(CodeEdge {
                        from: caller_id.to_string(),
                        to: callee_id.clone(),
                        relation: EdgeRelation::Calls,
                        weight: 0.5,
                        call_count: 1,
                        in_error_path: false,
                        confidence: 0.6,
                    });
                }
            }
        }
    }
}

fn add_override_edges(nodes: &[CodeNode], edges: &mut Vec<CodeEdge>) {
    let mut class_methods: HashMap<String, Vec<(String, String)>> = HashMap::new();
    for edge in edges.iter() {
        if edge.relation == EdgeRelation::DefinedIn && edge.to.starts_with("class:") {
            if let Some(method) = nodes.iter().find(|n| n.id == edge.from && n.kind == NodeKind::Function) {
                class_methods
                    .entry(edge.to.clone())
                    .or_default()
                    .push((method.name.clone(), method.id.clone()));
            }
        }
    }

    let inherits_pairs: Vec<(String, String)> = edges
        .iter()
        .filter(|e| e.relation == EdgeRelation::Inherits)
        .map(|e| (e.from.clone(), e.to.clone()))
        .collect();

    let mut new_edges = Vec::new();
    for (sub_class_id, base_class_id) in &inherits_pairs {
        let sub_methods = match class_methods.get(sub_class_id) {
            Some(m) => m,
            None => continue,
        };
        let base_methods = match class_methods.get(base_class_id) {
            Some(m) => m,
            None => continue,
        };

        for (sub_name, sub_id) in sub_methods {
            for (base_name, base_id) in base_methods {
                if sub_name == base_name && sub_id != base_id {
                    new_edges.push(CodeEdge {
                        from: base_id.clone(),
                        to: sub_id.clone(),
                        relation: EdgeRelation::Overrides,
                        weight: 0.4,
                        call_count: 1,
                        in_error_path: false,
                        confidence: 0.6,
                    });
                }
            }
        }
    }

    edges.extend(new_edges);
}

// ═══ Language-Specific Extractors (Rust, TypeScript) ═══

// ─── Rust Tree-Sitter Extraction ───

/// Extract from Rust source using tree-sitter AST parsing.
/// Handles structs, enums, traits, impl blocks, functions, modules, and type aliases.
fn extract_rust_tree_sitter(
    path: &str,
    content: &str,
    parser: &mut Parser,
    class_id_map: &mut HashMap<String, String>,
) -> (Vec<CodeNode>, Vec<CodeEdge>, HashSet<String>) {
    let mut nodes = Vec::new();
    let mut edges = Vec::new();
    let mut imports = HashSet::new();

    // Set language for parser
    if parser.set_language(&tree_sitter_rust::LANGUAGE.into()).is_err() {
        return (nodes, edges, imports);
    }

    let tree = match parser.parse(content, None) {
        Some(t) => t,
        None => return (nodes, edges, imports),
    };

    let file_id = format!("file:{}", path);
    let source = content.as_bytes();
    let root = tree.root_node();

    // Track impl blocks to associate methods with types
    let mut impl_target_map: HashMap<String, String> = HashMap::new();

    let mut cursor = root.walk();
    for child in root.children(&mut cursor) {
        extract_rust_node(
            child,
            source,
            content,
            path,
            &file_id,
            &mut nodes,
            &mut edges,
            class_id_map,
            &mut impl_target_map,
            &mut imports,
            "",  // no parent module prefix at root
        );
    }

    (nodes, edges, imports)
}

/// Recursively extract Rust nodes from AST
fn extract_rust_node(
    node: tree_sitter::Node,
    source: &[u8],
    source_str: &str,
    path: &str,
    file_id: &str,
    nodes: &mut Vec<CodeNode>,
    edges: &mut Vec<CodeEdge>,
    class_id_map: &mut HashMap<String, String>,
    impl_target_map: &mut HashMap<String, String>,
    imports: &mut HashSet<String>,
    module_prefix: &str,
) {
    let text = |n: tree_sitter::Node| -> String {
        n.utf8_text(source).unwrap_or("").to_string()
    };

    match node.kind() {
        "use_declaration" => {
            // Extract import path
            let use_text = text(node);
            // Parse: use crate::foo::bar; or use std::collections::HashMap;
            if let Some(path_part) = use_text.strip_prefix("use ") {
                let clean_path = path_part.trim_end_matches(';').trim();
                // Skip std/core library imports
                if !clean_path.starts_with("std::") && !clean_path.starts_with("core::") && !clean_path.starts_with("alloc::") {
                    // Handle use paths with braces: use foo::{bar, baz}
                    let module = if clean_path.contains('{') {
                        clean_path.split("::").next().unwrap_or(clean_path).to_string()
                    } else {
                        clean_path.split("::").take(2).collect::<Vec<_>>().join("::")
                    };
                    if !module.is_empty() {
                        edges.push(CodeEdge {
                            from: file_id.to_string(),
                            to: format!("module_ref:{}", module),
                            relation: EdgeRelation::Imports,
                            weight: 0.5,
                            call_count: 1,
                            in_error_path: false,
                            confidence: 1.0,
                        });
                        imports.insert(module);
                    }
                }
            }
        }

        "struct_item" => {
            let name = node.child_by_field_name("name")
                .and_then(|n| n.utf8_text(source).ok())
                .unwrap_or("")
                .to_string();
            if name.is_empty() { return; }

            let full_name = if module_prefix.is_empty() { name.clone() } else { format!("{}::{}", module_prefix, name) };
            let line = node.start_position().row + 1;
            let class_id = format!("class:{}:{}", path, full_name);

            let signature = extract_rust_signature(node, source_str);
            let docstring = extract_rust_docstring(node, source_str);
            let line_count = node.end_position().row - node.start_position().row + 1;

            nodes.push(CodeNode {
                id: class_id.clone(),
                kind: NodeKind::Class,
                name: full_name.clone(),
                file_path: path.to_string(),
                line: Some(line),
                decorators: extract_rust_attributes(node, source),
                signature,
                docstring,
                line_count,
                is_test: path.contains("/tests/") || full_name.contains("Test"),
            });

            edges.push(CodeEdge::defined_in(&class_id, file_id));
            class_id_map.insert(name.clone(), class_id);
        }

        "enum_item" => {
            let name = node.child_by_field_name("name")
                .and_then(|n| n.utf8_text(source).ok())
                .unwrap_or("")
                .to_string();
            if name.is_empty() { return; }

            let full_name = if module_prefix.is_empty() { name.clone() } else { format!("{}::{}", module_prefix, name) };
            let line = node.start_position().row + 1;
            let class_id = format!("class:{}:{}", path, full_name);

            let signature = extract_rust_signature(node, source_str);
            let docstring = extract_rust_docstring(node, source_str);
            let line_count = node.end_position().row - node.start_position().row + 1;

            nodes.push(CodeNode {
                id: class_id.clone(),
                kind: NodeKind::Class,
                name: full_name.clone(),
                file_path: path.to_string(),
                line: Some(line),
                decorators: extract_rust_attributes(node, source),
                signature,
                docstring,
                line_count,
                is_test: path.contains("/tests/") || full_name.contains("Test"),
            });

            edges.push(CodeEdge::defined_in(&class_id, file_id));
            class_id_map.insert(name.clone(), class_id);
        }

        "trait_item" => {
            let name = node.child_by_field_name("name")
                .and_then(|n| n.utf8_text(source).ok())
                .unwrap_or("")
                .to_string();
            if name.is_empty() { return; }

            let full_name = if module_prefix.is_empty() { name.clone() } else { format!("{}::{}", module_prefix, name) };
            let line = node.start_position().row + 1;
            let trait_id = format!("class:{}:{}", path, full_name);

            let signature = extract_rust_signature(node, source_str);
            let docstring = extract_rust_docstring(node, source_str);
            let line_count = node.end_position().row - node.start_position().row + 1;

            nodes.push(CodeNode {
                id: trait_id.clone(),
                kind: NodeKind::Class,
                name: full_name.clone(),
                file_path: path.to_string(),
                line: Some(line),
                decorators: extract_rust_attributes(node, source),
                signature,
                docstring,
                line_count,
                is_test: path.contains("/tests/") || full_name.contains("Test"),
            });

            edges.push(CodeEdge::defined_in(&trait_id, file_id));
            class_id_map.insert(name.clone(), trait_id.clone());

            // Extract trait methods
            if let Some(body) = node.child_by_field_name("body") {
                let mut body_cursor = body.walk();
                for body_child in body.children(&mut body_cursor) {
                    if body_child.kind() == "function_item" || body_child.kind() == "function_signature_item" {
                        extract_rust_method(body_child, source, source_str, path, &trait_id, nodes, edges);
                    }
                }
            }
        }

        "impl_item" => {
            // Determine the target type and optional trait
            let mut trait_name: Option<String> = None;
            let mut type_name: Option<String> = None;

            // Parse impl structure: impl [Trait for] Type
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                match child.kind() {
                    "type_identifier" | "generic_type" => {
                        // This could be either the trait or the type
                        let name = if child.kind() == "generic_type" {
                            // Get the base type from generic: Vec<T> -> Vec
                            child.child_by_field_name("type")
                                .and_then(|n| n.utf8_text(source).ok())
                                .unwrap_or("")
                                .to_string()
                        } else {
                            text(child)
                        };
                        
                        if type_name.is_none() {
                            type_name = Some(name);
                        } else if trait_name.is_none() {
                            // If we already have a type, this first one was actually the trait
                            trait_name = type_name.take();
                            type_name = Some(name);
                        }
                    }
                    _ => {}
                }
            }

            let type_name = match type_name {
                Some(n) => n,
                None => return,
            };

            // Look for existing type node or create reference
            let type_id = class_id_map.get(&type_name)
                .cloned()
                .unwrap_or_else(|| format!("class:{}:{}", path, type_name));

            // If this is a trait impl, add inheritance edge
            if let Some(ref trait_n) = trait_name {
                edges.push(CodeEdge {
                    from: type_id.clone(),
                    to: format!("class_ref:{}", trait_n),
                    relation: EdgeRelation::Inherits,
                    weight: 0.5,
                    call_count: 1,
                    in_error_path: false,
                    confidence: 1.0,
                });
            }

            // Extract methods from impl block
            if let Some(body) = node.child_by_field_name("body") {
                let mut body_cursor = body.walk();
                for body_child in body.children(&mut body_cursor) {
                    if body_child.kind() == "function_item" {
                        extract_rust_method(body_child, source, source_str, path, &type_id, nodes, edges);
                    }
                }
            }
        }

        "function_item" => {
            // Top-level function (not in impl block)
            let name = node.child_by_field_name("name")
                .and_then(|n| n.utf8_text(source).ok())
                .unwrap_or("")
                .to_string();
            if name.is_empty() { return; }

            let full_name = if module_prefix.is_empty() { name.clone() } else { format!("{}::{}", module_prefix, name) };
            let line = node.start_position().row + 1;
            let func_id = format!("func:{}:{}", path, full_name);

            let signature = extract_rust_signature(node, source_str);
            let docstring = extract_rust_docstring(node, source_str);
            let line_count = node.end_position().row - node.start_position().row + 1;
            let is_test = path.contains("/tests/") || full_name.starts_with("test_") ||
                extract_rust_attributes(node, source).iter().any(|a| a.contains("test"));

            nodes.push(CodeNode {
                id: func_id.clone(),
                kind: NodeKind::Function,
                name: full_name,
                file_path: path.to_string(),
                line: Some(line),
                decorators: extract_rust_attributes(node, source),
                signature,
                docstring,
                line_count,
                is_test,
            });

            edges.push(CodeEdge::defined_in(&func_id, file_id));
        }

        "mod_item" => {
            let name = node.child_by_field_name("name")
                .and_then(|n| n.utf8_text(source).ok())
                .unwrap_or("")
                .to_string();
            if name.is_empty() { return; }

            let new_prefix = if module_prefix.is_empty() { name.clone() } else { format!("{}::{}", module_prefix, name) };

            // If module has a body (inline module), recurse into it
            if let Some(body) = node.child_by_field_name("body") {
                let mut body_cursor = body.walk();
                for body_child in body.children(&mut body_cursor) {
                    extract_rust_node(
                        body_child,
                        source,
                        source_str,
                        path,
                        file_id,
                        nodes,
                        edges,
                        class_id_map,
                        impl_target_map,
                        imports,
                        &new_prefix,
                    );
                }
            }
        }

        "type_item" => {
            // Type alias: type Foo = Bar;
            let name = node.child_by_field_name("name")
                .and_then(|n| n.utf8_text(source).ok())
                .unwrap_or("")
                .to_string();
            if name.is_empty() { return; }

            let full_name = if module_prefix.is_empty() { name.clone() } else { format!("{}::{}", module_prefix, name) };
            let line = node.start_position().row + 1;
            let type_id = format!("class:{}:{}", path, full_name);

            let signature = extract_rust_signature(node, source_str);
            let line_count = node.end_position().row - node.start_position().row + 1;

            nodes.push(CodeNode {
                id: type_id.clone(),
                kind: NodeKind::Class,
                name: full_name.clone(),
                file_path: path.to_string(),
                line: Some(line),
                decorators: extract_rust_attributes(node, source),
                signature,
                docstring: None,
                line_count,
                is_test: false,
            });

            edges.push(CodeEdge::defined_in(&type_id, file_id));
            class_id_map.insert(name, type_id);
        }

        "const_item" | "static_item" => {
            // Optional: track const/static as class-like nodes
            let name = node.child_by_field_name("name")
                .and_then(|n| n.utf8_text(source).ok())
                .unwrap_or("")
                .to_string();
            if name.is_empty() || name.starts_with('_') { return; }

            let full_name = if module_prefix.is_empty() { name.clone() } else { format!("{}::{}", module_prefix, name) };
            let line = node.start_position().row + 1;
            let const_id = format!("const:{}:{}", path, full_name);

            let signature = extract_rust_signature(node, source_str);

            nodes.push(CodeNode {
                id: const_id.clone(),
                kind: NodeKind::Class,  // Treat as class for graph purposes
                name: full_name,
                file_path: path.to_string(),
                line: Some(line),
                decorators: extract_rust_attributes(node, source),
                signature,
                docstring: None,
                line_count: 1,
                is_test: false,
            });

            edges.push(CodeEdge::defined_in(&const_id, file_id));
        }

        "macro_definition" => {
            // macro_rules! foo { ... }
            let name = node.child_by_field_name("name")
                .and_then(|n| n.utf8_text(source).ok())
                .unwrap_or("")
                .to_string();
            if name.is_empty() { return; }

            let full_name = if module_prefix.is_empty() { name.clone() } else { format!("{}::{}", module_prefix, name) };
            let line = node.start_position().row + 1;
            let macro_id = format!("macro:{}:{}", path, full_name);

            let line_count = node.end_position().row - node.start_position().row + 1;

            nodes.push(CodeNode {
                id: macro_id.clone(),
                kind: NodeKind::Function,  // Treat macros as function-like
                name: format!("{}!", full_name),
                file_path: path.to_string(),
                line: Some(line),
                decorators: vec!["macro".to_string()],
                signature: Some(format!("macro_rules! {}", name)),
                docstring: extract_rust_docstring(node, source_str),
                line_count,
                is_test: false,
            });

            edges.push(CodeEdge::defined_in(&macro_id, file_id));
        }

        _ => {}
    }
}

/// Extract method from impl or trait block
fn extract_rust_method(
    node: tree_sitter::Node,
    source: &[u8],
    source_str: &str,
    path: &str,
    parent_id: &str,
    nodes: &mut Vec<CodeNode>,
    edges: &mut Vec<CodeEdge>,
) {
    let name = node.child_by_field_name("name")
        .and_then(|n| n.utf8_text(source).ok())
        .unwrap_or("")
        .to_string();
    if name.is_empty() { return; }

    let line = node.start_position().row + 1;
    let method_id = format!("method:{}:{}", path, name);

    let signature = extract_rust_signature(node, source_str);
    let docstring = extract_rust_docstring(node, source_str);
    let line_count = node.end_position().row - node.start_position().row + 1;
    let attrs = extract_rust_attributes(node, source);
    let is_test = path.contains("/tests/") || name.starts_with("test_") ||
        attrs.iter().any(|a| a.contains("test"));

    nodes.push(CodeNode {
        id: method_id.clone(),
        kind: NodeKind::Function,
        name,
        file_path: path.to_string(),
        line: Some(line),
        decorators: attrs,
        signature,
        docstring,
        line_count,
        is_test,
    });

    edges.push(CodeEdge {
        from: method_id,
        to: parent_id.to_string(),
        relation: EdgeRelation::DefinedIn,
        weight: 0.5,
        call_count: 1,
        in_error_path: false,
        confidence: 1.0,
    });
}

/// Extract Rust attributes (#[...])
fn extract_rust_attributes(node: tree_sitter::Node, source: &[u8]) -> Vec<String> {
    let mut attrs = Vec::new();
    // Look for attribute_item siblings before this node
    if let Some(parent) = node.parent() {
        let mut cursor = parent.walk();
        let mut prev_was_attr = false;
        for child in parent.children(&mut cursor) {
            if child.kind() == "attribute_item" {
                if let Ok(attr_text) = child.utf8_text(source) {
                    let clean = attr_text.trim_start_matches("#[").trim_end_matches(']');
                    attrs.push(clean.to_string());
                }
                prev_was_attr = true;
            } else if child.id() == node.id() && prev_was_attr {
                break;
            } else {
                // Not an attribute and not our target node - reset if we passed attributes
                if prev_was_attr && child.kind() != "line_comment" {
                    attrs.clear();
                }
                prev_was_attr = false;
            }
        }
    }
    
    // Also check for inner attributes
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "attribute_item" {
            if let Ok(attr_text) = child.utf8_text(source) {
                let clean = attr_text.trim_start_matches("#[").trim_end_matches(']');
                attrs.push(clean.to_string());
            }
        }
    }
    
    attrs
}

/// Extract signature from Rust node
fn extract_rust_signature(node: tree_sitter::Node, source_str: &str) -> Option<String> {
    let start = node.start_byte();
    if start >= source_str.len() { return None; }
    
    let sig_text = &source_str[start..];
    // Find the end of signature (before body block or semicolon)
    let sig_end = sig_text.find(" {")
        .or_else(|| sig_text.find("\n{"))
        .or_else(|| sig_text.find(";\n"))
        .or_else(|| sig_text.find(';'))
        .unwrap_or(sig_text.len().min(200));
    
    let sig = sig_text[..sig_end].trim();
    if sig.is_empty() { None } else { Some(sig.to_string()) }
}

/// Extract doc comment from Rust node (/// or //!)
fn extract_rust_docstring(node: tree_sitter::Node, source_str: &str) -> Option<String> {
    // Look for line_comment siblings before the node that start with ///
    let start_line = node.start_position().row;
    if start_line == 0 { return None; }
    
    let lines: Vec<&str> = source_str.lines().collect();
    let mut doc_lines: Vec<&str> = Vec::new();
    
    // Walk backwards from the line before the node
    for i in (0..start_line).rev() {
        if i >= lines.len() { continue; }
        let line = lines[i].trim();
        if line.starts_with("///") {
            doc_lines.push(line.trim_start_matches("///").trim());
        } else if line.starts_with("//!") {
            doc_lines.push(line.trim_start_matches("//!").trim());
        } else if line.is_empty() || line.starts_with("#[") {
            // Skip empty lines and attributes
            continue;
        } else {
            break;
        }
    }
    
    if doc_lines.is_empty() {
        return None;
    }
    
    doc_lines.reverse();
    let first_line = doc_lines.first().copied().unwrap_or("");
    let truncated = if first_line.len() > 100 {
        &first_line[..100]
    } else {
        first_line
    };
    
    if truncated.is_empty() { None } else { Some(truncated.to_string()) }
}

// ─── TypeScript Tree-Sitter Extraction ───

/// Extract from TypeScript/JavaScript source using tree-sitter AST parsing.
/// Handles classes, interfaces, functions, enums, type aliases, and export statements.
fn extract_typescript_tree_sitter(
    path: &str,
    content: &str,
    parser: &mut Parser,
    class_id_map: &mut HashMap<String, String>,
    extension: &str,
) -> (Vec<CodeNode>, Vec<CodeEdge>, HashSet<String>) {
    let mut nodes = Vec::new();
    let mut edges = Vec::new();
    let mut imports = HashSet::new();

    // Choose language based on file extension
    let lang_result = match extension {
        "tsx" => parser.set_language(&tree_sitter_typescript::LANGUAGE_TSX.into()),
        "ts" => parser.set_language(&tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()),
        "jsx" => parser.set_language(&tree_sitter_javascript::LANGUAGE.into()),
        _ => parser.set_language(&tree_sitter_javascript::LANGUAGE.into()),  // .js default
    };
    
    if lang_result.is_err() {
        return (nodes, edges, imports);
    }

    let tree = match parser.parse(content, None) {
        Some(t) => t,
        None => return (nodes, edges, imports),
    };

    let file_id = format!("file:{}", path);
    let source = content.as_bytes();
    let root = tree.root_node();

    let mut cursor = root.walk();
    for child in root.children(&mut cursor) {
        extract_typescript_node(
            child,
            source,
            content,
            path,
            &file_id,
            &mut nodes,
            &mut edges,
            class_id_map,
            &mut imports,
        );
    }

    (nodes, edges, imports)
}

/// Extract TypeScript/JavaScript nodes from AST
fn extract_typescript_node(
    node: tree_sitter::Node,
    source: &[u8],
    source_str: &str,
    path: &str,
    file_id: &str,
    nodes: &mut Vec<CodeNode>,
    edges: &mut Vec<CodeEdge>,
    class_id_map: &mut HashMap<String, String>,
    imports: &mut HashSet<String>,
) {
    let text = |n: tree_sitter::Node| -> String {
        n.utf8_text(source).unwrap_or("").to_string()
    };

    match node.kind() {
        "import_statement" => {
            // Extract: import { ... } from 'module'; or import x from 'module';
            let import_text = text(node);
            if let Some(from_idx) = import_text.rfind(" from ") {
                let module_part = import_text[from_idx + 6..].trim();
                let module = module_part.trim_matches(|c| c == '\'' || c == '"' || c == ';');
                if module.starts_with('.') || module.starts_with("@/") {
                    edges.push(CodeEdge {
                        from: file_id.to_string(),
                        to: format!("module_ref:{}", module),
                        relation: EdgeRelation::Imports,
                        weight: 0.5,
                        call_count: 1,
                        in_error_path: false,
                        confidence: 1.0,
                    });
                }
                imports.insert(module.to_string());
                
                // Extract imported names
                if let Some(start) = import_text.find('{') {
                    if let Some(end) = import_text.find('}') {
                        let names_part = &import_text[start+1..end];
                        for name in names_part.split(',') {
                            let clean = name.trim().split(" as ").next().unwrap_or("").trim();
                            if !clean.is_empty() {
                                imports.insert(clean.to_string());
                            }
                        }
                    }
                }
            }
        }

        "class_declaration" | "class" => {
            extract_typescript_class(node, source, source_str, path, file_id, nodes, edges, class_id_map);
        }

        "abstract_class_declaration" => {
            extract_typescript_class(node, source, source_str, path, file_id, nodes, edges, class_id_map);
        }

        "interface_declaration" => {
            let name = node.child_by_field_name("name")
                .and_then(|n| n.utf8_text(source).ok())
                .unwrap_or("")
                .to_string();
            if name.is_empty() { return; }

            let line = node.start_position().row + 1;
            let interface_id = format!("class:{}:{}", path, name);

            let signature = extract_typescript_signature(node, source_str);
            let line_count = node.end_position().row - node.start_position().row + 1;

            nodes.push(CodeNode {
                id: interface_id.clone(),
                kind: NodeKind::Class,
                name: name.clone(),
                file_path: path.to_string(),
                line: Some(line),
                decorators: vec!["interface".to_string()],
                signature,
                docstring: extract_typescript_docstring(node, source_str),
                line_count,
                is_test: path.contains("/test") || name.contains("Test"),
            });

            edges.push(CodeEdge::defined_in(&interface_id, file_id));
            class_id_map.insert(name, interface_id);
        }

        "function_declaration" | "function" => {
            let name = node.child_by_field_name("name")
                .and_then(|n| n.utf8_text(source).ok())
                .unwrap_or("")
                .to_string();
            if name.is_empty() { return; }

            let line = node.start_position().row + 1;
            let func_id = format!("func:{}:{}", path, name);

            let signature = extract_typescript_signature(node, source_str);
            let docstring = extract_typescript_docstring(node, source_str);
            let line_count = node.end_position().row - node.start_position().row + 1;
            let decorators = extract_typescript_decorators(node, source);

            nodes.push(CodeNode {
                id: func_id.clone(),
                kind: NodeKind::Function,
                name,
                file_path: path.to_string(),
                line: Some(line),
                decorators,
                signature,
                docstring,
                line_count,
                is_test: path.contains("/test") || path.contains(".test.") || path.contains(".spec."),
            });

            edges.push(CodeEdge::defined_in(&func_id, file_id));
        }

        "lexical_declaration" | "variable_declaration" => {
            // Check for arrow functions: const foo = () => { ... }
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                if child.kind() == "variable_declarator" {
                    let name = child.child_by_field_name("name")
                        .and_then(|n| n.utf8_text(source).ok())
                        .unwrap_or("")
                        .to_string();
                    
                    if let Some(value) = child.child_by_field_name("value") {
                        if value.kind() == "arrow_function" || value.kind() == "function" {
                            if name.is_empty() { continue; }
                            
                            let line = node.start_position().row + 1;
                            let func_id = format!("func:{}:{}", path, name);

                            let signature = extract_typescript_signature(node, source_str);
                            let line_count = node.end_position().row - node.start_position().row + 1;

                            nodes.push(CodeNode {
                                id: func_id.clone(),
                                kind: NodeKind::Function,
                                name,
                                file_path: path.to_string(),
                                line: Some(line),
                                decorators: Vec::new(),
                                signature,
                                docstring: extract_typescript_docstring(node, source_str),
                                line_count,
                                is_test: path.contains("/test") || path.contains(".test.") || path.contains(".spec."),
                            });

                            edges.push(CodeEdge::defined_in(&func_id, file_id));
                        }
                    }
                }
            }
        }

        "enum_declaration" => {
            let name = node.child_by_field_name("name")
                .and_then(|n| n.utf8_text(source).ok())
                .unwrap_or("")
                .to_string();
            if name.is_empty() { return; }

            let line = node.start_position().row + 1;
            let enum_id = format!("class:{}:{}", path, name);

            let signature = extract_typescript_signature(node, source_str);
            let line_count = node.end_position().row - node.start_position().row + 1;

            nodes.push(CodeNode {
                id: enum_id.clone(),
                kind: NodeKind::Class,
                name: name.clone(),
                file_path: path.to_string(),
                line: Some(line),
                decorators: vec!["enum".to_string()],
                signature,
                docstring: extract_typescript_docstring(node, source_str),
                line_count,
                is_test: false,
            });

            edges.push(CodeEdge::defined_in(&enum_id, file_id));
            class_id_map.insert(name, enum_id);
        }

        "type_alias_declaration" => {
            let name = node.child_by_field_name("name")
                .and_then(|n| n.utf8_text(source).ok())
                .unwrap_or("")
                .to_string();
            if name.is_empty() { return; }

            let line = node.start_position().row + 1;
            let type_id = format!("class:{}:{}", path, name);

            let signature = extract_typescript_signature(node, source_str);
            let line_count = node.end_position().row - node.start_position().row + 1;

            nodes.push(CodeNode {
                id: type_id.clone(),
                kind: NodeKind::Class,
                name: name.clone(),
                file_path: path.to_string(),
                line: Some(line),
                decorators: vec!["type".to_string()],
                signature,
                docstring: None,
                line_count,
                is_test: false,
            });

            edges.push(CodeEdge::defined_in(&type_id, file_id));
            class_id_map.insert(name, type_id);
        }

        "export_statement" => {
            // Unwrap export and process inner declaration
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                match child.kind() {
                    "class_declaration" | "class" | "abstract_class_declaration" |
                    "interface_declaration" | "function_declaration" | "function" |
                    "lexical_declaration" | "variable_declaration" | "enum_declaration" |
                    "type_alias_declaration" => {
                        extract_typescript_node(child, source, source_str, path, file_id, nodes, edges, class_id_map, imports);
                    }
                    _ => {}
                }
            }
        }

        "expression_statement" => {
            // Handle wrapped statements like namespace (which appears as expression_statement → internal_module)
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                extract_typescript_node(child, source, source_str, path, file_id, nodes, edges, class_id_map, imports);
            }
        }

        "module" | "internal_module" | "namespace" => {
            // namespace/module declarations
            let name = node.child_by_field_name("name")
                .and_then(|n| n.utf8_text(source).ok())
                .unwrap_or("")
                .to_string();
            
            if !name.is_empty() {
                let line = node.start_position().row + 1;
                let module_id = format!("class:{}:{}", path, name);

                nodes.push(CodeNode {
                    id: module_id.clone(),
                    kind: NodeKind::Class,
                    name: name.clone(),
                    file_path: path.to_string(),
                    line: Some(line),
                    decorators: vec!["namespace".to_string()],
                    signature: Some(format!("namespace {}", name)),
                    docstring: None,
                    line_count: node.end_position().row - node.start_position().row + 1,
                    is_test: false,
                });

                edges.push(CodeEdge::defined_in(&module_id, file_id));
            }

            // Recurse into module body
            if let Some(body) = node.child_by_field_name("body") {
                let mut body_cursor = body.walk();
                for body_child in body.children(&mut body_cursor) {
                    extract_typescript_node(body_child, source, source_str, path, file_id, nodes, edges, class_id_map, imports);
                }
            }
        }

        _ => {}
    }
}

/// Extract TypeScript class with methods
fn extract_typescript_class(
    node: tree_sitter::Node,
    source: &[u8],
    source_str: &str,
    path: &str,
    file_id: &str,
    nodes: &mut Vec<CodeNode>,
    edges: &mut Vec<CodeEdge>,
    class_id_map: &mut HashMap<String, String>,
) {
    let name = node.child_by_field_name("name")
        .and_then(|n| n.utf8_text(source).ok())
        .unwrap_or("")
        .to_string();
    if name.is_empty() { return; }

    let line = node.start_position().row + 1;
    let class_id = format!("class:{}:{}", path, name);

    let signature = extract_typescript_signature(node, source_str);
    let docstring = extract_typescript_docstring(node, source_str);
    let line_count = node.end_position().row - node.start_position().row + 1;
    let decorators = extract_typescript_decorators(node, source);

    nodes.push(CodeNode {
        id: class_id.clone(),
        kind: NodeKind::Class,
        name: name.clone(),
        file_path: path.to_string(),
        line: Some(line),
        decorators,
        signature,
        docstring,
        line_count,
        is_test: path.contains("/test") || name.contains("Test"),
    });

    edges.push(CodeEdge::defined_in(&class_id, file_id));
    class_id_map.insert(name.clone(), class_id.clone());

    // Find parent class from extends clause
    fn find_extends_identifier(node: tree_sitter::Node, source: &[u8]) -> Option<String> {
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            match child.kind() {
                "identifier" | "type_identifier" => {
                    return child.utf8_text(source).ok().map(|s| s.to_string());
                }
                "extends_clause" | "class_heritage" | "extends_type_clause" => {
                    if let Some(name) = find_extends_identifier(child, source) {
                        return Some(name);
                    }
                }
                _ => {}
            }
        }
        None
    }
    
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "class_heritage" || child.kind() == "extends_clause" {
            if let Some(parent_name) = find_extends_identifier(child, source) {
                if !parent_name.is_empty() {
                    edges.push(CodeEdge {
                        from: class_id.clone(),
                        to: format!("class_ref:{}", parent_name),
                        relation: EdgeRelation::Inherits,
                        weight: 0.5,
                        call_count: 1,
                        in_error_path: false,
                        confidence: 1.0,
                    });
                }
            }
        }
    }

    // Extract methods from class body
    if let Some(body) = node.child_by_field_name("body") {
        let mut body_cursor = body.walk();
        for body_child in body.children(&mut body_cursor) {
            match body_child.kind() {
                "method_definition" | "public_field_definition" | "method_signature" => {
                    extract_typescript_method(body_child, source, source_str, path, &class_id, nodes, edges);
                }
                _ => {}
            }
        }
    }
}

/// Extract method from class
fn extract_typescript_method(
    node: tree_sitter::Node,
    source: &[u8],
    source_str: &str,
    path: &str,
    class_id: &str,
    nodes: &mut Vec<CodeNode>,
    edges: &mut Vec<CodeEdge>,
) {
    let mut name = node.child_by_field_name("name")
        .and_then(|n| n.utf8_text(source).ok())
        .unwrap_or("")
        .to_string();
    
    // Handle computed property names [key]
    if name.is_empty() {
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if child.kind() == "property_identifier" || child.kind() == "identifier" {
                if let Ok(text) = child.utf8_text(source) {
                    name = text.to_string();
                    break;
                }
            }
        }
    }
    
    if name.is_empty() { return; }

    let line = node.start_position().row + 1;
    let method_id = format!("method:{}:{}", path, name);

    let signature = extract_typescript_signature(node, source_str);
    let docstring = extract_typescript_docstring(node, source_str);
    let line_count = node.end_position().row - node.start_position().row + 1;
    let decorators = extract_typescript_decorators(node, source);

    nodes.push(CodeNode {
        id: method_id.clone(),
        kind: NodeKind::Function,
        name,
        file_path: path.to_string(),
        line: Some(line),
        decorators,
        signature,
        docstring,
        line_count,
        is_test: path.contains("/test") || path.contains(".test.") || path.contains(".spec."),
    });

    edges.push(CodeEdge {
        from: method_id,
        to: class_id.to_string(),
        relation: EdgeRelation::DefinedIn,
        weight: 0.5,
        call_count: 1,
        in_error_path: false,
        confidence: 1.0,
    });
}

/// Extract TypeScript decorators (@decorator)
fn extract_typescript_decorators(node: tree_sitter::Node, source: &[u8]) -> Vec<String> {
    let mut decorators = Vec::new();
    
    // Look for decorator siblings before this node
    if let Some(parent) = node.parent() {
        let mut cursor = parent.walk();
        for child in parent.children(&mut cursor) {
            if child.kind() == "decorator" {
                if let Ok(dec_text) = child.utf8_text(source) {
                    let name = dec_text.trim_start_matches('@');
                    let name = name.split('(').next().unwrap_or(name).trim();
                    if !name.is_empty() {
                        decorators.push(name.to_string());
                    }
                }
            }
            if child.id() == node.id() {
                break;
            }
        }
    }
    
    decorators
}

/// Extract signature from TypeScript node
fn extract_typescript_signature(node: tree_sitter::Node, source_str: &str) -> Option<String> {
    let start = node.start_byte();
    if start >= source_str.len() { return None; }
    
    let sig_text = &source_str[start..];
    // Find the end of signature (before body block)
    let sig_end = sig_text.find(" {")
        .or_else(|| sig_text.find("\n{"))
        .or_else(|| sig_text.find("{\n"))
        .unwrap_or(sig_text.len().min(200));
    
    let sig = sig_text[..sig_end].trim();
    if sig.is_empty() { None } else { Some(sig.to_string()) }
}

/// Extract JSDoc comment from TypeScript node
fn extract_typescript_docstring(node: tree_sitter::Node, source_str: &str) -> Option<String> {
    let start_line = node.start_position().row;
    if start_line == 0 { return None; }
    
    let lines: Vec<&str> = source_str.lines().collect();
    
    // Look for /** ... */ comment before the node
    for i in (0..start_line).rev() {
        if i >= lines.len() { continue; }
        let line = lines[i].trim();
        
        if line.ends_with("*/") {
            // Found end of JSDoc, find the start
            let mut doc_lines: Vec<&str> = Vec::new();
            for j in (0..=i).rev() {
                if j >= lines.len() { continue; }
                let doc_line = lines[j].trim();
                if doc_line.starts_with("/**") {
                    let first = doc_line.trim_start_matches("/**").trim_start_matches('*').trim();
                    if !first.is_empty() && !first.starts_with('@') {
                        doc_lines.push(first);
                    }
                    break;
                } else if doc_line.starts_with('*') {
                    let content = doc_line.trim_start_matches('*').trim();
                    if !content.is_empty() && !content.starts_with('@') {
                        doc_lines.push(content);
                    }
                }
            }
            
            if doc_lines.is_empty() {
                return None;
            }
            
            doc_lines.reverse();
            let first_line = doc_lines.first().copied().unwrap_or("");
            let truncated = if first_line.len() > 100 {
                &first_line[..100]
            } else {
                first_line
            };
            
            return if truncated.is_empty() { None } else { Some(truncated.to_string()) };
        } else if line.is_empty() || line.starts_with('@') || line.starts_with("//") {
            continue;
        } else {
            break;
        }
    }
    
    None
}

// ─── Regex-Based Fallbacks (kept for reference) ───

/// Extract from Rust source (regex-based fallback, kept for reference).
#[allow(dead_code)]
fn extract_rust_regex(path: &str, content: &str) -> (Vec<CodeNode>, Vec<CodeEdge>, HashSet<String>) {
    let mut nodes = Vec::new();
    let mut edges = Vec::new();

    let file_id = format!("file:{}", path);

    let re_use = Regex::new(r"(?m)^use\s+([\w:]+)").unwrap();
    let re_struct = Regex::new(r"(?m)^(?:pub\s+)?struct\s+(\w+)").unwrap();
    let re_enum = Regex::new(r"(?m)^(?:pub\s+)?enum\s+(\w+)").unwrap();
    let re_impl = Regex::new(r"(?m)^impl(?:<[^>]+>)?\s+(?:(\w+)\s+for\s+)?(\w+)").unwrap();
    let re_fn = Regex::new(r"(?m)^\s*(?:pub\s+)?(?:async\s+)?fn\s+(\w+)").unwrap();

    for cap in re_use.captures_iter(content) {
        let module = cap[1].to_string();
        if !module.starts_with("std::") && !module.starts_with("core::") {
            edges.push(CodeEdge::new(
                &file_id,
                &format!("module_ref:{}", module),
                EdgeRelation::Imports,
            ));
        }
    }

    for cap in re_struct.captures_iter(content) {
        let name = cap[1].to_string();
        let line = content[..cap.get(0).unwrap().start()].lines().count() + 1;
        let node = CodeNode::new_class(path, &name, line);
        edges.push(CodeEdge::defined_in(&node.id, &file_id));
        nodes.push(node);
    }

    for cap in re_enum.captures_iter(content) {
        let name = cap[1].to_string();
        let line = content[..cap.get(0).unwrap().start()].lines().count() + 1;
        let node = CodeNode::new_class(path, &name, line);
        edges.push(CodeEdge::defined_in(&node.id, &file_id));
        nodes.push(node);
    }

    for cap in re_impl.captures_iter(content) {
        if let Some(trait_match) = cap.get(1) {
            let type_name = &cap[2];
            let trait_name = trait_match.as_str();
            if let Some(type_node) = nodes.iter().find(|n| n.name == type_name) {
                edges.push(CodeEdge::new(
                    &type_node.id,
                    &format!("class_ref:{}", trait_name),
                    EdgeRelation::Inherits,
                ));
            }
        }
    }

    for cap in re_fn.captures_iter(content) {
        let name = cap[1].to_string();
        let line = content[..cap.get(0).unwrap().start()].lines().count() + 1;
        let node = CodeNode::new_function(path, &name, line, false);
        edges.push(CodeEdge::defined_in(&node.id, &file_id));
        nodes.push(node);
    }

    (nodes, edges, HashSet::new())
}

/// Extract from TypeScript/JavaScript source (regex-based fallback, kept for reference).
#[allow(dead_code)]
fn extract_typescript_regex(path: &str, content: &str) -> (Vec<CodeNode>, Vec<CodeEdge>, HashSet<String>) {
    let mut nodes = Vec::new();
    let mut edges = Vec::new();

    let file_id = format!("file:{}", path);

    let re_import = Regex::new(r#"(?m)^import\s+.*?\s+from\s+['"]([^'"]+)['"]"#).unwrap();
    let re_class = Regex::new(r"(?m)^(?:export\s+)?(?:abstract\s+)?class\s+(\w+)(?:\s+extends\s+(\w+))?").unwrap();
    let re_interface = Regex::new(r"(?m)^(?:export\s+)?interface\s+(\w+)(?:\s+extends\s+(\w+))?").unwrap();
    let re_function = Regex::new(r"(?m)^(?:export\s+)?(?:async\s+)?function\s+(\w+)").unwrap();
    let re_arrow = Regex::new(r"(?m)^(?:export\s+)?(?:const|let)\s+(\w+)\s*=\s*(?:async\s+)?\([^)]*\)\s*=>").unwrap();

    for cap in re_import.captures_iter(content) {
        let module = cap[1].to_string();
        if module.starts_with('.') || module.starts_with("@/") {
            edges.push(CodeEdge::new(
                &file_id,
                &format!("module_ref:{}", module),
                EdgeRelation::Imports,
            ));
        }
    }

    for cap in re_class.captures_iter(content) {
        let name = cap[1].to_string();
        let line = content[..cap.get(0).unwrap().start()].lines().count() + 1;
        let node = CodeNode::new_class(path, &name, line);
        edges.push(CodeEdge::defined_in(&node.id, &file_id));

        if let Some(parent) = cap.get(2) {
            edges.push(CodeEdge::new(
                &node.id,
                &format!("class_ref:{}", parent.as_str()),
                EdgeRelation::Inherits,
            ));
        }

        nodes.push(node);
    }

    for cap in re_interface.captures_iter(content) {
        let name = cap[1].to_string();
        let line = content[..cap.get(0).unwrap().start()].lines().count() + 1;
        let node = CodeNode::new_class(path, &name, line);
        edges.push(CodeEdge::defined_in(&node.id, &file_id));
        nodes.push(node);
    }

    for cap in re_function.captures_iter(content) {
        let name = cap[1].to_string();
        let line = content[..cap.get(0).unwrap().start()].lines().count() + 1;
        let node = CodeNode::new_function(path, &name, line, false);
        edges.push(CodeEdge::defined_in(&node.id, &file_id));
        nodes.push(node);
    }

    for cap in re_arrow.captures_iter(content) {
        let name = cap[1].to_string();
        let line = content[..cap.get(0).unwrap().start()].lines().count() + 1;
        let node = CodeNode::new_function(path, &name, line, false);
        edges.push(CodeEdge::defined_in(&node.id, &file_id));
        nodes.push(node);
    }

    (nodes, edges, HashSet::new())
}

// ═══ Helpers ═══

fn is_python_builtin(name: &str) -> bool {
    matches!(
        name,
        "if" | "for"
            | "while"
            | "return"
            | "print"
            | "len"
            | "range"
            | "str"
            | "int"
            | "float"
            | "list"
            | "dict"
            | "set"
            | "tuple"
            | "type"
            | "isinstance"
            | "issubclass"
            | "super"
            | "hasattr"
            | "getattr"
            | "setattr"
            | "property"
            | "staticmethod"
            | "classmethod"
            | "enumerate"
            | "zip"
            | "map"
            | "filter"
            | "sorted"
            | "reversed"
            | "any"
            | "all"
            | "min"
            | "max"
            | "sum"
            | "abs"
            | "bool"
            | "repr"
            | "hash"
            | "id"
            | "open"
            | "format"
            | "not"
            | "and"
            | "or"
            | "bytes"
            | "bytearray"
            | "memoryview"
            | "object"
            | "complex"
            | "frozenset"
            | "iter"
            | "next"
            | "callable"
            | "delattr"
            | "dir"
            | "divmod"
            | "eval"
            | "exec"
            | "globals"
            | "hex"
            | "input"
            | "locals"
            | "oct"
            | "ord"
            | "pow"
            | "round"
            | "slice"
            | "vars"
            | "chr"
            | "bin"
            | "breakpoint"
            | "compile"
            | "__import__"
            | "ValueError"
            | "TypeError"
            | "KeyError"
            | "IndexError"
            | "AttributeError"
            | "RuntimeError"
            | "Exception"
            | "NotImplementedError"
            | "StopIteration"
            | "OSError"
            | "IOError"
            | "FileNotFoundError"
            | "ImportError"
            | "AssertionError"
            | "NameError"
            | "OverflowError"
            | "ZeroDivisionError"
            | "UnicodeError"
            | "SyntaxError"
    )
}

fn is_stdlib(module: &str) -> bool {
    let stdlib_prefixes = [
        "os", "sys", "re", "json", "math", "io", "abc", "collections", "typing", "unittest",
        "pytest", "copy", "functools", "itertools", "pathlib", "shutil", "tempfile", "logging",
        "warnings", "inspect", "textwrap", "string", "datetime", "time", "hashlib", "base64",
        "pickle", "csv", "xml", "html", "http", "urllib", "socket", "threading",
        "multiprocessing", "subprocess", "contextlib", "enum", "dataclasses", "struct", "array",
        "queue", "heapq", "bisect", "decimal", "fractions", "random", "statistics", "operator",
        "pdb", "traceback", "dis", "ast", "token", "importlib", "pkgutil", "site", "zipimport",
        "numpy", "scipy", "matplotlib", "pandas", "setuptools", "pip", "wheel", "pkg_resources",
        "distutils",
    ];

    let first_part = module.split('.').next().unwrap_or(module);
    stdlib_prefixes.contains(&first_part)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_extract_python() {
        let content = r#"
import os
from pathlib import Path

class MyClass(BaseClass):
    def method(self):
        pass

def top_level():
    pass
"#;
        let mut parser = Parser::new();
        let language = tree_sitter_python::LANGUAGE;
        parser.set_language(&language.into()).unwrap();
        let mut class_map = HashMap::new();

        let (nodes, edges, _) = extract_python_tree_sitter("test.py", content, &mut parser, &mut class_map);

        assert!(nodes.iter().any(|n| n.name == "MyClass"));
        assert!(nodes.iter().any(|n| n.name == "method"));
        assert!(nodes.iter().any(|n| n.name == "top_level"));
        assert!(edges.iter().any(|e| e.to.contains("BaseClass")));
    }

    #[test]
    fn test_extract_rust() {
        let content = r#"
use std::path::Path;
use crate::module;

pub struct MyStruct {
    field: i32,
}

impl MyTrait for MyStruct {
    fn method(&self) {}
}

pub fn top_level() {}
"#;
        let mut parser = Parser::new();
        let mut class_map = HashMap::new();
        let (nodes, edges, _) = extract_rust_tree_sitter("test.rs", content, &mut parser, &mut class_map);

        assert!(nodes.iter().any(|n| n.name == "MyStruct"), "Should find MyStruct");
        assert!(nodes.iter().any(|n| n.name == "method"), "Should find method");
        assert!(nodes.iter().any(|n| n.name == "top_level"), "Should find top_level");
        assert!(edges.iter().any(|e| e.to.contains("module")), "Should have module import edge");
        
        // Tree-sitter should also capture trait implementation relationship
        assert!(edges.iter().any(|e| e.relation == EdgeRelation::Inherits && e.to.contains("MyTrait")),
            "Should capture trait impl inheritance");
    }

    #[test]
    fn test_extract_rust_comprehensive() {
        let content = r#"
use crate::foo::bar;

/// A documented struct
pub struct Person {
    name: String,
    age: u32,
}

/// A documented enum
pub enum Status {
    Active,
    Inactive,
}

/// A trait
pub trait Greeter {
    fn greet(&self) -> String;
}

impl Greeter for Person {
    fn greet(&self) -> String {
        format!("Hello, {}", self.name)
    }
}

impl Person {
    pub fn new(name: String) -> Self {
        Self { name, age: 0 }
    }
    
    pub fn birthday(&mut self) {
        self.age += 1;
    }
}

mod inner {
    pub fn nested_fn() {}
}

type MyAlias = Vec<String>;

pub fn standalone() {}

#[test]
fn test_something() {}
"#;
        let mut parser = Parser::new();
        let mut class_map = HashMap::new();
        let (nodes, edges, _) = extract_rust_tree_sitter("test.rs", content, &mut parser, &mut class_map);

        // Structs and enums
        assert!(nodes.iter().any(|n| n.name == "Person"), "Should find Person struct");
        assert!(nodes.iter().any(|n| n.name == "Status"), "Should find Status enum");
        
        // Traits
        assert!(nodes.iter().any(|n| n.name == "Greeter"), "Should find Greeter trait");
        
        // Methods from impl blocks
        assert!(nodes.iter().any(|n| n.name == "greet"), "Should find greet method");
        assert!(nodes.iter().any(|n| n.name == "new"), "Should find new method");
        assert!(nodes.iter().any(|n| n.name == "birthday"), "Should find birthday method");
        
        // Nested module functions
        assert!(nodes.iter().any(|n| n.name.contains("nested_fn")), "Should find nested_fn");
        
        // Type aliases
        assert!(nodes.iter().any(|n| n.name == "MyAlias"), "Should find type alias");
        
        // Standalone function
        assert!(nodes.iter().any(|n| n.name == "standalone"), "Should find standalone fn");
        
        // Test function should be marked as test
        let test_node = nodes.iter().find(|n| n.name == "test_something");
        assert!(test_node.is_some(), "Should find test function");
        assert!(test_node.unwrap().is_test, "Test function should be marked as test");
        
        // Methods should be linked to their impl target
        let greet_edges: Vec<_> = edges.iter()
            .filter(|e| e.from.contains("greet") && e.relation == EdgeRelation::DefinedIn)
            .collect();
        assert!(!greet_edges.is_empty(), "greet should have DefinedIn edge");
    }

    #[test]
    fn test_extract_typescript() {
        let content = r#"
import { Component } from './component';

export class MyClass extends BaseClass {
    method(): void {}
}

export function topLevel(): void {}

export const arrowFn = () => {};
"#;
        let mut parser = Parser::new();
        let mut class_map = HashMap::new();
        let (nodes, edges, _) = extract_typescript_tree_sitter("test.ts", content, &mut parser, &mut class_map, "ts");

        assert!(nodes.iter().any(|n| n.name == "MyClass"), "Should find MyClass");
        assert!(nodes.iter().any(|n| n.name == "topLevel"), "Should find topLevel");
        assert!(nodes.iter().any(|n| n.name == "arrowFn"), "Should find arrowFn");
        assert!(edges.iter().any(|e| e.to.contains("component")), "Should have component import");
        
        // Tree-sitter should also find the method inside the class
        assert!(nodes.iter().any(|n| n.name == "method"), "Should find method inside class");
        
        // Should capture inheritance
        assert!(edges.iter().any(|e| e.relation == EdgeRelation::Inherits && e.to.contains("BaseClass")),
            "Should capture class inheritance");
    }

    #[test]
    fn test_extract_typescript_comprehensive() {
        let content = r#"
import { Injectable } from '@angular/core';
import type { User } from './types';

/**
 * A service class
 */
@Injectable()
export class UserService {
    private users: User[] = [];
    
    /**
     * Get all users
     */
    getUsers(): User[] {
        return this.users;
    }
    
    addUser(user: User): void {
        this.users.push(user);
    }
}

export interface IRepository<T> {
    find(id: string): T | undefined;
    save(item: T): void;
}

export type UserId = string;

export enum UserRole {
    Admin = 'admin',
    User = 'user',
}

export function createUser(name: string): User {
    return { name };
}

export const fetchUser = async (id: string) => {
    return null;
};

export default class DefaultExport {}

namespace MyNamespace {
    export function innerFn() {}
}
"#;
        let mut parser = Parser::new();
        let mut class_map = HashMap::new();
        let (nodes, edges, _) = extract_typescript_tree_sitter("test.ts", content, &mut parser, &mut class_map, "ts");

        // Classes
        assert!(nodes.iter().any(|n| n.name == "UserService"), "Should find UserService class");
        assert!(nodes.iter().any(|n| n.name == "DefaultExport"), "Should find default export class");
        
        // Methods inside class
        assert!(nodes.iter().any(|n| n.name == "getUsers"), "Should find getUsers method");
        assert!(nodes.iter().any(|n| n.name == "addUser"), "Should find addUser method");
        
        // Interfaces
        assert!(nodes.iter().any(|n| n.name == "IRepository"), "Should find interface");
        
        // Type aliases
        assert!(nodes.iter().any(|n| n.name == "UserId"), "Should find type alias");
        
        // Enums
        assert!(nodes.iter().any(|n| n.name == "UserRole"), "Should find enum");
        
        // Functions
        assert!(nodes.iter().any(|n| n.name == "createUser"), "Should find function");
        
        // Arrow functions
        assert!(nodes.iter().any(|n| n.name == "fetchUser"), "Should find arrow function");
        
        // Namespace
        assert!(nodes.iter().any(|n| n.name == "MyNamespace"), "Should find namespace");
        
        // Imports
        assert!(edges.iter().any(|e| e.relation == EdgeRelation::Imports), "Should have import edges");
    }
}