sqry-lang-java 6.0.19

Java language plugin for sqry
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
use std::{collections::HashMap, path::Path};

use crate::relations::java_common::{PackageResolver, build_member_symbol, build_symbol};
use crate::relations::local_scopes::{self, JavaScopeTree, ResolutionOutcome};
use sqry_core::graph::unified::StagingGraph;
use sqry_core::graph::unified::build::helper::GraphBuildHelper;
use sqry_core::graph::unified::edge::FfiConvention;
use sqry_core::graph::{GraphBuilder, GraphBuilderError, GraphResult, Language, Span};
use tree_sitter::{Node, Tree};

const DEFAULT_SCOPE_DEPTH: usize = 4;

/// File-level module name for exports/imports.
/// Distinct from `<module>` to avoid node kind collision in `GraphBuildHelper` cache.
const FILE_MODULE_NAME: &str = "<file_module>";

/// Graph builder for Java files using unified `CodeGraph` architecture.
///
/// This implementation follows the two-phase `ASTGraph` architecture introduced
/// in JavaScript and Rust for O(1) context lookups during call edge detection.
///
/// # Supported Features
///
/// - Class and interface definitions
/// - Method definitions (instance, static, constructors)
/// - Method call expressions
/// - Constructor calls (new expressions)
/// - Static method calls (`Class.method()`)
/// - Import declarations (single and wildcard)
/// - Export edges (public classes, interfaces, methods, fields)
/// - Package declarations
/// - JNI detection (native methods)
/// - Anonymous classes and lambda expressions
/// - Nested classes
/// - Synchronized detection
/// - Proper argument counting
#[derive(Debug, Clone, Copy)]
pub struct JavaGraphBuilder {
    max_scope_depth: usize,
}

impl Default for JavaGraphBuilder {
    fn default() -> Self {
        Self {
            max_scope_depth: DEFAULT_SCOPE_DEPTH,
        }
    }
}

impl JavaGraphBuilder {
    #[must_use]
    pub fn new(max_scope_depth: usize) -> Self {
        Self { max_scope_depth }
    }
}

impl GraphBuilder for JavaGraphBuilder {
    fn build_graph(
        &self,
        tree: &Tree,
        content: &[u8],
        file: &Path,
        staging: &mut StagingGraph,
    ) -> GraphResult<()> {
        let mut helper = GraphBuildHelper::new(staging, file, Language::Java);

        // Build AST context for O(1) method lookups
        let ast_graph = ASTGraph::from_tree(tree, content, self.max_scope_depth);
        let mut scope_tree = local_scopes::build(tree.root_node(), content)?;

        // Phase 1: Create method/constructor nodes and JNI FFI edges for native methods
        for context in ast_graph.contexts() {
            let qualified_name = context.qualified_name();
            let span = Span::from_bytes(context.span.0, context.span.1);

            if context.is_constructor {
                helper.add_method_with_visibility(
                    qualified_name,
                    Some(span),
                    false,
                    false,
                    context.visibility.as_deref(),
                );
            } else {
                // Use add_method_with_signature to store return type for `returns:` queries
                helper.add_method_with_signature(
                    qualified_name,
                    Some(span),
                    false,
                    context.is_static,
                    context.visibility.as_deref(),
                    context.return_type.as_deref(),
                );

                // JNI: Create FFI edge for native methods
                if context.is_native {
                    build_jni_native_method_edge(context, &mut helper);
                }
            }
        }

        // Phase 1.5: Add TypeOf edges for fields
        add_field_typeof_edges(&ast_graph, &mut helper);

        // Phase 2: Walk the tree to find calls, imports, classes, interfaces
        let root = tree.root_node();
        walk_tree_for_edges(
            root,
            content,
            &ast_graph,
            &mut scope_tree,
            &mut helper,
            tree,
        )?;

        Ok(())
    }

    fn language(&self) -> Language {
        Language::Java
    }
}

// ================================
// ASTGraph: In-memory function context index
// ================================

#[derive(Debug)]
struct ASTGraph {
    contexts: Vec<MethodContext>,
    /// Maps qualified field names to their metadata: (`type_fqn`, `is_final`, visibility, `is_static`)
    /// - Key: Qualified field name (e.g., `ClassName::fieldName`)
    /// - Tuple: (`type_fqn`, `is_final`, visibility, `is_static`)
    ///   - `type_fqn`: Fully qualified type name (e.g., `com.example.service.UserService`)
    ///   - `is_final`: true if field has `final` modifier (determines Constant vs Property node)
    ///   - visibility: Public or Private (public fields are Public, others are Private)
    ///   - `is_static`: true if field has `static` modifier
    ///
    /// Used to resolve method calls on fields and create appropriate node types with metadata
    field_types: HashMap<String, (String, bool, Option<sqry_core::schema::Visibility>, bool)>,
    /// Maps simple type names to FQNs (e.g., `UserService` -> `com.example.service.UserService`)
    /// Used to resolve static method calls (e.g., `UserRepository.method` ->
    /// `com.example.repository.UserRepository.method`)
    import_map: HashMap<String, String>,
    /// Whether this file imports JNA (`com.sun.jna.*`)
    has_jna_import: bool,
    /// Whether this file imports Panama Foreign Function API (`java.lang.foreign.*`)
    has_panama_import: bool,
    /// Interfaces that extend JNA Library (simple names)
    jna_library_interfaces: Vec<String>,
}

impl ASTGraph {
    fn from_tree(tree: &Tree, content: &[u8], max_depth: usize) -> Self {
        // Extract package name from AST
        let package_name = PackageResolver::package_from_ast(tree, content);

        let mut contexts = Vec::new();
        let mut class_stack = Vec::new();

        // Create recursion guard
        let recursion_limits = sqry_core::config::RecursionLimits::load_or_default()
            .expect("Failed to load recursion limits");
        let file_ops_depth = recursion_limits
            .effective_file_ops_depth()
            .expect("Invalid file_ops_depth configuration");
        let mut guard = sqry_core::query::security::RecursionGuard::new(file_ops_depth)
            .expect("Failed to create recursion guard");

        if let Err(e) = extract_java_contexts(
            tree.root_node(),
            content,
            &mut contexts,
            &mut class_stack,
            package_name.as_deref(),
            0,
            max_depth,
            &mut guard,
        ) {
            eprintln!("Warning: Java AST traversal hit recursion limit: {e}");
        }

        // Extract field declarations and imports to enable type resolution
        let (field_types, import_map) = extract_field_and_import_types(tree.root_node(), content);

        // Detect FFI-related imports
        let (has_jna_import, has_panama_import) = detect_ffi_imports(tree.root_node(), content);

        // Find interfaces extending JNA Library
        let jna_library_interfaces = find_jna_library_interfaces(tree.root_node(), content);

        Self {
            contexts,
            field_types,
            import_map,
            has_jna_import,
            has_panama_import,
            jna_library_interfaces,
        }
    }

    fn contexts(&self) -> &[MethodContext] {
        &self.contexts
    }

    /// Find the enclosing method context for a given byte position
    fn find_enclosing(&self, byte_pos: usize) -> Option<&MethodContext> {
        self.contexts
            .iter()
            .filter(|ctx| byte_pos >= ctx.span.0 && byte_pos < ctx.span.1)
            .max_by_key(|ctx| ctx.depth)
    }
}

#[derive(Debug, Clone)]
#[allow(clippy::struct_excessive_bools)] // Captures explicit method traits for graph resolution.
struct MethodContext {
    /// Fully qualified name: `com.example.Class.method` or `com.example.Class.<init>`
    qualified_name: String,
    /// Byte span of the method body
    span: (usize, usize),
    /// Nesting depth (for resolving ambiguity)
    depth: usize,
    /// Whether this is a static method
    is_static: bool,
    /// Whether this is synchronized
    #[allow(dead_code)] // Reserved for threading analysis
    is_synchronized: bool,
    /// Whether this is a constructor
    is_constructor: bool,
    /// Whether this is a native method (JNI)
    #[allow(dead_code)] // Reserved for JNI bridge analysis
    is_native: bool,
    /// Package name for use in call resolution (e.g., `com.example`)
    package_name: Option<String>,
    /// Class stack for use in call resolution (e.g., `["Outer", "Inner"]`)
    class_stack: Vec<String>,
    /// Return type of the method (e.g., `Optional<User>`, `void`)
    return_type: Option<String>,
    /// Visibility modifier (e.g., "public", "private", "protected", "package-private")
    visibility: Option<String>,
}

impl MethodContext {
    fn qualified_name(&self) -> &str {
        &self.qualified_name
    }
}

// ================================
// Context Extraction
// ================================

/// Recursively extract method contexts from Java AST
/// # Errors
///
/// Returns [`RecursionError::DepthLimitExceeded`] if recursion depth exceeds the guard's limit.
fn extract_java_contexts(
    node: Node,
    content: &[u8],
    contexts: &mut Vec<MethodContext>,
    class_stack: &mut Vec<String>,
    package_name: Option<&str>,
    depth: usize,
    max_depth: usize,
    guard: &mut sqry_core::query::security::RecursionGuard,
) -> Result<(), sqry_core::query::security::RecursionError> {
    guard.enter()?;

    if depth > max_depth {
        guard.exit();
        return Ok(());
    }

    match node.kind() {
        "class_declaration" | "interface_declaration" | "enum_declaration" => {
            // Extract class/interface name
            if let Some(name_node) = node.child_by_field_name("name") {
                let class_name = extract_identifier(name_node, content);

                // Push class onto stack for nested context
                class_stack.push(class_name.clone());

                // Extract methods within this class
                if let Some(body_node) = node.child_by_field_name("body") {
                    extract_methods_from_body(
                        body_node,
                        content,
                        class_stack,
                        package_name,
                        contexts,
                        depth + 1,
                        max_depth,
                        guard,
                    )?;

                    // Handle nested classes (recursively)
                    for i in 0..body_node.child_count() {
                        if let Some(child) = body_node.child(i as u32) {
                            extract_java_contexts(
                                child,
                                content,
                                contexts,
                                class_stack,
                                package_name,
                                depth + 1,
                                max_depth,
                                guard,
                            )?;
                        }
                    }
                }

                // Pop class from stack when exiting
                class_stack.pop();

                guard.exit();
                return Ok(());
            }
        }
        _ => {}
    }

    // Continue traversing for top-level declarations
    for i in 0..node.child_count() {
        if let Some(child) = node.child(i as u32) {
            extract_java_contexts(
                child,
                content,
                contexts,
                class_stack,
                package_name,
                depth,
                max_depth,
                guard,
            )?;
        }
    }

    guard.exit();
    Ok(())
}

/// # Errors
///
/// Returns [`RecursionError::DepthLimitExceeded`] if recursion depth exceeds the guard's limit.
#[allow(clippy::unnecessary_wraps)]
fn extract_methods_from_body(
    body_node: Node,
    content: &[u8],
    class_stack: &[String],
    package_name: Option<&str>,
    contexts: &mut Vec<MethodContext>,
    depth: usize,
    _max_depth: usize,
    _guard: &mut sqry_core::query::security::RecursionGuard,
) -> Result<(), sqry_core::query::security::RecursionError> {
    for i in 0..body_node.child_count() {
        if let Some(child) = body_node.child(i as u32) {
            match child.kind() {
                "method_declaration" => {
                    if let Some(method_context) =
                        extract_method_context(child, content, class_stack, package_name, depth)
                    {
                        contexts.push(method_context);
                    }
                }
                "constructor_declaration" => {
                    let constructor_context = extract_constructor_context(
                        child,
                        content,
                        class_stack,
                        package_name,
                        depth,
                    );
                    contexts.push(constructor_context);
                }
                _ => {}
            }
        }
    }
    Ok(())
}

fn extract_method_context(
    method_node: Node,
    content: &[u8],
    class_stack: &[String],
    package_name: Option<&str>,
    depth: usize,
) -> Option<MethodContext> {
    let name_node = method_node.child_by_field_name("name")?;
    let method_name = extract_identifier(name_node, content);

    let is_static = has_modifier(method_node, "static", content);
    let is_synchronized = has_modifier(method_node, "synchronized", content);
    let is_native = has_modifier(method_node, "native", content);
    let visibility = extract_visibility(method_node, content);

    // Extract return type from method_declaration
    // tree-sitter-java structure: (method_declaration type: <type_node> name: identifier ...)
    let return_type = method_node
        .child_by_field_name("type")
        .map(|type_node| extract_full_return_type(type_node, content));

    // Use build_member_symbol to create fully qualified name
    let qualified_name = build_member_symbol(package_name, class_stack, &method_name);

    Some(MethodContext {
        qualified_name,
        span: (method_node.start_byte(), method_node.end_byte()),
        depth,
        is_static,
        is_synchronized,
        is_constructor: false,
        is_native,
        package_name: package_name.map(std::string::ToString::to_string),
        class_stack: class_stack.to_vec(),
        return_type,
        visibility,
    })
}

fn extract_constructor_context(
    constructor_node: Node,
    content: &[u8],
    class_stack: &[String],
    package_name: Option<&str>,
    depth: usize,
) -> MethodContext {
    // Use build_member_symbol with "<init>" as method name
    let qualified_name = build_member_symbol(package_name, class_stack, "<init>");
    let visibility = extract_visibility(constructor_node, content);

    MethodContext {
        qualified_name,
        span: (constructor_node.start_byte(), constructor_node.end_byte()),
        depth,
        is_static: false,
        is_synchronized: false,
        is_constructor: true,
        is_native: false,
        package_name: package_name.map(std::string::ToString::to_string),
        class_stack: class_stack.to_vec(),
        return_type: None, // Constructors don't have return types
        visibility,
    }
}

// ================================
// Edge Building with GraphBuildHelper
// ================================

/// Walk the AST tree and build edges using `GraphBuildHelper`
fn walk_tree_for_edges(
    node: Node,
    content: &[u8],
    ast_graph: &ASTGraph,
    scope_tree: &mut JavaScopeTree,
    helper: &mut GraphBuildHelper,
    tree: &Tree,
) -> GraphResult<()> {
    match node.kind() {
        "class_declaration" | "interface_declaration" | "enum_declaration" => {
            // handle_type_declaration already walks the body children, so return early
            return handle_type_declaration(node, content, ast_graph, scope_tree, helper, tree);
        }
        "method_declaration" | "constructor_declaration" => {
            // Handle both method and constructor parameters
            handle_method_declaration_parameters(node, content, ast_graph, scope_tree, helper);

            // Detect Spring MVC route annotations on method declarations
            if node.kind() == "method_declaration"
                && let Some((http_method, path)) = extract_spring_route_info(node, content)
            {
                // Compose class-level @RequestMapping prefix with method path
                let full_path =
                    if let Some(class_prefix) = extract_class_request_mapping_path(node, content) {
                        let prefix = class_prefix.trim_end_matches('/');
                        let suffix = path.trim_start_matches('/');
                        if suffix.is_empty() {
                            class_prefix
                        } else {
                            format!("{prefix}/{suffix}")
                        }
                    } else {
                        path
                    };
                let qualified_name = format!("route::{http_method}::{full_path}");
                let span = Span::from_bytes(node.start_byte(), node.end_byte());
                let endpoint_id = helper.add_endpoint(&qualified_name, Some(span));

                // Link endpoint to the handler method via Contains edge
                let byte_pos = node.start_byte();
                if let Some(context) = ast_graph.find_enclosing(byte_pos) {
                    let method_id = helper.ensure_method(
                        context.qualified_name(),
                        Some(Span::from_bytes(context.span.0, context.span.1)),
                        false,
                        context.is_static,
                    );
                    helper.add_contains_edge(endpoint_id, method_id);
                }
            }
        }
        "compact_constructor_declaration" => {
            handle_compact_constructor_parameters(node, content, ast_graph, scope_tree, helper);
        }
        "method_invocation" => {
            handle_method_invocation(node, content, ast_graph, helper);
        }
        "object_creation_expression" => {
            handle_constructor_call(node, content, ast_graph, helper);
        }
        "import_declaration" => {
            handle_import_declaration(node, content, helper);
        }
        "local_variable_declaration" => {
            handle_local_variable_declaration(node, content, ast_graph, scope_tree, helper);
        }
        "enhanced_for_statement" => {
            handle_enhanced_for_declaration(node, content, ast_graph, scope_tree, helper);
        }
        "catch_clause" => {
            handle_catch_parameter_declaration(node, content, ast_graph, scope_tree, helper);
        }
        "lambda_expression" => {
            handle_lambda_parameter_declaration(node, content, ast_graph, scope_tree, helper);
        }
        "try_with_resources_statement" => {
            handle_try_with_resources_declaration(node, content, ast_graph, scope_tree, helper);
        }
        "instanceof_expression" => {
            handle_instanceof_pattern_declaration(node, content, ast_graph, scope_tree, helper);
        }
        "switch_label" => {
            handle_switch_pattern_declaration(node, content, ast_graph, scope_tree, helper);
        }
        "identifier" => {
            handle_identifier_for_reference(node, content, ast_graph, scope_tree, helper);
        }
        _ => {}
    }

    // Recurse to children
    for i in 0..node.child_count() {
        if let Some(child) = node.child(i as u32) {
            walk_tree_for_edges(child, content, ast_graph, scope_tree, helper, tree)?;
        }
    }

    Ok(())
}

fn handle_type_declaration(
    node: Node,
    content: &[u8],
    ast_graph: &ASTGraph,
    scope_tree: &mut JavaScopeTree,
    helper: &mut GraphBuildHelper,
    tree: &Tree,
) -> GraphResult<()> {
    let Some(name_node) = node.child_by_field_name("name") else {
        return Ok(());
    };
    let class_name = extract_identifier(name_node, content);
    let span = Span::from_bytes(node.start_byte(), node.end_byte());

    let package = PackageResolver::package_from_ast(tree, content);
    let class_stack = extract_declaration_class_stack(node, content);
    let qualified_name = qualify_class_name(&class_name, &class_stack, package.as_deref());
    let class_node_id = add_type_node(helper, node.kind(), &qualified_name, span);

    if is_public(node, content) {
        export_from_file_module(helper, class_node_id);
    }

    process_inheritance(node, content, package.as_deref(), class_node_id, helper);
    if node.kind() == "class_declaration" {
        process_implements(node, content, package.as_deref(), class_node_id, helper);
    }
    if node.kind() == "interface_declaration" {
        process_interface_extends(node, content, package.as_deref(), class_node_id, helper);
    }

    if let Some(body_node) = node.child_by_field_name("body") {
        let is_interface = node.kind() == "interface_declaration";
        process_class_member_exports(body_node, content, &qualified_name, helper, is_interface);

        for i in 0..body_node.child_count() {
            if let Some(child) = body_node.child(i as u32) {
                walk_tree_for_edges(child, content, ast_graph, scope_tree, helper, tree)?;
            }
        }
    }

    Ok(())
}

fn extract_declaration_class_stack(node: Node, content: &[u8]) -> Vec<String> {
    let mut class_stack = Vec::new();
    let mut current_node = Some(node);

    while let Some(current) = current_node {
        if matches!(
            current.kind(),
            "class_declaration" | "interface_declaration" | "enum_declaration"
        ) && let Some(name_node) = current.child_by_field_name("name")
        {
            class_stack.push(extract_identifier(name_node, content));
        }

        current_node = current.parent();
    }

    class_stack.reverse();
    class_stack
}

fn qualify_class_name(class_name: &str, class_stack: &[String], package: Option<&str>) -> String {
    let scope = class_stack
        .split_last()
        .map_or(&[][..], |(_, parent_stack)| parent_stack);
    build_symbol(package, scope, class_name)
}

fn add_type_node(
    helper: &mut GraphBuildHelper,
    kind: &str,
    qualified_name: &str,
    span: Span,
) -> sqry_core::graph::unified::node::NodeId {
    match kind {
        "interface_declaration" => helper.add_interface(qualified_name, Some(span)),
        _ => helper.add_class(qualified_name, Some(span)),
    }
}

fn handle_method_invocation(
    node: Node,
    content: &[u8],
    ast_graph: &ASTGraph,
    helper: &mut GraphBuildHelper,
) {
    if let Some(caller_context) = ast_graph.find_enclosing(node.start_byte()) {
        let is_ffi = build_ffi_call_edge(node, content, caller_context, ast_graph, helper);
        if is_ffi {
            return;
        }
    }

    process_method_call_unified(node, content, ast_graph, helper);
}

fn handle_constructor_call(
    node: Node,
    content: &[u8],
    ast_graph: &ASTGraph,
    helper: &mut GraphBuildHelper,
) {
    process_constructor_call_unified(node, content, ast_graph, helper);
}

fn handle_import_declaration(node: Node, content: &[u8], helper: &mut GraphBuildHelper) {
    process_import_unified(node, content, helper);
}

/// Add `TypeOf` edges for all field declarations
/// Creates Property nodes for mutable fields and Constant nodes for final fields
fn add_field_typeof_edges(ast_graph: &ASTGraph, helper: &mut GraphBuildHelper) {
    for (field_name, (type_fqn, is_final, visibility, is_static)) in &ast_graph.field_types {
        // Create appropriate node type based on 'final' modifier, with visibility and static metadata
        let field_id = if *is_final {
            // final fields are constants
            if let Some(vis) = visibility {
                helper.add_constant_with_static_and_visibility(
                    field_name,
                    None,
                    *is_static,
                    Some(vis.as_str()),
                )
            } else {
                helper.add_constant_with_static_and_visibility(field_name, None, *is_static, None)
            }
        } else {
            // non-final fields are properties
            if let Some(vis) = visibility {
                helper.add_property_with_static_and_visibility(
                    field_name,
                    None,
                    *is_static,
                    Some(vis.as_str()),
                )
            } else {
                helper.add_property_with_static_and_visibility(field_name, None, *is_static, None)
            }
        };

        // Create class node for the type
        let type_id = helper.add_class(type_fqn, None);

        // Create TypeOf edge from field to its type
        helper.add_typeof_edge(field_id, type_id);
    }
}

/// Extract method parameters and create Parameter nodes with `TypeOf` edges
/// Should be called during method context creation
fn extract_method_parameters(
    method_node: Node,
    content: &[u8],
    qualified_method_name: &str,
    helper: &mut GraphBuildHelper,
    import_map: &HashMap<String, String>,
    scope_tree: &mut JavaScopeTree,
) {
    // Find formal_parameters node in the method declaration
    let mut cursor = method_node.walk();
    for child in method_node.children(&mut cursor) {
        if child.kind() == "formal_parameters" {
            // Iterate through each parameter (formal, varargs, receiver)
            let mut param_cursor = child.walk();
            for param_child in child.children(&mut param_cursor) {
                match param_child.kind() {
                    "formal_parameter" => {
                        handle_formal_parameter(
                            param_child,
                            content,
                            qualified_method_name,
                            helper,
                            import_map,
                            scope_tree,
                        );
                    }
                    "spread_parameter" => {
                        handle_spread_parameter(
                            param_child,
                            content,
                            qualified_method_name,
                            helper,
                            import_map,
                            scope_tree,
                        );
                    }
                    "receiver_parameter" => {
                        handle_receiver_parameter(
                            param_child,
                            content,
                            qualified_method_name,
                            helper,
                            import_map,
                            scope_tree,
                        );
                    }
                    _ => {}
                }
            }
        }
    }
}

/// Handle a single formal parameter and create Parameter node with `TypeOf` edge
fn handle_formal_parameter(
    param_node: Node,
    content: &[u8],
    method_name: &str,
    helper: &mut GraphBuildHelper,
    import_map: &HashMap<String, String>,
    scope_tree: &mut JavaScopeTree,
) {
    use sqry_core::graph::unified::node::NodeKind;

    // Extract type from formal_parameter
    let Some(type_node) = param_node.child_by_field_name("type") else {
        return;
    };

    // Extract parameter name
    let Some(name_node) = param_node.child_by_field_name("name") else {
        return;
    };

    // Get type and parameter name texts
    let type_text = extract_type_name(type_node, content);
    let param_name = extract_identifier(name_node, content);

    if type_text.is_empty() || param_name.is_empty() {
        return;
    }

    // Resolve type to FQN using import map
    let resolved_type = import_map.get(&type_text).cloned().unwrap_or(type_text);

    // Create qualified parameter name (method::param)
    let qualified_param = format!("{method_name}::{param_name}");
    let span = Span::from_bytes(param_node.start_byte(), param_node.end_byte());

    // Create parameter node
    let param_id = helper.add_node(&qualified_param, Some(span), NodeKind::Parameter);

    scope_tree.attach_node_id(&param_name, name_node.start_byte(), param_id);

    // Create type node (class/interface)
    let type_id = helper.add_class(&resolved_type, None);

    // Add TypeOf edge from parameter to its type
    helper.add_typeof_edge(param_id, type_id);
}

/// Handle a spread parameter (varargs like String... args)
fn handle_spread_parameter(
    param_node: Node,
    content: &[u8],
    method_name: &str,
    helper: &mut GraphBuildHelper,
    import_map: &HashMap<String, String>,
    scope_tree: &mut JavaScopeTree,
) {
    use sqry_core::graph::unified::node::NodeKind;

    // spread_parameter structure:
    // (spread_parameter
    //   type_identifier
    //   ...
    //   variable_declarator
    //     identifier)

    // Find type node (first type_identifier child)
    let mut type_text = String::new();
    let mut param_name = String::new();
    let mut param_name_node = None;

    let mut cursor = param_node.walk();
    for child in param_node.children(&mut cursor) {
        match child.kind() {
            "type_identifier" | "generic_type" | "scoped_type_identifier" => {
                type_text = extract_type_name(child, content);
            }
            "variable_declarator" => {
                // Name is inside variable_declarator
                if let Some(name_node) = child.child_by_field_name("name") {
                    param_name = extract_identifier(name_node, content);
                    param_name_node = Some(name_node);
                }
            }
            _ => {}
        }
    }

    if type_text.is_empty() || param_name.is_empty() {
        return;
    }

    // Resolve type to FQN using import map
    let resolved_type = import_map.get(&type_text).cloned().unwrap_or(type_text);

    // Create qualified parameter name (method::param)
    let qualified_param = format!("{method_name}::{param_name}");
    let span = Span::from_bytes(param_node.start_byte(), param_node.end_byte());

    // Create parameter node
    let param_id = helper.add_node(&qualified_param, Some(span), NodeKind::Parameter);

    if let Some(name_node) = param_name_node {
        scope_tree.attach_node_id(&param_name, name_node.start_byte(), param_id);
    }

    // Create type node for the array type (resolved_type represents the element type)
    // For varargs, the actual type is an array of the base type
    let type_id = helper.add_class(&resolved_type, None);

    // Add TypeOf edge from parameter to its type
    helper.add_typeof_edge(param_id, type_id);
}

/// Handle a receiver parameter (e.g., Outer.this in inner class methods)
fn handle_receiver_parameter(
    param_node: Node,
    content: &[u8],
    method_name: &str,
    helper: &mut GraphBuildHelper,
    import_map: &HashMap<String, String>,
    _scope_tree: &mut JavaScopeTree,
) {
    use sqry_core::graph::unified::node::NodeKind;

    // receiver_parameter structure:
    // (receiver_parameter
    //   type_identifier
    //   identifier (optional - class name)
    //   .
    //   this)

    let mut type_text = String::new();
    let mut cursor = param_node.walk();

    // Find the type_identifier child
    for child in param_node.children(&mut cursor) {
        if matches!(
            child.kind(),
            "type_identifier" | "generic_type" | "scoped_type_identifier"
        ) {
            type_text = extract_type_name(child, content);
            break;
        }
    }

    if type_text.is_empty() {
        return;
    }

    // Receiver parameter name is always "this"
    let param_name = "this";

    // Resolve type to FQN using import map
    let resolved_type = import_map.get(&type_text).cloned().unwrap_or(type_text);

    // Create qualified parameter name (method::this)
    let qualified_param = format!("{method_name}::{param_name}");
    let span = Span::from_bytes(param_node.start_byte(), param_node.end_byte());

    // Create parameter node
    let param_id = helper.add_node(&qualified_param, Some(span), NodeKind::Parameter);

    // Create type node (class)
    let type_id = helper.add_class(&resolved_type, None);

    // Add TypeOf edge from parameter to its type
    helper.add_typeof_edge(param_id, type_id);
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
enum FieldAccessRole {
    Default,
    ExplicitThisOrSuper,
    Skip,
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
enum FieldResolutionMode {
    Default,
    CurrentOnly,
}

fn field_access_role(
    node: Node,
    content: &[u8],
    ast_graph: &ASTGraph,
    scope_tree: &JavaScopeTree,
    identifier_text: &str,
) -> FieldAccessRole {
    let Some(parent) = node.parent() else {
        return FieldAccessRole::Default;
    };

    if parent.kind() == "field_access" {
        if let Some(field_node) = parent.child_by_field_name("field")
            && field_node.id() == node.id()
            && let Some(object_node) = parent.child_by_field_name("object")
        {
            if is_explicit_this_or_super(object_node, content) {
                return FieldAccessRole::ExplicitThisOrSuper;
            }
            return FieldAccessRole::Skip;
        }

        if let Some(object_node) = parent.child_by_field_name("object")
            && object_node.id() == node.id()
            && !scope_tree.has_local_binding(identifier_text, node.start_byte())
            && is_static_type_identifier(identifier_text, ast_graph, scope_tree)
        {
            return FieldAccessRole::Skip;
        }
    }

    if parent.kind() == "method_invocation"
        && let Some(object_node) = parent.child_by_field_name("object")
        && object_node.id() == node.id()
        && !scope_tree.has_local_binding(identifier_text, node.start_byte())
        && is_static_type_identifier(identifier_text, ast_graph, scope_tree)
    {
        return FieldAccessRole::Skip;
    }

    if parent.kind() == "method_reference"
        && let Some(object_node) = parent.child_by_field_name("object")
        && object_node.id() == node.id()
        && !scope_tree.has_local_binding(identifier_text, node.start_byte())
        && is_static_type_identifier(identifier_text, ast_graph, scope_tree)
    {
        return FieldAccessRole::Skip;
    }

    FieldAccessRole::Default
}

fn is_static_type_identifier(
    identifier_text: &str,
    ast_graph: &ASTGraph,
    scope_tree: &JavaScopeTree,
) -> bool {
    ast_graph.import_map.contains_key(identifier_text)
        || scope_tree.is_known_type_name(identifier_text)
}

fn is_explicit_this_or_super(node: Node, content: &[u8]) -> bool {
    if matches!(node.kind(), "this" | "super") {
        return true;
    }
    if node.kind() == "identifier" {
        let text = extract_identifier(node, content);
        return matches!(text.as_str(), "this" | "super");
    }
    if node.kind() == "field_access"
        && let Some(field) = node.child_by_field_name("field")
    {
        let text = extract_identifier(field, content);
        if matches!(text.as_str(), "this" | "super") {
            return true;
        }
    }
    false
}

/// Check if an identifier node is part of a declaration context
/// Returns true if the identifier is being declared (not referenced)
#[allow(clippy::too_many_lines)]
fn is_declaration_context(node: Node) -> bool {
    // Check if parent is a declaration node
    let Some(parent) = node.parent() else {
        return false;
    };

    // For variable_declarator, only the 'name' field is a declaration, not 'value'
    // Example: `String key = API_KEY`
    //   - 'key' has parent variable_declarator with field 'name' (declaration)
    //   - 'API_KEY' has parent variable_declarator with field 'value' (NOT declaration)
    if parent.kind() == "variable_declarator" {
        // Check if this identifier is the 'name' field
        let mut cursor = parent.walk();
        for (idx, child) in parent.children(&mut cursor).enumerate() {
            if child.id() == node.id() {
                #[allow(clippy::cast_possible_truncation)]
                if let Some(field_name) = parent.field_name_for_child(idx as u32) {
                    // Only 'name' field is declaration context, not 'value'
                    return field_name == "name";
                }
                break;
            }
        }

        // If inside variable_declarator that's inside spread_parameter, it's a declaration
        if let Some(grandparent) = parent.parent()
            && grandparent.kind() == "spread_parameter"
        {
            return true;
        }

        return false;
    }

    // For formal_parameter, only the 'name' field is a declaration
    if parent.kind() == "formal_parameter" {
        let mut cursor = parent.walk();
        for (idx, child) in parent.children(&mut cursor).enumerate() {
            if child.id() == node.id() {
                #[allow(clippy::cast_possible_truncation)]
                if let Some(field_name) = parent.field_name_for_child(idx as u32) {
                    return field_name == "name";
                }
                break;
            }
        }
        return false;
    }

    // For enhanced_for_statement, only the loop variable 'name' field is a declaration
    // Example: `for (String item : items)` - 'item' is declaration, 'items' is not
    if parent.kind() == "enhanced_for_statement" {
        // Check if this identifier is the loop variable name field
        let mut cursor = parent.walk();
        for (idx, child) in parent.children(&mut cursor).enumerate() {
            if child.id() == node.id() {
                #[allow(clippy::cast_possible_truncation)]
                if let Some(field_name) = parent.field_name_for_child(idx as u32) {
                    // Only the 'name' field is declaration, not the iterable expression
                    return field_name == "name";
                }
                break;
            }
        }
        return false;
    }

    if parent.kind() == "lambda_expression" {
        if let Some(params) = parent.child_by_field_name("parameters") {
            return params.id() == node.id();
        }
        return false;
    }

    if parent.kind() == "inferred_parameters" {
        return true;
    }

    if parent.kind() == "resource" {
        if let Some(name_node) = parent.child_by_field_name("name")
            && name_node.id() == node.id()
        {
            let has_type = parent.child_by_field_name("type").is_some();
            let has_value = parent.child_by_field_name("value").is_some();
            return has_type || has_value;
        }
        return false;
    }

    // Pattern variables (Java 16+)
    // Type pattern: case String s -> ...; if (obj instanceof String s)
    // The 'name' field is the pattern variable declaration
    if parent.kind() == "type_pattern" {
        if let Some(name_node) = parent.child_by_field_name("name")
            && name_node.id() == node.id()
        {
            return true;
        }
        return false;
    }

    // instanceof pattern: if (obj instanceof String value)
    if parent.kind() == "instanceof_expression" {
        let mut cursor = parent.walk();
        for (idx, child) in parent.children(&mut cursor).enumerate() {
            if child.id() == node.id() {
                #[allow(clippy::cast_possible_truncation)]
                if let Some(field_name) = parent.field_name_for_child(idx as u32) {
                    // The 'name' field in instanceof_expression is the pattern variable
                    return field_name == "name";
                }
                break;
            }
        }
        return false;
    }

    // Record pattern components: case Point(int x, int y)
    // The identifiers in record_pattern_component are declarations
    if parent.kind() == "record_pattern_component" {
        // In record pattern component, the second child (after type) is the identifier declaration
        let mut cursor = parent.walk();
        for child in parent.children(&mut cursor) {
            if child.id() == node.id() && child.kind() == "identifier" {
                // This is a pattern variable declaration
                return true;
            }
        }
        return false;
    }

    if parent.kind() == "record_component" {
        if let Some(name_node) = parent.child_by_field_name("name") {
            return name_node.id() == node.id();
        }
        return false;
    }

    // For other declaration contexts, any direct child identifier is considered a declaration
    matches!(
        parent.kind(),
        "method_declaration"
            | "constructor_declaration"
            | "compact_constructor_declaration"
            | "class_declaration"
            | "interface_declaration"
            | "enum_declaration"
            | "field_declaration"
            | "catch_formal_parameter"
    )
}

fn is_method_invocation_name(node: Node) -> bool {
    let Some(parent) = node.parent() else {
        return false;
    };
    if parent.kind() != "method_invocation" {
        return false;
    }
    parent
        .child_by_field_name("name")
        .is_some_and(|name_node| name_node.id() == node.id())
}

fn is_method_reference_name(node: Node) -> bool {
    let Some(parent) = node.parent() else {
        return false;
    };
    if parent.kind() != "method_reference" {
        return false;
    }
    parent
        .child_by_field_name("name")
        .is_some_and(|name_node| name_node.id() == node.id())
}

fn is_label_identifier(node: Node) -> bool {
    let Some(parent) = node.parent() else {
        return false;
    };
    if parent.kind() == "labeled_statement" {
        return true;
    }
    if matches!(parent.kind(), "break_statement" | "continue_statement")
        && let Some(label) = parent.child_by_field_name("label")
    {
        return label.id() == node.id();
    }
    false
}

fn is_class_literal(node: Node) -> bool {
    let Some(parent) = node.parent() else {
        return false;
    };
    parent.kind() == "class_literal"
}

fn is_type_identifier_context(node: Node) -> bool {
    let Some(parent) = node.parent() else {
        return false;
    };
    matches!(
        parent.kind(),
        "type_identifier"
            | "scoped_type_identifier"
            | "scoped_identifier"
            | "generic_type"
            | "type_argument"
            | "type_bound"
    )
}

fn add_reference_edge_for_target(
    usage_node: Node,
    identifier_text: &str,
    target_id: sqry_core::graph::unified::node::NodeId,
    helper: &mut GraphBuildHelper,
) {
    let usage_span = Span::from_bytes(usage_node.start_byte(), usage_node.end_byte());
    let usage_id = helper.add_node(
        &format!("{}@{}", identifier_text, usage_node.start_byte()),
        Some(usage_span),
        sqry_core::graph::unified::node::NodeKind::Variable,
    );
    helper.add_reference_edge(usage_id, target_id);
}

fn resolve_field_reference(
    node: Node,
    identifier_text: &str,
    ast_graph: &ASTGraph,
    helper: &mut GraphBuildHelper,
    mode: FieldResolutionMode,
) {
    let context = ast_graph.find_enclosing(node.start_byte());
    let mut candidates = Vec::new();
    if let Some(ctx) = context
        && !ctx.class_stack.is_empty()
    {
        if mode == FieldResolutionMode::CurrentOnly {
            let class_path = ctx.class_stack.join("::");
            candidates.push(format!("{class_path}::{identifier_text}"));
        } else {
            let stack_len = ctx.class_stack.len();
            for idx in (1..=stack_len).rev() {
                let class_path = ctx.class_stack[..idx].join("::");
                candidates.push(format!("{class_path}::{identifier_text}"));
            }
        }
    }

    if mode != FieldResolutionMode::CurrentOnly {
        candidates.push(identifier_text.to_string());
    }

    for candidate in candidates {
        if ast_graph.field_types.contains_key(&candidate) {
            add_field_reference(node, identifier_text, &candidate, ast_graph, helper);
            return;
        }
    }
}

fn add_field_reference(
    node: Node,
    identifier_text: &str,
    field_name: &str,
    ast_graph: &ASTGraph,
    helper: &mut GraphBuildHelper,
) {
    let usage_span = Span::from_bytes(node.start_byte(), node.end_byte());
    let usage_id = helper.add_node(
        &format!("{}@{}", identifier_text, node.start_byte()),
        Some(usage_span),
        sqry_core::graph::unified::node::NodeKind::Variable,
    );

    let field_metadata = ast_graph.field_types.get(field_name);
    let field_id = if let Some((_, is_final, visibility, is_static)) = field_metadata {
        if *is_final {
            if let Some(vis) = visibility {
                helper.add_constant_with_static_and_visibility(
                    field_name,
                    None,
                    *is_static,
                    Some(vis.as_str()),
                )
            } else {
                helper.add_constant_with_static_and_visibility(field_name, None, *is_static, None)
            }
        } else if let Some(vis) = visibility {
            helper.add_property_with_static_and_visibility(
                field_name,
                None,
                *is_static,
                Some(vis.as_str()),
            )
        } else {
            helper.add_property_with_static_and_visibility(field_name, None, *is_static, None)
        }
    } else {
        helper.add_property_with_static_and_visibility(field_name, None, false, None)
    };

    helper.add_reference_edge(usage_id, field_id);
}

/// Handle identifier nodes to create Reference edges for variable/field accesses
#[allow(clippy::similar_names)]
fn handle_identifier_for_reference(
    node: Node,
    content: &[u8],
    ast_graph: &ASTGraph,
    scope_tree: &mut JavaScopeTree,
    helper: &mut GraphBuildHelper,
) {
    let identifier_text = extract_identifier(node, content);

    if identifier_text.is_empty() {
        return;
    }

    // Skip if this identifier is part of a declaration
    if is_declaration_context(node) {
        return;
    }

    if is_method_invocation_name(node)
        || is_method_reference_name(node)
        || is_label_identifier(node)
        || is_class_literal(node)
    {
        return;
    }

    if is_type_identifier_context(node) {
        return;
    }

    let field_access_role =
        field_access_role(node, content, ast_graph, scope_tree, &identifier_text);
    if matches!(field_access_role, FieldAccessRole::Skip) {
        return;
    }

    let allow_local = matches!(field_access_role, FieldAccessRole::Default);
    let allow_field = !matches!(field_access_role, FieldAccessRole::Skip);
    let field_mode = if matches!(field_access_role, FieldAccessRole::ExplicitThisOrSuper) {
        FieldResolutionMode::CurrentOnly
    } else {
        FieldResolutionMode::Default
    };

    if allow_local {
        match scope_tree.resolve_identifier(node.start_byte(), &identifier_text) {
            ResolutionOutcome::Local(binding) => {
                let target_id = if let Some(node_id) = binding.node_id {
                    node_id
                } else {
                    let span = Span::from_bytes(binding.decl_start_byte, binding.decl_end_byte);
                    let qualified_var = format!("{}@{}", identifier_text, binding.decl_start_byte);
                    let var_id = helper.add_variable(&qualified_var, Some(span));
                    scope_tree.attach_node_id(&identifier_text, binding.decl_start_byte, var_id);
                    var_id
                };
                add_reference_edge_for_target(node, &identifier_text, target_id, helper);
                return;
            }
            ResolutionOutcome::Member { qualified_name } => {
                if let Some(field_name) = qualified_name {
                    add_field_reference(node, &identifier_text, &field_name, ast_graph, helper);
                }
                return;
            }
            ResolutionOutcome::Ambiguous => {
                return;
            }
            ResolutionOutcome::NoMatch => {}
        }
    }

    if !allow_field {
        return;
    }

    resolve_field_reference(node, &identifier_text, ast_graph, helper, field_mode);
}

/// Handle method declarations to extract parameter `TypeOf` edges
fn handle_method_declaration_parameters(
    node: Node,
    content: &[u8],
    ast_graph: &ASTGraph,
    scope_tree: &mut JavaScopeTree,
    helper: &mut GraphBuildHelper,
) {
    // Find the enclosing method context to get the qualified name
    let byte_pos = node.start_byte();
    if let Some(context) = ast_graph.find_enclosing(byte_pos) {
        let qualified_method_name = &context.qualified_name;

        // Extract parameters from this method
        extract_method_parameters(
            node,
            content,
            qualified_method_name,
            helper,
            &ast_graph.import_map,
            scope_tree,
        );
    }
}

/// Handle local variable declarations and create `TypeOf` edges
fn handle_local_variable_declaration(
    node: Node,
    content: &[u8],
    ast_graph: &ASTGraph,
    scope_tree: &mut JavaScopeTree,
    helper: &mut GraphBuildHelper,
) {
    // Extract the type from the local variable declaration
    let Some(type_node) = node.child_by_field_name("type") else {
        return;
    };

    let type_text = extract_type_name(type_node, content);
    if type_text.is_empty() {
        return;
    }

    // Resolve type through import map (e.g., Optional<User> -> java.util.Optional)
    let resolved_type = ast_graph
        .import_map
        .get(&type_text)
        .cloned()
        .unwrap_or_else(|| type_text.clone());

    // Process all variable declarators (handles cases like: String a, b, c;)
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "variable_declarator"
            && let Some(name_node) = child.child_by_field_name("name")
        {
            let var_name = extract_identifier(name_node, content);

            // Create unique variable name using byte position to avoid conflicts
            let qualified_var = format!("{}@{}", var_name, name_node.start_byte());

            // Create variable node
            let span = Span::from_bytes(child.start_byte(), child.end_byte());
            let var_id = helper.add_variable(&qualified_var, Some(span));
            scope_tree.attach_node_id(&var_name, name_node.start_byte(), var_id);

            // Create type node
            let type_id = helper.add_class(&resolved_type, None);

            // Create TypeOf edge
            helper.add_typeof_edge(var_id, type_id);
        }
    }
}

fn handle_enhanced_for_declaration(
    node: Node,
    content: &[u8],
    ast_graph: &ASTGraph,
    scope_tree: &mut JavaScopeTree,
    helper: &mut GraphBuildHelper,
) {
    let Some(type_node) = node.child_by_field_name("type") else {
        return;
    };
    let Some(name_node) = node.child_by_field_name("name") else {
        return;
    };
    let Some(body_node) = node.child_by_field_name("body") else {
        return;
    };

    let type_text = extract_type_name(type_node, content);
    let var_name = extract_identifier(name_node, content);
    if type_text.is_empty() || var_name.is_empty() {
        return;
    }

    let resolved_type = ast_graph
        .import_map
        .get(&type_text)
        .cloned()
        .unwrap_or(type_text);

    let qualified_var = format!("{}@{}", var_name, name_node.start_byte());
    let span = Span::from_bytes(name_node.start_byte(), name_node.end_byte());
    let var_id = helper.add_variable(&qualified_var, Some(span));
    scope_tree.attach_node_id(&var_name, body_node.start_byte(), var_id);

    let type_id = helper.add_class(&resolved_type, None);
    helper.add_typeof_edge(var_id, type_id);
}

fn handle_catch_parameter_declaration(
    node: Node,
    content: &[u8],
    ast_graph: &ASTGraph,
    scope_tree: &mut JavaScopeTree,
    helper: &mut GraphBuildHelper,
) {
    let Some(param_node) = node
        .child_by_field_name("parameter")
        .or_else(|| first_child_of_kind(node, "catch_formal_parameter"))
        .or_else(|| first_child_of_kind(node, "formal_parameter"))
    else {
        return;
    };
    let Some(name_node) = param_node
        .child_by_field_name("name")
        .or_else(|| first_child_of_kind(param_node, "identifier"))
    else {
        return;
    };

    let var_name = extract_identifier(name_node, content);
    if var_name.is_empty() {
        return;
    }

    let qualified_var = format!("{}@{}", var_name, name_node.start_byte());
    let span = Span::from_bytes(param_node.start_byte(), param_node.end_byte());
    let var_id = helper.add_variable(&qualified_var, Some(span));
    scope_tree.attach_node_id(&var_name, name_node.start_byte(), var_id);

    if let Some(type_node) = param_node
        .child_by_field_name("type")
        .or_else(|| first_child_of_kind(param_node, "type_identifier"))
        .or_else(|| first_child_of_kind(param_node, "scoped_type_identifier"))
        .or_else(|| first_child_of_kind(param_node, "generic_type"))
    {
        add_typeof_for_catch_type(type_node, content, ast_graph, helper, var_id);
    }
}

fn add_typeof_for_catch_type(
    type_node: Node,
    content: &[u8],
    ast_graph: &ASTGraph,
    helper: &mut GraphBuildHelper,
    var_id: sqry_core::graph::unified::node::NodeId,
) {
    if type_node.kind() == "union_type" {
        let mut cursor = type_node.walk();
        for child in type_node.children(&mut cursor) {
            if matches!(
                child.kind(),
                "type_identifier" | "scoped_type_identifier" | "generic_type"
            ) {
                let type_text = extract_type_name(child, content);
                if !type_text.is_empty() {
                    let resolved_type = ast_graph
                        .import_map
                        .get(&type_text)
                        .cloned()
                        .unwrap_or(type_text);
                    let type_id = helper.add_class(&resolved_type, None);
                    helper.add_typeof_edge(var_id, type_id);
                }
            }
        }
        return;
    }

    let type_text = extract_type_name(type_node, content);
    if type_text.is_empty() {
        return;
    }
    let resolved_type = ast_graph
        .import_map
        .get(&type_text)
        .cloned()
        .unwrap_or(type_text);
    let type_id = helper.add_class(&resolved_type, None);
    helper.add_typeof_edge(var_id, type_id);
}

fn handle_lambda_parameter_declaration(
    node: Node,
    content: &[u8],
    ast_graph: &ASTGraph,
    scope_tree: &mut JavaScopeTree,
    helper: &mut GraphBuildHelper,
) {
    use sqry_core::graph::unified::node::NodeKind;

    let Some(params_node) = node.child_by_field_name("parameters") else {
        return;
    };
    let lambda_prefix = format!("lambda@{}", node.start_byte());

    if params_node.kind() == "identifier" {
        let name = extract_identifier(params_node, content);
        if name.is_empty() {
            return;
        }
        let qualified_param = format!("{lambda_prefix}::{name}");
        let span = Span::from_bytes(params_node.start_byte(), params_node.end_byte());
        let param_id = helper.add_node(&qualified_param, Some(span), NodeKind::Parameter);
        scope_tree.attach_node_id(&name, params_node.start_byte(), param_id);
        return;
    }

    let mut cursor = params_node.walk();
    for child in params_node.children(&mut cursor) {
        match child.kind() {
            "identifier" => {
                let name = extract_identifier(child, content);
                if name.is_empty() {
                    continue;
                }
                let qualified_param = format!("{lambda_prefix}::{name}");
                let span = Span::from_bytes(child.start_byte(), child.end_byte());
                let param_id = helper.add_node(&qualified_param, Some(span), NodeKind::Parameter);
                scope_tree.attach_node_id(&name, child.start_byte(), param_id);
            }
            "formal_parameter" => {
                let Some(name_node) = child.child_by_field_name("name") else {
                    continue;
                };
                let Some(type_node) = child.child_by_field_name("type") else {
                    continue;
                };
                let name = extract_identifier(name_node, content);
                if name.is_empty() {
                    continue;
                }
                let type_text = extract_type_name(type_node, content);
                let resolved_type = ast_graph
                    .import_map
                    .get(&type_text)
                    .cloned()
                    .unwrap_or(type_text);
                let qualified_param = format!("{lambda_prefix}::{name}");
                let span = Span::from_bytes(child.start_byte(), child.end_byte());
                let param_id = helper.add_node(&qualified_param, Some(span), NodeKind::Parameter);
                scope_tree.attach_node_id(&name, name_node.start_byte(), param_id);
                let type_id = helper.add_class(&resolved_type, None);
                helper.add_typeof_edge(param_id, type_id);
            }
            _ => {}
        }
    }
}

fn handle_try_with_resources_declaration(
    node: Node,
    content: &[u8],
    ast_graph: &ASTGraph,
    scope_tree: &mut JavaScopeTree,
    helper: &mut GraphBuildHelper,
) {
    let Some(resources) = node.child_by_field_name("resources") else {
        return;
    };

    let mut cursor = resources.walk();
    for resource in resources.children(&mut cursor) {
        if resource.kind() != "resource" {
            continue;
        }
        let name_node = resource.child_by_field_name("name");
        let type_node = resource.child_by_field_name("type");
        let value_node = resource.child_by_field_name("value");
        if let Some(name_node) = name_node {
            if type_node.is_none() && value_node.is_none() {
                continue;
            }
            let name = extract_identifier(name_node, content);
            if name.is_empty() {
                continue;
            }

            let qualified_var = format!("{}@{}", name, name_node.start_byte());
            let span = Span::from_bytes(resource.start_byte(), resource.end_byte());
            let var_id = helper.add_variable(&qualified_var, Some(span));
            scope_tree.attach_node_id(&name, name_node.start_byte(), var_id);

            if let Some(type_node) = type_node {
                let type_text = extract_type_name(type_node, content);
                if !type_text.is_empty() {
                    let resolved_type = ast_graph
                        .import_map
                        .get(&type_text)
                        .cloned()
                        .unwrap_or(type_text);
                    let type_id = helper.add_class(&resolved_type, None);
                    helper.add_typeof_edge(var_id, type_id);
                }
            }
        }
    }
}

fn handle_instanceof_pattern_declaration(
    node: Node,
    content: &[u8],
    ast_graph: &ASTGraph,
    scope_tree: &mut JavaScopeTree,
    helper: &mut GraphBuildHelper,
) {
    let mut patterns = Vec::new();
    collect_pattern_declarations(node, &mut patterns);
    for (name_node, type_node) in patterns {
        let name = extract_identifier(name_node, content);
        if name.is_empty() {
            continue;
        }
        let qualified_var = format!("{}@{}", name, name_node.start_byte());
        let span = Span::from_bytes(name_node.start_byte(), name_node.end_byte());
        let var_id = helper.add_variable(&qualified_var, Some(span));
        scope_tree.attach_node_id(&name, name_node.start_byte(), var_id);

        if let Some(type_node) = type_node {
            let type_text = extract_type_name(type_node, content);
            if !type_text.is_empty() {
                let resolved_type = ast_graph
                    .import_map
                    .get(&type_text)
                    .cloned()
                    .unwrap_or(type_text);
                let type_id = helper.add_class(&resolved_type, None);
                helper.add_typeof_edge(var_id, type_id);
            }
        }
    }
}

fn handle_switch_pattern_declaration(
    node: Node,
    content: &[u8],
    ast_graph: &ASTGraph,
    scope_tree: &mut JavaScopeTree,
    helper: &mut GraphBuildHelper,
) {
    let mut patterns = Vec::new();
    collect_pattern_declarations(node, &mut patterns);
    for (name_node, type_node) in patterns {
        let name = extract_identifier(name_node, content);
        if name.is_empty() {
            continue;
        }
        let qualified_var = format!("{}@{}", name, name_node.start_byte());
        let span = Span::from_bytes(name_node.start_byte(), name_node.end_byte());
        let var_id = helper.add_variable(&qualified_var, Some(span));
        scope_tree.attach_node_id(&name, name_node.start_byte(), var_id);

        if let Some(type_node) = type_node {
            let type_text = extract_type_name(type_node, content);
            if !type_text.is_empty() {
                let resolved_type = ast_graph
                    .import_map
                    .get(&type_text)
                    .cloned()
                    .unwrap_or(type_text);
                let type_id = helper.add_class(&resolved_type, None);
                helper.add_typeof_edge(var_id, type_id);
            }
        }
    }
}

fn handle_compact_constructor_parameters(
    node: Node,
    content: &[u8],
    ast_graph: &ASTGraph,
    scope_tree: &mut JavaScopeTree,
    helper: &mut GraphBuildHelper,
) {
    use sqry_core::graph::unified::node::NodeKind;

    let Some(record_node) = node
        .parent()
        .and_then(|parent| find_record_declaration(parent))
    else {
        return;
    };

    let Some(record_name_node) = record_node.child_by_field_name("name") else {
        return;
    };
    let record_name = extract_identifier(record_name_node, content);
    if record_name.is_empty() {
        return;
    }

    let mut components = Vec::new();
    collect_record_components_nodes(record_node, &mut components);
    for component in components {
        let Some(name_node) = component.child_by_field_name("name") else {
            continue;
        };
        let Some(type_node) = component.child_by_field_name("type") else {
            continue;
        };
        let name = extract_identifier(name_node, content);
        if name.is_empty() {
            continue;
        }

        let type_text = extract_type_name(type_node, content);
        if type_text.is_empty() {
            continue;
        }
        let resolved_type = ast_graph
            .import_map
            .get(&type_text)
            .cloned()
            .unwrap_or(type_text);

        let qualified_param = format!("{record_name}.<init>::{name}");
        let span = Span::from_bytes(component.start_byte(), component.end_byte());
        let param_id = helper.add_node(&qualified_param, Some(span), NodeKind::Parameter);
        scope_tree.attach_node_id(&name, name_node.start_byte(), param_id);

        let type_id = helper.add_class(&resolved_type, None);
        helper.add_typeof_edge(param_id, type_id);
    }
}

fn collect_pattern_declarations<'a>(
    node: Node<'a>,
    output: &mut Vec<(Node<'a>, Option<Node<'a>>)>,
) {
    if node.kind() == "type_pattern" {
        let name_node = node.child_by_field_name("name");
        let type_node = node.child_by_field_name("type").or_else(|| {
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                if matches!(
                    child.kind(),
                    "type_identifier" | "scoped_type_identifier" | "generic_type"
                ) {
                    return Some(child);
                }
            }
            None
        });
        if let Some(name_node) = name_node {
            output.push((name_node, type_node));
        }
    }

    if node.kind() == "record_pattern_component" {
        let mut name_node = None;
        let mut type_node = None;
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if child.kind() == "identifier" {
                name_node = Some(child);
            } else if matches!(
                child.kind(),
                "type_identifier" | "scoped_type_identifier" | "generic_type"
            ) {
                type_node = Some(child);
            }
        }
        if let Some(name_node) = name_node {
            output.push((name_node, type_node));
        }
    }

    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        collect_pattern_declarations(child, output);
    }
}

fn find_record_declaration(node: Node) -> Option<Node> {
    if node.kind() == "record_declaration" {
        return Some(node);
    }
    node.parent().and_then(find_record_declaration)
}

fn collect_record_components_nodes<'a>(node: Node<'a>, output: &mut Vec<Node<'a>>) {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "record_component" {
            output.push(child);
        }
        collect_record_components_nodes(child, output);
    }
}

/// Process method invocation using `GraphBuildHelper`
fn process_method_call_unified(
    call_node: Node,
    content: &[u8],
    ast_graph: &ASTGraph,
    helper: &mut GraphBuildHelper,
) {
    let Some(caller_context) = ast_graph.find_enclosing(call_node.start_byte()) else {
        return;
    };
    let Ok(callee_name) = extract_method_invocation_name(call_node, content) else {
        return;
    };

    let callee_qualified =
        resolve_callee_qualified(&call_node, content, ast_graph, caller_context, &callee_name);
    let caller_method_id = ensure_caller_method(helper, caller_context);
    let target_method_id = helper.ensure_method(&callee_qualified, None, false, false);

    add_call_edge(helper, caller_method_id, target_method_id, call_node);
}

/// Process constructor call (new expression) using `GraphBuildHelper`
fn process_constructor_call_unified(
    new_node: Node,
    content: &[u8],
    ast_graph: &ASTGraph,
    helper: &mut GraphBuildHelper,
) {
    let Some(caller_context) = ast_graph.find_enclosing(new_node.start_byte()) else {
        return;
    };

    let Some(type_node) = new_node.child_by_field_name("type") else {
        return;
    };

    let class_name = extract_type_name(type_node, content);
    if class_name.is_empty() {
        return;
    }

    let qualified_class = qualify_constructor_class(&class_name, caller_context);
    let constructor_name = format!("{qualified_class}.<init>");

    let caller_method_id = ensure_caller_method(helper, caller_context);
    let target_method_id = helper.ensure_method(&constructor_name, None, false, false);
    add_call_edge(helper, caller_method_id, target_method_id, new_node);
}

fn count_call_arguments(call_node: Node<'_>) -> u8 {
    let Some(args_node) = call_node.child_by_field_name("arguments") else {
        return 255;
    };
    let count = args_node.named_child_count();
    if count <= 254 {
        u8::try_from(count).unwrap_or(u8::MAX)
    } else {
        u8::MAX
    }
}

/// Process import declaration using `GraphBuildHelper`
fn process_import_unified(import_node: Node, content: &[u8], helper: &mut GraphBuildHelper) {
    let has_asterisk = import_has_wildcard(import_node);
    let Some(mut imported_name) = extract_import_name(import_node, content) else {
        return;
    };
    if has_asterisk {
        imported_name = format!("{imported_name}.*");
    }

    let module_id = helper.add_module("<module>", None);
    let external_id = helper.add_import(
        &imported_name,
        Some(Span::from_bytes(
            import_node.start_byte(),
            import_node.end_byte(),
        )),
    );

    helper.add_import_edge(module_id, external_id);
}

fn ensure_caller_method(
    helper: &mut GraphBuildHelper,
    caller_context: &MethodContext,
) -> sqry_core::graph::unified::node::NodeId {
    helper.ensure_method(
        caller_context.qualified_name(),
        Some(Span::from_bytes(
            caller_context.span.0,
            caller_context.span.1,
        )),
        false,
        caller_context.is_static,
    )
}

fn resolve_callee_qualified(
    call_node: &Node,
    content: &[u8],
    ast_graph: &ASTGraph,
    caller_context: &MethodContext,
    callee_name: &str,
) -> String {
    if let Some(object_node) = call_node.child_by_field_name("object") {
        let object_text = extract_node_text(object_node, content);
        return resolve_member_call_target(&object_text, ast_graph, caller_context, callee_name);
    }

    build_member_symbol(
        caller_context.package_name.as_deref(),
        &caller_context.class_stack,
        callee_name,
    )
}

fn resolve_member_call_target(
    object_text: &str,
    ast_graph: &ASTGraph,
    caller_context: &MethodContext,
    callee_name: &str,
) -> String {
    if object_text.contains('.') {
        return format!("{object_text}.{callee_name}");
    }
    if object_text == "this" {
        return build_member_symbol(
            caller_context.package_name.as_deref(),
            &caller_context.class_stack,
            callee_name,
        );
    }

    // Try qualified field lookup (ClassName::fieldName)
    if let Some(class_name) = caller_context.class_stack.last() {
        let qualified_field = format!("{class_name}::{object_text}");
        if let Some((field_type, _is_final, _visibility, _is_static)) =
            ast_graph.field_types.get(&qualified_field)
        {
            return format!("{field_type}.{callee_name}");
        }
    }

    // Fallback: try unqualified field lookup (for backwards compatibility)
    if let Some((field_type, _is_final, _visibility, _is_static)) =
        ast_graph.field_types.get(object_text)
    {
        return format!("{field_type}.{callee_name}");
    }

    if let Some(type_fqn) = ast_graph.import_map.get(object_text) {
        return format!("{type_fqn}.{callee_name}");
    }

    format!("{object_text}.{callee_name}")
}

fn qualify_constructor_class(class_name: &str, caller_context: &MethodContext) -> String {
    if class_name.contains('.') {
        class_name.to_string()
    } else if let Some(pkg) = caller_context.package_name.as_deref() {
        format!("{pkg}.{class_name}")
    } else {
        class_name.to_string()
    }
}

fn add_call_edge(
    helper: &mut GraphBuildHelper,
    caller_method_id: sqry_core::graph::unified::node::NodeId,
    target_method_id: sqry_core::graph::unified::node::NodeId,
    call_node: Node,
) {
    let argument_count = count_call_arguments(call_node);
    let call_span = Span::from_bytes(call_node.start_byte(), call_node.end_byte());
    helper.add_call_edge_full_with_span(
        caller_method_id,
        target_method_id,
        argument_count,
        false,
        vec![call_span],
    );
}

fn import_has_wildcard(import_node: Node) -> bool {
    let mut cursor = import_node.walk();
    import_node
        .children(&mut cursor)
        .any(|child| child.kind() == "asterisk")
}

fn extract_import_name(import_node: Node, content: &[u8]) -> Option<String> {
    let mut cursor = import_node.walk();
    for child in import_node.children(&mut cursor) {
        if child.kind() == "scoped_identifier" || child.kind() == "identifier" {
            return Some(extract_full_identifier(child, content));
        }
    }
    None
}

// ================================
// Inheritance and Interface Implementation
// ================================

/// Process class inheritance (extends clause).
///
/// Handles patterns like:
/// - `class Child extends Parent`
/// - `class Dog extends Animal`
fn process_inheritance(
    class_node: Node,
    content: &[u8],
    package_name: Option<&str>,
    child_class_id: sqry_core::graph::unified::node::NodeId,
    helper: &mut GraphBuildHelper,
) {
    // In tree-sitter-java, the superclass is in a "superclass" field
    if let Some(superclass_node) = class_node.child_by_field_name("superclass") {
        // The superclass node typically wraps a type_identifier
        let parent_type_name = extract_type_from_superclass(superclass_node, content);
        if !parent_type_name.is_empty() {
            // Build qualified name for parent (may be in same package or imported)
            let parent_qualified = qualify_type_name(&parent_type_name, package_name);
            let parent_id = helper.add_class(&parent_qualified, None);
            helper.add_inherits_edge(child_class_id, parent_id);
        }
    }
}

/// Process implements clause for classes.
///
/// Handles patterns like:
/// - `class Foo implements IBar`
/// - `class Foo implements IBar, IBaz`
fn process_implements(
    class_node: Node,
    content: &[u8],
    package_name: Option<&str>,
    class_id: sqry_core::graph::unified::node::NodeId,
    helper: &mut GraphBuildHelper,
) {
    // In tree-sitter-java, the implements clause may be:
    // - Field named "interfaces" or "super_interfaces"
    // - A child node with kind "super_interfaces"

    // First try field-based access
    let interfaces_node = class_node
        .child_by_field_name("interfaces")
        .or_else(|| class_node.child_by_field_name("super_interfaces"));

    if let Some(node) = interfaces_node {
        extract_interface_types(node, content, package_name, class_id, helper);
        return;
    }

    // Walk children to find super_interfaces node by kind
    let mut cursor = class_node.walk();
    for child in class_node.children(&mut cursor) {
        // tree-sitter-java uses "super_interfaces" node kind for implements clause
        if child.kind() == "super_interfaces" {
            extract_interface_types(child, content, package_name, class_id, helper);
            return;
        }
    }
}

/// Process interface inheritance (extends clause for interfaces).
///
/// Handles patterns like:
/// - `interface IChild extends IParent`
/// - `interface IChild extends IParent, IOther`
///
/// tree-sitter-java structure:
/// ```text
/// interface_declaration
///   interface (keyword)
///   identifier "Stream"
///   extends_interfaces  <- not a field, but a child node by kind
///     extends (keyword)
///     type_list
///       type_identifier "Readable"
///       type_identifier "Closeable"
/// ```
fn process_interface_extends(
    interface_node: Node,
    content: &[u8],
    package_name: Option<&str>,
    interface_id: sqry_core::graph::unified::node::NodeId,
    helper: &mut GraphBuildHelper,
) {
    // Walk children to find extends_interfaces by node kind
    let mut cursor = interface_node.walk();
    for child in interface_node.children(&mut cursor) {
        if child.kind() == "extends_interfaces" {
            // Found the extends clause - extract parent interfaces using same logic as implements
            extract_parent_interfaces_for_inherits(
                child,
                content,
                package_name,
                interface_id,
                helper,
            );
            return;
        }
    }
}

/// Extract parent interfaces for Inherits edges (interface extends).
/// Reuses the same tree structure as `extract_interface_types` but creates Inherits edges.
fn extract_parent_interfaces_for_inherits(
    extends_node: Node,
    content: &[u8],
    package_name: Option<&str>,
    child_interface_id: sqry_core::graph::unified::node::NodeId,
    helper: &mut GraphBuildHelper,
) {
    let mut cursor = extends_node.walk();
    for child in extends_node.children(&mut cursor) {
        match child.kind() {
            "type_identifier" => {
                let type_name = extract_identifier(child, content);
                if !type_name.is_empty() {
                    let parent_qualified = qualify_type_name(&type_name, package_name);
                    let parent_id = helper.add_interface(&parent_qualified, None);
                    helper.add_inherits_edge(child_interface_id, parent_id);
                }
            }
            "type_list" => {
                let mut type_cursor = child.walk();
                for type_child in child.children(&mut type_cursor) {
                    if let Some(type_name) = extract_type_identifier(type_child, content)
                        && !type_name.is_empty()
                    {
                        let parent_qualified = qualify_type_name(&type_name, package_name);
                        let parent_id = helper.add_interface(&parent_qualified, None);
                        helper.add_inherits_edge(child_interface_id, parent_id);
                    }
                }
            }
            "generic_type" | "scoped_type_identifier" => {
                if let Some(type_name) = extract_type_identifier(child, content)
                    && !type_name.is_empty()
                {
                    let parent_qualified = qualify_type_name(&type_name, package_name);
                    let parent_id = helper.add_interface(&parent_qualified, None);
                    helper.add_inherits_edge(child_interface_id, parent_id);
                }
            }
            _ => {}
        }
    }
}

/// Extract type name from superclass node.
fn extract_type_from_superclass(superclass_node: Node, content: &[u8]) -> String {
    // The superclass node may directly be a type_identifier or contain one
    if superclass_node.kind() == "type_identifier" {
        return extract_identifier(superclass_node, content);
    }

    // Look for type_identifier among children
    let mut cursor = superclass_node.walk();
    for child in superclass_node.children(&mut cursor) {
        if let Some(name) = extract_type_identifier(child, content) {
            return name;
        }
    }

    // Fallback: try to extract the entire text
    extract_identifier(superclass_node, content)
}

/// Extract all interface types from a `super_interfaces` or `extends_interfaces` node.
///
/// tree-sitter-java structure:
/// ```text
/// super_interfaces
///   implements (keyword)
///   type_list
///     type_identifier "Runnable"
///     type_identifier "Serializable" (if multiple)
/// ```
fn extract_interface_types(
    interfaces_node: Node,
    content: &[u8],
    package_name: Option<&str>,
    implementor_id: sqry_core::graph::unified::node::NodeId,
    helper: &mut GraphBuildHelper,
) {
    // Walk all children to find type_list or direct type identifiers
    let mut cursor = interfaces_node.walk();
    for child in interfaces_node.children(&mut cursor) {
        match child.kind() {
            // Direct type identifiers at this level
            "type_identifier" => {
                let type_name = extract_identifier(child, content);
                if !type_name.is_empty() {
                    let interface_qualified = qualify_type_name(&type_name, package_name);
                    let interface_id = helper.add_interface(&interface_qualified, None);
                    helper.add_implements_edge(implementor_id, interface_id);
                }
            }
            // type_list contains the actual interfaces
            "type_list" => {
                let mut type_cursor = child.walk();
                for type_child in child.children(&mut type_cursor) {
                    if let Some(type_name) = extract_type_identifier(type_child, content)
                        && !type_name.is_empty()
                    {
                        let interface_qualified = qualify_type_name(&type_name, package_name);
                        let interface_id = helper.add_interface(&interface_qualified, None);
                        helper.add_implements_edge(implementor_id, interface_id);
                    }
                }
            }
            // Generic type at this level
            "generic_type" | "scoped_type_identifier" => {
                if let Some(type_name) = extract_type_identifier(child, content)
                    && !type_name.is_empty()
                {
                    let interface_qualified = qualify_type_name(&type_name, package_name);
                    let interface_id = helper.add_interface(&interface_qualified, None);
                    helper.add_implements_edge(implementor_id, interface_id);
                }
            }
            _ => {}
        }
    }
}

/// Extract type identifier from a node (handles `type_identifier` and `generic_type`).
fn extract_type_identifier(node: Node, content: &[u8]) -> Option<String> {
    match node.kind() {
        "type_identifier" => Some(extract_identifier(node, content)),
        "generic_type" => {
            // For generic types like `List<String>`, extract base type
            if let Some(name_node) = node.child_by_field_name("name") {
                Some(extract_identifier(name_node, content))
            } else {
                // Fallback: get first child if it's a type_identifier
                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    if child.kind() == "type_identifier" {
                        return Some(extract_identifier(child, content));
                    }
                }
                None
            }
        }
        "scoped_type_identifier" => {
            // Fully qualified type like `java.util.List`
            Some(extract_full_identifier(node, content))
        }
        _ => None,
    }
}

/// Qualify a type name with package prefix if not already qualified.
fn qualify_type_name(type_name: &str, package_name: Option<&str>) -> String {
    // If already qualified (contains '.'), keep as-is
    if type_name.contains('.') {
        return type_name.to_string();
    }

    // Otherwise, prefix with package if available
    if let Some(pkg) = package_name {
        format!("{pkg}.{type_name}")
    } else {
        type_name.to_string()
    }
}

// ================================
// Field Type Extraction
// ================================

/// Extract field declarations and imports to build type resolution maps.
/// Returns (`field_types`, `import_map`) where:
/// - `field_types` maps field names to (`type_fqn`, `is_final`) tuples
/// - `import_map` maps simple type names to FQNs (e.g., "`UserService`" -> "com.example.service.UserService")
#[allow(clippy::type_complexity)]
fn extract_field_and_import_types(
    node: Node,
    content: &[u8],
) -> (
    HashMap<String, (String, bool, Option<sqry_core::schema::Visibility>, bool)>,
    HashMap<String, String>,
) {
    // First, build import map (simple name -> FQN)
    let import_map = extract_import_map(node, content);

    let mut field_types = HashMap::new();
    let mut class_stack = Vec::new();
    extract_field_types_recursive(
        node,
        content,
        &import_map,
        &mut field_types,
        &mut class_stack,
    );

    (field_types, import_map)
}

/// Build a map from simple type names to their FQNs based on import declarations
fn extract_import_map(node: Node, content: &[u8]) -> HashMap<String, String> {
    let mut import_map = HashMap::new();
    collect_import_map_recursive(node, content, &mut import_map);
    import_map
}

fn collect_import_map_recursive(
    node: Node,
    content: &[u8],
    import_map: &mut HashMap<String, String>,
) {
    if node.kind() == "import_declaration" {
        // import com.example.service.UserService;
        // Tree structure: (import_declaration (scoped_identifier ...))
        // Try to get the full import path
        let full_path = node.utf8_text(content).unwrap_or("");

        // Parse out the class name from the import statement
        // "import com.example.service.UserService;" -> "com.example.service.UserService"
        if let Some(path_start) = full_path.find("import ") {
            let after_import = &full_path[path_start + 7..].trim();
            if let Some(path_end) = after_import.find(';') {
                let import_path = &after_import[..path_end].trim();

                // Get the simple name (last part)
                if let Some(simple_name) = import_path.rsplit('.').next() {
                    import_map.insert(simple_name.to_string(), (*import_path).to_string());
                }
            }
        }
    }

    // Recurse into children
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        collect_import_map_recursive(child, content, import_map);
    }
}

fn extract_field_types_recursive(
    node: Node,
    content: &[u8],
    import_map: &HashMap<String, String>,
    field_types: &mut HashMap<String, (String, bool, Option<sqry_core::schema::Visibility>, bool)>,
    class_stack: &mut Vec<String>,
) {
    // Handle class/interface/enum declarations - push onto stack
    if matches!(
        node.kind(),
        "class_declaration" | "interface_declaration" | "enum_declaration"
    ) && let Some(name_node) = node.child_by_field_name("name")
    {
        let class_name = extract_identifier(name_node, content);
        class_stack.push(class_name);

        // Recurse into body
        if let Some(body_node) = node.child_by_field_name("body") {
            let mut cursor = body_node.walk();
            for child in body_node.children(&mut cursor) {
                extract_field_types_recursive(child, content, import_map, field_types, class_stack);
            }
        }

        // Pop class from stack
        class_stack.pop();
        return; // Already recursed into body
    }

    // field_declaration node structure:
    // (field_declaration
    //   modifiers?: (modifiers) - may contain "final", "static", "public", etc.
    //   type: (type_identifier) @type
    //   declarator: (variable_declarator
    //     name: (identifier) @name))
    if node.kind() == "field_declaration" {
        // Check for modifiers using the helper function
        let is_final = has_modifier(node, "final", content);
        let is_static = has_modifier(node, "static", content);

        // Extract visibility (Java has: public, private, protected, package-private)
        // Map to sqry Visibility: public -> Public, others -> Private
        let visibility = if has_modifier(node, "public", content) {
            Some(sqry_core::schema::Visibility::Public)
        } else {
            // private, protected, or package-private (default) all map to Private
            Some(sqry_core::schema::Visibility::Private)
        };

        // Extract type
        if let Some(type_node) = node.child_by_field_name("type") {
            let type_text = extract_type_name_internal(type_node, content);
            if !type_text.is_empty() {
                // Resolve simple type name to FQN using imports
                let resolved_type = import_map
                    .get(&type_text)
                    .cloned()
                    .unwrap_or(type_text.clone());

                // Extract all declarators (there can be multiple: "String a, b;")
                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    if child.kind() == "variable_declarator"
                        && let Some(name_node) = child.child_by_field_name("name")
                    {
                        let field_name = extract_identifier(name_node, content);

                        // Create qualified field name using full class path (OuterClass::InnerClass::fieldName)
                        // This prevents collisions for fields with same name in different nested classes
                        let qualified_field = if class_stack.is_empty() {
                            field_name
                        } else {
                            let class_path = class_stack.join("::");
                            format!("{class_path}::{field_name}")
                        };

                        field_types.insert(
                            qualified_field,
                            (resolved_type.clone(), is_final, visibility, is_static),
                        );
                    }
                }
            }
        }
    }

    // Recurse into children (for non-class nodes)
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        extract_field_types_recursive(child, content, import_map, field_types, class_stack);
    }
}

/// Helper to extract type names for field extraction.
fn extract_type_name_internal(type_node: Node, content: &[u8]) -> String {
    match type_node.kind() {
        "generic_type" => {
            // Extract base type (e.g., "List" from "List<String>")
            if let Some(name_node) = type_node.child_by_field_name("name") {
                extract_identifier(name_node, content)
            } else {
                extract_identifier(type_node, content)
            }
        }
        "scoped_type_identifier" => {
            // e.g., "java.util.List"
            extract_full_identifier(type_node, content)
        }
        _ => extract_identifier(type_node, content),
    }
}

// ================================
// AST Extraction Helpers
// ================================

fn extract_identifier(node: Node, content: &[u8]) -> String {
    node.utf8_text(content).unwrap_or("").to_string()
}

fn extract_node_text(node: Node, content: &[u8]) -> String {
    node.utf8_text(content).unwrap_or("").to_string()
}

fn extract_full_identifier(node: Node, content: &[u8]) -> String {
    node.utf8_text(content).unwrap_or("").to_string()
}

fn first_child_of_kind<'a>(node: Node<'a>, kind: &str) -> Option<Node<'a>> {
    let mut cursor = node.walk();
    node.children(&mut cursor)
        .find(|&child| child.kind() == kind)
}

fn extract_method_invocation_name(call_node: Node, content: &[u8]) -> GraphResult<String> {
    // method_invocation has a "name" field
    if let Some(name_node) = call_node.child_by_field_name("name") {
        Ok(extract_identifier(name_node, content))
    } else {
        // Fallback: try to find identifier
        let mut cursor = call_node.walk();
        for child in call_node.children(&mut cursor) {
            if child.kind() == "identifier" {
                return Ok(extract_identifier(child, content));
            }
        }

        Err(GraphBuilderError::ParseError {
            span: Span::from_bytes(call_node.start_byte(), call_node.end_byte()),
            reason: "Method invocation missing name".into(),
        })
    }
}

fn extract_type_name(type_node: Node, content: &[u8]) -> String {
    // Type can be simple identifier or generic type
    match type_node.kind() {
        "generic_type" => {
            // Extract base type (e.g., "List" from "List<String>")
            if let Some(name_node) = type_node.child_by_field_name("name") {
                extract_identifier(name_node, content)
            } else {
                extract_identifier(type_node, content)
            }
        }
        "scoped_type_identifier" => {
            // e.g., "java.util.List"
            extract_full_identifier(type_node, content)
        }
        _ => extract_identifier(type_node, content),
    }
}

/// Extract the full return type including generics (e.g., `Optional<User>`, `List<String>`).
/// Unlike `extract_type_name` which extracts just the base type, this preserves the full type signature.
fn extract_full_return_type(type_node: Node, content: &[u8]) -> String {
    // For the `returns:` predicate, we need the full type representation
    // including generic parameters like Optional<User>, List<Map<String, Integer>>
    type_node.utf8_text(content).unwrap_or("").to_string()
}

fn has_modifier(node: Node, modifier: &str, content: &[u8]) -> bool {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "modifiers" {
            let mut mod_cursor = child.walk();
            for modifier_child in child.children(&mut mod_cursor) {
                if extract_identifier(modifier_child, content) == modifier {
                    return true;
                }
            }
        }
    }
    false
}

/// Extract visibility modifier from a method or constructor node.
/// Returns "public", "private", "protected", or "package-private" (no explicit modifier).
#[allow(clippy::unnecessary_wraps)]
fn extract_visibility(node: Node, content: &[u8]) -> Option<String> {
    if has_modifier(node, "public", content) {
        Some("public".to_string())
    } else if has_modifier(node, "private", content) {
        Some("private".to_string())
    } else if has_modifier(node, "protected", content) {
        Some("protected".to_string())
    } else {
        // No explicit modifier means package-private in Java
        Some("package-private".to_string())
    }
}

// ================================
// Export Detection (public visibility)
// ================================

/// Check if a node has the `public` visibility modifier.
fn is_public(node: Node, content: &[u8]) -> bool {
    has_modifier(node, "public", content)
}

/// Check if a node has the `private` visibility modifier.
fn is_private(node: Node, content: &[u8]) -> bool {
    has_modifier(node, "private", content)
}

/// Create an export edge from the file module to the exported node.
fn export_from_file_module(
    helper: &mut GraphBuildHelper,
    exported: sqry_core::graph::unified::node::NodeId,
) {
    let module_id = helper.add_module(FILE_MODULE_NAME, None);
    helper.add_export_edge(module_id, exported);
}

/// Process public methods, constructors, and fields within a class body for export edges.
///
/// For interfaces, methods are implicitly public UNLESS explicitly marked private (Java 9+).
/// For classes, only explicitly public members are exported.
fn process_class_member_exports(
    body_node: Node,
    content: &[u8],
    class_qualified_name: &str,
    helper: &mut GraphBuildHelper,
    is_interface: bool,
) {
    for i in 0..body_node.child_count() {
        if let Some(child) = body_node.child(i as u32) {
            match child.kind() {
                "method_declaration" => {
                    // Interface methods are implicitly public UNLESS explicitly private (Java 9+)
                    // Class methods need explicit public modifier
                    let should_export = if is_interface {
                        // Export interface method if NOT explicitly private
                        !is_private(child, content)
                    } else {
                        // Export class method only if explicitly public
                        is_public(child, content)
                    };

                    if should_export && let Some(name_node) = child.child_by_field_name("name") {
                        let method_name = extract_identifier(name_node, content);
                        let qualified_name = format!("{class_qualified_name}.{method_name}");
                        let span = Span::from_bytes(child.start_byte(), child.end_byte());
                        let is_static = has_modifier(child, "static", content);
                        let method_id =
                            helper.add_method(&qualified_name, Some(span), false, is_static);
                        export_from_file_module(helper, method_id);
                    }
                }
                "constructor_declaration" => {
                    if is_public(child, content) {
                        let qualified_name = format!("{class_qualified_name}.<init>");
                        let span = Span::from_bytes(child.start_byte(), child.end_byte());
                        let method_id =
                            helper.add_method(&qualified_name, Some(span), false, false);
                        export_from_file_module(helper, method_id);
                    }
                }
                "field_declaration" => {
                    if is_public(child, content) {
                        // Extract all field names from the declaration
                        let mut cursor = child.walk();
                        for field_child in child.children(&mut cursor) {
                            if field_child.kind() == "variable_declarator"
                                && let Some(name_node) = field_child.child_by_field_name("name")
                            {
                                let field_name = extract_identifier(name_node, content);
                                let qualified_name = format!("{class_qualified_name}.{field_name}");
                                let span = Span::from_bytes(
                                    field_child.start_byte(),
                                    field_child.end_byte(),
                                );

                                // Use constant for final fields, variable otherwise
                                let is_final = has_modifier(child, "final", content);
                                let field_id = if is_final {
                                    helper.add_constant(&qualified_name, Some(span))
                                } else {
                                    helper.add_variable(&qualified_name, Some(span))
                                };
                                export_from_file_module(helper, field_id);
                            }
                        }
                    }
                }
                "constant_declaration" => {
                    // Constants in interfaces are always public
                    let mut cursor = child.walk();
                    for const_child in child.children(&mut cursor) {
                        if const_child.kind() == "variable_declarator"
                            && let Some(name_node) = const_child.child_by_field_name("name")
                        {
                            let const_name = extract_identifier(name_node, content);
                            let qualified_name = format!("{class_qualified_name}.{const_name}");
                            let span =
                                Span::from_bytes(const_child.start_byte(), const_child.end_byte());
                            let const_id = helper.add_constant(&qualified_name, Some(span));
                            export_from_file_module(helper, const_id);
                        }
                    }
                }
                "enum_constant" => {
                    // Enum constants are always public
                    if let Some(name_node) = child.child_by_field_name("name") {
                        let const_name = extract_identifier(name_node, content);
                        let qualified_name = format!("{class_qualified_name}.{const_name}");
                        let span = Span::from_bytes(child.start_byte(), child.end_byte());
                        let const_id = helper.add_constant(&qualified_name, Some(span));
                        export_from_file_module(helper, const_id);
                    }
                }
                _ => {}
            }
        }
    }
}

// ================================
// FFI Detection (JNI, JNA, Panama)
// ================================

/// Detect FFI-related imports in the file.
/// Returns (`has_jna_import`, `has_panama_import`).
fn detect_ffi_imports(node: Node, content: &[u8]) -> (bool, bool) {
    let mut has_jna = false;
    let mut has_panama = false;

    detect_ffi_imports_recursive(node, content, &mut has_jna, &mut has_panama);

    (has_jna, has_panama)
}

fn detect_ffi_imports_recursive(
    node: Node,
    content: &[u8],
    has_jna: &mut bool,
    has_panama: &mut bool,
) {
    if node.kind() == "import_declaration" {
        let import_text = node.utf8_text(content).unwrap_or("");

        // JNA: com.sun.jna.* or net.java.dev.jna.*
        if import_text.contains("com.sun.jna") || import_text.contains("net.java.dev.jna") {
            *has_jna = true;
        }

        // Panama Foreign Function API: java.lang.foreign.*
        if import_text.contains("java.lang.foreign") {
            *has_panama = true;
        }
    }

    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        detect_ffi_imports_recursive(child, content, has_jna, has_panama);
    }
}

/// Find interfaces that extend JNA Library.
/// These interfaces define native function signatures.
fn find_jna_library_interfaces(node: Node, content: &[u8]) -> Vec<String> {
    let mut jna_interfaces = Vec::new();
    find_jna_library_interfaces_recursive(node, content, &mut jna_interfaces);
    jna_interfaces
}

fn find_jna_library_interfaces_recursive(
    node: Node,
    content: &[u8],
    jna_interfaces: &mut Vec<String>,
) {
    if node.kind() == "interface_declaration" {
        // Check if this interface extends Library
        if let Some(name_node) = node.child_by_field_name("name") {
            let interface_name = extract_identifier(name_node, content);

            // Look for extends clause
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                if child.kind() == "extends_interfaces" {
                    let extends_text = child.utf8_text(content).unwrap_or("");
                    // Check if extends Library or com.sun.jna.Library
                    if extends_text.contains("Library") {
                        jna_interfaces.push(interface_name.clone());
                    }
                }
            }
        }
    }

    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        find_jna_library_interfaces_recursive(child, content, jna_interfaces);
    }
}

/// Check if a method call is an FFI call and build the appropriate edge.
/// Returns true if an FFI edge was created.
fn build_ffi_call_edge(
    call_node: Node,
    content: &[u8],
    caller_context: &MethodContext,
    ast_graph: &ASTGraph,
    helper: &mut GraphBuildHelper,
) -> bool {
    // Extract method name
    let Ok(method_name) = extract_method_invocation_name(call_node, content) else {
        return false;
    };

    // Check for JNA Native.load() call
    if ast_graph.has_jna_import && is_jna_native_load(call_node, content, &method_name) {
        let library_name = extract_jna_library_name(call_node, content);
        build_jna_native_load_edge(caller_context, &library_name, call_node, helper);
        return true;
    }

    // Check for JNA interface method call (calling methods on loaded library)
    if ast_graph.has_jna_import
        && let Some(object_node) = call_node.child_by_field_name("object")
    {
        let object_text = extract_node_text(object_node, content);

        // Try qualified field lookup first (ClassName::fieldName)
        let field_type = if let Some(class_name) = caller_context.class_stack.last() {
            let qualified_field = format!("{class_name}::{object_text}");
            ast_graph
                .field_types
                .get(&qualified_field)
                .or_else(|| ast_graph.field_types.get(&object_text))
        } else {
            ast_graph.field_types.get(&object_text)
        };

        // Check if the object type is a JNA Library interface
        if let Some((type_name, _is_final, _visibility, _is_static)) = field_type {
            let simple_type = simple_type_name(type_name);
            if ast_graph.jna_library_interfaces.contains(&simple_type) {
                build_jna_method_call_edge(
                    caller_context,
                    &simple_type,
                    &method_name,
                    call_node,
                    helper,
                );
                return true;
            }
        }
    }

    // Check for Panama Foreign Function API calls
    if ast_graph.has_panama_import {
        if let Some(object_node) = call_node.child_by_field_name("object") {
            let object_text = extract_node_text(object_node, content);

            // Linker.nativeLinker() and downcallHandle()
            if object_text == "Linker" && method_name == "nativeLinker" {
                build_panama_linker_edge(caller_context, call_node, helper);
                return true;
            }

            // SymbolLookup.libraryLookup()
            if object_text == "SymbolLookup" && method_name == "libraryLookup" {
                let library_name = extract_first_string_arg(call_node, content);
                build_panama_library_lookup_edge(caller_context, &library_name, call_node, helper);
                return true;
            }

            // MethodHandle.invokeExact() on a downcall handle
            if method_name == "invokeExact" || method_name == "invoke" {
                // Check if this might be a foreign function call
                // This is a heuristic - we mark it as FFI if in Panama context
                if is_potential_panama_invoke(call_node, content) {
                    build_panama_invoke_edge(caller_context, &method_name, call_node, helper);
                    return true;
                }
            }
        }

        // Direct Linker.nativeLinker() static call
        if method_name == "nativeLinker" {
            let full_text = call_node.utf8_text(content).unwrap_or("");
            if full_text.contains("Linker") {
                build_panama_linker_edge(caller_context, call_node, helper);
                return true;
            }
        }
    }

    false
}

/// Check if this is a JNA `Native.load()` or `Native.loadLibrary()` call.
fn is_jna_native_load(call_node: Node, content: &[u8], method_name: &str) -> bool {
    if method_name != "load" && method_name != "loadLibrary" {
        return false;
    }

    if let Some(object_node) = call_node.child_by_field_name("object") {
        let object_text = extract_node_text(object_node, content);
        return object_text == "Native" || object_text == "com.sun.jna.Native";
    }

    false
}

/// Extract the library name from JNA `Native.load()` call.
/// Native.load("c", CLibrary.class) -> "c"
fn extract_jna_library_name(call_node: Node, content: &[u8]) -> String {
    if let Some(args_node) = call_node.child_by_field_name("arguments") {
        let mut cursor = args_node.walk();
        for child in args_node.children(&mut cursor) {
            if child.kind() == "string_literal" {
                let text = child.utf8_text(content).unwrap_or("\"unknown\"");
                // Remove quotes
                return text.trim_matches('"').to_string();
            }
        }
    }
    "unknown".to_string()
}

/// Extract the first string argument from a method call.
fn extract_first_string_arg(call_node: Node, content: &[u8]) -> String {
    if let Some(args_node) = call_node.child_by_field_name("arguments") {
        let mut cursor = args_node.walk();
        for child in args_node.children(&mut cursor) {
            if child.kind() == "string_literal" {
                let text = child.utf8_text(content).unwrap_or("\"unknown\"");
                return text.trim_matches('"').to_string();
            }
        }
    }
    "unknown".to_string()
}

/// Check if this is potentially a Panama foreign function invoke.
fn is_potential_panama_invoke(call_node: Node, content: &[u8]) -> bool {
    // Check if the call is on a MethodHandle that might be a downcall
    if let Some(object_node) = call_node.child_by_field_name("object") {
        let object_text = extract_node_text(object_node, content);
        // Heuristics: variable names often contain "handle", "downcall", or "mh"
        let lower = object_text.to_lowercase();
        return lower.contains("handle")
            || lower.contains("downcall")
            || lower.contains("mh")
            || lower.contains("foreign");
    }
    false
}

/// Get simple type name from potentially qualified name.
fn simple_type_name(type_name: &str) -> String {
    type_name
        .rsplit('.')
        .next()
        .unwrap_or(type_name)
        .to_string()
}

/// Build FFI edge for JNA `Native.load()` call.
fn build_jna_native_load_edge(
    caller_context: &MethodContext,
    library_name: &str,
    call_node: Node,
    helper: &mut GraphBuildHelper,
) {
    let caller_id = helper.ensure_method(
        caller_context.qualified_name(),
        Some(Span::from_bytes(
            caller_context.span.0,
            caller_context.span.1,
        )),
        false,
        caller_context.is_static,
    );

    let target_name = format!("native::{library_name}");
    let target_id = helper.add_function(
        &target_name,
        Some(Span::from_bytes(
            call_node.start_byte(),
            call_node.end_byte(),
        )),
        false,
        false,
    );

    helper.add_ffi_edge(caller_id, target_id, FfiConvention::C);
}

/// Build FFI edge for JNA interface method call.
fn build_jna_method_call_edge(
    caller_context: &MethodContext,
    interface_name: &str,
    method_name: &str,
    call_node: Node,
    helper: &mut GraphBuildHelper,
) {
    let caller_id = helper.ensure_method(
        caller_context.qualified_name(),
        Some(Span::from_bytes(
            caller_context.span.0,
            caller_context.span.1,
        )),
        false,
        caller_context.is_static,
    );

    let target_name = format!("native::{interface_name}::{method_name}");
    let target_id = helper.add_function(
        &target_name,
        Some(Span::from_bytes(
            call_node.start_byte(),
            call_node.end_byte(),
        )),
        false,
        false,
    );

    helper.add_ffi_edge(caller_id, target_id, FfiConvention::C);
}

/// Build FFI edge for Panama `Linker.nativeLinker()` call.
fn build_panama_linker_edge(
    caller_context: &MethodContext,
    call_node: Node,
    helper: &mut GraphBuildHelper,
) {
    let caller_id = helper.ensure_method(
        caller_context.qualified_name(),
        Some(Span::from_bytes(
            caller_context.span.0,
            caller_context.span.1,
        )),
        false,
        caller_context.is_static,
    );

    let target_name = "native::panama::nativeLinker";
    let target_id = helper.add_function(
        target_name,
        Some(Span::from_bytes(
            call_node.start_byte(),
            call_node.end_byte(),
        )),
        false,
        false,
    );

    helper.add_ffi_edge(caller_id, target_id, FfiConvention::C);
}

/// Build FFI edge for Panama `SymbolLookup.libraryLookup()` call.
fn build_panama_library_lookup_edge(
    caller_context: &MethodContext,
    library_name: &str,
    call_node: Node,
    helper: &mut GraphBuildHelper,
) {
    let caller_id = helper.ensure_method(
        caller_context.qualified_name(),
        Some(Span::from_bytes(
            caller_context.span.0,
            caller_context.span.1,
        )),
        false,
        caller_context.is_static,
    );

    let target_name = format!("native::panama::{library_name}");
    let target_id = helper.add_function(
        &target_name,
        Some(Span::from_bytes(
            call_node.start_byte(),
            call_node.end_byte(),
        )),
        false,
        false,
    );

    helper.add_ffi_edge(caller_id, target_id, FfiConvention::C);
}

/// Build FFI edge for Panama `MethodHandle` invoke.
fn build_panama_invoke_edge(
    caller_context: &MethodContext,
    method_name: &str,
    call_node: Node,
    helper: &mut GraphBuildHelper,
) {
    let caller_id = helper.ensure_method(
        caller_context.qualified_name(),
        Some(Span::from_bytes(
            caller_context.span.0,
            caller_context.span.1,
        )),
        false,
        caller_context.is_static,
    );

    let target_name = format!("native::panama::{method_name}");
    let target_id = helper.add_function(
        &target_name,
        Some(Span::from_bytes(
            call_node.start_byte(),
            call_node.end_byte(),
        )),
        false,
        false,
    );

    helper.add_ffi_edge(caller_id, target_id, FfiConvention::C);
}

/// Build FFI edge for JNI native method declaration.
/// This is called when we encounter a native method declaration.
fn build_jni_native_method_edge(method_context: &MethodContext, helper: &mut GraphBuildHelper) {
    // The method itself is the caller (conceptually, calling into native code)
    let method_id = helper.ensure_method(
        method_context.qualified_name(),
        Some(Span::from_bytes(
            method_context.span.0,
            method_context.span.1,
        )),
        false,
        method_context.is_static,
    );

    // Create a synthetic target representing the native implementation
    // Convention: Java_<package>_<class>_<method>
    let native_target = format!("native::jni::{}", method_context.qualified_name());
    let target_id = helper.add_function(&native_target, None, false, false);

    helper.add_ffi_edge(method_id, target_id, FfiConvention::C);
}

// ================================
// Spring MVC Route Endpoint Detection
// ================================

/// Extract Spring MVC route information from a `method_declaration` node.
///
/// Detects annotations like `@GetMapping("/api/users")`, `@PostMapping("/api/items")`,
/// `@RequestMapping(path="/api/users", method=RequestMethod.GET)`, etc.
///
/// # Returns
///
/// `Some((http_method, path))` if a Spring route annotation is found, `None` otherwise.
/// For example: `Some(("GET", "/api/users"))`.
fn extract_spring_route_info(method_node: Node, content: &[u8]) -> Option<(String, String)> {
    // Navigate to the modifiers child node (contains annotations)
    let mut cursor = method_node.walk();
    let modifiers_node = method_node
        .children(&mut cursor)
        .find(|child| child.kind() == "modifiers")?;

    // Iterate through children of modifiers looking for annotation nodes
    let mut mod_cursor = modifiers_node.walk();
    for annotation_node in modifiers_node.children(&mut mod_cursor) {
        if annotation_node.kind() != "annotation" {
            continue;
        }

        // Extract the annotation name (identifier or scoped_identifier)
        let Some(annotation_name) = extract_annotation_name(annotation_node, content) else {
            continue;
        };

        // Map annotation name to HTTP method
        let http_method: String = match annotation_name.as_str() {
            "GetMapping" => "GET".to_string(),
            "PostMapping" => "POST".to_string(),
            "PutMapping" => "PUT".to_string(),
            "DeleteMapping" => "DELETE".to_string(),
            "PatchMapping" => "PATCH".to_string(),
            "RequestMapping" => {
                // For @RequestMapping, extract method from arguments or default to GET
                extract_request_mapping_method(annotation_node, content)
                    .unwrap_or_else(|| "GET".to_string())
            }
            _ => continue,
        };

        // Extract the path from the annotation arguments
        let Some(path) = extract_annotation_path(annotation_node, content) else {
            continue;
        };

        return Some((http_method, path));
    }

    None
}

/// Extract the simple name from an annotation node.
///
/// Handles both `@GetMapping` (identifier) and `@org.springframework...GetMapping`
/// (`scoped_identifier`) by returning just the final identifier segment.
fn extract_annotation_name(annotation_node: Node, content: &[u8]) -> Option<String> {
    let mut cursor = annotation_node.walk();
    for child in annotation_node.children(&mut cursor) {
        match child.kind() {
            "identifier" => {
                return Some(extract_identifier(child, content));
            }
            "scoped_identifier" => {
                // For scoped identifiers like org.springframework.web.bind.annotation.GetMapping,
                // extract just the last segment (the actual annotation name)
                let full_text = extract_identifier(child, content);
                return full_text.rsplit('.').next().map(String::from);
            }
            _ => {}
        }
    }
    None
}

/// Extract the path string from a Spring annotation's argument list.
///
/// Handles these patterns:
/// - `@GetMapping("/api/users")` -> `/api/users`
/// - `@RequestMapping(path = "/api/users")` -> `/api/users`
/// - `@RequestMapping(value = "/api/users")` -> `/api/users`
fn extract_annotation_path(annotation_node: Node, content: &[u8]) -> Option<String> {
    // Find the annotation_argument_list child
    let mut cursor = annotation_node.walk();
    let args_node = annotation_node
        .children(&mut cursor)
        .find(|child| child.kind() == "annotation_argument_list")?;

    // Iterate through the argument list children
    let mut args_cursor = args_node.walk();
    for arg_child in args_node.children(&mut args_cursor) {
        match arg_child.kind() {
            // Direct string literal: @GetMapping("/api/users")
            "string_literal" => {
                return extract_string_content(arg_child, content);
            }
            // Named argument: @RequestMapping(path = "/api/users") or value = "/api/users"
            "element_value_pair" => {
                if let Some(path) = extract_path_from_element_value_pair(arg_child, content) {
                    return Some(path);
                }
            }
            _ => {}
        }
    }

    None
}

/// Extract the HTTP method from a `@RequestMapping` annotation's `method` argument.
///
/// Handles patterns like:
/// - `@RequestMapping(method = RequestMethod.POST)` -> `Some("POST")`
/// - `@RequestMapping(method = RequestMethod.GET)` -> `Some("GET")`
///
/// Returns `None` if no method argument is found (caller defaults to GET).
fn extract_request_mapping_method(annotation_node: Node, content: &[u8]) -> Option<String> {
    // Find the annotation_argument_list child
    let mut cursor = annotation_node.walk();
    let args_node = annotation_node
        .children(&mut cursor)
        .find(|child| child.kind() == "annotation_argument_list")?;

    // Look for element_value_pair with key "method"
    let mut args_cursor = args_node.walk();
    for arg_child in args_node.children(&mut args_cursor) {
        if arg_child.kind() != "element_value_pair" {
            continue;
        }

        // Check if the key is "method"
        let Some(key_node) = arg_child.child_by_field_name("key") else {
            continue;
        };
        let key_text = extract_identifier(key_node, content);
        if key_text != "method" {
            continue;
        }

        // Extract the value — expect something like RequestMethod.GET
        let Some(value_node) = arg_child.child_by_field_name("value") else {
            continue;
        };
        let value_text = extract_identifier(value_node, content);

        // Handle RequestMethod.GET, RequestMethod.POST, etc.
        if let Some(method) = value_text.rsplit('.').next() {
            let method_upper = method.to_uppercase();
            if matches!(
                method_upper.as_str(),
                "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "HEAD" | "OPTIONS"
            ) {
                return Some(method_upper);
            }
        }
    }

    None
}

/// Extract a path string from an `element_value_pair` node.
///
/// Matches `path = "/api/users"` or `value = "/api/users"` patterns.
fn extract_path_from_element_value_pair(pair_node: Node, content: &[u8]) -> Option<String> {
    let key_node = pair_node.child_by_field_name("key")?;
    let key_text = extract_identifier(key_node, content);

    // Only extract from "path" or "value" keys
    if key_text != "path" && key_text != "value" {
        return None;
    }

    let value_node = pair_node.child_by_field_name("value")?;
    if value_node.kind() == "string_literal" {
        return extract_string_content(value_node, content);
    }

    None
}

/// Extract the class-level `@RequestMapping` path prefix from the enclosing class.
///
/// Walks up the AST from a `method_declaration` to find the enclosing `class_declaration`,
/// then checks for a `@RequestMapping` annotation with a path value.
///
/// # Example
///
/// ```java
/// @RequestMapping("/api")
/// public class UserController {
///     @GetMapping("/users")
///     public List<User> getUsers() { ... }
/// }
/// ```
///
/// For the `getUsers` method node, returns `Some("/api")`.
fn extract_class_request_mapping_path(method_node: Node, content: &[u8]) -> Option<String> {
    // Walk up to find the enclosing class_declaration
    let mut current = method_node.parent()?;
    loop {
        if current.kind() == "class_declaration" {
            break;
        }
        current = current.parent()?;
    }

    // Look for modifiers → @RequestMapping annotation on the class
    let mut cursor = current.walk();
    let modifiers = current
        .children(&mut cursor)
        .find(|child| child.kind() == "modifiers")?;

    let mut mod_cursor = modifiers.walk();
    for annotation in modifiers.children(&mut mod_cursor) {
        if annotation.kind() != "annotation" {
            continue;
        }
        let Some(name) = extract_annotation_name(annotation, content) else {
            continue;
        };
        if name == "RequestMapping" {
            return extract_annotation_path(annotation, content);
        }
    }

    None
}

/// Extract the content of a string literal node, stripping surrounding quotes.
///
/// Handles `"path"` -> `path`.
fn extract_string_content(string_node: Node, content: &[u8]) -> Option<String> {
    let text = string_node.utf8_text(content).ok()?;
    let trimmed = text.trim();

    // Strip surrounding double quotes
    if trimmed.starts_with('"') && trimmed.ends_with('"') && trimmed.len() >= 2 {
        Some(trimmed[1..trimmed.len() - 1].to_string())
    } else {
        None
    }
}