tldr-core 0.1.6

Core analysis engine for TLDR code analysis tool
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
//! Reference Finding Core Types and Functions
//!
//! This module provides reference finding for the `references` CLI command.
//!
//! # Type Overview
//!
//! - [`ReferencesReport`]: Complete reference finding report
//! - [`Reference`]: A single reference to a symbol
//! - [`Definition`]: Location where symbol is defined
//! - [`DefinitionKind`]: Kind of definition (function, class, variable, etc.)
//! - [`ReferenceKind`]: Kind of reference (call, read, write, import, type)
//! - [`SearchScope`]: Search scope for reference finding
//! - [`ReferenceStats`]: Search statistics
//! - [`ReferencesOptions`]: Configuration for reference finding
//! - [`TextCandidate`]: Candidate match from text search (Phase 9)
//!
//! # Risk Mitigations
//!
//! - S7-R17: Reference context truncation - limit context to 200 chars
//! - S7-R38: Line numbers - ensure 1-indexed throughout
//! - S7-R9: Memory usage - read one file at a time, don't load all (Phase 9)
//! - S7-R10: Regex compilation per file - compile once, reuse (Phase 9)
//! - S7-R4: Unicode position mapping - use byte offsets consistently (Phase 9, 10)
//! - S7-R5: Method call classification - check grandparent for call expression (Phase 10)
//! - S7-R6: Multi-match same line - verify each match independently (Phase 10)
//! - S7-R12: Re-parsing files - group candidates by file, parse once per file (Phase 10)
//! - S7-R22: f-string interpolation - handle formatted_string AST node (Phase 10)
//! - S7-R48: String matches - check AST node type is identifier, not string_literal (Phase 10)
//!
//! # References
//!
//! - Spec: session7-spec.md section 2.2 (Type Definitions)
//! - Phased plan: session7-phased-plan.yaml Phase 8, 9, 10

use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use tree_sitter::Node;
use walkdir::WalkDir;

use crate::ast::parser::parse_file;
use crate::security::ast_utils;
use crate::types::Language;
use crate::TldrResult;

// =============================================================================
// Core Types
// =============================================================================

/// Maximum context line length before truncation (S7-R17)
const MAX_CONTEXT_LENGTH: usize = 200;

/// Complete reference finding report
///
/// Contains all information about references to a symbol including
/// the definition location, all references found, and search statistics.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ReferencesReport {
    /// Symbol that was searched for
    pub symbol: String,

    /// Definition location (if found)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub definition: Option<Definition>,

    /// All references found
    pub references: Vec<Reference>,

    /// Total number of references
    pub total_references: usize,

    /// Search scope used
    pub search_scope: SearchScope,

    /// Search statistics
    pub stats: ReferenceStats,
}

impl ReferencesReport {
    /// Create a new empty report for a symbol
    pub fn new(symbol: String) -> Self {
        Self {
            symbol,
            ..Default::default()
        }
    }

    /// Create a report with no matches found
    pub fn no_matches(symbol: String, scope: SearchScope, stats: ReferenceStats) -> Self {
        Self {
            symbol,
            definition: None,
            references: Vec::new(),
            total_references: 0,
            search_scope: scope,
            stats,
        }
    }
}

/// Location where symbol is defined
///
/// Contains file path, position (1-indexed), kind, and optional signature.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Definition {
    /// File containing the definition
    pub file: PathBuf,

    /// Line number (1-indexed, S7-R38)
    pub line: usize,

    /// Column number (1-indexed, S7-R38)
    pub column: usize,

    /// Kind of definition
    pub kind: DefinitionKind,

    /// Function/class signature if applicable
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub signature: Option<String>,
}

impl Definition {
    /// Create a new definition with minimal information
    pub fn new(file: PathBuf, line: usize, column: usize, kind: DefinitionKind) -> Self {
        Self {
            file,
            line,
            column,
            kind,
            signature: None,
        }
    }

    /// Create a definition with signature
    pub fn with_signature(
        file: PathBuf,
        line: usize,
        column: usize,
        kind: DefinitionKind,
        signature: String,
    ) -> Self {
        Self {
            file,
            line,
            column,
            kind,
            signature: Some(signature),
        }
    }
}

/// Kind of definition
///
/// Categorizes what type of construct the definition is.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash, Default)]
#[serde(rename_all = "lowercase")]
pub enum DefinitionKind {
    /// Function definition
    Function,

    /// Class definition
    Class,

    /// Variable definition
    Variable,

    /// Constant definition
    Constant,

    /// Type alias or type definition
    Type,

    /// Module definition
    Module,

    /// Method definition (function in a class)
    Method,

    /// Property or field definition
    Property,

    /// Unknown or other kind
    #[default]
    Other,
}

impl DefinitionKind {
    /// Get a human-readable string representation
    pub fn as_str(&self) -> &'static str {
        match self {
            DefinitionKind::Function => "function",
            DefinitionKind::Class => "class",
            DefinitionKind::Variable => "variable",
            DefinitionKind::Constant => "constant",
            DefinitionKind::Type => "type",
            DefinitionKind::Module => "module",
            DefinitionKind::Method => "method",
            DefinitionKind::Property => "property",
            DefinitionKind::Other => "other",
        }
    }
}

impl std::fmt::Display for DefinitionKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// A single reference to the symbol
///
/// Contains file path, position (1-indexed), kind, and context.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Reference {
    /// File containing the reference
    pub file: PathBuf,

    /// Line number (1-indexed, S7-R38)
    pub line: usize,

    /// Column number (1-indexed, S7-R38)
    pub column: usize,

    /// Kind of reference
    pub kind: ReferenceKind,

    /// Line of code containing the reference (context)
    /// Truncated to MAX_CONTEXT_LENGTH (S7-R17)
    pub context: String,

    /// Confidence of this being a true reference (0.0 - 1.0)
    /// 1.0 = verified by AST, lower = text match only
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub confidence: Option<f64>,

    /// End column for highlighting (optional)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub end_column: Option<usize>,
}

impl Reference {
    /// Create a new reference with minimal information
    pub fn new(
        file: PathBuf,
        line: usize,
        column: usize,
        kind: ReferenceKind,
        context: String,
    ) -> Self {
        Self {
            file,
            line,
            column,
            kind,
            context: truncate_context(context),
            confidence: None,
            end_column: None,
        }
    }

    /// Create a reference with full information
    pub fn with_details(
        file: PathBuf,
        line: usize,
        column: usize,
        end_column: usize,
        kind: ReferenceKind,
        context: String,
        confidence: f64,
    ) -> Self {
        Self {
            file,
            line,
            column,
            kind,
            context: truncate_context(context),
            confidence: Some(confidence),
            end_column: Some(end_column),
        }
    }

    /// Create a reference verified by AST (confidence = 1.0)
    pub fn verified(
        file: PathBuf,
        line: usize,
        column: usize,
        kind: ReferenceKind,
        context: String,
    ) -> Self {
        Self {
            file,
            line,
            column,
            kind,
            context: truncate_context(context),
            confidence: Some(1.0),
            end_column: None,
        }
    }
}

/// Truncate context to MAX_CONTEXT_LENGTH (S7-R17)
fn truncate_context(context: String) -> String {
    if context.len() > MAX_CONTEXT_LENGTH {
        let truncated: String = context.chars().take(MAX_CONTEXT_LENGTH - 3).collect();
        format!("{}...", truncated)
    } else {
        context
    }
}

/// Kind of reference
///
/// Categorizes how the symbol is being used at this reference site.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash, Default)]
#[serde(rename_all = "lowercase")]
pub enum ReferenceKind {
    /// Function/method invocation
    Call,

    /// Variable read
    Read,

    /// Variable assignment/write
    Write,

    /// Import statement
    Import,

    /// Type annotation
    Type,

    /// Definition site itself
    Definition,

    /// Unknown or other kind
    #[default]
    Other,
}

impl ReferenceKind {
    /// Get a human-readable string representation
    pub fn as_str(&self) -> &'static str {
        match self {
            ReferenceKind::Call => "call",
            ReferenceKind::Read => "read",
            ReferenceKind::Write => "write",
            ReferenceKind::Import => "import",
            ReferenceKind::Type => "type",
            ReferenceKind::Definition => "definition",
            ReferenceKind::Other => "other",
        }
    }

    /// Parse from string (case-insensitive)
    pub fn parse(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "call" => Some(ReferenceKind::Call),
            "read" => Some(ReferenceKind::Read),
            "write" => Some(ReferenceKind::Write),
            "import" => Some(ReferenceKind::Import),
            "type" => Some(ReferenceKind::Type),
            "definition" => Some(ReferenceKind::Definition),
            "other" => Some(ReferenceKind::Other),
            _ => None,
        }
    }
}

impl std::fmt::Display for ReferenceKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// Search scope for reference finding
///
/// Controls how much of the workspace is searched for references.
/// Used for optimization based on symbol visibility.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash, Default)]
#[serde(rename_all = "lowercase")]
pub enum SearchScope {
    /// Search only within the current function (local variables)
    Local,

    /// Search only within the current file (private items)
    File,

    /// Search entire workspace (public items)
    #[default]
    Workspace,
}

impl SearchScope {
    /// Get a human-readable string representation
    pub fn as_str(&self) -> &'static str {
        match self {
            SearchScope::Local => "local",
            SearchScope::File => "file",
            SearchScope::Workspace => "workspace",
        }
    }

    /// Parse from string (case-insensitive)
    pub fn parse(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "local" => Some(SearchScope::Local),
            "file" => Some(SearchScope::File),
            "workspace" => Some(SearchScope::Workspace),
            _ => None,
        }
    }
}

impl std::fmt::Display for SearchScope {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// Search statistics
///
/// Provides information about the search process for debugging
/// and performance analysis.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ReferenceStats {
    /// Number of files searched
    pub files_searched: usize,

    /// Number of text match candidates found (before AST verification)
    pub candidates_found: usize,

    /// Number of verified references (after AST pruning)
    pub verified_references: usize,

    /// Search time in milliseconds
    pub search_time_ms: u64,
}

impl ReferenceStats {
    /// Create stats with counts
    pub fn new(files_searched: usize, candidates_found: usize, verified_references: usize) -> Self {
        Self {
            files_searched,
            candidates_found,
            verified_references,
            search_time_ms: 0,
        }
    }

    /// Set search time
    pub fn with_time(mut self, time_ms: u64) -> Self {
        self.search_time_ms = time_ms;
        self
    }
}

/// Options for reference finding
///
/// Configuration options that control the behavior of reference finding.
#[derive(Debug, Clone, Default)]
pub struct ReferencesOptions {
    /// Include the definition in results
    pub include_definition: bool,

    /// Filter by reference kinds (None = all kinds)
    pub kinds: Option<Vec<ReferenceKind>>,

    /// Search scope (None = infer from symbol)
    pub scope: SearchScope,

    /// Language to analyze (None = auto-detect)
    pub language: Option<String>,

    /// Maximum results to return
    pub limit: Option<usize>,

    /// File containing the symbol definition (helps scope optimization)
    pub definition_file: Option<PathBuf>,

    /// Number of context lines to include
    pub context_lines: usize,
}

impl ReferencesOptions {
    /// Create new default options
    pub fn new() -> Self {
        Self::default()
    }

    /// Include definition in results
    pub fn with_definition(mut self) -> Self {
        self.include_definition = true;
        self
    }

    /// Filter by specific reference kinds
    pub fn with_kinds(mut self, kinds: Vec<ReferenceKind>) -> Self {
        self.kinds = Some(kinds);
        self
    }

    /// Set search scope
    pub fn with_scope(mut self, scope: SearchScope) -> Self {
        self.scope = scope;
        self
    }

    /// Set language
    pub fn with_language(mut self, language: String) -> Self {
        self.language = Some(language);
        self
    }

    /// Set maximum results
    pub fn with_limit(mut self, limit: usize) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Set definition file for scope optimization
    pub fn with_definition_file(mut self, file: PathBuf) -> Self {
        self.definition_file = Some(file);
        self
    }

    /// Set context lines
    pub fn with_context_lines(mut self, lines: usize) -> Self {
        self.context_lines = lines;
        self
    }
}

// =============================================================================
// Phase 9: Text Search for Reference Candidates
// =============================================================================

/// Candidate match from text search (before AST verification)
///
/// These are potential references found by text search that need
/// to be verified using AST parsing in Phase 10.
#[derive(Debug, Clone)]
pub struct TextCandidate {
    /// File containing the candidate match
    pub file: PathBuf,
    /// Line number (1-indexed)
    pub line: usize,
    /// Column number (1-indexed)
    pub column: usize,
    /// End column (1-indexed)
    pub end_column: usize,
    /// The full line text containing the match
    pub line_text: String,
}

impl TextCandidate {
    /// Create a new text candidate
    pub fn new(
        file: PathBuf,
        line: usize,
        column: usize,
        end_column: usize,
        line_text: String,
    ) -> Self {
        Self {
            file,
            line,
            column,
            end_column,
            line_text,
        }
    }
}

/// Find all text occurrences of a symbol (fast, overapproximating)
///
/// This is the first step in the rust-analyzer pattern:
/// "text search to find superset, then prune with semantic resolve"
///
/// # Arguments
///
/// * `symbol` - The symbol name to search for
/// * `root` - The root directory to search in
/// * `language` - Optional language filter (e.g., "python", "typescript")
///
/// # Returns
///
/// A vector of TextCandidate structs representing potential matches.
/// These need to be verified using AST parsing in Phase 10.
///
/// # Risk Mitigations
///
/// - S7-R9: Memory usage - read one file at a time, don't load all
/// - S7-R10: Regex compilation per file - compile once, reuse
pub fn find_text_candidates(
    symbol: &str,
    root: &Path,
    language: Option<&str>,
) -> TldrResult<Vec<TextCandidate>> {
    let mut candidates = Vec::new();

    // Build regex with word boundaries to avoid partial matches
    // e.g., searching for "get" shouldn't match "forget"
    // S7-R10: Compile regex once, reuse for all files
    let pattern = format!(r"\b{}\b", regex::escape(symbol));
    let re = Regex::new(&pattern)?;

    // Walk directory, filter by language extension
    // S7-R9: Files are read one at a time to bound memory usage
    // Skip common non-source directories (matches callgraph/scanner.rs SKIP_DIRECTORIES)
    for entry in WalkDir::new(root)
        .into_iter()
        .filter_entry(|e| {
            if e.file_type().is_dir() {
                let name = e.file_name().to_string_lossy();
                !matches!(
                    name.as_ref(),
                    ".git"
                        | "__pycache__"
                        | "node_modules"
                        | ".tox"
                        | "venv"
                        | ".venv"
                        | "__pypackages__"
                        | ".mypy_cache"
                        | ".pytest_cache"
                        | ".ruff_cache"
                        | "target"
                        | "build"
                        | "dist"
                        | ".next"
                        | ".nuxt"
                        | "vendor"
                        | ".bundle"
                        | "Pods"
                        | ".gradle"
                        | ".idea"
                        | ".vscode"
                        | ".eggs"
                )
            } else {
                true
            }
        })
        .filter_map(|e| e.ok())
        .filter(|e| e.file_type().is_file())
        .filter(|e| is_source_file(e.path(), language))
    {
        let content = match std::fs::read_to_string(entry.path()) {
            Ok(c) => c,
            Err(_) => continue, // Skip files we can't read
        };

        for (line_num, line) in content.lines().enumerate() {
            // Skip comment lines (basic heuristic for common cases)
            if is_comment_line(line, language) {
                continue;
            }

            for mat in re.find_iter(line) {
                candidates.push(TextCandidate {
                    file: entry.path().to_path_buf(),
                    line: line_num + 1,        // 1-indexed (S7-R38)
                    column: mat.start() + 1,   // 1-indexed (S7-R38)
                    end_column: mat.end() + 1, // 1-indexed
                    line_text: line.to_string(),
                });
            }
        }
    }

    Ok(candidates)
}

/// Check if file is a source file for the given language.
///
/// Uses `Language::from_path` to support all 18 languages (Python, TypeScript,
/// JavaScript, Go, Rust, Java, C, C++, Ruby, Kotlin, Swift, C#, Scala, PHP,
/// Lua, Luau, Elixir, OCaml).
fn is_source_file(path: &Path, language: Option<&str>) -> bool {
    match Language::from_path(path) {
        Some(detected) => {
            match language {
                None => true, // No filter — accept any supported language
                Some(lang) => {
                    // Check if detected language matches the requested filter
                    let normalized = lang.to_lowercase();
                    match normalized.as_str() {
                        "python" => matches!(detected, Language::Python),
                        "typescript" => matches!(detected, Language::TypeScript),
                        "javascript" => {
                            matches!(detected, Language::JavaScript | Language::TypeScript)
                        }
                        "go" => matches!(detected, Language::Go),
                        "rust" => matches!(detected, Language::Rust),
                        "java" => matches!(detected, Language::Java),
                        "c" => matches!(detected, Language::C),
                        "cpp" => matches!(detected, Language::Cpp),
                        "csharp" => matches!(detected, Language::CSharp),
                        "kotlin" => matches!(detected, Language::Kotlin),
                        "scala" => matches!(detected, Language::Scala),
                        "swift" => matches!(detected, Language::Swift),
                        "php" => matches!(detected, Language::Php),
                        "ruby" => matches!(detected, Language::Ruby),
                        "lua" => matches!(detected, Language::Lua),
                        "luau" => matches!(detected, Language::Luau),
                        "elixir" => matches!(detected, Language::Elixir),
                        "ocaml" => matches!(detected, Language::Ocaml),
                        _ => false,
                    }
                }
            }
        }
        None => false, // Not a recognized source file
    }
}

/// Basic check if line is a comment (for filtering obvious false positives)
///
/// This is a heuristic to reduce noise from text search. Full comment
/// detection is done in AST verification (Phase 10).
fn is_comment_line(line: &str, language: Option<&str>) -> bool {
    let trimmed = line.trim();

    match language {
        // Hash-style comments: Python, Ruby, PHP, Elixir
        Some("python") | Some("ruby") | Some("elixir") => trimmed.starts_with('#'),
        // PHP also supports // and /* */
        Some("php") => {
            trimmed.starts_with("//")
                || trimmed.starts_with('#')
                || trimmed.starts_with("/*")
                || trimmed.starts_with('*')
        }
        // C-style comments: TypeScript, JavaScript, Go, Rust, Java, C, C++, C#, Kotlin, Scala, Swift
        Some("typescript") | Some("javascript") | Some("go") | Some("rust") | Some("java")
        | Some("c") | Some("cpp") | Some("csharp") | Some("kotlin") | Some("scala")
        | Some("swift") => {
            trimmed.starts_with("//") || trimmed.starts_with("/*") || trimmed.starts_with('*')
        }
        // Lua / Luau: -- comments
        Some("lua") | Some("luau") => trimmed.starts_with("--"),
        // OCaml: (* comments *)
        Some("ocaml") => trimmed.starts_with("(*"),
        // Default: handle all common comment patterns
        None => {
            trimmed.starts_with("//")
                || trimmed.starts_with('#')
                || trimmed.starts_with("/*")
                || trimmed.starts_with('*')
                || trimmed.starts_with("--")
                || trimmed.starts_with("(*")
        }
        _ => false,
    }
}

/// Count source files in a directory for statistics
fn count_source_files(root: &Path, language: Option<&str>) -> usize {
    WalkDir::new(root)
        .into_iter()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_type().is_file())
        .filter(|e| is_source_file(e.path(), language))
        .count()
}

// =============================================================================
// Phase 10: AST Verification and Reference Kind Classification
// =============================================================================

/// Verified reference from AST analysis
///
/// Contains the reference kind determined by AST context and confidence score.
#[derive(Debug, Clone)]
pub struct VerifiedReference {
    /// The determined reference kind
    pub kind: ReferenceKind,
    /// Confidence score (1.0 = fully verified by AST)
    pub confidence: f64,
    /// Whether this is a valid reference (not in string/comment)
    pub is_valid: bool,
}

/// Verify text candidates using AST parsing
///
/// Groups candidates by file, parses each file once, and verifies each
/// candidate against the AST. Returns only valid references with
/// correct kind classification.
///
/// # Risk Mitigations
///
/// - S7-R12: Re-parsing files - group candidates by file, parse once per file
/// - S7-R4: Unicode position mapping - use byte offsets consistently
/// - S7-R48: String matches - check AST node type is identifier, not string_literal
pub fn verify_candidates_with_ast(
    candidates: &[TextCandidate],
    symbol: &str,
    _language_str: Option<&str>,
) -> Vec<(TextCandidate, VerifiedReference)> {
    let mut verified = Vec::new();

    // S7-R12: Group candidates by file to parse each file only once
    let mut by_file: HashMap<PathBuf, Vec<&TextCandidate>> = HashMap::new();
    for candidate in candidates {
        by_file
            .entry(candidate.file.clone())
            .or_default()
            .push(candidate);
    }

    // Process each file
    for (file_path, file_candidates) in by_file {
        // Try to parse the file
        let parsed = match parse_file(&file_path) {
            Ok(p) => p,
            Err(_) => {
                // Parse failed, include candidates as unverified
                for candidate in file_candidates {
                    verified.push((
                        candidate.clone(),
                        VerifiedReference {
                            kind: ReferenceKind::Other,
                            confidence: 0.5, // Text match only
                            is_valid: true,  // Assume valid if we can't verify
                        },
                    ));
                }
                continue;
            }
        };

        let (tree, source, lang) = parsed;
        let source_bytes = source.as_bytes();

        // Verify each candidate in this file
        for candidate in file_candidates {
            if let Some(verified_ref) =
                verify_single_candidate(candidate, symbol, &tree, source_bytes, lang)
            {
                if verified_ref.is_valid {
                    verified.push((candidate.clone(), verified_ref));
                }
                // If not valid (e.g., in string), skip this candidate
            }
        }
    }

    verified
}

/// Verify a single candidate against the AST
///
/// Returns Some(VerifiedReference) if the candidate can be verified,
/// None if verification fails (should not happen normally).
fn verify_single_candidate(
    candidate: &TextCandidate,
    symbol: &str,
    tree: &tree_sitter::Tree,
    source: &[u8],
    language: Language,
) -> Option<VerifiedReference> {
    // Convert 1-indexed line/column to tree-sitter Point (0-indexed)
    let point = tree_sitter::Point::new(candidate.line - 1, candidate.column - 1);

    // Find the smallest node containing this position
    let node = tree.root_node().descendant_for_point_range(point, point)?;

    // Get the text of this node
    let node_text = node.utf8_text(source).ok()?;

    // S7-R48: Check if the node text matches the symbol exactly
    // This filters out partial matches
    if node_text != symbol {
        // The node text doesn't match - might be part of a larger identifier
        // or the position is off. Try to find exact match nearby.
        return find_exact_match_node(&node, symbol, source, language);
    }

    // Check if this node is in an invalid context (string, comment)
    if is_in_invalid_context(&node, language) {
        return Some(VerifiedReference {
            kind: ReferenceKind::Other,
            confidence: 1.0,
            is_valid: false, // In string/comment, not a real reference
        });
    }

    // Classify the reference kind based on AST context
    let kind = classify_reference_kind(&node, source, language);

    Some(VerifiedReference {
        kind,
        confidence: 1.0, // Fully verified by AST
        is_valid: true,
    })
}

/// Try to find the exact match node when position lookup returns a parent node
fn find_exact_match_node(
    node: &Node,
    symbol: &str,
    source: &[u8],
    language: Language,
) -> Option<VerifiedReference> {
    // Check this node and its descendants for exact match
    let mut cursor = node.walk();

    // Check children
    for child in node.children(&mut cursor) {
        if let Ok(text) = child.utf8_text(source) {
            if text == symbol {
                if is_in_invalid_context(&child, language) {
                    return Some(VerifiedReference {
                        kind: ReferenceKind::Other,
                        confidence: 1.0,
                        is_valid: false,
                    });
                }
                let kind = classify_reference_kind(&child, source, language);
                return Some(VerifiedReference {
                    kind,
                    confidence: 1.0,
                    is_valid: true,
                });
            }
        }
    }

    // If no exact match found, return unverified
    Some(VerifiedReference {
        kind: ReferenceKind::Other,
        confidence: 0.5,
        is_valid: true,
    })
}

/// Check if a node is in an invalid context (string literal, comment)
///
/// # Risk Mitigations
///
/// - S7-R48: String matches - check AST node type is identifier, not string_literal
/// - S7-R22: f-string interpolation - handle formatted_string AST node
fn is_in_invalid_context(node: &Node, language: Language) -> bool {
    // Check the node type itself
    let node_kind = node.kind();

    // Common string/comment node types across languages
    let invalid_self_kinds = [
        "string",
        "string_literal",
        "string_content",
        "template_string",
        "raw_string_literal",
        "comment",
        "line_comment",
        "block_comment",
        "heredoc_content",
    ];

    if invalid_self_kinds.contains(&node_kind) {
        return true;
    }

    // Walk up the tree to check ancestors
    let mut current = node.parent();
    while let Some(ancestor) = current {
        let kind = ancestor.kind();

        match language {
            Language::Python => {
                // Python string types
                if matches!(
                    kind,
                    "string" | "string_content" | "concatenated_string" | "comment"
                ) {
                    return true;
                }
                // S7-R22: f-string interpolation is OK - the code inside is real
                // formatted_string contains format_expression which should be verified
                if kind == "string" {
                    // Check if we're NOT inside a format_expression
                    if !is_inside_format_expression(node) {
                        return true;
                    }
                }
            }
            Language::TypeScript | Language::JavaScript => {
                if matches!(
                    kind,
                    "string" | "template_string" | "string_fragment" | "comment"
                ) {
                    // Template literals with ${} expressions are OK
                    if kind == "template_string" && has_template_substitution(&ancestor) {
                        // Check if we're inside the substitution
                        if is_inside_template_substitution(node) {
                            return false;
                        }
                    }
                    return true;
                }
            }
            Language::Go => {
                if matches!(
                    kind,
                    "raw_string_literal" | "interpreted_string_literal" | "comment"
                ) {
                    return true;
                }
            }
            Language::Rust => {
                if matches!(
                    kind,
                    "string_literal" | "raw_string_literal" | "line_comment" | "block_comment"
                ) {
                    return true;
                }
            }
            _ => {
                // Generic check for other languages
                if kind.contains("string") || kind.contains("comment") {
                    return true;
                }
            }
        }

        current = ancestor.parent();
    }

    false
}

/// Check if node is inside a Python f-string format expression
fn is_inside_format_expression(node: &Node) -> bool {
    let mut current = node.parent();
    while let Some(ancestor) = current {
        if ancestor.kind() == "interpolation" || ancestor.kind() == "format_expression" {
            return true;
        }
        if ancestor.kind() == "string" || ancestor.kind() == "concatenated_string" {
            return false; // Hit string boundary without finding format_expression
        }
        current = ancestor.parent();
    }
    false
}

/// Check if a template string has substitutions
fn has_template_substitution(node: &Node) -> bool {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "template_substitution" {
            return true;
        }
    }
    false
}

/// Check if node is inside a template substitution (${...})
fn is_inside_template_substitution(node: &Node) -> bool {
    let mut current = node.parent();
    while let Some(ancestor) = current {
        if ancestor.kind() == "template_substitution" {
            return true;
        }
        if ancestor.kind() == "template_string" {
            return false;
        }
        current = ancestor.parent();
    }
    false
}

/// Classify reference kind based on AST context
///
/// Examines the parent and grandparent nodes to determine how the symbol
/// is being used.
///
/// # Risk Mitigations
///
/// - S7-R5: Method call classification - check grandparent for call expression
pub fn classify_reference_kind(node: &Node, source: &[u8], language: Language) -> ReferenceKind {
    let parent = match node.parent() {
        Some(p) => p,
        None => return ReferenceKind::Other,
    };

    match language {
        Language::Python => classify_python_reference(node, &parent, source),
        Language::TypeScript | Language::JavaScript => {
            classify_typescript_reference(node, &parent, source)
        }
        Language::Go => classify_go_reference(node, &parent, source),
        Language::Rust => classify_rust_reference(node, &parent, source),
        Language::Java => classify_java_reference(node, &parent, source),
        Language::C => classify_c_reference(node, &parent, source),
        Language::Cpp => classify_cpp_reference(node, &parent, source),
        Language::CSharp => classify_csharp_reference(node, &parent, source),
        Language::Kotlin => classify_kotlin_reference(node, &parent, source),
        Language::Scala => classify_scala_reference(node, &parent, source),
        Language::Swift => classify_swift_reference(node, &parent, source),
        Language::Php => classify_php_reference(node, &parent, source),
        Language::Ruby => classify_ruby_reference(node, &parent, source),
        Language::Lua => classify_lua_reference(node, &parent, source),
        Language::Luau => classify_luau_reference(node, &parent, source),
        Language::Elixir => classify_elixir_reference(node, &parent, source),
        Language::Ocaml => classify_ocaml_reference(node, &parent, source),
    }
}

/// Classify Python reference kind
fn classify_python_reference(node: &Node, parent: &Node, _source: &[u8]) -> ReferenceKind {
    let parent_kind = parent.kind();

    match parent_kind {
        // Function/method call: func() or obj.method()
        "call" => ReferenceKind::Call,

        // S7-R5: Check if we're the function being called (not an argument)
        "argument_list" => {
            // We're an argument to a call, likely a Read
            ReferenceKind::Read
        }

        // Assignment: x = value
        "assignment" => {
            // Check if node is on LHS (target) or RHS (value)
            if let Some(left) = parent.child_by_field_name("left") {
                if node_contains(node, &left) {
                    return ReferenceKind::Write;
                }
            }
            ReferenceKind::Read
        }

        // Augmented assignment: x += 1 (both read and write, report as Write)
        "augmented_assignment" => {
            if let Some(left) = parent.child_by_field_name("left") {
                if node_contains(node, &left) {
                    return ReferenceKind::Write;
                }
            }
            ReferenceKind::Read
        }

        // Import statements
        "import_statement" | "import_from_statement" | "dotted_name" | "aliased_import" => {
            // Check if we're actually in an import context
            let mut current = Some(*parent);
            while let Some(ancestor) = current {
                if ancestor.kind() == "import_statement"
                    || ancestor.kind() == "import_from_statement"
                {
                    return ReferenceKind::Import;
                }
                current = ancestor.parent();
            }
            ReferenceKind::Read
        }

        // Type annotations
        "type" | "annotation" | "subscript" => {
            // Check if this is in a type annotation context
            if is_type_context(parent) {
                return ReferenceKind::Type;
            }
            ReferenceKind::Read
        }

        // Function/class definition
        "function_definition" | "class_definition" => {
            // Check if this is the name being defined
            if let Some(name) = parent.child_by_field_name("name") {
                if node.id() == name.id() {
                    return ReferenceKind::Definition;
                }
            }
            ReferenceKind::Read
        }

        // Parameter definition
        "parameter" | "typed_parameter" | "default_parameter" | "typed_default_parameter" => {
            // The parameter name itself is a Definition
            if let Some(name) = parent.child_by_field_name("name") {
                if node.id() == name.id() {
                    return ReferenceKind::Definition;
                }
            }
            // Type annotation in parameter
            if let Some(type_node) = parent.child_by_field_name("type") {
                if node_contains(node, &type_node) {
                    return ReferenceKind::Type;
                }
            }
            ReferenceKind::Read
        }

        // For loop variable
        "for_statement" => {
            if let Some(left) = parent.child_by_field_name("left") {
                if node_contains(node, &left) {
                    return ReferenceKind::Write;
                }
            }
            ReferenceKind::Read
        }

        // Comprehension
        "for_in_clause" => {
            if let Some(left) = parent.child_by_field_name("left") {
                if node_contains(node, &left) {
                    return ReferenceKind::Write;
                }
            }
            ReferenceKind::Read
        }

        // Attribute access: obj.attr - we need to check grandparent for call
        "attribute" => {
            // S7-R5: Check grandparent for call expression
            if let Some(grandparent) = parent.parent() {
                if grandparent.kind() == "call" {
                    // Check if the call's function is this attribute
                    if let Some(func) = grandparent.child_by_field_name("function") {
                        if func.id() == parent.id() {
                            return ReferenceKind::Call;
                        }
                    }
                }
            }
            ReferenceKind::Read
        }

        // Default: assume it's a read
        _ => ReferenceKind::Read,
    }
}

/// Classify TypeScript/JavaScript reference kind
fn classify_typescript_reference(node: &Node, parent: &Node, _source: &[u8]) -> ReferenceKind {
    let parent_kind = parent.kind();

    match parent_kind {
        // Function call
        "call_expression" => {
            if let Some(func) = parent.child_by_field_name("function") {
                if node_contains(node, &func) {
                    return ReferenceKind::Call;
                }
            }
            ReferenceKind::Read
        }

        // Assignment
        "assignment_expression" => {
            if let Some(left) = parent.child_by_field_name("left") {
                if node_contains(node, &left) {
                    return ReferenceKind::Write;
                }
            }
            ReferenceKind::Read
        }

        // Variable declarator: let x = ...
        "variable_declarator" => {
            if let Some(name) = parent.child_by_field_name("name") {
                if node.id() == name.id() {
                    return ReferenceKind::Definition;
                }
            }
            ReferenceKind::Read
        }

        // Import statements
        "import_specifier" | "import_clause" | "namespace_import" => ReferenceKind::Import,

        // Type annotations
        "type_annotation" | "type_identifier" | "generic_type" | "type_arguments" => {
            ReferenceKind::Type
        }

        // Function/class declaration
        "function_declaration" | "class_declaration" | "method_definition" => {
            if let Some(name) = parent.child_by_field_name("name") {
                if node.id() == name.id() {
                    return ReferenceKind::Definition;
                }
            }
            ReferenceKind::Read
        }

        // Member expression: obj.prop - check grandparent for call
        "member_expression" => {
            if let Some(grandparent) = parent.parent() {
                if grandparent.kind() == "call_expression" {
                    if let Some(func) = grandparent.child_by_field_name("function") {
                        if func.id() == parent.id() {
                            return ReferenceKind::Call;
                        }
                    }
                }
            }
            ReferenceKind::Read
        }

        _ => ReferenceKind::Read,
    }
}

/// Classify Go reference kind
fn classify_go_reference(node: &Node, parent: &Node, _source: &[u8]) -> ReferenceKind {
    let parent_kind = parent.kind();

    match parent_kind {
        // Function call
        "call_expression" => {
            if let Some(func) = parent.child_by_field_name("function") {
                if node_contains(node, &func) {
                    return ReferenceKind::Call;
                }
            }
            ReferenceKind::Read
        }

        // Assignment
        "assignment_statement" => {
            if let Some(left) = parent.child_by_field_name("left") {
                if node_contains(node, &left) {
                    return ReferenceKind::Write;
                }
            }
            ReferenceKind::Read
        }

        // Short variable declaration: x := value
        "short_var_declaration" => {
            if let Some(left) = parent.child_by_field_name("left") {
                if node_contains(node, &left) {
                    return ReferenceKind::Definition;
                }
            }
            ReferenceKind::Read
        }

        // Import
        "import_spec" => ReferenceKind::Import,

        // Type reference
        "type_identifier" | "qualified_type" | "pointer_type" | "slice_type" | "array_type" => {
            ReferenceKind::Type
        }

        // Function declaration
        "function_declaration" | "method_declaration" => {
            if let Some(name) = parent.child_by_field_name("name") {
                if node.id() == name.id() {
                    return ReferenceKind::Definition;
                }
            }
            ReferenceKind::Read
        }

        // Selector expression: pkg.Func or obj.Method
        "selector_expression" => {
            if let Some(grandparent) = parent.parent() {
                if grandparent.kind() == "call_expression" {
                    if let Some(func) = grandparent.child_by_field_name("function") {
                        if func.id() == parent.id() {
                            return ReferenceKind::Call;
                        }
                    }
                }
            }
            ReferenceKind::Read
        }

        _ => ReferenceKind::Read,
    }
}

/// Classify Rust reference kind
fn classify_rust_reference(node: &Node, parent: &Node, _source: &[u8]) -> ReferenceKind {
    let parent_kind = parent.kind();

    match parent_kind {
        // Function call
        "call_expression" => {
            if let Some(func) = parent.child_by_field_name("function") {
                if node_contains(node, &func) {
                    return ReferenceKind::Call;
                }
            }
            ReferenceKind::Read
        }

        // Assignment (let with value or reassignment)
        "assignment_expression" => {
            if let Some(left) = parent.child_by_field_name("left") {
                if node_contains(node, &left) {
                    return ReferenceKind::Write;
                }
            }
            ReferenceKind::Read
        }

        // Let binding
        "let_declaration" => {
            if let Some(pattern) = parent.child_by_field_name("pattern") {
                if node_contains(node, &pattern) {
                    return ReferenceKind::Definition;
                }
            }
            ReferenceKind::Read
        }

        // Use declaration (imports)
        "use_declaration" | "use_clause" | "scoped_identifier" => {
            // Check if we're in a use context
            let mut current = Some(*parent);
            while let Some(ancestor) = current {
                if ancestor.kind() == "use_declaration" {
                    return ReferenceKind::Import;
                }
                current = ancestor.parent();
            }
            ReferenceKind::Read
        }

        // Type references
        "type_identifier" | "generic_type" | "scoped_type_identifier" | "reference_type" => {
            ReferenceKind::Type
        }

        // Function definition
        "function_item" => {
            if let Some(name) = parent.child_by_field_name("name") {
                if node.id() == name.id() {
                    return ReferenceKind::Definition;
                }
            }
            ReferenceKind::Read
        }

        // Method call: obj.method()
        "field_expression" => {
            if let Some(grandparent) = parent.parent() {
                if grandparent.kind() == "call_expression" {
                    if let Some(func) = grandparent.child_by_field_name("function") {
                        if func.id() == parent.id() {
                            return ReferenceKind::Call;
                        }
                    }
                }
            }
            ReferenceKind::Read
        }

        _ => ReferenceKind::Read,
    }
}

/// Return the first named child of `node` whose kind is in `kinds`.
fn first_named_child_of_kind<'a>(node: &Node<'a>, kinds: &[&str]) -> Option<Node<'a>> {
    for i in 0..node.child_count() {
        if let Some(child) = node.child(i) {
            if kinds.contains(&child.kind()) {
                return Some(child);
            }
        }
    }
    None
}

/// Classify Java reference kind.
///
/// Grammar reference: tree-sitter-java. `method_declaration` /
/// `constructor_declaration` hold the method name as their first `identifier`
/// child (return types are `type_identifier` / `void_type`, so not confused).
/// Call sites use `method_invocation` whose callee identifier is a direct
/// `identifier` child (for `obj.method()` the callee is under a `field_access`
/// parent — we classify on the direct identifier attached to the invocation).
fn classify_java_reference(node: &Node, parent: &Node, _source: &[u8]) -> ReferenceKind {
    let parent_kind = parent.kind();

    match parent_kind {
        // Direct call site: greet()
        "method_invocation" => {
            // The callee identifier appears as the "name" field or the first
            // identifier child of the invocation. Arguments are in argument_list,
            // so an identifier that is NOT inside argument_list is the callee.
            if let Some(name) = parent.child_by_field_name("name") {
                if node.id() == name.id() {
                    return ReferenceKind::Call;
                }
            }
            // Fallback: if no "name" field, the first identifier child is the callee.
            if let Some(first_id) = first_named_child_of_kind(parent, &["identifier"]) {
                if node.id() == first_id.id() {
                    return ReferenceKind::Call;
                }
            }
            ReferenceKind::Read
        }

        // Method / constructor definition: first identifier child is the name.
        "method_declaration" | "constructor_declaration" => {
            if let Some(name) = parent.child_by_field_name("name") {
                if node.id() == name.id() {
                    return ReferenceKind::Definition;
                }
            }
            if let Some(first_id) = first_named_child_of_kind(parent, &["identifier"]) {
                if node.id() == first_id.id() {
                    return ReferenceKind::Definition;
                }
            }
            ReferenceKind::Read
        }

        // Class / interface / enum declarations: name field
        "class_declaration" | "interface_declaration" | "enum_declaration" => {
            if let Some(name) = parent.child_by_field_name("name") {
                if node.id() == name.id() {
                    return ReferenceKind::Definition;
                }
            }
            ReferenceKind::Read
        }

        // Assignment: lhs is Write
        "assignment_expression" => {
            if let Some(left) = parent.child_by_field_name("left") {
                if node_contains(node, &left) {
                    return ReferenceKind::Write;
                }
            }
            ReferenceKind::Read
        }

        // Imports
        "import_declaration" => ReferenceKind::Import,

        // Field access / scoped access: if grandparent is method_invocation
        // and this field_access is the callee, it's a Call.
        "field_access" => {
            if let Some(grandparent) = parent.parent() {
                if grandparent.kind() == "method_invocation" {
                    if let Some(name) = grandparent.child_by_field_name("name") {
                        if node_contains(node, &name) {
                            return ReferenceKind::Call;
                        }
                    }
                }
            }
            ReferenceKind::Read
        }

        // Type references
        "type_identifier" | "generic_type" | "array_type" => ReferenceKind::Type,

        _ => ReferenceKind::Read,
    }
}

/// Classify C reference kind.
///
/// Grammar reference: tree-sitter-c. `function_definition` contains a
/// `function_declarator` whose first `identifier` child is the function name.
/// `call_expression` has the callee as its first child (an `identifier` for
/// direct calls).
fn classify_c_reference(node: &Node, parent: &Node, _source: &[u8]) -> ReferenceKind {
    let parent_kind = parent.kind();

    match parent_kind {
        // Direct call: greet()
        "call_expression" => {
            if let Some(func) = parent.child_by_field_name("function") {
                if node_contains(node, &func) {
                    return ReferenceKind::Call;
                }
            }
            // Fallback: first child of call_expression is the callee
            if let Some(first) = parent.child(0) {
                if node.id() == first.id() {
                    return ReferenceKind::Call;
                }
            }
            ReferenceKind::Read
        }

        // Function name inside function_declarator: definition
        "function_declarator" => {
            // The first identifier child is the function name.
            if let Some(decl) = parent.child_by_field_name("declarator") {
                if node.id() == decl.id() {
                    return classify_c_declarator_as_definition(parent);
                }
            }
            if let Some(first_id) = first_named_child_of_kind(parent, &["identifier"]) {
                if node.id() == first_id.id() {
                    // Check whether this declarator is inside a function_definition
                    // — if so, this is a Definition. Otherwise it's still the name
                    // of a declared function (forward declaration), also Definition.
                    return ReferenceKind::Definition;
                }
            }
            ReferenceKind::Read
        }

        // Parameter declaration name
        "parameter_declaration" => {
            if let Some(decl) = parent.child_by_field_name("declarator") {
                if node_contains(node, &decl) {
                    return ReferenceKind::Definition;
                }
            }
            ReferenceKind::Read
        }

        // Initializers / assignments: lhs of assignment_expression is a Write.
        "assignment_expression" => {
            if let Some(left) = parent.child_by_field_name("left") {
                if node_contains(node, &left) {
                    return ReferenceKind::Write;
                }
            }
            ReferenceKind::Read
        }

        // Preprocessor includes
        "preproc_include" => ReferenceKind::Import,

        // Field access used as callee
        "field_expression" => {
            if let Some(grandparent) = parent.parent() {
                if grandparent.kind() == "call_expression" {
                    if let Some(first) = grandparent.child(0) {
                        if first.id() == parent.id() {
                            return ReferenceKind::Call;
                        }
                    }
                }
            }
            ReferenceKind::Read
        }

        // Type references
        "type_identifier" | "sized_type_specifier" => ReferenceKind::Type,

        _ => ReferenceKind::Read,
    }
}

/// Helper: a function_declarator within a function_definition/declaration
/// always names a function-kind entity (not a variable), so its identifier
/// is a Definition. Kept as a tiny helper to match the established pattern.
fn classify_c_declarator_as_definition(_declarator: &Node) -> ReferenceKind {
    ReferenceKind::Definition
}

/// Classify C++ reference kind.
///
/// Grammar reference: tree-sitter-cpp. Structure mirrors C for the
/// must-have cases (`function_definition` → `function_declarator` →
/// `identifier` for the name; `call_expression` with direct `identifier`
/// callee). Adds handling for qualified identifiers (ns::func()) and
/// field expressions for method calls.
fn classify_cpp_reference(node: &Node, parent: &Node, _source: &[u8]) -> ReferenceKind {
    let parent_kind = parent.kind();

    match parent_kind {
        "call_expression" => {
            if let Some(func) = parent.child_by_field_name("function") {
                if node_contains(node, &func) {
                    return ReferenceKind::Call;
                }
            }
            if let Some(first) = parent.child(0) {
                if node.id() == first.id() {
                    return ReferenceKind::Call;
                }
            }
            ReferenceKind::Read
        }

        "function_declarator" => {
            if let Some(first_id) = first_named_child_of_kind(
                parent,
                &[
                    "identifier",
                    "field_identifier",
                    "qualified_identifier",
                    "destructor_name",
                ],
            ) {
                if node.id() == first_id.id() || node_contains(node, &first_id) {
                    return ReferenceKind::Definition;
                }
            }
            ReferenceKind::Read
        }

        // Qualified identifier: ns::func — if part of a call, it's a Call
        "qualified_identifier" => {
            if let Some(grandparent) = parent.parent() {
                if grandparent.kind() == "call_expression" {
                    if let Some(first) = grandparent.child(0) {
                        if first.id() == parent.id() {
                            return ReferenceKind::Call;
                        }
                    }
                }
                // Qualified identifier inside a declarator is part of a Definition.
                if grandparent.kind() == "function_declarator" {
                    return ReferenceKind::Definition;
                }
            }
            ReferenceKind::Read
        }

        "field_expression" => {
            if let Some(grandparent) = parent.parent() {
                if grandparent.kind() == "call_expression" {
                    if let Some(first) = grandparent.child(0) {
                        if first.id() == parent.id() {
                            return ReferenceKind::Call;
                        }
                    }
                }
            }
            ReferenceKind::Read
        }

        "assignment_expression" => {
            if let Some(left) = parent.child_by_field_name("left") {
                if node_contains(node, &left) {
                    return ReferenceKind::Write;
                }
            }
            ReferenceKind::Read
        }

        "parameter_declaration" => {
            if let Some(decl) = parent.child_by_field_name("declarator") {
                if node_contains(node, &decl) {
                    return ReferenceKind::Definition;
                }
            }
            ReferenceKind::Read
        }

        "preproc_include" => ReferenceKind::Import,

        "type_identifier" | "template_type" | "sized_type_specifier" => ReferenceKind::Type,

        "class_specifier" | "struct_specifier" | "namespace_definition" => {
            if let Some(name) = parent.child_by_field_name("name") {
                if node_contains(node, &name) {
                    return ReferenceKind::Definition;
                }
            }
            ReferenceKind::Read
        }

        _ => ReferenceKind::Read,
    }
}

/// Classify C# reference kind.
///
/// Grammar reference: tree-sitter-c-sharp. `method_declaration`,
/// `constructor_declaration`, and `class_declaration` expose a "name" field
/// (and also have the name as a direct identifier child). Call sites are
/// `invocation_expression` — the callee is a direct `identifier` child or
/// a `member_access_expression`.
fn classify_csharp_reference(node: &Node, parent: &Node, _source: &[u8]) -> ReferenceKind {
    let parent_kind = parent.kind();

    match parent_kind {
        "invocation_expression" => {
            if let Some(func) = parent.child_by_field_name("function") {
                if node_contains(node, &func) {
                    return ReferenceKind::Call;
                }
            }
            if let Some(first) = parent.child(0) {
                if node.id() == first.id() {
                    return ReferenceKind::Call;
                }
            }
            ReferenceKind::Read
        }

        "method_declaration" | "constructor_declaration" | "local_function_statement" => {
            if let Some(name) = parent.child_by_field_name("name") {
                if node.id() == name.id() {
                    return ReferenceKind::Definition;
                }
            }
            // Fallback: for method_declaration the name is the second identifier
            // (first is return type when type_identifier isn't emitted). Safely
            // take the first identifier — this is the established fallback in
            // the C# callgraph handler.
            if let Some(first_id) = first_named_child_of_kind(parent, &["identifier"]) {
                if node.id() == first_id.id() {
                    return ReferenceKind::Definition;
                }
            }
            ReferenceKind::Read
        }

        "class_declaration" | "interface_declaration" | "struct_declaration"
        | "enum_declaration" | "record_declaration" => {
            if let Some(name) = parent.child_by_field_name("name") {
                if node.id() == name.id() {
                    return ReferenceKind::Definition;
                }
            }
            ReferenceKind::Read
        }

        "member_access_expression" => {
            if let Some(grandparent) = parent.parent() {
                if grandparent.kind() == "invocation_expression" {
                    if let Some(func) = grandparent.child_by_field_name("function") {
                        if func.id() == parent.id() {
                            return ReferenceKind::Call;
                        }
                    }
                    if let Some(first) = grandparent.child(0) {
                        if first.id() == parent.id() {
                            return ReferenceKind::Call;
                        }
                    }
                }
            }
            ReferenceKind::Read
        }

        "assignment_expression" => {
            if let Some(left) = parent.child_by_field_name("left") {
                if node_contains(node, &left) {
                    return ReferenceKind::Write;
                }
            }
            ReferenceKind::Read
        }

        "using_directive" | "namespace_declaration" => ReferenceKind::Import,

        "type_parameter" | "type_argument_list" => ReferenceKind::Type,

        _ => ReferenceKind::Read,
    }
}

/// Classify Kotlin reference kind.
///
/// Grammar reference: tree-sitter-kotlin. `function_declaration` /
/// `class_declaration` have the name as a direct `identifier` child.
/// `call_expression` has the callee as a direct `identifier` or a
/// `navigation_expression` child.
fn classify_kotlin_reference(node: &Node, parent: &Node, _source: &[u8]) -> ReferenceKind {
    let parent_kind = parent.kind();

    match parent_kind {
        "call_expression" => {
            if let Some(first) = parent.child(0) {
                if node.id() == first.id() || node_contains(node, &first) {
                    return ReferenceKind::Call;
                }
            }
            ReferenceKind::Read
        }

        "function_declaration" | "class_declaration" | "object_declaration"
        | "property_declaration" => {
            if let Some(name) = parent.child_by_field_name("name") {
                if node.id() == name.id() {
                    return ReferenceKind::Definition;
                }
            }
            if let Some(first_id) = first_named_child_of_kind(parent, &["identifier"]) {
                if node.id() == first_id.id() {
                    return ReferenceKind::Definition;
                }
            }
            ReferenceKind::Read
        }

        "navigation_expression" => {
            if let Some(grandparent) = parent.parent() {
                if grandparent.kind() == "call_expression" {
                    if let Some(first) = grandparent.child(0) {
                        if first.id() == parent.id() {
                            return ReferenceKind::Call;
                        }
                    }
                }
            }
            ReferenceKind::Read
        }

        "assignment" => {
            if let Some(left) = parent.child_by_field_name("left") {
                if node_contains(node, &left) {
                    return ReferenceKind::Write;
                }
            }
            ReferenceKind::Read
        }

        "import_header" | "import_list" => ReferenceKind::Import,

        "user_type" | "type_reference" => ReferenceKind::Type,

        _ => ReferenceKind::Read,
    }
}

/// Classify Scala reference kind.
///
/// Grammar reference: tree-sitter-scala. `function_definition` /
/// `function_declaration` / `class_definition` / `object_definition` have the
/// name as a direct `identifier` or `type_identifier` child. Call sites are
/// `call_expression` with the callee as the first non-arguments child.
fn classify_scala_reference(node: &Node, parent: &Node, _source: &[u8]) -> ReferenceKind {
    let parent_kind = parent.kind();

    match parent_kind {
        "call_expression" => {
            if let Some(first) = parent.child(0) {
                if node.id() == first.id() || node_contains(node, &first) {
                    return ReferenceKind::Call;
                }
            }
            ReferenceKind::Read
        }

        "function_definition" | "function_declaration" => {
            if let Some(name) = parent.child_by_field_name("name") {
                if node.id() == name.id() {
                    return ReferenceKind::Definition;
                }
            }
            if let Some(first_id) =
                first_named_child_of_kind(parent, &["identifier", "type_identifier"])
            {
                if node.id() == first_id.id() {
                    return ReferenceKind::Definition;
                }
            }
            ReferenceKind::Read
        }

        "class_definition" | "object_definition" | "trait_definition" => {
            if let Some(name) = parent.child_by_field_name("name") {
                if node.id() == name.id() {
                    return ReferenceKind::Definition;
                }
            }
            if let Some(first_id) =
                first_named_child_of_kind(parent, &["identifier", "type_identifier"])
            {
                if node.id() == first_id.id() {
                    return ReferenceKind::Definition;
                }
            }
            ReferenceKind::Read
        }

        "field_expression" | "select_expression" => {
            if let Some(grandparent) = parent.parent() {
                if grandparent.kind() == "call_expression" {
                    if let Some(first) = grandparent.child(0) {
                        if first.id() == parent.id() {
                            return ReferenceKind::Call;
                        }
                    }
                }
            }
            ReferenceKind::Read
        }

        "assignment_expression" => {
            if let Some(left) = parent.child_by_field_name("left") {
                if node_contains(node, &left) {
                    return ReferenceKind::Write;
                }
            }
            ReferenceKind::Read
        }

        "import_declaration" | "import_expression" | "import_selectors" => ReferenceKind::Import,

        "type_identifier" | "generic_type" | "compound_type" => ReferenceKind::Type,

        _ => ReferenceKind::Read,
    }
}

/// Classify Swift reference kind.
///
/// Grammar reference: tree-sitter-swift. `function_declaration` /
/// `protocol_function_declaration` expose a "name" field (a
/// `simple_identifier`). `init_declaration` doesn't have a simple name but
/// its identifier site is still a Definition. `call_expression` has the
/// callable as its first child (usually `simple_identifier` or
/// `navigation_expression`).
fn classify_swift_reference(node: &Node, parent: &Node, _source: &[u8]) -> ReferenceKind {
    let parent_kind = parent.kind();

    match parent_kind {
        "call_expression" => {
            if let Some(first) = parent.child(0) {
                if node.id() == first.id() || node_contains(node, &first) {
                    return ReferenceKind::Call;
                }
            }
            ReferenceKind::Read
        }

        "function_declaration" | "protocol_function_declaration" | "init_declaration" => {
            if let Some(name) = parent.child_by_field_name("name") {
                if node.id() == name.id() {
                    return ReferenceKind::Definition;
                }
            }
            if let Some(first_id) = first_named_child_of_kind(parent, &["simple_identifier"]) {
                if node.id() == first_id.id() {
                    return ReferenceKind::Definition;
                }
            }
            ReferenceKind::Read
        }

        "class_declaration" | "protocol_declaration" => {
            if let Some(name) = parent.child_by_field_name("name") {
                if node_contains(node, &name) {
                    return ReferenceKind::Definition;
                }
            }
            ReferenceKind::Read
        }

        "property_declaration" => {
            if let Some(name) = parent.child_by_field_name("name") {
                if node_contains(node, &name) {
                    return ReferenceKind::Definition;
                }
            }
            ReferenceKind::Read
        }

        "navigation_expression" => {
            if let Some(grandparent) = parent.parent() {
                if grandparent.kind() == "call_expression" {
                    if let Some(first) = grandparent.child(0) {
                        if first.id() == parent.id() {
                            return ReferenceKind::Call;
                        }
                    }
                }
            }
            ReferenceKind::Read
        }

        "assignment" => {
            if let Some(left) = parent.child_by_field_name("left") {
                if node_contains(node, &left) {
                    return ReferenceKind::Write;
                }
            }
            ReferenceKind::Read
        }

        "import_declaration" => ReferenceKind::Import,

        "user_type" | "type_identifier" => ReferenceKind::Type,

        _ => ReferenceKind::Read,
    }
}

/// Classify PHP reference kind.
///
/// Grammar reference: tree-sitter-php. `function_definition` and
/// `method_declaration` expose a "name" field (a `name` node). Call sites are
/// `function_call_expression` / `member_call_expression` /
/// `scoped_call_expression` — all with a "function"/"name" field.
fn classify_php_reference(node: &Node, parent: &Node, _source: &[u8]) -> ReferenceKind {
    let parent_kind = parent.kind();

    match parent_kind {
        "function_call_expression" => {
            if let Some(func) = parent.child_by_field_name("function") {
                if node_contains(node, &func) {
                    return ReferenceKind::Call;
                }
            }
            ReferenceKind::Read
        }

        "member_call_expression" | "scoped_call_expression" => {
            if let Some(name) = parent.child_by_field_name("name") {
                if node_contains(node, &name) {
                    return ReferenceKind::Call;
                }
            }
            ReferenceKind::Read
        }

        "function_definition" | "method_declaration" => {
            if let Some(name) = parent.child_by_field_name("name") {
                if node.id() == name.id() {
                    return ReferenceKind::Definition;
                }
            }
            ReferenceKind::Read
        }

        "class_declaration" | "trait_declaration" | "interface_declaration" => {
            if let Some(name) = parent.child_by_field_name("name") {
                if node.id() == name.id() {
                    return ReferenceKind::Definition;
                }
            }
            ReferenceKind::Read
        }

        "assignment_expression" => {
            if let Some(left) = parent.child_by_field_name("left") {
                if node_contains(node, &left) {
                    return ReferenceKind::Write;
                }
            }
            ReferenceKind::Read
        }

        "namespace_use_declaration" | "namespace_use_clause" | "namespace_name" => {
            ReferenceKind::Import
        }

        "named_type" | "primitive_type" => ReferenceKind::Type,

        _ => ReferenceKind::Read,
    }
}

/// Classify Ruby reference kind.
///
/// Grammar reference: tree-sitter-ruby. `method` / `singleton_method` have
/// the name as a direct `identifier` child. Call sites are `call` nodes
/// where the callee identifier is also a direct `identifier` child (with
/// `argument_list` containing arguments).
fn classify_ruby_reference(node: &Node, parent: &Node, _source: &[u8]) -> ReferenceKind {
    let parent_kind = parent.kind();

    match parent_kind {
        "call" => {
            // The callee is the identifier that is NOT inside argument_list and
            // NOT a receiver. Ruby's `call` can look like:
            //   call { identifier(callee), argument_list }
            //   call { identifier(receiver), ".", identifier(callee), argument_list }
            // The callee is the LAST identifier child before the argument_list
            // (or at the end if no arguments).
            if let Some(name) = parent.child_by_field_name("method") {
                if node_contains(node, &name) {
                    return ReferenceKind::Call;
                }
            }
            // Fallback: find the last identifier child before argument_list.
            let mut last_id: Option<Node> = None;
            for i in 0..parent.child_count() {
                if let Some(child) = parent.child(i) {
                    if child.kind() == "argument_list" {
                        break;
                    }
                    if child.kind() == "identifier" {
                        last_id = Some(child);
                    }
                }
            }
            if let Some(id) = last_id {
                if node.id() == id.id() {
                    return ReferenceKind::Call;
                }
            }
            ReferenceKind::Read
        }

        "method" | "singleton_method" => {
            if let Some(name) = parent.child_by_field_name("name") {
                if node.id() == name.id() {
                    return ReferenceKind::Definition;
                }
            }
            if let Some(first_id) = first_named_child_of_kind(parent, &["identifier"]) {
                if node.id() == first_id.id() {
                    return ReferenceKind::Definition;
                }
            }
            ReferenceKind::Read
        }

        "class" | "module" => {
            if let Some(name) = parent.child_by_field_name("name") {
                if node_contains(node, &name) {
                    return ReferenceKind::Definition;
                }
            }
            ReferenceKind::Read
        }

        "assignment" | "operator_assignment" => {
            if let Some(left) = parent.child_by_field_name("left") {
                if node_contains(node, &left) {
                    return ReferenceKind::Write;
                }
            }
            ReferenceKind::Read
        }

        _ => ReferenceKind::Read,
    }
}

/// Classify Lua reference kind.
///
/// Grammar reference: tree-sitter-lua (nvim-treesitter). `function_declaration`
/// has the name as a direct `identifier` child (or `dot_index_expression` /
/// `method_index_expression`). Call sites are `function_call` with the callee
/// as the first child.
fn classify_lua_reference(node: &Node, parent: &Node, _source: &[u8]) -> ReferenceKind {
    classify_lua_family_reference(node, parent)
}

/// Classify Luau reference kind.
///
/// Luau's grammar mirrors Lua's for the core call/definition nodes
/// (`function_call`, `function_declaration`, `identifier`). Share the impl.
fn classify_luau_reference(node: &Node, parent: &Node, _source: &[u8]) -> ReferenceKind {
    classify_lua_family_reference(node, parent)
}

fn classify_lua_family_reference(node: &Node, parent: &Node) -> ReferenceKind {
    let parent_kind = parent.kind();

    match parent_kind {
        "function_call" => {
            if let Some(first) = parent.child(0) {
                if node.id() == first.id() || node_contains(node, &first) {
                    return ReferenceKind::Call;
                }
            }
            ReferenceKind::Read
        }

        "function_declaration" | "local_function" | "function_definition_statement" => {
            if let Some(name) = parent.child_by_field_name("name") {
                if node.id() == name.id() {
                    return ReferenceKind::Definition;
                }
            }
            if let Some(first_id) = first_named_child_of_kind(parent, &["identifier"]) {
                if node.id() == first_id.id() {
                    return ReferenceKind::Definition;
                }
            }
            ReferenceKind::Read
        }

        "dot_index_expression" | "method_index_expression" => {
            // If we're the function name (last identifier) and grandparent is
            // function_call, it's a Call. If grandparent is function_declaration,
            // it's a Definition.
            if let Some(grandparent) = parent.parent() {
                match grandparent.kind() {
                    "function_call" => {
                        if let Some(first) = grandparent.child(0) {
                            if first.id() == parent.id() {
                                return ReferenceKind::Call;
                            }
                        }
                    }
                    "function_declaration" => {
                        return ReferenceKind::Definition;
                    }
                    _ => {}
                }
            }
            ReferenceKind::Read
        }

        "assignment_statement" => {
            if let Some(left) = parent.child_by_field_name("variables") {
                if node_contains(node, &left) {
                    return ReferenceKind::Write;
                }
            }
            // Fallback: check if the node is in the "variable_list" (first
            // named child) — that's the LHS in the nvim grammar.
            for i in 0..parent.child_count() {
                if let Some(child) = parent.child(i) {
                    if child.kind() == "variable_list" {
                        if node_contains(node, &child) {
                            return ReferenceKind::Write;
                        }
                        break;
                    }
                }
            }
            ReferenceKind::Read
        }

        "variable_declaration" => {
            // Local declarations: `local foo = ...` — the name is a Definition.
            ReferenceKind::Definition
        }

        _ => ReferenceKind::Read,
    }
}

/// Classify Elixir reference kind.
///
/// Elixir's grammar uses `call` nodes for nearly everything. The pattern for a
/// function definition is `call { identifier("def"|"defp"), arguments { call {
/// identifier(funcname), ... } } }`. So to detect Definition, we check: our
/// identifier is the first identifier child of a `call`, that call's parent is
/// `arguments`, and the argument's parent `call` has first identifier "def" /
/// "defp" / "defmacro" / "defmacrop".
///
/// Direct call sites: our identifier is the first identifier child of a `call`
/// node (not inside the def-pattern above). Dotted calls (`Mod.func`) have
/// parent `dot`.
fn classify_elixir_reference(node: &Node, parent: &Node, source: &[u8]) -> ReferenceKind {
    let parent_kind = parent.kind();

    match parent_kind {
        "call" => {
            // Is this the first identifier child of the call?
            if let Some(first_id) = first_named_child_of_kind(parent, &["identifier"]) {
                if node.id() == first_id.id() {
                    // Check if this call is inside `arguments` of a def-style call.
                    if is_elixir_def_call(parent, source) {
                        return ReferenceKind::Definition;
                    }
                    // Otherwise it's a plain function call.
                    return ReferenceKind::Call;
                }
            }
            ReferenceKind::Read
        }

        "dot" => {
            // Dotted call: App.greet — if the dot's parent is a call whose first
            // child is this dot, it's a Call.
            if let Some(grandparent) = parent.parent() {
                if grandparent.kind() == "call" {
                    if let Some(first) = grandparent.child(0) {
                        if first.id() == parent.id() {
                            // Check we're the name side (usually the LAST identifier child of dot).
                            let mut last_id: Option<Node> = None;
                            for i in 0..parent.child_count() {
                                if let Some(child) = parent.child(i) {
                                    if child.kind() == "identifier" {
                                        last_id = Some(child);
                                    }
                                }
                            }
                            if let Some(id) = last_id {
                                if node.id() == id.id() {
                                    return ReferenceKind::Call;
                                }
                            }
                        }
                    }
                }
            }
            ReferenceKind::Read
        }

        _ => ReferenceKind::Read,
    }
}

/// Returns true if `call_node` is the inner `call` inside
/// `outer_call(def|defp|defmacro|defmacrop, arguments { call_node, ... })`.
fn is_elixir_def_call(call_node: &Node, source: &[u8]) -> bool {
    // call_node.parent() should be `arguments`.
    let args = match call_node.parent() {
        Some(p) if p.kind() == "arguments" => p,
        _ => return false,
    };
    let outer_call = match args.parent() {
        Some(p) if p.kind() == "call" => p,
        _ => return false,
    };
    // Find the first identifier child of outer_call.
    for i in 0..outer_call.child_count() {
        if let Some(child) = outer_call.child(i) {
            if child.kind() == "identifier" {
                let start = child.start_byte();
                let end = child.end_byte();
                if end <= source.len() {
                    let text = &source[start..end];
                    return matches!(text, b"def" | b"defp" | b"defmacro" | b"defmacrop");
                }
                return false;
            }
        }
    }
    false
}

/// Classify OCaml reference kind.
///
/// Grammar reference: tree-sitter-ocaml. The identifier-like node is a
/// `value_name`. At definition sites its parent is `let_binding` (or
/// `value_definition`). At call sites its parent is `value_path`, whose
/// parent is `application_expression` with this `value_path` as the first
/// child. Shadowing rebinding is another Definition (per OCaml semantics —
/// `let x = ... let x = ...` is two separate bindings, not a Write).
fn classify_ocaml_reference(node: &Node, parent: &Node, _source: &[u8]) -> ReferenceKind {
    let parent_kind = parent.kind();

    match parent_kind {
        "let_binding" | "value_definition" => {
            // The bound name is the first `value_name` child.
            if let Some(name) = parent.child_by_field_name("pattern") {
                if node.id() == name.id() || node_contains(node, &name) {
                    return ReferenceKind::Definition;
                }
            }
            if let Some(first_name) = first_named_child_of_kind(parent, &["value_name"]) {
                if node.id() == first_name.id() {
                    return ReferenceKind::Definition;
                }
            }
            ReferenceKind::Read
        }

        "value_path" => {
            // If this path is the callee of an application_expression, it's a Call.
            // Otherwise it's a Read.
            if let Some(grandparent) = parent.parent() {
                if matches!(grandparent.kind(), "application_expression" | "application") {
                    if let Some(first) = grandparent.child(0) {
                        if first.id() == parent.id() {
                            return ReferenceKind::Call;
                        }
                    }
                }
            }
            ReferenceKind::Read
        }

        "application_expression" | "application" => {
            // Bare value_name used as callee (no module qualifier).
            if let Some(first) = parent.child(0) {
                if node.id() == first.id() {
                    return ReferenceKind::Call;
                }
            }
            ReferenceKind::Read
        }

        "module_binding" | "module_definition" => {
            if let Some(first_name) = first_named_child_of_kind(parent, &["module_name"]) {
                if node.id() == first_name.id() {
                    return ReferenceKind::Definition;
                }
            }
            ReferenceKind::Read
        }

        "open_module" | "include_module" => ReferenceKind::Import,

        "type_constructor" | "type_constructor_path" => ReferenceKind::Type,

        _ => ReferenceKind::Read,
    }
}

/// Check if a node is contained within another node (by position)
fn node_contains(inner: &Node, outer: &Node) -> bool {
    inner.start_byte() >= outer.start_byte() && inner.end_byte() <= outer.end_byte()
}

/// Check if parent is in a type annotation context
fn is_type_context(node: &Node) -> bool {
    let mut current = Some(*node);
    while let Some(n) = current {
        let kind = n.kind();
        if matches!(
            kind,
            "type"
                | "annotation"
                | "type_annotation"
                | "return_type"
                | "parameter"
                | "typed_parameter"
                | "generic_type"
                | "type_arguments"
        ) {
            return true;
        }
        // Stop at statement boundaries
        if kind.ends_with("_statement") || kind.ends_with("_definition") {
            return false;
        }
        current = n.parent();
    }
    false
}

// =============================================================================
// Phase 11: Definition Finding and Cross-File Tracking
// =============================================================================

/// Find the definition location for a symbol
///
/// Searches for definition patterns in the AST across all files in the workspace:
/// - Python: function_definition, class_definition, assignment
/// - TypeScript: function_declaration, class_declaration, variable_declaration
/// - Go: function_declaration, type_declaration
/// - Rust: function_item, struct_item, enum_item
///
/// # Arguments
///
/// * `symbol` - The symbol name to find the definition for
/// * `root` - The root directory to search in
/// * `language` - Optional language filter
///
/// # Returns
///
/// `Some(Definition)` if found, `None` otherwise.
pub fn find_definition(
    symbol: &str,
    root: &Path,
    language: Option<&str>,
) -> TldrResult<Option<Definition>> {
    // Walk all source files
    for entry in WalkDir::new(root)
        .into_iter()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_type().is_file())
        .filter(|e| is_source_file(e.path(), language))
    {
        // Try to find definition in this file
        if let Ok(Some(def)) = find_definition_in_file(symbol, entry.path(), language) {
            return Ok(Some(def));
        }
    }

    Ok(None)
}

/// Find definition of a symbol in a specific file
fn find_definition_in_file(
    symbol: &str,
    file_path: &Path,
    _language_str: Option<&str>,
) -> TldrResult<Option<Definition>> {
    let parsed = parse_file(file_path)?;
    let (tree, source, language) = parsed;
    let source_bytes = source.as_bytes();

    // Search recursively through the AST for definition nodes
    let root = tree.root_node();
    find_definition_in_node(&root, symbol, source_bytes, language, file_path)
}

/// Recursively search for a definition in an AST node
fn find_definition_in_node(
    node: &Node,
    symbol: &str,
    source: &[u8],
    language: Language,
    file_path: &Path,
) -> TldrResult<Option<Definition>> {
    // Check if this node is a definition matching our symbol
    if let Some(def) = check_definition_node(node, symbol, source, language, file_path)? {
        return Ok(Some(def));
    }

    // Recurse into children
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if let Some(def) = find_definition_in_node(&child, symbol, source, language, file_path)? {
            return Ok(Some(def));
        }
    }

    Ok(None)
}

/// Check if a node is a definition of the target symbol
fn check_definition_node(
    node: &Node,
    symbol: &str,
    source: &[u8],
    language: Language,
    file_path: &Path,
) -> TldrResult<Option<Definition>> {
    match language {
        Language::Python => check_python_definition(node, symbol, source, file_path),
        Language::TypeScript | Language::JavaScript => {
            check_ts_definition(node, symbol, source, file_path)
        }
        Language::Go => check_go_definition(node, symbol, source, file_path),
        Language::Rust => check_rust_definition(node, symbol, source, file_path),
        _ => Ok(None),
    }
}

/// Check if a Python node is a definition of the target symbol
fn check_python_definition(
    node: &Node,
    symbol: &str,
    source: &[u8],
    file_path: &Path,
) -> TldrResult<Option<Definition>> {
    let node_kind = node.kind();

    match node_kind {
        "function_definition" => {
            // def symbol(...):
            if let Some(name_node) = node.child_by_field_name("name") {
                if name_node.utf8_text(source).unwrap_or("") == symbol {
                    let signature = extract_signature(node, source, Language::Python);
                    return Ok(Some(Definition {
                        file: file_path.to_path_buf(),
                        line: node.start_position().row + 1,
                        column: name_node.start_position().column + 1,
                        kind: DefinitionKind::Function,
                        signature,
                    }));
                }
            }
        }
        "class_definition" => {
            // class Symbol:
            if let Some(name_node) = node.child_by_field_name("name") {
                if name_node.utf8_text(source).unwrap_or("") == symbol {
                    let signature = extract_signature(node, source, Language::Python);
                    return Ok(Some(Definition {
                        file: file_path.to_path_buf(),
                        line: node.start_position().row + 1,
                        column: name_node.start_position().column + 1,
                        kind: DefinitionKind::Class,
                        signature,
                    }));
                }
            }
        }
        "assignment" | "expression_statement" => {
            // symbol = value (module-level assignment)
            // Check if parent is module (top-level)
            if let Some(parent) = node.parent() {
                if parent.kind() == "module" || parent.kind() == "expression_statement" {
                    // Look for identifier on left side
                    let target_node = if node_kind == "assignment" {
                        node.child_by_field_name("left")
                    } else {
                        // expression_statement wraps assignment
                        node.child(0).and_then(|c| c.child_by_field_name("left"))
                    };

                    if let Some(left) = target_node {
                        if left.kind() == "identifier"
                            && left.utf8_text(source).unwrap_or("") == symbol
                        {
                            return Ok(Some(Definition {
                                file: file_path.to_path_buf(),
                                line: left.start_position().row + 1,
                                column: left.start_position().column + 1,
                                kind: DefinitionKind::Variable,
                                signature: None,
                            }));
                        }
                    }
                }
            }
        }
        _ => {}
    }

    Ok(None)
}

/// Check if a TypeScript/JavaScript node is a definition of the target symbol
fn check_ts_definition(
    node: &Node,
    symbol: &str,
    source: &[u8],
    file_path: &Path,
) -> TldrResult<Option<Definition>> {
    let node_kind = node.kind();

    match node_kind {
        "function_declaration" => {
            if let Some(name_node) = node.child_by_field_name("name") {
                if name_node.utf8_text(source).unwrap_or("") == symbol {
                    let signature = extract_signature(node, source, Language::TypeScript);
                    return Ok(Some(Definition {
                        file: file_path.to_path_buf(),
                        line: node.start_position().row + 1,
                        column: name_node.start_position().column + 1,
                        kind: DefinitionKind::Function,
                        signature,
                    }));
                }
            }
        }
        "class_declaration" => {
            if let Some(name_node) = node.child_by_field_name("name") {
                if name_node.utf8_text(source).unwrap_or("") == symbol {
                    let signature = extract_signature(node, source, Language::TypeScript);
                    return Ok(Some(Definition {
                        file: file_path.to_path_buf(),
                        line: node.start_position().row + 1,
                        column: name_node.start_position().column + 1,
                        kind: DefinitionKind::Class,
                        signature,
                    }));
                }
            }
        }
        "variable_declarator" => {
            if let Some(name_node) = node.child_by_field_name("name") {
                if name_node.utf8_text(source).unwrap_or("") == symbol {
                    // Determine if const (constant) or let/var (variable)
                    let kind = if let Some(parent) = node.parent() {
                        if let Some(gp) = parent.parent() {
                            let decl_text = gp.utf8_text(source).unwrap_or("");
                            if decl_text.starts_with("const") {
                                DefinitionKind::Constant
                            } else {
                                DefinitionKind::Variable
                            }
                        } else {
                            DefinitionKind::Variable
                        }
                    } else {
                        DefinitionKind::Variable
                    };

                    return Ok(Some(Definition {
                        file: file_path.to_path_buf(),
                        line: name_node.start_position().row + 1,
                        column: name_node.start_position().column + 1,
                        kind,
                        signature: None,
                    }));
                }
            }
        }
        "type_alias_declaration" => {
            if let Some(name_node) = node.child_by_field_name("name") {
                if name_node.utf8_text(source).unwrap_or("") == symbol {
                    let signature = extract_signature(node, source, Language::TypeScript);
                    return Ok(Some(Definition {
                        file: file_path.to_path_buf(),
                        line: node.start_position().row + 1,
                        column: name_node.start_position().column + 1,
                        kind: DefinitionKind::Type,
                        signature,
                    }));
                }
            }
        }
        "interface_declaration" => {
            if let Some(name_node) = node.child_by_field_name("name") {
                if name_node.utf8_text(source).unwrap_or("") == symbol {
                    let signature = extract_signature(node, source, Language::TypeScript);
                    return Ok(Some(Definition {
                        file: file_path.to_path_buf(),
                        line: node.start_position().row + 1,
                        column: name_node.start_position().column + 1,
                        kind: DefinitionKind::Type,
                        signature,
                    }));
                }
            }
        }
        _ => {}
    }

    Ok(None)
}

/// Check if a Go node is a definition of the target symbol
fn check_go_definition(
    node: &Node,
    symbol: &str,
    source: &[u8],
    file_path: &Path,
) -> TldrResult<Option<Definition>> {
    let node_kind = node.kind();

    match node_kind {
        "function_declaration" => {
            if let Some(name_node) = node.child_by_field_name("name") {
                if name_node.utf8_text(source).unwrap_or("") == symbol {
                    let signature = extract_signature(node, source, Language::Go);
                    return Ok(Some(Definition {
                        file: file_path.to_path_buf(),
                        line: node.start_position().row + 1,
                        column: name_node.start_position().column + 1,
                        kind: DefinitionKind::Function,
                        signature,
                    }));
                }
            }
        }
        "method_declaration" => {
            if let Some(name_node) = node.child_by_field_name("name") {
                if name_node.utf8_text(source).unwrap_or("") == symbol {
                    let signature = extract_signature(node, source, Language::Go);
                    return Ok(Some(Definition {
                        file: file_path.to_path_buf(),
                        line: node.start_position().row + 1,
                        column: name_node.start_position().column + 1,
                        kind: DefinitionKind::Method,
                        signature,
                    }));
                }
            }
        }
        "type_declaration" | "type_spec" => {
            if let Some(name_node) = node.child_by_field_name("name") {
                if name_node.utf8_text(source).unwrap_or("") == symbol {
                    let signature = extract_signature(node, source, Language::Go);
                    return Ok(Some(Definition {
                        file: file_path.to_path_buf(),
                        line: node.start_position().row + 1,
                        column: name_node.start_position().column + 1,
                        kind: DefinitionKind::Type,
                        signature,
                    }));
                }
            }
        }
        _ => {}
    }

    Ok(None)
}

/// Check if a Rust node is a definition of the target symbol
fn check_rust_definition(
    node: &Node,
    symbol: &str,
    source: &[u8],
    file_path: &Path,
) -> TldrResult<Option<Definition>> {
    let node_kind = node.kind();

    match node_kind {
        "function_item" => {
            if let Some(name_node) = node.child_by_field_name("name") {
                if name_node.utf8_text(source).unwrap_or("") == symbol {
                    let signature = extract_signature(node, source, Language::Rust);
                    return Ok(Some(Definition {
                        file: file_path.to_path_buf(),
                        line: node.start_position().row + 1,
                        column: name_node.start_position().column + 1,
                        kind: DefinitionKind::Function,
                        signature,
                    }));
                }
            }
        }
        "struct_item" => {
            if let Some(name_node) = node.child_by_field_name("name") {
                if name_node.utf8_text(source).unwrap_or("") == symbol {
                    let signature = extract_signature(node, source, Language::Rust);
                    return Ok(Some(Definition {
                        file: file_path.to_path_buf(),
                        line: node.start_position().row + 1,
                        column: name_node.start_position().column + 1,
                        kind: DefinitionKind::Type,
                        signature,
                    }));
                }
            }
        }
        "enum_item" => {
            if let Some(name_node) = node.child_by_field_name("name") {
                if name_node.utf8_text(source).unwrap_or("") == symbol {
                    let signature = extract_signature(node, source, Language::Rust);
                    return Ok(Some(Definition {
                        file: file_path.to_path_buf(),
                        line: node.start_position().row + 1,
                        column: name_node.start_position().column + 1,
                        kind: DefinitionKind::Type,
                        signature,
                    }));
                }
            }
        }
        "const_item" => {
            if let Some(name_node) = node.child_by_field_name("name") {
                if name_node.utf8_text(source).unwrap_or("") == symbol {
                    let signature = extract_signature(node, source, Language::Rust);
                    return Ok(Some(Definition {
                        file: file_path.to_path_buf(),
                        line: node.start_position().row + 1,
                        column: name_node.start_position().column + 1,
                        kind: DefinitionKind::Constant,
                        signature,
                    }));
                }
            }
        }
        "static_item" => {
            if let Some(name_node) = node.child_by_field_name("name") {
                if name_node.utf8_text(source).unwrap_or("") == symbol {
                    let signature = extract_signature(node, source, Language::Rust);
                    return Ok(Some(Definition {
                        file: file_path.to_path_buf(),
                        line: node.start_position().row + 1,
                        column: name_node.start_position().column + 1,
                        kind: DefinitionKind::Variable,
                        signature,
                    }));
                }
            }
        }
        "type_item" => {
            if let Some(name_node) = node.child_by_field_name("name") {
                if name_node.utf8_text(source).unwrap_or("") == symbol {
                    let signature = extract_signature(node, source, Language::Rust);
                    return Ok(Some(Definition {
                        file: file_path.to_path_buf(),
                        line: node.start_position().row + 1,
                        column: name_node.start_position().column + 1,
                        kind: DefinitionKind::Type,
                        signature,
                    }));
                }
            }
        }
        _ => {}
    }

    Ok(None)
}

/// Extract function/class signature from AST node
///
/// Returns the first line of the definition as the signature:
/// - Python: "def login(username, password):" or "class User:"
/// - TypeScript: "function login(username: string): boolean"
/// - Go: "func Login(username string) bool"
/// - Rust: "pub fn login(username: &str) -> bool"
fn extract_signature(node: &Node, source: &[u8], _language: Language) -> Option<String> {
    let node_text = node.utf8_text(source).ok()?;

    // Get the first line of the definition
    let first_line = node_text.lines().next()?;

    // Truncate if too long
    let signature = if first_line.len() > MAX_CONTEXT_LENGTH {
        format!("{}...", &first_line[..MAX_CONTEXT_LENGTH - 3])
    } else {
        first_line.to_string()
    };

    Some(signature.trim().to_string())
}

/// Main entry point for reference finding (text search + AST verification)
///
/// # Arguments
///
/// * `symbol` - The symbol name to search for
/// * `root` - The root directory to search in
/// * `options` - Configuration options for the search
///
/// # Returns
///
/// A ReferencesReport containing all found references with statistics.
///
/// # Phases
///
/// - Phase 9: Text search for candidates
/// - Phase 10: AST verification and kind classification
/// - Phase 11: Definition tracking and cross-file references
pub fn find_references(
    symbol: &str,
    root: &Path,
    options: &ReferencesOptions,
) -> TldrResult<ReferencesReport> {
    let start = std::time::Instant::now();

    let language = options.language.as_deref();

    // Phase 13: Determine search scope based on symbol visibility
    // If scope is explicitly set in options, use it; otherwise auto-detect
    let effective_scope = if options.scope != SearchScope::Workspace {
        // User explicitly set a non-default scope
        options.scope
    } else if let Some(lang) = language {
        // Auto-detect scope based on symbol naming conventions
        determine_search_scope(symbol, options.definition_file.as_deref(), lang)
    } else {
        SearchScope::Workspace
    };

    // Step 1: Text search for candidates (Phase 9)
    let candidates = find_text_candidates(symbol, root, language)?;
    let candidates_found = candidates.len();

    // Phase 13: Apply scope filter before AST verification (for performance)
    let scoped_candidates = apply_scope_filter(
        candidates,
        effective_scope,
        options.definition_file.as_deref(),
    );

    // Step 2: AST verification and kind classification (Phase 10)
    let verified = verify_candidates_with_ast(&scoped_candidates, symbol, language);

    // Step 3: Convert verified references to Reference structs
    let mut references: Vec<Reference> = verified
        .into_iter()
        .map(|(candidate, verified_ref)| Reference {
            file: candidate.file,
            line: candidate.line,
            column: candidate.column,
            kind: verified_ref.kind,
            context: truncate_context(candidate.line_text),
            confidence: Some(verified_ref.confidence),
            end_column: Some(candidate.end_column),
        })
        .collect();

    // Step 4: Find definition (Phase 11)
    let definition = find_definition(symbol, root, language)?;

    // Apply kind filter if specified (Phase 13)
    if let Some(ref kinds) = options.kinds {
        references.retain(|r| kinds.contains(&r.kind));
    }

    // Apply limit if specified
    if let Some(limit) = options.limit {
        references.truncate(limit);
    }

    let files_searched = count_source_files(root, language);
    let verified_references = references.len();

    let stats = ReferenceStats {
        files_searched,
        candidates_found,
        verified_references,
        search_time_ms: start.elapsed().as_millis() as u64,
    };

    Ok(ReferencesReport {
        symbol: symbol.to_string(),
        definition,
        references,
        total_references: verified_references,
        search_scope: effective_scope, // Use the effective scope (auto-detected or explicit)
        stats,
    })
}

// =============================================================================
// Phase 13: Advanced Features - Search Scope Optimization & Kind Filtering
// =============================================================================

/// Determine optimal search scope based on symbol visibility
///
/// This function infers the appropriate search scope based on:
/// - Python: `_prefix` = File scope, `__dunder__` = Workspace, normal = Workspace
/// - TypeScript: non-exported = File scope, exported = Workspace
/// - Go: lowercase = File (package-private), uppercase = Workspace
/// - Rust: pub = Workspace, pub(crate) = Workspace, private = File
///
/// # Arguments
///
/// * `symbol` - The symbol name to analyze
/// * `definition_file` - Optional path to the file containing the definition
/// * `language` - The programming language (e.g., "python", "typescript", "go", "rust")
///
/// # Returns
///
/// The inferred `SearchScope` for the symbol.
///
/// # Phase 13 Risks Addressed
///
/// - S7-R19: SearchScope Go package - handles Go visibility
/// - S7-R29: Private class methods - conservative: if unsure, use Workspace
/// - S7-R30: Rust pub(crate)/pub(super) - maps to appropriate scope
pub fn determine_search_scope(
    symbol: &str,
    definition_file: Option<&Path>,
    language: &str,
) -> SearchScope {
    match language.to_lowercase().as_str() {
        "python" => determine_python_scope(symbol, definition_file),
        "typescript" | "javascript" => determine_ts_scope(symbol, definition_file),
        "go" => determine_go_scope(symbol, definition_file),
        "rust" => determine_rust_scope(symbol, definition_file),
        _ => SearchScope::Workspace, // Conservative default
    }
}

/// Determine Python scope based on naming conventions
///
/// - `_single_underscore` = private by convention = File scope
/// - `__dunder__` = special methods = Workspace scope (implicit calls)
/// - `__name_mangled` (double underscore, no trailing) = File scope
/// - Other = Workspace scope
fn determine_python_scope(symbol: &str, _definition_file: Option<&Path>) -> SearchScope {
    // __dunder__ methods are special - they're called implicitly
    if symbol.starts_with("__") && symbol.ends_with("__") {
        return SearchScope::Workspace;
    }

    // __name_mangled (double underscore without trailing) = private
    if symbol.starts_with("__") && !symbol.ends_with("__") {
        return SearchScope::File;
    }

    // _single_underscore = private by convention
    if symbol.starts_with('_') && !symbol.starts_with("__") {
        return SearchScope::File;
    }

    // Default: public symbol
    SearchScope::Workspace
}

/// Determine TypeScript/JavaScript scope
///
/// Without parsing the file, we can't know if a symbol is exported.
/// Conservative approach: assume Workspace scope.
fn determine_ts_scope(_symbol: &str, _definition_file: Option<&Path>) -> SearchScope {
    // TODO: Parse definition_file to check for export keyword
    // For now, be conservative and search workspace
    SearchScope::Workspace
}

/// Determine Go scope based on capitalization
///
/// - Uppercase first letter = exported = Workspace
/// - Lowercase first letter = package-private = File (approximation)
fn determine_go_scope(symbol: &str, _definition_file: Option<&Path>) -> SearchScope {
    if let Some(first_char) = symbol.chars().next() {
        if first_char.is_uppercase() {
            return SearchScope::Workspace;
        }
        // Lowercase = package-private, approximate as File scope
        return SearchScope::File;
    }
    SearchScope::Workspace
}

/// Determine Rust scope based on naming (conservative)
///
/// Without parsing the file, we can't know visibility modifiers.
/// Conservative approach: assume Workspace scope.
fn determine_rust_scope(_symbol: &str, _definition_file: Option<&Path>) -> SearchScope {
    // TODO: Parse definition_file to check pub/pub(crate)/private
    // For now, be conservative and search workspace
    SearchScope::Workspace
}

/// Apply scope filtering to text search candidates
///
/// Filters candidates based on the search scope:
/// - `Local`: Only candidates in the same file (TODO: same function)
/// - `File`: Only candidates in the definition file
/// - `Workspace`: No filtering, return all candidates
///
/// # Arguments
///
/// * `candidates` - Vector of text search candidates
/// * `scope` - The search scope to apply
/// * `definition_file` - The file containing the symbol definition
///
/// # Returns
///
/// Filtered vector of candidates matching the scope.
pub fn apply_scope_filter(
    candidates: Vec<TextCandidate>,
    scope: SearchScope,
    definition_file: Option<&Path>,
) -> Vec<TextCandidate> {
    match scope {
        SearchScope::Workspace => candidates, // No filter
        SearchScope::File => {
            if let Some(def_file) = definition_file {
                candidates
                    .into_iter()
                    .filter(|c| c.file == def_file)
                    .collect()
            } else {
                candidates // Can't filter without definition file
            }
        }
        SearchScope::Local => {
            // Local scope: restrict to same file
            // TODO: Further restrict to same function/block
            if let Some(def_file) = definition_file {
                candidates
                    .into_iter()
                    .filter(|c| c.file == def_file)
                    .collect()
            } else {
                candidates
            }
        }
    }
}

/// Filter references by allowed kinds
///
/// Returns only references whose kind is in the allowed_kinds list.
///
/// # Arguments
///
/// * `references` - Vector of references to filter
/// * `allowed_kinds` - Slice of allowed ReferenceKind values
///
/// # Returns
///
/// Filtered vector containing only references with allowed kinds.
///
/// # Example
///
/// ```ignore
/// let filtered = filter_by_kinds(refs, &[ReferenceKind::Call, ReferenceKind::Import]);
/// ```
pub fn filter_by_kinds(
    references: Vec<Reference>,
    allowed_kinds: &[ReferenceKind],
) -> Vec<Reference> {
    references
        .into_iter()
        .filter(|r| allowed_kinds.contains(&r.kind))
        .collect()
}

/// Get incoming calls (who calls this function)
///
/// This is a basic call hierarchy feature that finds all locations
/// where the specified symbol is called.
///
/// # Arguments
///
/// * `symbol` - The function/method name to find callers for
/// * `root` - The root directory to search in
/// * `options` - Reference finding options
///
/// # Returns
///
/// Vector of References with kind == Call
pub fn get_incoming_calls(
    symbol: &str,
    root: &Path,
    options: &ReferencesOptions,
) -> TldrResult<Vec<Reference>> {
    let report = find_references(symbol, root, options)?;
    Ok(report
        .references
        .into_iter()
        .filter(|r| r.kind == ReferenceKind::Call)
        .collect())
}

/// Get outgoing calls (what this function calls)
///
/// This finds all function calls made within a specific function.
/// Uses the AST to find all call expressions within the function body.
///
/// # Arguments
///
/// * `file` - Path to the file containing the function
/// * `function` - Name of the function to analyze
///
/// # Returns
///
/// Vector of function names that are called by the specified function.
///
/// # Note
///
/// This is a simplified implementation. For full call graph analysis,
/// use the `tldr calls` command infrastructure.
pub fn get_outgoing_calls(file: &Path, function: &str) -> TldrResult<Vec<String>> {
    use crate::ast::parser::parse_file;

    let (tree, source, language) = parse_file(file)?;
    let source_bytes = source.as_bytes();

    // Find the function node and extract calls in one pass
    let root = tree.root_node();
    let calls = find_and_extract_calls(&root, function, source_bytes, language);
    Ok(calls)
}

/// Find a function by name and extract all calls from it
///
/// Combines function finding and call extraction to avoid lifetime issues.
fn find_and_extract_calls(
    node: &tree_sitter::Node,
    function_name: &str,
    source: &[u8],
    language: Language,
) -> Vec<String> {
    let node_kind = node.kind();

    // Check if this is a function definition with matching name
    let is_function = ast_utils::function_node_kinds(language).contains(&node_kind);

    if is_function {
        if let Some(name_node) = node.child_by_field_name("name") {
            if name_node.utf8_text(source).unwrap_or("") == function_name {
                // Found the function, extract all calls from it
                let mut calls = Vec::new();
                extract_calls_recursive(node, source, language, &mut calls);
                return calls;
            }
        }
    }

    // Recurse into children
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        let calls = find_and_extract_calls(&child, function_name, source, language);
        if !calls.is_empty() {
            return calls;
        }
    }

    Vec::new()
}

/// Recursively extract call expressions from a node
fn extract_calls_recursive(
    node: &tree_sitter::Node,
    source: &[u8],
    language: Language,
    calls: &mut Vec<String>,
) {
    let node_kind = node.kind();

    // Check if this is a call expression
    let is_call = ast_utils::call_node_kinds(language).contains(&node_kind);

    if is_call {
        // Extract the function name being called
        if let Some(func_node) = node.child_by_field_name("function") {
            let func_text = func_node.utf8_text(source).unwrap_or("");
            // For simple identifiers, use as-is; for member access, extract the method name
            let call_name = if func_text.contains('.') {
                func_text.rsplit('.').next().unwrap_or(func_text)
            } else {
                func_text
            };
            if !call_name.is_empty() {
                calls.push(call_name.to_string());
            }
        }
    }

    // Recurse into children
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        extract_calls_recursive(&child, source, language, calls);
    }
}

// =============================================================================
// Unit Tests
// =============================================================================

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

    #[test]
    fn test_references_report_default() {
        let report = ReferencesReport::default();
        assert!(report.symbol.is_empty());
        assert!(report.definition.is_none());
        assert!(report.references.is_empty());
        assert_eq!(report.total_references, 0);
        assert_eq!(report.search_scope, SearchScope::Workspace);
    }

    #[test]
    fn test_references_report_new() {
        let report = ReferencesReport::new("test_symbol".to_string());
        assert_eq!(report.symbol, "test_symbol");
        assert!(report.definition.is_none());
        assert!(report.references.is_empty());
    }

    #[test]
    fn test_definition_kind_serialization() {
        let kinds = vec![
            DefinitionKind::Function,
            DefinitionKind::Class,
            DefinitionKind::Variable,
            DefinitionKind::Constant,
            DefinitionKind::Type,
            DefinitionKind::Module,
            DefinitionKind::Method,
            DefinitionKind::Property,
            DefinitionKind::Other,
        ];

        for kind in kinds {
            let json = serde_json::to_string(&kind).unwrap();
            let parsed: DefinitionKind = serde_json::from_str(&json).unwrap();
            assert_eq!(kind, parsed);
        }
    }

    #[test]
    fn test_reference_kind_serialization() {
        let kinds = vec![
            ReferenceKind::Call,
            ReferenceKind::Read,
            ReferenceKind::Write,
            ReferenceKind::Import,
            ReferenceKind::Type,
            ReferenceKind::Definition,
            ReferenceKind::Other,
        ];

        for kind in kinds {
            let json = serde_json::to_string(&kind).unwrap();
            let parsed: ReferenceKind = serde_json::from_str(&json).unwrap();
            assert_eq!(kind, parsed);
        }
    }

    #[test]
    fn test_search_scope_serialization() {
        let scopes = vec![
            SearchScope::Local,
            SearchScope::File,
            SearchScope::Workspace,
        ];

        for scope in scopes {
            let json = serde_json::to_string(&scope).unwrap();
            let parsed: SearchScope = serde_json::from_str(&json).unwrap();
            assert_eq!(scope, parsed);
        }
    }

    #[test]
    fn test_reference_kind_parse() {
        assert_eq!(ReferenceKind::parse("call"), Some(ReferenceKind::Call));
        assert_eq!(ReferenceKind::parse("CALL"), Some(ReferenceKind::Call));
        assert_eq!(ReferenceKind::parse("read"), Some(ReferenceKind::Read));
        assert_eq!(ReferenceKind::parse("invalid"), None);
    }

    #[test]
    fn test_search_scope_parse() {
        assert_eq!(SearchScope::parse("local"), Some(SearchScope::Local));
        assert_eq!(SearchScope::parse("FILE"), Some(SearchScope::File));
        assert_eq!(
            SearchScope::parse("workspace"),
            Some(SearchScope::Workspace)
        );
        assert_eq!(SearchScope::parse("invalid"), None);
    }

    #[test]
    fn test_truncate_context_short() {
        let short = "def login(): pass".to_string();
        let result = truncate_context(short.clone());
        assert_eq!(result, short);
    }

    #[test]
    fn test_truncate_context_long() {
        let long: String = "x".repeat(300);
        let result = truncate_context(long);
        assert!(result.len() <= MAX_CONTEXT_LENGTH);
        assert!(result.ends_with("..."));
    }

    #[test]
    fn test_definition_new() {
        let def = Definition::new(
            PathBuf::from("src/auth.py"),
            42,
            5,
            DefinitionKind::Function,
        );
        assert_eq!(def.file, PathBuf::from("src/auth.py"));
        assert_eq!(def.line, 42);
        assert_eq!(def.column, 5);
        assert_eq!(def.kind, DefinitionKind::Function);
        assert!(def.signature.is_none());
    }

    #[test]
    fn test_definition_with_signature() {
        let def = Definition::with_signature(
            PathBuf::from("src/auth.py"),
            42,
            5,
            DefinitionKind::Function,
            "def login(username: str, password: str) -> bool:".to_string(),
        );
        assert!(def.signature.is_some());
        assert!(def.signature.as_ref().unwrap().contains("login"));
    }

    #[test]
    fn test_reference_new() {
        let ref_ = Reference::new(
            PathBuf::from("src/routes.py"),
            15,
            12,
            ReferenceKind::Call,
            "result = auth.login(username, password)".to_string(),
        );
        assert_eq!(ref_.file, PathBuf::from("src/routes.py"));
        assert_eq!(ref_.line, 15);
        assert_eq!(ref_.column, 12);
        assert_eq!(ref_.kind, ReferenceKind::Call);
        assert!(ref_.confidence.is_none());
    }

    #[test]
    fn test_reference_verified() {
        let ref_ = Reference::verified(
            PathBuf::from("src/routes.py"),
            15,
            12,
            ReferenceKind::Call,
            "login()".to_string(),
        );
        assert_eq!(ref_.confidence, Some(1.0));
    }

    #[test]
    fn test_reference_stats_default() {
        let stats = ReferenceStats::default();
        assert_eq!(stats.files_searched, 0);
        assert_eq!(stats.candidates_found, 0);
        assert_eq!(stats.verified_references, 0);
        assert_eq!(stats.search_time_ms, 0);
    }

    #[test]
    fn test_reference_stats_with_time() {
        let stats = ReferenceStats::new(10, 50, 25).with_time(127);
        assert_eq!(stats.files_searched, 10);
        assert_eq!(stats.candidates_found, 50);
        assert_eq!(stats.verified_references, 25);
        assert_eq!(stats.search_time_ms, 127);
    }

    #[test]
    fn test_references_options_builder() {
        let opts = ReferencesOptions::new()
            .with_definition()
            .with_kinds(vec![ReferenceKind::Call, ReferenceKind::Import])
            .with_scope(SearchScope::File)
            .with_limit(100)
            .with_context_lines(2);

        assert!(opts.include_definition);
        assert_eq!(opts.kinds.as_ref().unwrap().len(), 2);
        assert_eq!(opts.scope, SearchScope::File);
        assert_eq!(opts.limit, Some(100));
        assert_eq!(opts.context_lines, 2);
    }

    #[test]
    fn test_report_serialization() {
        let report = ReferencesReport {
            symbol: "login".to_string(),
            definition: Some(Definition::new(
                PathBuf::from("src/auth.py"),
                42,
                5,
                DefinitionKind::Function,
            )),
            references: vec![Reference::new(
                PathBuf::from("src/routes.py"),
                15,
                12,
                ReferenceKind::Call,
                "login()".to_string(),
            )],
            total_references: 1,
            search_scope: SearchScope::Workspace,
            stats: ReferenceStats::new(10, 5, 1).with_time(50),
        };

        let json = serde_json::to_string_pretty(&report).unwrap();
        let parsed: ReferencesReport = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.symbol, "login");
        assert!(parsed.definition.is_some());
        assert_eq!(parsed.references.len(), 1);
        assert_eq!(parsed.total_references, 1);
        assert_eq!(parsed.search_scope, SearchScope::Workspace);
    }

    #[test]
    fn test_no_matches_report() {
        let report = ReferencesReport::no_matches(
            "nonexistent".to_string(),
            SearchScope::Workspace,
            ReferenceStats::new(50, 0, 0),
        );

        assert_eq!(report.symbol, "nonexistent");
        assert!(report.definition.is_none());
        assert!(report.references.is_empty());
        assert_eq!(report.total_references, 0);
        assert_eq!(report.stats.files_searched, 50);
    }

    // =========================================================================
    // Tier-2 classifier tests (VAL-Java..VAL-Ocaml)
    //
    // Each test parses a minimal fixture with one definition of `greet`
    // and two call sites. It walks the tree, classifies every identifier
    // whose text is `greet`, and asserts:
    //   1. at least one Definition
    //   2. at least two Calls
    //   3. NO Other for any occurrence of `greet`
    // =========================================================================

    /// Collect (kind, line) for every identifier-like node whose text equals `needle`.
    fn collect_reference_kinds_for(
        source: &str,
        lang: Language,
        needle: &str,
        identifier_kinds: &[&str],
    ) -> Vec<(ReferenceKind, usize)> {
        use crate::ast::parser;
        let tree = parser::parse(source, lang).expect("parse should succeed");
        let src_bytes = source.as_bytes();
        let mut results = Vec::new();

        fn walk<'a>(
            node: tree_sitter::Node<'a>,
            source: &'a [u8],
            src_str: &'a str,
            needle: &str,
            identifier_kinds: &[&str],
            language: Language,
            out: &mut Vec<(ReferenceKind, usize)>,
        ) {
            if identifier_kinds.contains(&node.kind()) {
                let start = node.start_byte();
                let end = node.end_byte();
                if end <= src_str.len() {
                    let text = &src_str[start..end];
                    if text == needle {
                        let kind = classify_reference_kind(&node, source, language);
                        let line = node.start_position().row + 1;
                        out.push((kind, line));
                    }
                }
            }
            for i in 0..node.child_count() {
                if let Some(child) = node.child(i) {
                    walk(child, source, src_str, needle, identifier_kinds, language, out);
                }
            }
        }

        walk(
            tree.root_node(),
            src_bytes,
            source,
            needle,
            identifier_kinds,
            lang,
            &mut results,
        );
        results
    }

    /// Assert the classifier found at least one Definition and at least two Calls,
    /// and never returned Other for the needle identifier.
    fn assert_def_and_calls(results: &[(ReferenceKind, usize)], language_name: &str) {
        assert!(
            !results.is_empty(),
            "{}: no occurrences of `greet` matched by walker",
            language_name
        );
        let def_count = results
            .iter()
            .filter(|(k, _)| *k == ReferenceKind::Definition)
            .count();
        let call_count = results
            .iter()
            .filter(|(k, _)| *k == ReferenceKind::Call)
            .count();
        let other_count = results
            .iter()
            .filter(|(k, _)| *k == ReferenceKind::Other)
            .count();
        assert!(
            def_count >= 1,
            "{}: expected >=1 Definition, got {} (results={:?})",
            language_name,
            def_count,
            results
        );
        assert!(
            call_count >= 2,
            "{}: expected >=2 Calls, got {} (results={:?})",
            language_name,
            call_count,
            results
        );
        assert_eq!(
            other_count, 0,
            "{}: expected 0 Other, got {} (results={:?})",
            language_name, other_count, results
        );
    }

    #[test]
    fn test_java_classifier_emits_call_and_definition() {
        let src = r#"
class App {
    static String greet(String name) { return "Hello " + name; }
    public static void main(String[] args) {
        System.out.println(greet("World"));
        System.out.println(greet("Alice"));
    }
}
"#;
        let results = collect_reference_kinds_for(src, Language::Java, "greet", &["identifier"]);
        assert_def_and_calls(&results, "Java");
    }

    #[test]
    fn test_c_classifier_emits_call_and_definition() {
        let src = r#"
#include <stdio.h>
void greet(const char *name) { printf("Hello %s\n", name); }
int main(void) {
    greet("World");
    greet("Alice");
    return 0;
}
"#;
        let results = collect_reference_kinds_for(src, Language::C, "greet", &["identifier"]);
        assert_def_and_calls(&results, "C");
    }

    #[test]
    fn test_cpp_classifier_emits_call_and_definition() {
        let src = r#"
#include <iostream>
void greet(const std::string &name) { std::cout << "Hello " << name; }
int main() {
    greet("World");
    greet("Alice");
    return 0;
}
"#;
        let results = collect_reference_kinds_for(src, Language::Cpp, "greet", &["identifier"]);
        assert_def_and_calls(&results, "C++");
    }

    #[test]
    fn test_csharp_classifier_emits_call_and_definition() {
        let src = r#"
class App {
    static string greet(string name) { return "Hello " + name; }
    static void Main() {
        System.Console.WriteLine(greet("World"));
        System.Console.WriteLine(greet("Alice"));
    }
}
"#;
        let results =
            collect_reference_kinds_for(src, Language::CSharp, "greet", &["identifier"]);
        assert_def_and_calls(&results, "C#");
    }

    #[test]
    fn test_kotlin_classifier_emits_call_and_definition() {
        let src = r#"
fun greet(name: String): String { return "Hello " + name }
fun main() {
    println(greet("World"))
    println(greet("Alice"))
}
"#;
        let results =
            collect_reference_kinds_for(src, Language::Kotlin, "greet", &["identifier"]);
        assert_def_and_calls(&results, "Kotlin");
    }

    #[test]
    fn test_scala_classifier_emits_call_and_definition() {
        let src = r#"
object App {
  def greet(name: String): String = "Hello " + name
  def main(args: Array[String]): Unit = {
    println(greet("World"))
    println(greet("Alice"))
  }
}
"#;
        let results = collect_reference_kinds_for(
            src,
            Language::Scala,
            "greet",
            &["identifier", "type_identifier"],
        );
        assert_def_and_calls(&results, "Scala");
    }

    #[test]
    fn test_swift_classifier_emits_call_and_definition() {
        let src = r#"
func greet(name: String) -> String { return "Hello " + name }
func main() {
    print(greet(name: "World"))
    print(greet(name: "Alice"))
}
"#;
        let results =
            collect_reference_kinds_for(src, Language::Swift, "greet", &["simple_identifier"]);
        assert_def_and_calls(&results, "Swift");
    }

    #[test]
    fn test_php_classifier_emits_call_and_definition() {
        let src = r#"<?php
function greet($name) { return "Hello " . $name; }
echo greet("World");
echo greet("Alice");
"#;
        let results = collect_reference_kinds_for(src, Language::Php, "greet", &["name"]);
        assert_def_and_calls(&results, "PHP");
    }

    #[test]
    fn test_ruby_classifier_emits_call_and_definition() {
        let src = r#"
def greet(name)
  "Hello " + name
end
puts greet("World")
puts greet("Alice")
"#;
        let results = collect_reference_kinds_for(src, Language::Ruby, "greet", &["identifier"]);
        assert_def_and_calls(&results, "Ruby");
    }

    #[test]
    fn test_lua_classifier_emits_call_and_definition() {
        let src = r#"
function greet(name)
  return "Hello " .. name
end
print(greet("World"))
print(greet("Alice"))
"#;
        let results = collect_reference_kinds_for(src, Language::Lua, "greet", &["identifier"]);
        assert_def_and_calls(&results, "Lua");
    }

    #[test]
    fn test_luau_classifier_emits_call_and_definition() {
        let src = r#"
function greet(name: string): string
  return "Hello " .. name
end
print(greet("World"))
print(greet("Alice"))
"#;
        let results = collect_reference_kinds_for(src, Language::Luau, "greet", &["identifier"]);
        assert_def_and_calls(&results, "Luau");
    }

    #[test]
    fn test_elixir_classifier_emits_call_and_definition() {
        let src = r#"
defmodule App do
  def greet(name) do
    "Hello " <> name
  end
end

IO.puts(App.greet("World"))
IO.puts(App.greet("Alice"))
"#;
        let results =
            collect_reference_kinds_for(src, Language::Elixir, "greet", &["identifier"]);
        assert_def_and_calls(&results, "Elixir");
    }

    #[test]
    fn test_ocaml_classifier_emits_call_and_definition() {
        let src = r#"
let greet name = "Hello " ^ name
let _ = print_string (greet "World")
let _ = print_string (greet "Alice")
"#;
        let results =
            collect_reference_kinds_for(src, Language::Ocaml, "greet", &["value_name"]);
        assert_def_and_calls(&results, "OCaml");
    }
}