knot 1.6.2

Codebase Graph + Vector RAG Indexer for Java, TypeScript, JavaScript, Kotlin, Rust, Python, Groovy, C/C++, Build Systems, and HTML/CSS codebases
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
use std::borrow::Cow;

use crate::models::{EntityKind, ParsedEntity, ReferenceIntent};
use crate::pipeline::parser::comments::strip_comment_markers;

pub(crate) fn handle_groovy_capture(
    capture_name: &str,
    text: &str,
    _node: tree_sitter::Node,
) -> Option<(String, EntityKind, usize)> {
    let line = _node.start_position().row + 1;
    match capture_name {
        "groovy.class.name" => Some((text.to_string(), EntityKind::GroovyClass, line)),
        "groovy.interface.name" => Some((text.to_string(), EntityKind::GroovyInterface, line)),
        "groovy.enum.name" => Some((text.to_string(), EntityKind::GroovyEnum, line)),
        "groovy.method.name" => Some((text.to_string(), EntityKind::GroovyMethod, line)),
        "groovy.field.name" => Some((text.to_string(), EntityKind::GroovyProperty, line)),
        _ => None,
    }
}

// tree-sitter-groovy disabled: CI query compilation unreliable (v1.2.0)
#[expect(
    clippy::too_many_lines,
    reason = "function is verbose but correct — extraction deferred"
)]
#[expect(
    clippy::cognitive_complexity,
    reason = "function is verbose but correct — extraction deferred"
)]
pub(crate) fn extract_entities_groovy(
    source: &str,
    file_path: &str,
    repo_name: &str,
) -> Vec<ParsedEntity> {
    // tree-sitter-groovy (v0.1.2) query compilation fails intermittently on CI
    // runners with tree-sitter 0.26. The ad-hoc lexical parser provides equivalent
    // entity coverage (classes, interfaces, enums, traits, methods, properties) plus
    // scope tracking and reference intent extraction not available via tree-sitter alone.
    let mut entities: Vec<ParsedEntity> = vec![];

    // Extract package declaration
    let package = extract_package(source);

    // Keep track of lines where entities were found to avoid duplicates
    let mut known_lines = std::collections::HashSet::new();

    // Post-process entities from Tree-sitter
    for entity in entities.iter_mut() {
        known_lines.insert(entity.start_line);

        // Fix: tree-sitter-groovy parses `trait` as `class_declaration`.
        if entity.kind == EntityKind::GroovyClass
            && let Some(line_content) = source.lines().nth(entity.start_line.saturating_sub(1))
        {
            let trimmed = line_content.trim();
            if trimmed.starts_with("trait ") || trimmed.contains(" trait ") {
                entity.kind = EntityKind::GroovyTrait;
            }
        }

        // Set FQN for tree-sitter entities
        if let Some(pkg) = &package {
            entity.fqn = match entity.kind {
                EntityKind::GroovyClass
                | EntityKind::GroovyInterface
                | EntityKind::GroovyTrait
                | EntityKind::GroovyEnum => format!("{}.{}", pkg, entity.name),
                _ => continue,
            };
        }
    }

    // Ad-hoc extraction with scope tracking for enclosing_class
    // Scope stack: (name, brace_count_when_entered)
    let mut scope_stack: Vec<(String, usize)> = Vec::new();
    let mut brace_count = 0usize;
    let mut in_block_comment = false;

    // Side-car: property metadata needed for accessor synthesis (Phase 3).
    let mut prop_decls: std::collections::HashMap<(String, String), GroovyPropertyDecl> =
        std::collections::HashMap::new();

    // Materialize lines once: docstring extraction walks backwards from each
    // declaration and must not pay O(n²) re-scanning the source per entity.
    let lines: Vec<&str> = source.lines().collect();

    for (line_idx, line) in source.lines().enumerate() {
        let line_num = line_idx + 1;

        let effective = strip_comments_line(line, &mut in_block_comment);

        // Track braces on the effective (code-bearing) line only.
        let opened = effective.matches('{').count();
        let closed = effective.matches('}').count();
        let prev_brace_count = brace_count;
        brace_count += opened;

        let mut early_pop = false;
        if closed > opened {
            let temp_brace = brace_count.saturating_sub(closed);
            while let Some((_, entry_brace)) = scope_stack.last() {
                if temp_brace < *entry_brace {
                    scope_stack.pop();
                    early_pop = true;
                } else {
                    break;
                }
            }
        }

        if effective.is_empty() {
            continue;
        }

        // Try to extract class/interface/enum/trait if tree-sitter missed it
        if !known_lines.contains(&line_num)
            && let Some((name, kind)) = try_extract_type_declaration(effective.as_ref())
        {
            // Push to scope stack BEFORE brace_count is updated for the current line's `{`
            let fqn = if let Some(pkg) = &package {
                format!("{}.{}", pkg, name)
            } else {
                name.clone()
            };
            let current_brace = brace_count;
            // Build a multi-line declaration so that `extends X` / `implements Y`
            // on a following line still feed `extract_inheritance_intents`.
            // Falls back to the single trimmed line when no `{` is in the
            // lookahead window.
            let decl_text =
                build_type_declaration(source, line_idx).unwrap_or_else(|| effective.to_string());
            let inheritance_intents = extract_inheritance_intents(&decl_text, &kind, line_num);
            let docstring = extract_preceding_docstring(&lines, line_idx);
            let mut new_entity = ParsedEntity::new(
                &name, kind, &fqn, None, docstring, "groovy", file_path, line_num, line_num, None,
                repo_name,
            );
            new_entity.reference_intents.extend(inheritance_intents);
            entities.push(new_entity);
            scope_stack.push((name, current_brace));
        }

        // Re-read enclosing after potential scope push
        let enclosing = scope_stack.last().map(|(n, _)| n.clone());

        // Ad-hoc method/field/closure extraction only if tree-sitter didn't already find an entity at this line
        if !known_lines.contains(&line_num) {
            // Try to find a `def` method declaration
            if let Some((method_name, signature)) = try_extract_def_method(effective.as_ref()) {
                let fqn = build_fqn(&package, &enclosing, &method_name);
                let docstring = extract_preceding_docstring(&lines, line_idx);
                entities.push(ParsedEntity::new(
                    &method_name,
                    EntityKind::GroovyMethod,
                    &fqn,
                    Some(signature),
                    docstring,
                    "groovy",
                    file_path,
                    line_num,
                    line_num,
                    enclosing,
                    repo_name,
                ));
                continue;
            }

            // Try to find typed methods or script-level methods missed by tree-sitter
            // First, try single-line detection
            if let Some((method_name, _signature)) = try_extract_typed_method(effective.as_ref()) {
                // Filter false positives: method names that contain dots or look like object.method()
                if method_name.contains('.')
                    || method_name.chars().all(|c| c.is_uppercase() || c == '_')
                {
                    continue;
                }
                let sig_end = effective.find('{').unwrap_or(effective.len());
                let signature_full = effective[..sig_end].trim().to_string();
                let fqn = build_fqn(&package, &enclosing, &method_name);
                let docstring = extract_preceding_docstring(&lines, line_idx);
                entities.push(ParsedEntity::new(
                    &method_name,
                    EntityKind::GroovyMethod,
                    &fqn,
                    Some(signature_full),
                    docstring,
                    "groovy",
                    file_path,
                    line_num,
                    line_num,
                    enclosing,
                    repo_name,
                ));
                continue;
            }

            // Multi-line method detection: method signature with `(` but no `)` on this line,
            // spanning multiple lines (e.g., closure default parameter values)
            if let Some((method_name, method_start_line)) =
                try_extract_typed_method_multiline(source, line_idx)
                && !method_name.contains('.')
            {
                let fqn = build_fqn(&package, &enclosing, &method_name);
                // The docstring sits above the first line of the signature
                // (method_start_line is 1-based → subtract 1 for the 0-based index).
                let docstring = extract_preceding_docstring(&lines, method_start_line - 1);
                entities.push(ParsedEntity::new(
                    &method_name,
                    EntityKind::GroovyMethod,
                    &fqn,
                    None,
                    docstring,
                    "groovy",
                    file_path,
                    method_start_line,
                    line_num,
                    enclosing,
                    repo_name,
                ));
                continue;
            }
        }

        // Try to extract properties or script-level variables.
        // Gated at type-body depth, or at script level when no enclosing type is in scope.
        // `at_type_body_depth` uses the post-increment brace_count so that a single-line
        // class declaration (`class Foo { String name }`) matches: the type's `{` opens
        // before the body's `at_type_body_depth` check happens on the same line.
        // `at_script_level` uses `prev_brace_count == 0` so that a script-level property
        // declaring a closure literal on the same line (`def foo = { ... }`) also matches.
        let at_type_body_depth = scope_stack
            .last()
            .is_some_and(|(_, entry_brace)| brace_count == *entry_brace);
        let at_script_level = scope_stack.is_empty() && prev_brace_count == 0;

        if (at_type_body_depth || at_script_level)
            && !known_lines.contains(&line_num)
            && let Some(prop_decl) = try_extract_property(effective.as_ref())
        {
            let fqn = build_fqn(&package, &enclosing, &prop_decl.name);
            let docstring = extract_preceding_docstring(&lines, line_idx);
            let enclosing_for_prop = enclosing.clone();
            let name_clone = prop_decl.name.clone();
            let enc_clone = enclosing_for_prop.clone();
            entities.push(ParsedEntity::new(
                &prop_decl.name,
                EntityKind::GroovyProperty,
                &fqn,
                None,
                docstring,
                "groovy",
                file_path,
                line_num,
                line_num,
                enclosing_for_prop,
                repo_name,
            ));
            if let Some(enc) = enc_clone {
                prop_decls.insert((enc, name_clone), prop_decl);
            }
        }

        brace_count = brace_count.saturating_sub(closed);
        if !early_pop {
            while let Some((_, entry_brace)) = scope_stack.last() {
                if brace_count < *entry_brace {
                    scope_stack.pop();
                } else {
                    break;
                }
            }
        }
    }

    // Fix end_line for all methods (both tree-sitter and ad-hoc) that
    // couldn't determine their body closing line.
    for entity in entities.iter_mut() {
        if entity.kind == EntityKind::GroovyMethod
            && entity.end_line == entity.start_line
            && let Some(end_line) = find_method_body_end(source, entity.start_line)
            && end_line > entity.start_line
        {
            entity.end_line = end_line;
        }
    }

    // Phase 3: emit synthetic accessor entities for Groovy properties
    // so OVERRIDES linking can match against interface getters/setters.
    synthesize_property_accessors(&mut entities, &package, file_path, repo_name, &prop_decls);

    // Extract reference intents: for each method, scan source lines after its signature
    let mut method_spans: Vec<(usize, usize, usize)> = entities
        .iter()
        .enumerate()
        .filter(|(_, e)| {
            matches!(
                e.kind,
                EntityKind::GroovyMethod | EntityKind::GroovyFunction
            )
        })
        .map(|(i, e)| (e.start_line, e.end_line, i))
        .collect();
    method_spans.sort_by_key(|(s, _, _)| *s);

    let refs = extract_method_calls(source, &entities);

    // Assign each reference intent to the innermost containing method.
    // When methods are nested (e.g., hyperlinkUpdate inside showGrabbingFinishedMessage),
    // we assign the call to the deepest method, not the outer container.
    for method_ref in refs.iter() {
        if let ReferenceIntent::Call { line, .. } = method_ref {
            // Find all methods that contain this line
            let mut candidates: Vec<(usize, usize, usize)> = method_spans
                .iter()
                .filter(|(m_start, m_end, _)| {
                    let actual_end = if *m_end != *m_start { *m_end } else { *m_start };
                    *line > *m_start && *line <= actual_end
                })
                .copied()
                .collect();
            // Pick the innermost: smallest (end - start) wins
            candidates.sort_by_key(|(s, e, _)| e.saturating_sub(*s));
            if let Some(&(_, _, m_eidx)) = candidates.first() {
                entities[m_eidx].reference_intents.push(method_ref.clone());
            }
        }
    }

    entities
}

/// Emits Groovy's compiler-generated property accessors as first-class
/// method entities, so name-based OVERRIDES linking can match a subtype
/// property against a supertype getter (see resolve/overrides.rs).
#[expect(
    clippy::too_many_lines,
    reason = "function is verbose but correct — extraction deferred"
)]
fn synthesize_property_accessors(
    entities: &mut Vec<ParsedEntity>,
    package: &Option<String>,
    file_path: &str,
    repo_name: &str,
    prop_decls: &std::collections::HashMap<(String, String), GroovyPropertyDecl>,
) {
    use std::collections::{HashMap, HashSet};

    // Build declared method names per enclosing class.
    let mut declared: HashSet<(String, String)> = HashSet::new(); // (enclosing_class, method_name)
    let mut type_kind: HashMap<String, EntityKind> = HashMap::new();

    for e in entities.iter() {
        match e.kind {
            EntityKind::GroovyClass
            | EntityKind::GroovyInterface
            | EntityKind::GroovyTrait
            | EntityKind::GroovyEnum => {
                type_kind.insert(e.name.clone(), e.kind.clone());
            }
            EntityKind::GroovyMethod => {
                if let Some(ref cls) = e.enclosing_class {
                    declared.insert((cls.clone(), e.name.clone()));
                }
            }
            _ => {}
        }
    }

    let mut synthetic: Vec<ParsedEntity> = Vec::new();

    for e in entities.iter() {
        if e.kind != EntityKind::GroovyProperty {
            continue;
        }
        let Some(ref cls) = e.enclosing_class else {
            continue;
        };
        let Some(kind) = type_kind.get(cls.as_str()) else {
            continue;
        };

        // Interface fields are constants — no accessors generated.
        if *kind == EntityKind::GroovyInterface {
            continue;
        }

        let prop_name = &e.name;
        if prop_name.is_empty()
            || !prop_name
                .as_bytes()
                .first()
                .is_some_and(|b| b.is_ascii_alphabetic() || *b == b'_')
        {
            continue;
        }

        // Skip if the property name already starts with get/set/is (would collide).
        if (prop_name.starts_with("get")
            && prop_name.chars().nth(3).is_some_and(|c| c.is_uppercase()))
            || (prop_name.starts_with("set")
                && prop_name.chars().nth(3).is_some_and(|c| c.is_uppercase()))
            || (prop_name.starts_with("is")
                && prop_name.chars().nth(2).is_some_and(|c| c.is_uppercase()))
        {
            continue;
        }

        let cap = {
            let mut chars = prop_name.chars();
            let first = chars.next().unwrap().to_uppercase().to_string();
            let rest: String = chars.collect();
            format!("{first}{rest}")
        };

        let decl_info = prop_decls.get(&(cls.clone(), e.name.clone()));

        // Emit getter: `get{Cap}`
        let getter_name = format!("get{cap}");
        if !declared.contains(&(cls.clone(), getter_name.clone())) {
            synthetic.push(make_synthetic_accessor(
                &getter_name,
                e,
                package,
                file_path,
                repo_name,
                cls,
            ));
        }

        // Emit `is{Cap}` for boolean / Boolean properties
        if let Some(decl) = decl_info
            && let Some(ref dt) = decl.declared_type
            && (dt == "boolean" || dt == "Boolean")
        {
            let is_name = format!("is{cap}");
            if !declared.contains(&(cls.clone(), is_name.clone())) {
                synthetic.push(make_synthetic_accessor(
                    &is_name, e, package, file_path, repo_name, cls,
                ));
            }
        }

        // Emit setter: `set{Cap}` (suppressed for `final` properties and explicit declarations)
        let is_final = decl_info.is_some_and(|d| d.is_final);
        if !is_final {
            let setter_name = format!("set{cap}");
            if !declared.contains(&(cls.clone(), setter_name.clone())) {
                synthetic.push(make_synthetic_accessor(
                    &setter_name,
                    e,
                    package,
                    file_path,
                    repo_name,
                    cls,
                ));
            }
        }
    }

    entities.append(&mut synthetic);
}

#[expect(
    clippy::too_many_arguments,
    reason = "function is verbose but correct — extraction deferred"
)]
fn make_synthetic_accessor(
    name: &str,
    property: &ParsedEntity,
    package: &Option<String>,
    file_path: &str,
    repo_name: &str,
    enclosing_class: &str,
) -> ParsedEntity {
    let fqn = build_fqn(package, &Some(enclosing_class.to_string()), name);
    ParsedEntity::new(
        name,
        EntityKind::GroovyMethod,
        &fqn,
        Some("<synthetic Groovy property accessor>".to_string()),
        property.docstring.clone(),
        "groovy",
        file_path,
        property.start_line,
        property.end_line,
        Some(enclosing_class.to_string()),
        repo_name,
    )
}

/// Scans source for method call patterns and returns reference intents.
// Reserved for future reference extraction
#[expect(
    clippy::cognitive_complexity,
    reason = "function is verbose but correct — extraction deferred"
)]
fn extract_method_calls(source: &str, _entities: &[ParsedEntity]) -> Vec<ReferenceIntent> {
    let mut refs = Vec::new();
    let keywords = [
        "if",
        "else",
        "while",
        "for",
        "return",
        "new",
        "throw",
        "catch",
        "switch",
        "case",
        "import",
        "package",
        "class",
        "interface",
        "trait",
        "enum",
        "def",
        "try",
        "finally",
        "assert",
        "println",
        "void",
        "int",
        "String",
        "boolean",
        "double",
        "float",
        "long",
        "byte",
        "short",
        "char",
        "public",
        "private",
        "protected",
        "static",
        "final",
        "abstract",
        "synchronized",
        "volatile",
        "transient",
    ];

    for (line_idx, line) in source.lines().enumerate() {
        let line_num = line_idx + 1;
        let trimmed = line.trim();

        if trimmed.starts_with("//")
            || trimmed.starts_with("/*")
            || trimmed.starts_with("*")
            || trimmed.starts_with("package ")
            || trimmed.starts_with("import ")
        {
            continue;
        }

        let mut chars = trimmed.char_indices().peekable();
        while let Some((i, c)) = chars.next() {
            // Skip string literals to avoid false positives
            if c == '\"' || c == '\'' {
                while let Some((_, nc)) = chars.next() {
                    if nc == c {
                        break; // closing quote found
                    }
                    if nc == '\\' {
                        let _ = chars.next(); // skip escaped char
                    }
                }
                continue;
            }
            if !c.is_alphabetic() && c != '_' {
                continue;
            }

            let word_start = i;
            let mut word_end = i;
            while let Some((_, nc)) = chars.peek() {
                if nc.is_alphanumeric() || *nc == '_' {
                    word_end = chars.next().unwrap().0;
                } else {
                    break;
                }
            }

            let word = &trimmed[word_start..=word_end];
            if keywords.contains(&word) {
                continue;
            }

            let after_word = &trimmed[word_end + 1..];
            let after_trimmed = after_word.trim_start();

            // Pattern: word.word(...)
            if let Some(dot_rest) = after_trimmed.strip_prefix('.') {
                let dot_trimmed = dot_rest.trim_start();
                if let Some((next_word, rest)) = split_identifier(dot_trimmed) {
                    let after_next = rest.trim_start();
                    if after_next.starts_with('(') {
                        refs.push(ReferenceIntent::Call {
                            method: next_word.to_string(),
                            receiver: Some(word.to_string()),
                            line: line_num,
                            arg_count: None,
                        });
                        continue;
                    }
                }
            }

            // Pattern: word(...)
            if after_trimmed.starts_with('(') && !keywords.contains(&word) && word.len() > 1 {
                refs.push(ReferenceIntent::Call {
                    method: word.to_string(),
                    receiver: None,
                    line: line_num,
                    arg_count: None,
                });
            }

            // Pattern: no-paren call — word followed by string literal or identifier args
            // Groovy style: runAnalyzer "abc", 123 or doSomething arg1, arg2
            if !after_trimmed.is_empty()
                && !keywords.contains(&word)
                && word.len() > 1
                && !after_trimmed.starts_with('(')
                && !after_trimmed.starts_with('.')
                && !after_trimmed.starts_with('=')
                && !after_trimmed.starts_with('{')
                && !after_trimmed.starts_with(')')
                && !after_trimmed.starts_with(':')
                && !after_trimmed.starts_with(';')
            {
                let first_arg_char = after_trimmed.chars().next().unwrap();
                // Argument must start with string quote or identifier char
                if first_arg_char == '"'
                    || first_arg_char == '\''
                    || first_arg_char.is_alphabetic()
                    || first_arg_char == '$'
                {
                    refs.push(ReferenceIntent::Call {
                        method: word.to_string(),
                        receiver: None,
                        line: line_num,
                        arg_count: None,
                    });
                }
            }
        }
    }
    refs
}

/// Splits an identifier from the start of `s`, returns (identifier, rest).
// Reserved for future FQN construction
fn split_identifier(s: &str) -> Option<(&str, &str)> {
    let first = s.chars().next()?;
    if !first.is_alphabetic() && first != '_' {
        return None;
    }
    let end = s
        .find(|c: char| !c.is_alphanumeric() && c != '_')
        .unwrap_or(s.len());
    Some((&s[..end], &s[end..]))
}

/// Strips comment spans from a single source line, tracking multi-line
/// `/* … */` state across calls. Returns the code-bearing remainder.
///
/// The caller should count braces and inspect for declarations on the
/// returned effective line, *not* on the raw line — this is what prevents
/// Javadoc continuation lines from producing phantom entities and corrupting
/// scope tracking.
#[expect(
    clippy::cognitive_complexity,
    reason = "function is verbose but correct — extraction deferred"
)]
fn strip_comments_line<'a>(line: &'a str, in_block: &mut bool) -> Cow<'a, str> {
    let trimmed = line.trim();
    if !*in_block && !trimmed.contains('/') && !trimmed.contains('*') {
        return Cow::Borrowed(trimmed);
    }

    if *in_block {
        if let Some(end_idx) = trimmed.find("*/") {
            *in_block = false;
            let rest = trimmed[end_idx + 2..].to_string();
            if rest.trim().is_empty() {
                return Cow::Owned(String::new());
            }
            return Cow::Owned(rest);
        }
        return Cow::Owned(String::new());
    }

    let mut result = String::with_capacity(trimmed.len());
    let mut chars = trimmed.char_indices().peekable();

    while let Some((_i, c)) = chars.next() {
        if c == '/'
            && let Some(&(_, next)) = chars.peek()
        {
            if next == '/' {
                // Line comment — discard rest
                let effective = result.trim_end().to_string();
                return if effective.is_empty() {
                    Cow::Owned(String::new())
                } else {
                    Cow::Owned(effective)
                };
            }
            if next == '*' {
                chars.next(); // consume '*'
                // Look for matching */ on the same line
                let mut found_close = false;
                while let Some((_, c2)) = chars.next() {
                    if c2 == '*'
                        && let Some(&(_, '/')) = chars.peek()
                    {
                        chars.next(); // consume '/'
                        found_close = true;
                        break;
                    }
                }
                if !found_close {
                    *in_block = true;
                    let effective = result.trim_end().to_string();
                    return if effective.is_empty() {
                        Cow::Owned(String::new())
                    } else {
                        Cow::Owned(effective)
                    };
                }
                // Single-line block comment closed — continue processing rest of line
                continue;
            }
        }
        if c == '"' || c == '\'' {
            let quote = c;
            result.push(quote);
            while let Some((_, c2)) = chars.next() {
                result.push(c2);
                if c2 == '\\' {
                    if let Some((_, esc)) = chars.next() {
                        result.push(esc);
                    }
                } else if c2 == quote {
                    break;
                }
            }
            continue;
        }
        result.push(c);
    }

    let effective = result.trim().to_string();
    if effective.is_empty() {
        Cow::Owned(String::new())
    } else {
        Cow::Owned(effective)
    }
}

/// Extract package name from source (e.g., `package com.example.service`)
// Reserved for future package resolution
fn extract_package(source: &str) -> Option<String> {
    for line in source.lines().take(20) {
        let trimmed = line.trim();
        if let Some(pkg) = trimmed.strip_prefix("package ") {
            let name = pkg.trim().trim_end_matches(';').trim();
            if !name.is_empty() {
                return Some(name.to_string());
            }
        }
    }
    None
}

/// Build a fully-qualified name: package.parent.method or package.method
// Reserved for future FQN construction
fn build_fqn(package: &Option<String>, parent: &Option<String>, name: &str) -> String {
    match (package, parent) {
        (Some(pkg), Some(enclosing_class)) => format!("{}.{}.{}", pkg, enclosing_class, name),
        (Some(pkg), None) => format!("{}.{}", pkg, name),
        (None, Some(enclosing_class)) => format!("{}.{}", enclosing_class, name),
        (None, None) => name.to_string(),
    }
}

/// Walks backwards from the line preceding `decl_line_idx` (0-based) collecting
/// the GroovyDoc / comment block that documents the declaration.
///
/// Policy (backwards walk from the declaration):
/// 1. Skip (without stopping the search): annotation lines (`@X`) and at most
///    one blank line — same tolerance as the generic tree-sitter extractor.
/// 2. Capture: an adjacent `/** ... */` / `/* ... */` block, or a burst of
///    consecutive `//` lines. Only the adjacent block is taken.
/// 3. Stop immediately (returning whatever was captured, or `None`) on any
///    other non-empty code line (`package`, `import`, statements) or at the
///    start of the file — this protects against license headers leaking into
///    the first class of a file.
/// 4. Markers (`/**`, `*/`, leading `*`, `//`) are stripped via
///    [`strip_comment_markers`]; an empty cleaned result maps to `None`.
fn extract_preceding_docstring(lines: &[&str], decl_line_idx: usize) -> Option<String> {
    let non_empty = |cleaned: String| (!cleaned.trim().is_empty()).then_some(cleaned);

    // Phase 1: skip annotations and at most one blank line.
    let mut idx = decl_line_idx;
    let mut blank_seen = false;
    while idx > 0 {
        let prev = lines[idx - 1].trim();
        if prev.starts_with('@') {
            idx -= 1;
            continue;
        }
        if prev.is_empty() && !blank_seen {
            blank_seen = true;
            idx -= 1;
            continue;
        }
        break;
    }
    if idx == 0 {
        return None;
    }

    let last = lines[idx - 1].trim();

    // Case A: block comment — `/** ... */` or `/* ... */`.
    if last.ends_with("*/") {
        if last.starts_with("/*") {
            // Opener and closer on the same line (or this IS the opener line of
            // a block whose body sits above is impossible: the closer is here).
            return non_empty(strip_comment_markers(last));
        }
        if !last.starts_with('*') {
            // `code(); /* inline */` — trailing comment on a code line is not a
            // docstring.
            return None;
        }
        // Multi-line block: walk back through `*` continuation lines until the
        // `/*` opener.
        let mut block: Vec<&str> = vec![lines[idx - 1]];
        let mut j = idx - 1;
        while j > 0 {
            j -= 1;
            let t = lines[j].trim();
            if t.starts_with("/*") {
                block.push(lines[j]);
                block.reverse();
                return non_empty(strip_comment_markers(&block.join("\n")));
            }
            if t.starts_with('*') {
                block.push(lines[j]);
                continue;
            }
            // Non-comment line reached before the opener → malformed block.
            return None;
        }
        // Start of file reached without an opener → malformed block.
        return None;
    }

    // Case B: burst of consecutive `//` line comments.
    if last.starts_with("//") {
        let mut j = idx - 1;
        let mut burst: Vec<&str> = Vec::new();
        loop {
            if !lines[j].trim().starts_with("//") {
                break;
            }
            burst.push(lines[j]);
            if j == 0 {
                break;
            }
            j -= 1;
        }
        burst.reverse();
        return non_empty(strip_comment_markers(&burst.join("\n")));
    }

    None
}

/// Tries to extract class, interface, enum, or trait declarations
/// Scans forward from `line_num` to find the matching closing `}` of the method body.
// Reserved for future method body parsing
fn find_method_body_end(source: &str, line_num: usize) -> Option<usize> {
    let mut chars = source.chars().peekable();
    let mut current_line = 1usize;
    let mut brace_depth = 0i32;
    let mut found_opening = false;

    while current_line < line_num {
        match chars.next() {
            Some('\n') => current_line += 1,
            Some(_) => {}
            None => return None,
        }
    }

    while let Some(ch) = chars.next() {
        match ch {
            '\n' => current_line += 1,
            '/' if chars.peek() == Some(&'/') => {
                for c in chars.by_ref() {
                    if c == '\n' {
                        current_line += 1;
                        break;
                    }
                }
            }
            '"' | '\'' => {
                let quote = ch;
                while let Some(c) = chars.next() {
                    if c == '\\' {
                        let _ = chars.next();
                    } else if c == quote {
                        break;
                    }
                }
            }
            '{' => {
                brace_depth += 1;
                found_opening = true;
            }
            '}' => {
                brace_depth -= 1;
                if found_opening && brace_depth == 0 {
                    return Some(current_line);
                }
            }
            _ => {}
        }
    }
    None
}

// Reserved for future type declaration parsing
fn try_extract_type_declaration(line: &str) -> Option<(String, EntityKind)> {
    let tokens: Vec<&str> = line.split_whitespace().collect();

    for (i, token) in tokens.iter().enumerate() {
        let kind = match *token {
            "class" => EntityKind::GroovyClass,
            "interface" => EntityKind::GroovyInterface,
            "trait" => EntityKind::GroovyTrait,
            "enum" => EntityKind::GroovyEnum,
            _ => continue,
        };

        if i + 1 < tokens.len() {
            // The next token should be the name
            let name_raw = tokens[i + 1];
            // Remove generic types, extends, implements, curly braces
            let name = name_raw
                .split('<')
                .next()
                .unwrap_or(name_raw)
                .split('{')
                .next()
                .unwrap_or(name_raw)
                .trim();

            if !name.is_empty() && name.chars().next().unwrap().is_alphabetic() {
                return Some((name.to_string(), kind));
            }
        }
    }
    None
}

/// Builds the textual declaration of a type from `line_idx` onwards, stopping at
/// the first `{` (exclusive). Returns `None` if no `{` is found within
/// `MAX_LOOKAHEAD` lines — the caller then falls back to the single line.
fn build_type_declaration(source: &str, line_idx: usize) -> Option<String> {
    const MAX_LOOKAHEAD: usize = 5;
    let lines: Vec<&str> = source.lines().collect();
    let mut buf = String::new();
    for offset in 0..MAX_LOOKAHEAD {
        let raw = lines.get(line_idx + offset)?.trim();
        if raw.is_empty() {
            buf.push(' ');
            continue;
        }
        // Skip pure comment / javadoc continuations (mirrors the main loop's policy).
        if raw.starts_with("//") || raw.starts_with("/*") || raw.starts_with("* ") || raw == "*" {
            continue;
        }
        if !buf.is_empty() {
            buf.push(' ');
        }
        buf.push_str(raw);
        if raw.contains('{') {
            return Some(buf);
        }
    }
    None
}

/// Strips every balanced `<...>` section from `input`, preserving any characters
/// outside them. We use a manual depth counter instead of a regex so that nested
/// generics like `Map<List<X>, Y>` are erased in a single pass. This both
/// neutralises generic bounds (`class Box<T extends Comparable>`) and discards
/// type arguments on the parent (`extends AbstractRepo<Order, Long>`).
fn strip_balanced_generics(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    let mut depth: i32 = 0;
    for ch in input.chars() {
        match ch {
            '<' => depth += 1,
            '>' if depth > 0 => depth -= 1,
            '>' => {} // unbalanced '>' — drop silently (defensive)
            _ if depth == 0 => out.push(ch),
            _ => {} // skip chars inside generics
        }
    }
    out
}

/// Validates a single parent/interface name token: must start with an
/// alphabetic character, may contain alphanumerics, underscores and dots.
fn is_valid_type_name(s: &str) -> bool {
    if s.is_empty() {
        return false;
    }
    let mut chars = s.chars();
    let first = chars.next().unwrap();
    if !first.is_alphabetic() && first != '_' {
        return false;
    }
    chars.all(|c| c.is_alphanumeric() || c == '_' || c == '.')
}

/// Extracts `ReferenceIntent::Extends` / `Implements` from a Groovy type
/// declaration.
///
/// `decl` is the complete declaration text (possibly concatenated across
/// multiple lines, up to the opening `{`). `kind` decides the inheritance
/// semantics:
///
/// - `GroovyInterface`: every name after `extends` becomes an `Extends` intent
///   (mirrors the Kotlin parser' choice to treat interface-extends-interface as
///   `Extends`).
/// - `GroovyClass`, `GroovyTrait`, `GroovyEnum`: the first name after `extends`
///   becomes an `Extends` intent (Groovy only allows a single parent), and
///   every name after `implements` becomes an `Implements` intent.
///
/// Notes:
/// - Generic bounds inside the type header (`class Box<T extends Comparable>`)
///   are stripped before tokenisation so the `extends Comparable` token never
///   reaches the matcher.
/// - Generic arguments on the parent (`extends AbstractRepo<Order, Long>`) are
///   also stripped so resolution receives just the simple/FQN name.
/// - Declarations with embedded block comments on the same line are out of
///   scope — same robustness bar as the rest of the lexical parser.
pub(crate) fn extract_inheritance_intents(
    decl: &str,
    kind: &EntityKind,
    line: usize,
) -> Vec<ReferenceIntent> {
    let stripped = strip_balanced_generics(decl);
    let mut intents = Vec::new();

    // Look for `extends` and `implements` keywords (case-sensitive, word-bounded).
    let tokens: Vec<&str> = stripped.split_whitespace().collect();
    let extends_idx = tokens.iter().position(|t| *t == "extends");
    let implements_idx = tokens.iter().position(|t| *t == "implements");

    if let Some(idx) = extends_idx {
        let from = idx + 1;
        let to = implements_idx.unwrap_or(tokens.len());
        let parents: Vec<&str> = tokens[from..to]
            .iter()
            .copied()
            .flat_map(|t| t.split(','))
            .map(str::trim)
            .filter(|t| is_valid_type_name(t))
            .collect();

        match kind {
            EntityKind::GroovyInterface => {
                for parent in parents {
                    intents.push(ReferenceIntent::Extends {
                        parent: parent.to_string(),
                        line,
                    });
                }
            }
            _ => {
                if let Some(first) = parents.into_iter().next() {
                    intents.push(ReferenceIntent::Extends {
                        parent: first.to_string(),
                        line,
                    });
                }
            }
        }
    }

    if let Some(idx) = implements_idx {
        let from = idx + 1;
        for tok in &tokens[from..] {
            // Any `{` opens the class body — stop processing names so we don't
            // pick up enum constants or inner-class members as interfaces.
            if tok.contains('{') {
                break;
            }
            for piece in tok.split(',') {
                let trimmed = piece.trim();
                if trimmed.is_empty() {
                    continue;
                }
                if is_valid_type_name(trimmed) {
                    intents.push(ReferenceIntent::Implements {
                        interface: trimmed.to_string(),
                        line,
                    });
                }
            }
        }
    }

    intents
}

/// Metadata for a Groovy property declaration, carried forward into accessor
/// synthesis so the synthetic entity can inherit the declared type and `final`
/// flag.
#[derive(Debug, Clone)]
struct GroovyPropertyDecl {
    name: String,
    declared_type: Option<String>,
    is_final: bool,
}

/// Tries to extract properties (fields, script variables) from a single line.
///
/// Recognises both:
/// - Initialized: `String name = 'test'`, `def count = 0`
/// - Bare (no initializer): `Path baseDir`, `private static final Path ROOT`
///
/// The caller gates extraction via `scope_stack` depth so method-body locals
/// are never promoted to properties.
#[expect(
    clippy::too_many_lines,
    reason = "function is verbose but correct — extraction deferred"
)]
fn try_extract_property(line: &str) -> Option<GroovyPropertyDecl> {
    let mut cleaned = line.trim().trim_end_matches(';').trim().to_string();

    // Strip leading annotations (@Lazy, @PackageScope, @Deprecated, ...)
    loop {
        let trimmed = cleaned.trim_start();
        if let Some(rest) = trimmed.strip_prefix('@') {
            let end = rest.find(|c: char| c.is_whitespace()).unwrap_or(rest.len());
            cleaned = rest[end..].trim().to_string();
        } else {
            break;
        }
    }

    if cleaned.is_empty() {
        return None;
    }

    // Reject pure comments (shouldn't happen after strip_comments_line, but defensive)
    if cleaned.starts_with("//") || cleaned.starts_with("/*") || cleaned.starts_with('*') {
        return None;
    }

    // Reject keywords that can appear as the first token
    let rejection_keywords = [
        "return",
        "import",
        "package",
        "class",
        "interface",
        "trait",
        "enum",
        "new",
        "throw",
        "assert",
        "case",
        "else",
        "extends",
        "implements",
        "instanceof",
    ];

    // If the line has `=`, try the initialized path
    if let Some(eq_idx) = cleaned.find('=') {
        // Discard `==`, `!=`
        if cleaned.chars().nth(eq_idx + 1) == Some('=') {
            return None;
        }
        let left_side = cleaned[..eq_idx].trim();
        if left_side.is_empty() {
            return None;
        }

        let tokens: Vec<&str> = left_side.split_whitespace().collect();
        if tokens.len() >= 2 {
            let name = tokens.last().unwrap();
            if is_valid_identifier(name) {
                let first_token = tokens[0];
                let declared_type = if first_token == "def" {
                    if tokens.len() >= 2 {
                        Some(tokens[tokens.len() - 2].to_string())
                    } else {
                        None
                    }
                } else if is_valid_type_name(first_token) {
                    Some(first_token.to_string())
                } else {
                    tokens
                        .iter()
                        .find(|t| is_valid_type_name(t))
                        .map(|t| t.to_string())
                };
                let is_final = tokens.contains(&"final");
                return Some(GroovyPropertyDecl {
                    name: name.to_string(),
                    declared_type,
                    is_final,
                });
            }
        }
        return None;
    }

    // No `=` — bare declaration path
    if cleaned.contains('(')
        || cleaned.contains(')')
        || cleaned.contains('{')
        || cleaned.contains('}')
    {
        return None;
    }
    let tokens: Vec<&str> = cleaned.split_whitespace().collect();
    if tokens.is_empty() || tokens.len() < 2 {
        return None;
    }

    // Reject if the first significant token is a keyword
    let first_token = tokens[0];
    if rejection_keywords.contains(&first_token) {
        return None;
    }

    // Remove modifier tokens
    let modifiers: &[&str] = &[
        "private",
        "protected",
        "public",
        "static",
        "final",
        "transient",
        "volatile",
        "synchronized",
        "abstract",
        "native",
    ];
    let non_modifiers: Vec<&&str> = tokens.iter().filter(|t| !modifiers.contains(t)).collect();

    if non_modifiers.len() < 2 {
        return None;
    }

    // After removing modifiers, we need exactly 2 tokens: type + name
    // But we iterate to find a valid type-name pair
    let name = tokens.last().unwrap();
    if !is_valid_identifier(name) {
        return None;
    }

    // Find the type token (the token before name, or anywhere before it that's a valid type)
    let type_token = if tokens.len() >= 2 {
        let candidate = tokens[tokens.len() - 2];
        let candidate_stripped = strip_balanced_generics(candidate);
        if candidate == "def" || is_valid_type_name(&candidate_stripped) {
            Some(candidate.to_string())
        } else if modifiers.contains(&candidate) {
            // e.g., `private final String name` — search backwards
            tokens[..tokens.len() - 1]
                .iter()
                .rev()
                .find(|t| {
                    !modifiers.contains(t)
                        && **t != "def"
                        && is_valid_type_name(&strip_balanced_generics(t))
                })
                .map(|t| t.to_string())
        } else {
            None
        }
    } else {
        None
    };

    type_token.as_ref()?;

    let is_final = tokens.contains(&"final");
    Some(GroovyPropertyDecl {
        name: name.to_string(),
        declared_type: type_token,
        is_final,
    })
}

/// Returns true when `s` is a Groovy/Java identifier.
fn is_valid_identifier(s: &str) -> bool {
    if s.is_empty() {
        return false;
    }
    let mut chars = s.chars();
    let first = chars.next().unwrap();
    if !first.is_alphabetic() && first != '_' {
        return false;
    }
    chars.all(|c| c.is_alphanumeric() || c == '_')
}

/// Tries to extract a method name from a multi-line method signature.
///
/// Handles cases like:
///   private static SimpleHttpServer restartHttpServer(String id, String webRootPath,
///                                                      Closure handler = {null},
///                                                      Closure errorListener = {}) {
///
/// where the opening `(` and closing `)` are on different lines.
// Reserved for future multiline method parsing
#[expect(
    clippy::too_many_lines,
    reason = "function is verbose but correct — extraction deferred"
)]
fn try_extract_typed_method_multiline(source: &str, line_idx: usize) -> Option<(String, usize)> {
    let lines: Vec<&str> = source.lines().collect();
    let start_line = lines.get(line_idx)?;
    let trimmed = start_line.trim();

    let method_start_keywords = [
        "private",
        "public",
        "protected",
        "static",
        "final",
        "abstract",
        "synchronized",
        "volatile",
        "transient",
        "native",
        "void",
        "boolean",
        "byte",
        "short",
        "int",
        "long",
        "float",
        "double",
        "char",
        "String",
        "Object",
        "List",
        "Map",
        "Set",
        "Closure",
        "SimpleHttpServer",
    ];

    if trimmed.starts_with("if ")
        || trimmed.starts_with("while ")
        || trimmed.starts_with("for ")
        || trimmed.starts_with("catch ")
        || trimmed.starts_with("switch ")
        || trimmed.starts_with("return ")
    {
        return None;
    }

    // Must contain `(` but not `)` on the same line
    if !trimmed.contains('(') || trimmed.contains(')') {
        return None;
    }

    let paren_idx = trimmed.find('(').unwrap();
    if trimmed[..paren_idx].contains('=') {
        return None;
    }

    let before_paren = trimmed[..paren_idx].trim();
    let tokens: Vec<&str> = before_paren.split_whitespace().collect();

    // Need at least 2 tokens (type keyword + method name)
    if tokens.len() < 2 {
        return None;
    }

    // Check that tokens look like access modifiers / type / name pattern
    let has_modifier = tokens.iter().any(|t| method_start_keywords.contains(t));
    if !has_modifier {
        // Also check if the second-to-last token looks like a type (starts with uppercase)
        if tokens.len() >= 2 {
            let second_last = tokens[tokens.len() - 2];
            if !second_last.chars().next().is_some_and(|c| c.is_uppercase()) {
                return None;
            }
        } else {
            return None;
        }
    }

    let name = tokens.last().unwrap();
    let first_char = name.chars().next()?;
    if !first_char.is_alphabetic() && first_char != '_' {
        return None;
    }

    // Scan ahead for the closing `)` and opening `{` (within a reasonable window)
    let max_lookahead = 10;
    let mut found_close_paren = false;
    for offset in 1..=max_lookahead {
        let next_line = lines.get(line_idx + offset)?;
        let next_trimmed = next_line.trim();

        if !found_close_paren && next_trimmed.contains(')') {
            found_close_paren = true;
        }

        if next_trimmed.contains('{') {
            // Must have found `)` before `{`
            if found_close_paren {
                return Some((name.to_string(), line_idx + 1));
            }
            // `{` before `)` indicates a closure literal, not the method body
        }

        if next_trimmed.is_empty()
            || next_trimmed.starts_with("//")
            || next_trimmed.starts_with("/*")
        {
            continue;
        }
    }

    None
}

/// Tries to extract a typed method name and signature
// Reserved for future typed method parsing
fn try_extract_typed_method(line: &str) -> Option<(String, String)> {
    // Quick heuristic: contains `(` and `)` and `{`, doesn't start with `if`/`while`/`for`/`catch`
    if line.contains('(') && line.contains(')') && (line.contains('{') || line.ends_with(')')) {
        if line.starts_with("if ")
            || line.starts_with("while ")
            || line.starts_with("for ")
            || line.starts_with("catch ")
            || line.starts_with("switch ")
        {
            return None;
        }

        let paren_idx = line.find('(').unwrap();

        // Reject assignment patterns like `def foo = bar(...)` — these are calls, not declarations
        if line[..paren_idx].contains('=') {
            return None;
        }

        // Reject constructor calls like `new File(...)` or `new SimpleHttpServer()`
        if line[..paren_idx].contains("new ") || line[..paren_idx].ends_with(" new") {
            return None;
        }

        let before_paren = line[..paren_idx].trim();

        // Handle quoted method names (Spock feature methods)
        if let Some(quote_idx) = before_paren.find('\"') {
            // Find the closing quote
            if let Some(close_idx) = before_paren[quote_idx + 1..].find('\"') {
                let inner_name = &before_paren[quote_idx + 1..quote_idx + 1 + close_idx];
                let sig_end = line.find('{').unwrap_or(line.len());
                let signature = line[..sig_end].trim().to_string();
                return Some((inner_name.to_string(), signature));
            }
        }

        let tokens: Vec<&str> = before_paren.split_whitespace().collect();
        if tokens.len() >= 2 {
            let name = tokens.last().unwrap();
            let first_char = name.chars().next().unwrap();
            if first_char.is_alphabetic() || first_char == '_' {
                let sig_end = line.find('{').unwrap_or(line.len());
                let signature = line[..sig_end].trim().to_string();
                return Some((name.to_string(), signature));
            }
        }
    }
    None
}

/// Tries to extract a method name and signature from a line containing `def`
// Reserved for future def method parsing
fn try_extract_def_method(line: &str) -> Option<(String, String)> {
    // Look for `def `
    if let Some(def_idx) = line.find("def ") {
        // Ensure `def` is a word by checking the preceding character (if any)
        if def_idx > 0 {
            let prev_char = line.as_bytes()[def_idx - 1] as char;
            if prev_char.is_alphanumeric() || prev_char == '_' {
                return None;
            }
        }

        let after_def = &line[def_idx + 4..].trim_start();

        // Find the opening parenthesis for the method arguments
        if let Some(paren_idx) = after_def.find('(') {
            let potential_name = &after_def[..paren_idx].trim();

            // Validate the name: must be a valid identifier and not contain spaces
            if !potential_name.is_empty() && !potential_name.contains(|c: char| c.is_whitespace()) {
                // Must start with letter or underscore
                let first_char = potential_name.chars().next().unwrap();
                if first_char.is_alphabetic() || first_char == '_' {
                    // Extract signature from 'def' to the start of the block '{' or end of line
                    let sig_end = line[def_idx..]
                        .find('{')
                        .map(|i| i + def_idx)
                        .unwrap_or(line.len());
                    let signature = line[def_idx..sig_end].trim().to_string();

                    return Some((potential_name.to_string(), signature));
                }
            }
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::pipeline::parser::test_utils::{
        assert_extends, assert_implements, collect_extends, collect_implements,
    };

    /// Helper: pick the Groovy class entity for `name` from the parser output.
    fn pick_class<'a>(entities: &'a [ParsedEntity], name: &str) -> &'a ParsedEntity {
        entities
            .iter()
            .find(|e| e.name == name && e.kind == EntityKind::GroovyClass)
            .unwrap_or_else(|| panic!("Groovy class '{name}' not found in entities"))
    }

    fn pick_entity<'a>(
        entities: &'a [ParsedEntity],
        name: &str,
        kind: EntityKind,
    ) -> &'a ParsedEntity {
        entities
            .iter()
            .find(|e| e.name == name && e.kind == kind)
            .unwrap_or_else(|| {
                panic!(
                    "Entity '{name}' ({kind:?}) not found in entities. Available: {:?}",
                    entities
                        .iter()
                        .map(|e| (&e.name, &e.kind))
                        .collect::<Vec<_>>()
                )
            })
    }

    // ---- Groovy Standard (tree-sitter) extraction tests ----

    #[test]
    fn test_groovy_class_extraction() {
        let source = "class MyGroovyClass { def method() {} }";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        assert!(
            entities
                .iter()
                .any(|e| e.name == "MyGroovyClass" && e.kind == EntityKind::GroovyClass)
        );
    }

    #[test]
    fn test_groovy_interface_extraction() {
        let source = "interface MyGroovyInterface { void doIt() }";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        assert!(
            entities
                .iter()
                .any(|e| e.name == "MyGroovyInterface" && e.kind == EntityKind::GroovyInterface)
        );
    }

    #[test]
    fn test_groovy_enum_extraction() {
        let source = "enum Color { RED, GREEN, BLUE }";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        assert!(
            entities
                .iter()
                .any(|e| e.name == "Color" && e.kind == EntityKind::GroovyEnum)
        );
    }

    #[test]
    fn test_groovy_method_extraction() {
        let source = "class Foo { String greet(String name) { return name } }";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        let method = entities.iter().find(|e| e.name == "greet");
        assert!(method.is_some(), "Expected method 'greet' to be extracted");
        assert_eq!(method.unwrap().kind, EntityKind::GroovyMethod);
    }

    #[test]
    fn test_groovy_trait_extraction() {
        let source = "trait MyTrait { void doSomething() {} }";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        assert!(
            entities
                .iter()
                .any(|e| e.name == "MyTrait" && e.kind == EntityKind::GroovyTrait)
        );
    }

    #[test]
    fn test_groovy_property_extraction() {
        let source = "class Foo { String name = 'test' }";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        assert!(
            entities
                .iter()
                .any(|e| e.name == "name" && e.kind == EntityKind::GroovyProperty)
        );
    }

    #[test]
    fn test_groovy_multiple_classes() {
        let source = "package com.example\nclass First {}\nclass Second {}\nclass Third {}";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        let class_names: Vec<_> = entities
            .iter()
            .filter(|e| e.kind == EntityKind::GroovyClass)
            .map(|e| e.name.clone())
            .collect();
        assert!(class_names.contains(&"First".to_string()));
        assert!(class_names.contains(&"Second".to_string()));
        assert!(class_names.contains(&"Third".to_string()));
    }

    #[test]
    fn test_groovy_constructor_extraction() {
        let source = "class User { User(String name) { this.name = name } }";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        assert!(
            entities
                .iter()
                .any(|e| e.name == "User" && e.kind == EntityKind::GroovyMethod)
        );
    }

    #[test]
    fn test_groovy_empty_body_class() {
        let source = "class EmptyClass {}";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        assert!(
            entities
                .iter()
                .any(|e| e.name == "EmptyClass" && e.kind == EntityKind::GroovyClass)
        );
    }

    #[test]
    fn test_groovy_method_in_class_extracts_correctly() {
        let source = "class Calculator {\n  int add(int a, int b) { return a + b }\n  int subtract(int a, int b) { return a - b }\n}";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        assert!(
            entities
                .iter()
                .any(|e| e.name == "add" && e.kind == EntityKind::GroovyMethod)
        );
        assert!(
            entities
                .iter()
                .any(|e| e.name == "subtract" && e.kind == EntityKind::GroovyMethod)
        );
    }

    #[test]
    #[expect(
        clippy::too_many_lines,
        reason = "function is verbose but correct — extraction deferred"
    )]
    #[expect(
        clippy::cognitive_complexity,
        reason = "function is verbose but correct — extraction deferred"
    )]
    fn test_groovy_parse_sample_full_file() {
        let source = include_str!("../../../../tests/testing_files/sample_full.groovy");
        let entities = extract_entities_groovy(source, "sample_full.groovy", "test-repo");

        println!("--- Extracted Entities ---");
        for e in &entities {
            println!("{:?} - {}", e.kind, e.name);
        }
        println!("--------------------------");

        assert!(
            entities
                .iter()
                .any(|e| e.name == "UserService" && e.kind == EntityKind::GroovyClass)
        );
        assert!(
            entities
                .iter()
                .any(|e| e.name == "BaseService" && e.kind == EntityKind::GroovyClass)
        );
        assert!(
            entities
                .iter()
                .any(|e| e.name == "DatabaseConfig" && e.kind == EntityKind::GroovyClass)
        );
        assert!(
            entities
                .iter()
                .any(|e| e.name == "Repository" && e.kind == EntityKind::GroovyInterface)
        );
        assert!(
            entities
                .iter()
                .any(|e| e.name == "Auditable" && e.kind == EntityKind::GroovyTrait)
        );
        assert!(
            entities
                .iter()
                .any(|e| e.name == "Status" && e.kind == EntityKind::GroovyEnum)
        );
        assert!(
            entities
                .iter()
                .any(|e| e.name == "scriptMethod" && e.kind == EntityKind::GroovyMethod)
        );
        assert!(
            entities
                .iter()
                .any(|e| e.name == "anotherScriptMethod" && e.kind == EntityKind::GroovyMethod)
        );
        assert!(
            entities
                .iter()
                .any(|e| e.name == "globalConfig" && e.kind == EntityKind::GroovyProperty)
        );
        assert!(
            entities
                .iter()
                .any(|e| e.name == "processDataClosure" && e.kind == EntityKind::GroovyProperty)
        );
        assert!(
            entities
                .iter()
                .any(|e| e.name == "initialize" && e.kind == EntityKind::GroovyMethod)
        );
        assert!(
            entities
                .iter()
                .any(|e| e.name == "calculateTotal" && e.kind == EntityKind::GroovyMethod)
        );
        assert!(
            entities
                .iter()
                .any(|e| e.name == "logAction" && e.kind == EntityKind::GroovyMethod)
        );
        assert!(entities.iter().any(|e| e.name
            == "addition of #num1 and #num2 should be #expected"
            && e.kind == EntityKind::GroovyMethod));
        assert!(
            entities
                .iter()
                .any(|e| e.name == "DEFAULT_ROLE" && e.kind == EntityKind::GroovyProperty)
        );
        assert!(
            entities
                .iter()
                .any(|e| e.name == "maxLoginAttempts" && e.kind == EntityKind::GroovyProperty)
        );

        assert!(
            entities.len() >= 20,
            "Expected at least 20 entities, got {}",
            entities.len()
        );

        // Docstring extraction: comments in the fixture now surface as docstrings.
        let global_config = entities
            .iter()
            .find(|e| e.name == "globalConfig" && e.kind == EntityKind::GroovyProperty)
            .expect("globalConfig not extracted");
        assert_eq!(
            global_config.docstring.as_deref(),
            Some("1. Top-level script variables and closures")
        );
        let user_service = entities
            .iter()
            .find(|e| e.name == "UserService" && e.kind == EntityKind::GroovyClass)
            .expect("UserService not extracted");
        assert_eq!(
            user_service.docstring.as_deref(),
            Some("7. Main Class with Annotations, Inheritance, Traits, and inner classes")
        );
        let initialize = entities
            .iter()
            .find(|e| {
                e.name == "initialize"
                    && e.kind == EntityKind::GroovyMethod
                    && e.enclosing_class.as_deref() == Some("UserService")
            })
            .expect("UserService.initialize not extracted");
        assert_eq!(
            initialize.docstring.as_deref(),
            Some("Typed Method overriding base class")
        );
        // Regression: a property with no preceding comment keeps docstring == None.
        let max_login = entities
            .iter()
            .find(|e| e.name == "maxLoginAttempts" && e.kind == EntityKind::GroovyProperty)
            .expect("maxLoginAttempts not extracted");
        assert_eq!(max_login.docstring, None);
    }

    #[test]
    fn test_groovy_fqn_with_package() {
        let source = "package com.acme.app\nclass MyService { String greet(String name) { name } }";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");

        let class_entity = entities
            .iter()
            .find(|e| e.name == "MyService")
            .expect("MyService class not extracted");
        assert_eq!(class_entity.fqn, "com.acme.app.MyService");

        let method_entity = entities
            .iter()
            .find(|e| e.name == "greet")
            .expect("greet method not extracted");
        assert_eq!(method_entity.fqn, "com.acme.app.MyService.greet");
        assert_eq!(method_entity.enclosing_class.as_deref(), Some("MyService"));
    }

    #[test]
    fn test_groovy_method_parent_class() {
        let source = "class Calculator {\n  int add(int a, int b) { a + b }\n  def multiply(int x, int y) { x * y }\n}";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");

        let add_method = entities
            .iter()
            .find(|e| e.name == "add")
            .expect("add method not extracted");
        assert_eq!(add_method.enclosing_class.as_deref(), Some("Calculator"));
        assert_eq!(add_method.fqn, "Calculator.add");

        let multiply_method = entities
            .iter()
            .find(|e| e.name == "multiply")
            .expect("multiply method not extracted");
        assert_eq!(
            multiply_method.enclosing_class.as_deref(),
            Some("Calculator")
        );
        assert_eq!(multiply_method.fqn, "Calculator.multiply");
    }

    #[test]
    fn test_groovy_interface_method_has_parent() {
        let source = "interface Repository {\n  String findById(String id)\n}";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");

        let method = entities
            .iter()
            .find(|e| e.name == "findById")
            .expect("findById not extracted");
        assert_eq!(method.enclosing_class.as_deref(), Some("Repository"));
    }

    #[test]
    fn test_groovy_nested_scope_tracking() {
        let source = "class Outer {\n  class Inner {\n    String getValue() { 'val' }\n  }\n}";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");

        let outer = entities
            .iter()
            .find(|e| e.name == "Outer")
            .expect("Outer class not extracted");
        assert_eq!(outer.kind, EntityKind::GroovyClass);

        let inner = entities
            .iter()
            .find(|e| e.name == "Inner")
            .expect("Inner class not extracted");
        assert_eq!(inner.kind, EntityKind::GroovyClass);

        let method = entities
            .iter()
            .find(|e| e.name == "getValue")
            .expect("getValue method not extracted");
        assert_eq!(method.enclosing_class.as_deref(), Some("Inner"));
        assert_eq!(method.fqn, "Inner.getValue");
    }

    #[test]
    fn test_groovy_trait_method_has_parent() {
        let source = "trait Auditable {\n  def logAction(String msg) { println msg }\n}";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");

        let method = entities
            .iter()
            .find(|e| e.name == "logAction")
            .expect("logAction not extracted");
        assert_eq!(method.enclosing_class.as_deref(), Some("Auditable"));
        assert_eq!(method.fqn, "Auditable.logAction");
    }

    #[test]
    fn test_groovy_resilience_empty_file() {
        let entities = extract_entities_groovy("", "test.groovy", "test-repo");
        assert!(entities.is_empty());
    }

    #[test]
    fn test_groovy_resilience_malformed() {
        let source = "garbage {{{ // not valid groovy\nclass ";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        // Should not panic, just return what it can (likely empty)
        assert!(entities.is_empty() || entities.iter().any(|e| e.name == "class"));
    }

    #[test]
    fn test_innermost_assignment_nested_methods() {
        // Replicates code-history-mining UI.groovy pattern:
        // showGrabbingFinishedMessage contains hyperlinkUpdate which calls runAnalyzer.
        // Only hyperlinkUpdate (innermost) should get the reference, NOT the outer container.
        let source = r#"
package com.example

class NestedMethods {
    def showGrabbingFinishedMessage(String message) {
        show(message, new Listener() {
            @Override void hyperlinkUpdate(String event) {
                runAnalyzer("visualize")
            }
        })
    }

    def show(message, Listener listener) {
    }

    private void runAnalyzer(String action) {
        println action
    }
}
"#;
        let entities = extract_entities_groovy(source, "NestedMethods.groovy", "test-repo");

        // hyperlinkUpdate should get the runAnalyzer call
        let hyperlink = entities
            .iter()
            .find(|e| e.name == "hyperlinkUpdate")
            .expect("hyperlinkUpdate not found");
        let hyper_has_run = hyperlink
            .reference_intents
            .iter()
            .any(|r| matches!(r, ReferenceIntent::Call { method, .. } if method == "runAnalyzer"));
        assert!(
            hyper_has_run,
            "hyperlinkUpdate should have CALL to runAnalyzer"
        );

        // showGrabbingFinishedMessage must NOT have the runAnalyzer call
        let outer = entities
            .iter()
            .find(|e| e.name == "showGrabbingFinishedMessage")
            .expect("showGrabbingFinishedMessage not found");
        let outer_has_run = outer
            .reference_intents
            .iter()
            .any(|r| matches!(r, ReferenceIntent::Call { method, .. } if method == "runAnalyzer"));
        assert!(
            !outer_has_run,
            "showGrabbingFinishedMessage should NOT have CALL to runAnalyzer (belongs to hyperlinkUpdate)"
        );
    }

    #[test]
    fn test_groovy_resilience_missing_braces() {
        let source =
            "class Broken {\n  def method1() { }\n  def method2() { }\n// no closing brace";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        // Should extract what it can without panicking
        assert!(entities.iter().any(|e| e.name == "Broken"));
        assert!(entities.iter().any(|e| e.name == "method1"));
        assert!(entities.iter().any(|e| e.name == "method2"));
    }

    // ─────────────────────────────────────────────────────────────────────
    // Group: Groovy inheritance intent extraction (Extends / Implements)
    // ─────────────────────────────────────────────────────────────────────

    #[test]
    fn test_groovy_class_extends() {
        let source = "class Ext1 extends PluginExtensionPoint { }";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        let ext1 = pick_class(&entities, "Ext1");
        assert_extends(&ext1.reference_intents, "PluginExtensionPoint");
        assert!(collect_implements(&ext1.reference_intents).is_empty());
    }

    #[test]
    fn test_groovy_class_implements() {
        let source = "abstract class PluginExtensionPoint implements ExtensionPoint { }";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        let cls = pick_class(&entities, "PluginExtensionPoint");
        assert_implements(&cls.reference_intents, "ExtensionPoint");
        assert!(collect_extends(&cls.reference_intents).is_empty());
    }

    #[test]
    fn test_groovy_class_extends_and_implements_multiple() {
        let source =
            "class OrderService extends BaseService implements Auditable, Serializable { }";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        let cls = pick_class(&entities, "OrderService");
        let extends = collect_extends(&cls.reference_intents);
        let implements = collect_implements(&cls.reference_intents);
        assert_eq!(extends, vec!["BaseService"]);
        assert_eq!(implements.len(), 2);
        assert!(implements.contains(&"Auditable"));
        assert!(implements.contains(&"Serializable"));
    }

    #[test]
    fn test_groovy_extends_with_generics() {
        let source = "class Repo extends AbstractRepo<Order, Long> { }";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        let cls = pick_class(&entities, "Repo");
        assert_extends(&cls.reference_intents, "AbstractRepo");
    }

    #[test]
    fn test_groovy_generic_bound_is_not_extends() {
        let source = "class Box<T extends Comparable> { }";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        let cls = pick_class(&entities, "Box");
        assert!(collect_extends(&cls.reference_intents).is_empty());
        assert!(collect_implements(&cls.reference_intents).is_empty());
    }

    #[test]
    fn test_groovy_interface_extends_multiple() {
        let source = "interface EventBus extends Publisher, Subscriber { }";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        let iface = pick_entity(&entities, "EventBus", EntityKind::GroovyInterface);
        let extends = collect_extends(&iface.reference_intents);
        assert_eq!(extends.len(), 2);
        assert!(extends.contains(&"Publisher"));
        assert!(extends.contains(&"Subscriber"));
        assert!(collect_implements(&iface.reference_intents).is_empty());
    }

    #[test]
    fn test_groovy_trait_implements() {
        let source = "trait Auditable implements Serializable { }";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        let trait_entity = pick_entity(&entities, "Auditable", EntityKind::GroovyTrait);
        let implements = collect_implements(&trait_entity.reference_intents);
        assert_eq!(implements, vec!["Serializable"]);
        assert!(collect_extends(&trait_entity.reference_intents).is_empty());
    }

    #[test]
    fn test_groovy_enum_implements() {
        let source = "enum Status implements Describable { OK, KO }";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        let enum_entity = pick_entity(&entities, "Status", EntityKind::GroovyEnum);
        let implements = collect_implements(&enum_entity.reference_intents);
        assert_eq!(implements, vec!["Describable"]);
    }

    #[test]
    fn test_groovy_extends_qualified_name() {
        let source = "class Foo extends nextflow.plugin.BasePlugin { }";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        let cls = pick_class(&entities, "Foo");
        assert_extends(&cls.reference_intents, "nextflow.plugin.BasePlugin");
    }

    #[test]
    fn test_groovy_extends_multiline_declaration() {
        let source = "class OrderService extends BaseService<Order>\n        implements Auditable, Serializable {\n}";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        let cls = pick_class(&entities, "OrderService");
        let extends = collect_extends(&cls.reference_intents);
        let implements = collect_implements(&cls.reference_intents);
        assert_eq!(extends, vec!["BaseService"]);
        assert_eq!(implements.len(), 2);
        assert!(implements.contains(&"Auditable"));
        assert!(implements.contains(&"Serializable"));
        // The line on the intent must point at the class declaration's start line.
        for intent in &cls.reference_intents {
            match intent {
                ReferenceIntent::Extends { line, .. }
                | ReferenceIntent::Implements { line, .. } => {
                    assert_eq!(*line, cls.start_line);
                }
                _ => {}
            }
        }
    }

    #[test]
    fn test_groovy_class_without_inheritance_has_no_intents() {
        let source = "class Plain { def m() {} }";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        let cls = pick_class(&entities, "Plain");
        assert!(collect_extends(&cls.reference_intents).is_empty());
        assert!(collect_implements(&cls.reference_intents).is_empty());
    }

    #[test]
    fn test_groovy_extends_intent_attached_to_class_not_methods() {
        // Class with extends + a method body that contains a CALL.
        // The Extends intent must hang on the class, not on a method.
        let source = r#"
class Ext1 extends PluginExtensionPoint {
    protected void init(Object session) {
        runAnalyzer("foo")
    }
}
"#;
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        let cls = pick_class(&entities, "Ext1");
        assert_extends(&cls.reference_intents, "PluginExtensionPoint");
        let init = entities
            .iter()
            .find(|e| e.name == "init" && e.kind == EntityKind::GroovyMethod)
            .expect("method 'init' not extracted");
        // The method must NOT inherit its parent's Extends intent.
        assert!(
            !init
                .reference_intents
                .iter()
                .any(|r| matches!(r, ReferenceIntent::Extends { .. })),
            "method 'init' should not receive the class's Extends intent"
        );
        // The method should still have its Call intent intact.
        assert!(
            init.reference_intents.iter().any(
                |r| matches!(r, ReferenceIntent::Call { method, .. } if method == "runAnalyzer")
            ),
            "method 'init' should still have CALL to runAnalyzer"
        );
    }

    #[test]
    fn test_groovy_extends_line_number() {
        let source = "\n\nclass Foo extends Bar {\n}\n";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        let cls = pick_class(&entities, "Foo");
        // The class is declared on line 3 (1-indexed).
        assert_eq!(cls.start_line, 3);
        let extends = collect_extends(&cls.reference_intents);
        assert_eq!(extends, vec!["Bar"]);
        let intent_line = cls
            .reference_intents
            .iter()
            .find_map(|r| match r {
                ReferenceIntent::Extends { line, .. } => Some(*line),
                _ => None,
            })
            .expect("expected Extends intent on Foo");
        assert_eq!(
            intent_line, cls.start_line,
            "Extends intent line must match class declaration line"
        );
    }

    #[test]
    fn test_groovy_extends_ignores_comments() {
        // The commented-out class must NOT produce any intent; only the real class does.
        let source = r#"
// class Fake extends Nope
class Real extends Base {
}
"#;
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        // No Fake entity should exist.
        assert!(
            !entities.iter().any(|e| e.name == "Fake"),
            "Fake should not be extracted from a comment line"
        );
        let cls = pick_class(&entities, "Real");
        assert_extends(&cls.reference_intents, "Base");
    }

    // ─────────────────────────────────────────────────────────────────────
    // Group: GroovyDoc / docstring extraction (extract_preceding_docstring)
    // ─────────────────────────────────────────────────────────────────────

    /// Helper: materialize lines and run the docstring walker against the
    /// 0-based index of the declaration line.
    fn doc_of(source: &str, decl_line_idx: usize) -> Option<String> {
        let lines: Vec<&str> = source.lines().collect();
        extract_preceding_docstring(&lines, decl_line_idx)
    }

    #[test]
    fn test_groovy_docstring_block_comment_adjacent() {
        let source = "/**\n * Channel factory initialization. This method is invoked one and only once\n *\n * @param session The current nextflow session\n */\nabstract protected void init(Session session)\n";
        let doc = doc_of(source, 5).expect("expected docstring for init");
        assert!(doc.contains("Channel factory initialization"));
        assert!(doc.contains("@param session The current nextflow session"));
        assert!(!doc.contains("/**"), "markers must be stripped: {doc:?}");
        assert!(!doc.contains("*/"), "markers must be stripped: {doc:?}");
        assert!(
            !doc.lines().any(|l| l.trim_start().starts_with('*')),
            "leading '*' must be stripped: {doc:?}"
        );
    }

    #[test]
    fn test_groovy_docstring_skips_annotations() {
        // Exact shape of the nextflow `checkInit` case: GroovyDoc, then an
        // annotation, then the declaration.
        let source = "/** doc */\n@PackageScope\nsynchronized void checkInit(Object session) {\n";
        let doc = doc_of(source, 2);
        assert_eq!(doc.as_deref(), Some("doc"));
    }

    #[test]
    fn test_groovy_docstring_skips_multiple_annotations() {
        let source = "/** doc */\n@PackageScope\n@Override\nvoid m() {\n";
        let doc = doc_of(source, 3);
        assert_eq!(doc.as_deref(), Some("doc"));
    }

    #[test]
    fn test_groovy_docstring_line_comments_burst() {
        let source = "// a\n// b\nclass Foo {\n";
        let doc = doc_of(source, 2);
        assert_eq!(doc.as_deref(), Some("a\nb"));
    }

    #[test]
    fn test_groovy_docstring_tolerates_single_blank_line() {
        let source = "/** doc */\n\nvoid m() {\n";
        let doc = doc_of(source, 2);
        assert_eq!(doc.as_deref(), Some("doc"));
    }

    #[test]
    fn test_groovy_docstring_two_blank_lines_breaks() {
        let source = "/** doc */\n\n\nvoid m() {\n";
        let doc = doc_of(source, 3);
        assert_eq!(doc, None);
    }

    #[test]
    fn test_groovy_docstring_none_when_absent() {
        let source = "void other() {\nvoid m() {\n";
        let doc = doc_of(source, 1);
        assert_eq!(doc, None);
    }

    #[test]
    fn test_groovy_docstring_stops_at_import() {
        // License header must never leak into the first class's docstring.
        let source = "/*\n * Licensed under the Apache License\n */\npackage com.example\n\nimport foo.Bar\n\nclass Foo {\n";
        let doc = doc_of(source, 7);
        assert_eq!(doc, None);
    }

    #[test]
    fn test_groovy_docstring_empty_comment_is_none() {
        let source = "/** */\nvoid m() {\n";
        assert_eq!(doc_of(source, 1), None);
        let source2 = "//\nvoid m() {\n";
        assert_eq!(doc_of(source2, 1), None);
    }

    #[test]
    fn test_groovy_docstring_first_line_of_file() {
        let source = "class Foo {\n";
        assert_eq!(doc_of(source, 0), None);
    }

    #[test]
    fn test_groovy_docstring_malformed_block_no_panic() {
        // Orphan `*/` with no visible opener: must not panic, returns None.
        let source = "*/\nclass Foo {\n";
        assert_eq!(doc_of(source, 1), None);
        // Orphan closer further down the file.
        let source2 = "package p\n\n * dangling\n */\nclass Foo {\n";
        assert_eq!(doc_of(source2, 4), None);
    }

    // ─────────────────────────────────────────────────────────────────────
    // Group: docstring wiring into extract_entities_groovy
    // ─────────────────────────────────────────────────────────────────────

    #[test]
    fn test_groovy_class_has_docstring() {
        let source = "/**\n * A service class.\n */\nclass MyService {\n}\n";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        let cls = pick_class(&entities, "MyService");
        assert_eq!(cls.docstring.as_deref(), Some("A service class."));
    }

    #[test]
    fn test_groovy_abstract_method_has_docstring() {
        // Literal fragment of nextflow's PluginExtensionPoint.groovy — the exact
        // regression case: GroovyDoc on an abstract method with no body.
        let source = r#"package nextflow.plugin.extension

abstract class PluginExtensionPoint implements ExtensionPoint {

    private boolean initialised

    /**
     * Channel factory initialization. This method is invoked one and only once
     *
     * @param session The current nextflow session
     */
    abstract protected void init(Session session)
}
"#;
        let entities = extract_entities_groovy(source, "PluginExtensionPoint.groovy", "test-repo");
        let init = pick_entity(&entities, "init", EntityKind::GroovyMethod);
        let doc = init
            .docstring
            .as_deref()
            .expect("init must carry its GroovyDoc");
        assert!(doc.contains("Channel factory initialization"));
        assert!(!doc.contains("/**") && !doc.contains("*/"));
    }

    #[test]
    fn test_groovy_def_method_has_docstring() {
        let source = "class Foo {\n    /** Computes the answer. */\n    def compute() { 42 }\n}\n";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        let m = pick_entity(&entities, "compute", EntityKind::GroovyMethod);
        assert_eq!(m.docstring.as_deref(), Some("Computes the answer."));
    }

    #[test]
    fn test_groovy_property_has_docstring() {
        let source = "class Foo {\n    // The default role\n    String role = \"USER\"\n}\n";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        let prop = pick_entity(&entities, "role", EntityKind::GroovyProperty);
        assert_eq!(prop.docstring.as_deref(), Some("The default role"));
    }

    #[test]
    fn test_groovy_multiline_method_has_docstring() {
        // Multi-line signature (`(` without `)` on the first line): the docstring
        // must be located from the real method start line, not from the line
        // where the parser finished scanning the signature.
        let source = r#"class HttpUtil {
    /**
     * Restart the HTTP server.
     */
    private static SimpleHttpServer restartHttpServer(String id, String webRootPath,
                                                       Closure handler = {null},
                                                       Closure errorListener = {}) {
        new SimpleHttpServer()
    }
}
"#;
        let entities = extract_entities_groovy(source, "HttpUtil.groovy", "test-repo");
        let m = pick_entity(&entities, "restartHttpServer", EntityKind::GroovyMethod);
        assert_eq!(m.docstring.as_deref(), Some("Restart the HTTP server."));
    }

    #[test]
    fn test_groovy_method_without_doc_has_none() {
        // Regression: entities without a preceding comment keep docstring == None.
        let source = "class Foo {\n    int add(int a, int b) { a + b }\n}\n";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        let m = pick_entity(&entities, "add", EntityKind::GroovyMethod);
        assert_eq!(m.docstring, None);
        let cls = pick_class(&entities, "Foo");
        assert_eq!(cls.docstring, None);
    }

    // ─────────────────────────────────────────────────────────────────────
    // Phase 0-3: Groovy property accessors & parser hardening regression
    // ─────────────────────────────────────────────────────────────────────

    const ISESSION_SRC: &str = r#"
package nf

interface ISession {

    /**
     * The folder where the main script is contained
     */
    Path getBaseDir()

    /**
     * The pipeline script name (without parent path)
     */
    String getScriptName()
}
"#;

    const SESSION_SRC: &str = r#"
package nf

class Session implements ISession {

    /**
     * The folder where the main script is contained
     */
    Path baseDir

    /**
     * The pipeline script name (without parent path)
     */
    String scriptName

    void setBaseDir( Path baseDir ) {
        this.baseDir = baseDir
    }
}
"#;

    // --- Phase 0: Regression pinning (RED, fail before implementation) ---

    #[test]
    fn bug_javadoc_body_line_yields_no_entity() {
        let entities = extract_entities_groovy(ISESSION_SRC, "ISession.groovy", "test-repo");
        assert!(
            !entities.iter().any(|e| e.name == "name"),
            "Phantom entity 'name' from Javadoc body line must NOT exist"
        );
        assert!(
            entities
                .iter()
                .any(|e| e.name == "getBaseDir" && e.kind == EntityKind::GroovyMethod),
            "getBaseDir must still be extracted"
        );
        assert!(
            entities
                .iter()
                .any(|e| e.name == "getScriptName" && e.kind == EntityKind::GroovyMethod),
            "getScriptName must still be extracted"
        );
    }

    #[test]
    fn bug_bare_property_is_indexed() {
        let entities = extract_entities_groovy(SESSION_SRC, "Session.groovy", "test-repo");
        let base_dir = entities
            .iter()
            .find(|e| e.name == "baseDir" && e.kind == EntityKind::GroovyProperty);
        assert!(
            base_dir.is_some(),
            "Bare property 'baseDir' must be indexed"
        );
        assert_eq!(
            base_dir.unwrap().fqn,
            "nf.Session.baseDir",
            "FQN should include enclosing class"
        );
    }

    #[test]
    fn bug_property_getter_is_synthesised() {
        let entities = extract_entities_groovy(SESSION_SRC, "Session.groovy", "test-repo");
        let getter = entities.iter().find(|e| {
            e.name == "getBaseDir"
                && e.kind == EntityKind::GroovyMethod
                && e.enclosing_class.as_deref() == Some("Session")
        });
        assert!(
            getter.is_some(),
            "Synthetic getter 'Session.getBaseDir' must exist"
        );
        assert!(
            getter
                .unwrap()
                .signature
                .as_deref()
                .is_some_and(|s| s.contains("synthetic")),
            "Synthetic getter must carry a synthetic marker in its signature"
        );
    }

    #[test]
    fn bug_groovy_scm_query_compiles() {
        let q = tree_sitter::Query::new(
            &tree_sitter_groovy::LANGUAGE.into(),
            include_str!("../../../../queries/groovy.scm"),
        );
        assert!(q.is_ok(), "groovy.scm failed to compile: {:?}", q.err());
    }

    #[test]
    fn groovy_scm_captures_expected_patterns() {
        let q = tree_sitter::Query::new(
            &tree_sitter_groovy::LANGUAGE.into(),
            include_str!("../../../../queries/groovy.scm"),
        )
        .expect("groovy.scm must compile");
        assert!(
            q.pattern_count() >= 12,
            "expected at least 12 patterns, got {}",
            q.pattern_count()
        );
        let required: &[&str] = &[
            "groovy.method.name",
            "groovy.field.name",
            "groovy.class.name",
            "groovy.interface.name",
            "groovy.enum.name",
            "groovy.signature",
        ];
        let capture_names: Vec<String> = q.capture_names().iter().map(|c| c.to_string()).collect();
        for name in required {
            assert!(
                capture_names.iter().any(|c| c == name),
                "capture '{name}' missing from groovy.scm"
            );
        }
    }

    // --- Phase 1: Comment stripping regression ---

    #[test]
    fn javadoc_body_with_parens_is_not_a_method() {
        let entities = extract_entities_groovy(ISESSION_SRC, "ISession.groovy", "test-repo");
        for e in &entities {
            if e.kind == EntityKind::GroovyMethod {
                assert!(
                    !e.signature
                        .as_deref()
                        .is_some_and(|s| s.contains("parent path")),
                    "Javadoc body line '{}' must not be a method entity: {:?}",
                    e.name,
                    e.signature
                );
            }
        }
        // Confirm the real methods are intact
        assert!(
            entities
                .iter()
                .any(|e| e.name == "getBaseDir" && e.kind == EntityKind::GroovyMethod)
        );
        assert!(
            entities
                .iter()
                .any(|e| e.name == "getScriptName" && e.kind == EntityKind::GroovyMethod)
        );
    }

    #[test]
    fn javadoc_body_does_not_shadow_next_declaration() {
        let entities = extract_entities_groovy(SESSION_SRC, "Session.groovy", "test-repo");
        let setter = entities.iter().find(|e| {
            e.name == "setBaseDir"
                && e.kind == EntityKind::GroovyMethod
                && e.enclosing_class.as_deref() == Some("Session")
        });
        assert!(
            setter.is_some(),
            "setBaseDir must be present with enclosing_class=Session"
        );
    }

    #[test]
    fn braces_inside_block_comment_do_not_corrupt_scope() {
        let source = r#"
class MyService {
    /**
     * Example: if (x) { doSomething() }
     */
    String getName() { "svc" }
}
"#;
        let entities = extract_entities_groovy(source, "MyService.groovy", "test-repo");
        let method = entities
            .iter()
            .find(|e| e.name == "getName" && e.kind == EntityKind::GroovyMethod)
            .expect("getName not found");
        assert_eq!(
            method.enclosing_class.as_deref(),
            Some("MyService"),
            "method's enclosing_class must be the class, not None"
        );
    }

    #[test]
    fn single_line_block_comment_does_not_leak() {
        let source = "class Foo { /* note */ void run() {} }";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        assert!(
            entities
                .iter()
                .any(|e| e.name == "Foo" && e.kind == EntityKind::GroovyClass),
            "Foo should be extracted"
        );
    }

    #[test]
    fn trailing_line_comment_is_ignored() {
        let source = "class Foo {\n    Path baseDir // the base dir\n}";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        assert!(
            entities
                .iter()
                .any(|e| e.name == "baseDir" && e.kind == EntityKind::GroovyProperty),
            "baseDir with trailing line comment should be extracted"
        );
    }

    #[test]
    fn unterminated_block_comment_swallows_rest_of_file() {
        let source = "class Foo {\n/**\nPath baseDir\nString name\n}";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        assert!(
            !entities.iter().any(|e| e.name == "baseDir"),
            "entities after unterminated /** should not exist"
        );
        assert!(
            !entities.iter().any(|e| e.name == "name"),
            "entities after unterminated /** should not exist"
        );
    }

    #[test]
    fn strip_comments_line_unit() {
        // Table-driven tests for the comment-stripping helper.
        let cases: &[(&str, bool, &str, bool)] = &[
            // (input, in_block_before, expected_output, in_block_after)
            ("code", false, "code", false),
            ("code // comment", false, "code", false),
            ("/* block */ code", false, "code", false),
            ("/* start", false, "", true),
            ("* mid", true, "", true),
            ("*/ after", true, "after", false),
            ("/** doc */", false, "", false),
            ("  ", false, "", false),
            (
                "x = \"// not a comment\"",
                false,
                "x = \"// not a comment\"",
                false,
            ),
        ];
        for (i, (input, in_before, expected, in_after)) in cases.iter().enumerate() {
            let mut in_block = *in_before;
            let result = strip_comments_line(input, &mut in_block);
            assert_eq!(
                result.trim(),
                *expected,
                "case {i}: strip_comments_line({input:?}, {in_before})"
            );
            assert_eq!(
                in_block, *in_after,
                "case {i}: in_block after strip_comments_line"
            );
        }
    }

    // --- Phase 2: Bare property declarations ---

    #[test]
    fn bare_typed_property_is_extracted() {
        let source = "class Session {\n    Path baseDir\n}";
        let entities = extract_entities_groovy(source, "Session.groovy", "test-repo");
        let prop = pick_entity(&entities, "baseDir", EntityKind::GroovyProperty);
        assert_eq!(prop.enclosing_class.as_deref(), Some("Session"));
        assert_eq!(prop.fqn, "Session.baseDir");
    }

    #[test]
    fn generic_typed_property_is_extracted() {
        let source = "class Session {\n    Map<String,Object> config\n}";
        let entities = extract_entities_groovy(source, "Session.groovy", "test-repo");
        assert!(
            entities
                .iter()
                .any(|e| e.name == "config" && e.kind == EntityKind::GroovyProperty),
            "generic property 'config' not found"
        );
    }

    #[test]
    fn def_property_is_extracted() {
        let source = "class Session {\n    def anything\n}";
        let entities = extract_entities_groovy(source, "Session.groovy", "test-repo");
        assert!(
            entities
                .iter()
                .any(|e| e.name == "anything" && e.kind == EntityKind::GroovyProperty),
            "def property 'anything' not found"
        );
    }

    #[test]
    fn modifier_prefixed_property_is_extracted() {
        let source = "class Session {\n    private static final Path ROOT\n}";
        let entities = extract_entities_groovy(source, "Session.groovy", "test-repo");
        assert!(
            entities
                .iter()
                .any(|e| e.name == "ROOT" && e.kind == EntityKind::GroovyProperty),
            "modifier-prefixed property 'ROOT' not found"
        );
    }

    #[test]
    fn java_style_semicolon_field_is_extracted() {
        let source = "class Session {\n    private int count;\n}";
        let entities = extract_entities_groovy(source, "Session.groovy", "test-repo");
        assert!(
            entities
                .iter()
                .any(|e| e.name == "count" && e.kind == EntityKind::GroovyProperty),
            "semicolon field 'count' not found"
        );
    }

    #[test]
    fn initialized_property_still_extracted() {
        let source = "class Foo { String name = 'test' }";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        assert!(
            entities
                .iter()
                .any(|e| e.name == "name" && e.kind == EntityKind::GroovyProperty),
            "initialized property 'name' not found"
        );
    }

    #[test]
    fn local_variable_inside_method_is_not_a_property() {
        let source = "class Foo { void m() { Path tmp\n } }";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        assert!(
            !entities.iter().any(|e| e.name == "tmp"),
            "local variable 'tmp' inside method must NOT be a property"
        );
    }

    #[test]
    fn return_statement_is_not_a_property() {
        let source = "class Foo { void m() { return baseDir } }";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        assert!(
            !entities.iter().any(|e| e.name == "return"),
            "'return' must not be a property"
        );
    }

    #[test]
    fn import_and_package_lines_are_not_properties() {
        let source = "package com.foo\nimport java.nio.Path\nclass Foo { }";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        // import/java/nio/Path should not be properties
        assert!(
            !entities
                .iter()
                .any(|e| e.name == "Path" && e.kind == EntityKind::GroovyProperty),
            "'Path' from import must not be a property"
        );
    }

    #[test]
    fn type_declaration_line_is_not_a_property() {
        let source = "class Session implements ISession { String name }";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        // class/Session/implements/ISession should not be properties
        assert!(
            !entities
                .iter()
                .any(|e| e.name == "Session" && e.kind == EntityKind::GroovyProperty),
            "class name must not be misclassified as property"
        );
    }

    #[test]
    fn script_level_bare_identifier_is_not_a_property() {
        let source = "println";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        assert!(
            !entities
                .iter()
                .any(|e| e.name == "println" && e.kind == EntityKind::GroovyProperty),
            "single token 'println' must not be a property"
        );
    }

    // --- Phase 3: Synthetic accessor entities ---

    #[test]
    fn property_generates_getter_and_setter() {
        let source = "class Session {\n    Path baseDir\n}";
        let entities = extract_entities_groovy(source, "Session.groovy", "test-repo");
        let getter = entities.iter().find(|e| {
            e.name == "getBaseDir"
                && e.kind == EntityKind::GroovyMethod
                && e.enclosing_class.as_deref() == Some("Session")
        });
        assert!(getter.is_some(), "getter 'getBaseDir' must be synthesised");
        let setter = entities.iter().find(|e| {
            e.name == "setBaseDir"
                && e.kind == EntityKind::GroovyMethod
                && e.enclosing_class.as_deref() == Some("Session")
        });
        assert!(setter.is_some(), "setter 'setBaseDir' must be synthesised");
    }

    #[test]
    fn boolean_property_generates_is_and_get() {
        let source = "class Session {\n    boolean cacheable\n}";
        let entities = extract_entities_groovy(source, "Session.groovy", "test-repo");
        assert!(
            entities.iter().any(|e| {
                e.name == "isCacheable"
                    && e.kind == EntityKind::GroovyMethod
                    && e.enclosing_class.as_deref() == Some("Session")
            }),
            "boolean is-accessor not synthesised"
        );
        assert!(
            entities.iter().any(|e| {
                e.name == "getCacheable"
                    && e.kind == EntityKind::GroovyMethod
                    && e.enclosing_class.as_deref() == Some("Session")
            }),
            "boolean getter not synthesised"
        );
    }

    #[test]
    fn boxed_boolean_property_generates_is_and_get() {
        let source = "class Session {\n    Boolean resumeMode\n}";
        let entities = extract_entities_groovy(source, "Session.groovy", "test-repo");
        assert!(
            entities.iter().any(|e| e.name == "isResumeMode"),
            "Boolean is-accessor not synthesised"
        );
        assert!(
            entities.iter().any(|e| e.name == "getResumeMode"),
            "Boolean getter not synthesised"
        );
    }

    #[test]
    fn final_property_generates_getter_only() {
        let source = "class Session {\n    final Path root\n}";
        let entities = extract_entities_groovy(source, "Session.groovy", "test-repo");
        assert!(
            entities
                .iter()
                .any(|e| e.name == "getRoot" && e.kind == EntityKind::GroovyMethod),
            "final property must have getter"
        );
        assert!(
            !entities
                .iter()
                .any(|e| e.name == "setRoot" && e.kind == EntityKind::GroovyMethod),
            "final property must NOT have setter"
        );
    }

    #[test]
    fn explicit_setter_suppresses_synthetic_setter() {
        let entities = extract_entities_groovy(SESSION_SRC, "Session.groovy", "test-repo");
        let setters: Vec<_> = entities
            .iter()
            .filter(|e| e.name == "setBaseDir" && e.kind == EntityKind::GroovyMethod)
            .collect();
        assert_eq!(
            setters.len(),
            1,
            "must be exactly one setBaseDir, got {}",
            setters.len()
        );
        let s = setters[0];
        assert!(
            !s.signature
                .as_deref()
                .is_some_and(|sig| sig.contains("synthetic")),
            "the setBaseDir must be the real one, not synthetic"
        );
    }

    #[test]
    fn explicit_getter_suppresses_synthetic_getter() {
        let source = r#"
class Session {
    Path baseDir
    Path getBaseDir() { baseDir }
}
"#;
        let entities = extract_entities_groovy(source, "Session.groovy", "test-repo");
        let getters: Vec<_> = entities
            .iter()
            .filter(|e| e.name == "getBaseDir" && e.kind == EntityKind::GroovyMethod)
            .collect();
        assert_eq!(getters.len(), 1, "exactly one getBaseDir expected");
    }

    #[test]
    fn interface_constant_generates_no_accessor() {
        let source = "interface I { String NAME }";
        let entities = extract_entities_groovy(source, "I.groovy", "test-repo");
        assert!(
            !entities.iter().any(|e| e.name == "getNAME"),
            "interface constants must not generate accessors"
        );
    }

    #[test]
    fn script_level_variable_generates_no_accessor() {
        let source = "def globalConfig = [:]";
        let entities = extract_entities_groovy(source, "script.groovy", "test-repo");
        assert!(
            !entities.iter().any(|e| e.name == "getGlobalConfig"),
            "script-level variable must not generate accessor"
        );
    }

    #[test]
    fn synthetic_accessor_metadata() {
        let entities = extract_entities_groovy(SESSION_SRC, "Session.groovy", "test-repo");
        let getter = entities
            .iter()
            .find(|e| {
                e.name == "getBaseDir"
                    && e.kind == EntityKind::GroovyMethod
                    && e.signature
                        .as_deref()
                        .is_some_and(|s| s.contains("synthetic"))
            })
            .expect("synthetic getter not found");
        let prop = entities
            .iter()
            .find(|e| e.name == "baseDir" && e.kind == EntityKind::GroovyProperty)
            .expect("baseDir property not found");
        assert_eq!(
            getter.enclosing_class.as_deref(),
            Some("Session"),
            "synthetic getter must have enclosing class"
        );
        assert_eq!(
            getter.start_line, prop.start_line,
            "synthetic getter must share property's start_line"
        );
    }

    #[test]
    fn synthetic_accessor_uuid_is_distinct() {
        let entities = extract_entities_groovy(SESSION_SRC, "Session.groovy", "test-repo");
        let getter = entities
            .iter()
            .find(|e| {
                e.name == "getBaseDir"
                    && e.kind == EntityKind::GroovyMethod
                    && e.signature
                        .as_deref()
                        .is_some_and(|s| s.contains("synthetic"))
            })
            .expect("synthetic getter not found");
        let prop = entities
            .iter()
            .find(|e| e.name == "baseDir" && e.kind == EntityKind::GroovyProperty)
            .expect("baseDir property not found");
        assert_ne!(
            getter.uuid, prop.uuid,
            "synthetic getter UUID must be distinct from property UUID"
        );
    }

    #[test]
    fn synthetic_accessors_have_no_reference_intents() {
        let entities = extract_entities_groovy(SESSION_SRC, "Session.groovy", "test-repo");
        for e in entities.iter().filter(|e| {
            e.kind == EntityKind::GroovyMethod
                && e.signature
                    .as_deref()
                    .is_some_and(|s| s.contains("synthetic"))
        }) {
            assert!(
                e.reference_intents.is_empty(),
                "synthetic accessor '{}' must have no reference intents",
                e.name
            );
        }
    }

    #[test]
    fn url_string_with_double_slash_is_tolerated() {
        // Pinning test: current comment stripping may handle this imperfectly.
        // This test records behaviour — it must not panic.
        let source = "class Foo {\n    String url = \"https://example.com/path\"\n}";
        let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
        assert!(
            entities
                .iter()
                .any(|e| e.name == "url" && e.kind == EntityKind::GroovyProperty),
            "url property should still be extracted"
        );
    }
}

#[test]
fn test_all_typed_methods_no_duplication() {
    // Both methods typed → tree-sitter finds both, ad-hoc must NOT duplicate (Fix 3: known_lines)
    let source = r#"
class HttpUtil {
    private static void restartHttpServer() {
        println "hello"
    }
    void loadIntoHttpServer(String html) {
        restartHttpServer()
    }
}
"#;
    let entities = extract_entities_groovy(source, "HttpUtil.groovy", "test-repo");
    let r_count = entities
        .iter()
        .filter(|e| e.name == "restartHttpServer")
        .count();
    let l_count = entities
        .iter()
        .filter(|e| e.name == "loadIntoHttpServer")
        .count();
    assert_eq!(r_count, 1, "restartHttpServer duplicated");
    assert_eq!(l_count, 1, "loadIntoHttpServer duplicated");
}

#[test]
fn test_def_methods_call_typed_private_method() {
    // Simulates LLM scenario: def method calling private typed method
    let source = r#"
class HttpUtil {
    private static void restartHttpServer() {
        println "hello"
    }
    def loadIntoHttpServer(String html) {
        restartHttpServer()
    }
}
"#;
    let entities = extract_entities_groovy(source, "HttpUtil.groovy", "test-repo");
    let load = entities.iter().find(|e| e.name == "loadIntoHttpServer");
    assert!(load.is_some(), "loadIntoHttpServer not found");
    let load = load.unwrap();
    let calls_to_restart = load
        .reference_intents
        .iter()
        .filter(
            |r| matches!(r, ReferenceIntent::Call { method, .. } if method == "restartHttpServer"),
        )
        .count();
    assert!(
        calls_to_restart > 0,
        "Expected def method to have CALL to restartHttpServer"
    );
}

#[test]
fn test_no_paren_call_detection() {
    // Fix 2: Groovy no-paren call style: runAnalyzer "abc", 123 and doSomething arg1
    let source = r#"
class Worker {
    void process() {
        runAnalyzer "abc", 123
        doSomething result
        println "hello"
    }
}
"#;
    let entities = extract_entities_groovy(source, "Worker.groovy", "test-repo");
    let process = entities
        .iter()
        .find(|e| e.name == "process")
        .expect("process not found");
    let refs: Vec<String> = process
        .reference_intents
        .iter()
        .map(|r| match r {
            ReferenceIntent::Call {
                method,
                receiver,
                line,
                arg_count: _,
            } => format!(
                "Call({}{}, line {})",
                receiver
                    .as_ref()
                    .map(|r| format!("{}.", r))
                    .unwrap_or_default(),
                method,
                line
            ),
            _ => format!("{:?}", r),
        })
        .collect();
    eprintln!("process reference_intents: {:?}", refs);

    // runAnalyzer "abc", 123 — no-paren call with string arg
    let has_run = process
        .reference_intents
        .iter()
        .any(|r| matches!(r, ReferenceIntent::Call { method, .. } if method == "runAnalyzer"));
    assert!(has_run);

    // doSomething result — no-paren call with identifier arg
    let has_do = process
        .reference_intents
        .iter()
        .any(|r| matches!(r, ReferenceIntent::Call { method, .. } if method == "doSomething"));
    assert!(has_do);

    // println — must NOT be captured (it's a keyword)
    let has_println = process
        .reference_intents
        .iter()
        .any(|r| matches!(r, ReferenceIntent::Call { method, .. } if method == "println"));
    assert!(!has_println);
}

#[test]
fn test_private_method_with_closure_args_is_callable() {
    // Replicates exact pattern from HttpUtil.groovy in code-history-mining:
    // private static method with closure args, called from a public static method
    let source = r#"
package test
import com.example.SimpleHttpServer
class HttpUtil {
    static String loadIntoHttpServer(String html) {
        def server = restartHttpServer("web", "/tmp", {null}, {log?.errorOnHttpRequest(it.toString())})
        "http://localhost"
    }

    private static SimpleHttpServer restartHttpServer(String id, String webRootPath,
                                                       Closure handler = {null},
                                                       Closure errorListener = {}) {
        def server = new SimpleHttpServer()
        server
    }
}
"#;
    let entities = extract_entities_groovy(source, "HttpUtil.groovy", "test-repo");

    let load = entities.iter().find(|e| e.name == "loadIntoHttpServer");
    assert!(load.is_some(), "loadIntoHttpServer not found");
    let load = load.unwrap();
    assert_eq!(
        load.enclosing_class.as_deref(),
        Some("HttpUtil"),
        "loadIntoHttpServer should have enclosing_class HttpUtil"
    );
    assert!(
        !load.fqn.is_empty(),
        "loadIntoHttpServer should have non-empty FQN, got: '{}'",
        load.fqn
    );

    let calls_restart = load
        .reference_intents
        .iter()
        .filter(
            |r| matches!(r, ReferenceIntent::Call { method, .. } if method == "restartHttpServer"),
        )
        .count();
    assert!(
        calls_restart > 0,
        "Expected loadIntoHttpServer to have CALL to restartHttpServer, but found {} call(s). refs: {:?}",
        calls_restart,
        load.reference_intents
            .iter()
            .filter_map(|r| match r {
                ReferenceIntent::Call { method, line, .. } => Some(format!("{}@L{}", method, line)),
                _ => None,
            })
            .collect::<Vec<_>>()
    );

    let restart = entities.iter().find(|e| e.name == "restartHttpServer");
    assert!(restart.is_some(), "restartHttpServer not found in entities");
    let restart = restart.unwrap();
    assert_eq!(
        restart.enclosing_class.as_deref(),
        Some("HttpUtil"),
        "restartHttpServer should have enclosing_class HttpUtil"
    );
    assert!(
        !restart.fqn.is_empty(),
        "restartHttpServer should have non-empty FQN, got: '{}'",
        restart.fqn
    );
    assert!(
        restart.enclosing_class.is_some(),
        "restartHttpServer should have enclosing_class set"
    );
}

#[test]
fn test_new_constructor_not_method_declaration() {
    // `new File(...).write(...)` and `new SimpleHttpServer()` are constructor calls,
    // NOT method declarations. They should not create spurious method entities.
    let source = r#"
class HttpUtil {
    static String loadIntoHttpServer(String html) {
        def tempDir = FileUtil.createTempDirectory("proj", "")
        new File("path").write(html)
        def server = restartHttpServer("web", "/tmp", {null}, {log?.errorOnHttpRequest(it.toString())})
        "http://localhost"
    }
    private static SimpleHttpServer restartHttpServer(String id, String webRootPath,
                                                       Closure handler = {null},
                                                       Closure errorListener = {}) {
        def server = new SimpleHttpServer()
        server
    }
}
"#;
    let entities = extract_entities_groovy(source, "HttpUtil.groovy", "test-repo");

    // `File` must NOT appear as a method entity
    assert!(
        !entities
            .iter()
            .any(|e| e.kind == EntityKind::GroovyMethod && e.name == "File"),
        "new File(...) was incorrectly extracted as a method declaration"
    );

    // `SimpleHttpServer` constructor call inside method body must NOT appear as method
    // (allow the one at the return type position in the private method signature via multi-line though)
    let ssh_methods: Vec<_> = entities
        .iter()
        .filter(|e| e.kind == EntityKind::GroovyMethod && e.name == "SimpleHttpServer")
        .collect();
    assert!(
        ssh_methods.len() <= 1,
        "new SimpleHttpServer() constructor should not create method entities, found {}: {:?}",
        ssh_methods.len(),
        ssh_methods.iter().map(|e| e.start_line).collect::<Vec<_>>()
    );

    // restartHttpServer should be callable from loadIntoHttpServer
    let load = entities
        .iter()
        .find(|e| e.name == "loadIntoHttpServer")
        .expect("loadIntoHttpServer not found");
    let calls_restart = load
        .reference_intents
        .iter()
        .filter(
            |r| matches!(r, ReferenceIntent::Call { method, .. } if method == "restartHttpServer"),
        )
        .count();
    assert!(
        calls_restart > 0,
        "loadIntoHttpServer should call restartHttpServer"
    );
}