windjammer-lsp 0.35.1

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

use tower_lsp::lsp_types::Url;
use windjammer::{lexer, parser};

// ============================================================================
// Database Definition
// ============================================================================

/// The main Salsa database implementation
#[salsa::db]
#[derive(Clone)]
pub struct WindjammerDatabase {
    storage: salsa::Storage<Self>,
    /// Lazy loading cache for symbols (only load when accessed)
    symbol_cache: std::sync::Arc<std::sync::Mutex<std::collections::HashMap<Url, bool>>>,
    /// Lazy loading cache for references
    reference_cache: std::sync::Arc<std::sync::Mutex<std::collections::HashMap<Url, bool>>>,
}

impl Default for WindjammerDatabase {
    fn default() -> Self {
        Self::new()
    }
}

#[salsa::db]
impl salsa::Database for WindjammerDatabase {}

// ============================================================================
// Input Structs
// ============================================================================

/// Represents a source file
///
/// This is an input - it can be set by the caller and triggers recomputation
/// when changed.
#[salsa::input]
pub struct SourceFile {
    #[returns(ref)]
    pub uri: Url,

    #[returns(ref)]
    pub text: String,
}

// ============================================================================
// Tracked Structs (Intermediate Results)
// ============================================================================

/// A parsed program (memoized)
///
/// Now that parser::Program implements Hash/PartialEq/Eq, we can use it
/// in a tracked struct for better Salsa integration.
#[salsa::tracked]
pub struct ParsedProgram<'db> {
    #[returns(ref)]
    pub program: parser::Program,
}

/// Import information for a file
#[salsa::tracked]
pub struct ImportInfo<'db> {
    #[returns(ref)]
    pub imports: Vec<Url>,
}

/// Symbol information for a file
#[salsa::tracked]
pub struct SymbolTable<'db> {
    #[returns(ref)]
    pub symbols: Vec<Symbol>,
}

/// A symbol definition with detailed position information
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Symbol {
    pub name: String,
    pub kind: SymbolKind,
    pub line: u32,
    pub character: u32,
    /// Full range of the symbol (for precise selection)
    pub range: Option<SymbolRange>,
    /// Range of just the symbol name (for rename operations)
    pub name_range: Option<SymbolRange>,
    /// Type information (if available)
    pub type_info: Option<String>,
    /// Documentation comment
    pub doc: Option<String>,
}

/// A range in the source code
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SymbolRange {
    pub start_line: u32,
    pub start_character: u32,
    pub end_line: u32,
    pub end_character: u32,
}

/// A reference to a symbol (usage location)
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SymbolReference {
    pub name: String,
    pub uri: Url,
    pub line: u32,
    pub character: u32,
}

/// References found in a file
#[salsa::tracked]
pub struct ReferenceInfo<'db> {
    #[returns(ref)]
    pub references: Vec<SymbolReference>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SymbolKind {
    Function,
    Struct,
    Enum,
    Trait,
    Impl,
    Const,
    Static,
}

// ============================================================================
// Tracked Functions (Derived Computations)
// ============================================================================

/// Parse a source file into an AST
///
/// This function is memoized - it only recomputes if the source text changes.
#[salsa::tracked]
pub fn parse<'db>(db: &'db dyn salsa::Database, file: SourceFile) -> ParsedProgram<'db> {
    let uri = file.uri(db);
    let text = file.text(db);

    tracing::debug!("Salsa: Parsing {}", uri);

    // Lex and parse
    let mut lexer = lexer::Lexer::new(text);
    let tokens = lexer.tokenize_with_locations();
    let mut parser = parser::Parser::new(tokens);

    let program = match parser.parse() {
        Ok(prog) => prog,
        Err(e) => {
            tracing::error!("Parse error in {}: {}", uri, e);
            // Return empty program on error
            parser::Program { items: vec![] }
        }
    };

    ParsedProgram::new(db, program)
}

/// Extract imports from a source file
///
/// Returns URIs of files that this file imports.
#[salsa::tracked]
pub fn imports<'db>(db: &'db dyn salsa::Database, file: SourceFile) -> ImportInfo<'db> {
    let parsed = parse(db, file);
    let program = parsed.program(db);

    let uri = file.uri(db);
    tracing::debug!("Salsa: Extracting imports from {}", uri);

    let mut import_uris = Vec::new();

    // Extract and resolve imports from the AST
    for item in &program.items {
        if let parser::Item::Use {
            path,
            alias: _,
            location: _,
        } = item
        {
            let import_path = path.join(".");
            tracing::debug!("Found import: {}", import_path);

            // Resolve import path to actual file URI
            if let Some(resolved_uri) = resolve_import(uri, &import_path) {
                tracing::debug!("Resolved import '{}' to {}", import_path, resolved_uri);
                import_uris.push(resolved_uri);
            } else {
                tracing::debug!("Could not resolve import: {}", import_path);
            }
        }
    }

    tracing::debug!("Resolved {} imports from {}", import_uris.len(), uri);
    ImportInfo::new(db, import_uris)
}

/// Extract symbols from a source file
///
/// Returns all symbol definitions in the file (functions, structs, etc.)
#[salsa::tracked]
pub fn extract_symbols<'db>(db: &'db dyn salsa::Database, file: SourceFile) -> SymbolTable<'db> {
    let parsed = parse(db, file);
    let program = parsed.program(db);

    let uri = file.uri(db);
    tracing::debug!("Salsa: Extracting symbols from {}", uri);

    let mut symbols = Vec::new();

    // Extract symbols from top-level items
    for (idx, item) in program.items.iter().enumerate() {
        // Use item index as line heuristic (AST doesn't have position info yet)
        let line = idx as u32;

        match item {
            parser::Item::Function {
                decl: func,
                location: _,
            } => {
                symbols.push(Symbol {
                    name: func.name.clone(),
                    kind: SymbolKind::Function,
                    line,
                    character: 0,
                    range: None, // TODO: Extract from AST when available
                    name_range: None,
                    type_info: func.return_type.as_ref().map(|t| format!("{:?}", t)),
                    doc: None, // TODO: Extract doc comments
                });
            }
            parser::Item::Struct {
                decl: struct_decl,
                location: _,
            } => {
                symbols.push(Symbol {
                    name: struct_decl.name.clone(),
                    kind: SymbolKind::Struct,
                    line,
                    character: 0,
                    range: None,
                    name_range: None,
                    type_info: None,
                    doc: None,
                });
            }
            parser::Item::Enum {
                decl: enum_decl,
                location: _,
            } => {
                symbols.push(Symbol {
                    name: enum_decl.name.clone(),
                    kind: SymbolKind::Enum,
                    line,
                    character: 0,
                    range: None,
                    name_range: None,
                    type_info: None,
                    doc: None,
                });
            }
            parser::Item::Trait {
                decl: trait_decl,
                location: _,
            } => {
                symbols.push(Symbol {
                    name: trait_decl.name.clone(),
                    kind: SymbolKind::Trait,
                    line,
                    character: 0,
                    range: None,
                    name_range: None,
                    type_info: None,
                    doc: None,
                });
            }
            parser::Item::Impl {
                block: impl_block,
                location: _,
            } => {
                // Impl blocks don't have a name, use type name
                let name = if let Some(trait_name) = &impl_block.trait_name {
                    format!("impl {} for {}", trait_name, impl_block.type_name)
                } else {
                    format!("impl {}", impl_block.type_name)
                };
                symbols.push(Symbol {
                    name,
                    kind: SymbolKind::Impl,
                    line,
                    character: 0,
                    range: None,
                    name_range: None,
                    type_info: Some(impl_block.type_name.clone()),
                    doc: None,
                });
            }
            parser::Item::Const { name, type_, .. } => {
                symbols.push(Symbol {
                    name: name.clone(),
                    kind: SymbolKind::Const,
                    line,
                    character: 0,
                    range: None,
                    name_range: None,
                    type_info: Some(format!("{:?}", type_)), // Use Debug for now
                    doc: None,
                });
            }
            parser::Item::Static { name, type_, .. } => {
                symbols.push(Symbol {
                    name: name.clone(),
                    kind: SymbolKind::Static,
                    line,
                    character: 0,
                    range: None,
                    name_range: None,
                    type_info: Some(format!("{:?}", type_)), // Use Debug for now
                    doc: None,
                });
            }
            _ => {} // Skip other items (use statements, etc.)
        }
    }

    tracing::debug!("Found {} symbols in {}", symbols.len(), uri);
    SymbolTable::new(db, symbols)
}

/// Extract symbol references from a source file
///
/// Finds all usages of symbols in expressions, function calls, etc.
#[salsa::tracked]
pub fn extract_references<'db>(
    db: &'db dyn salsa::Database,
    file: SourceFile,
) -> ReferenceInfo<'db> {
    let parsed = parse(db, file);
    let program = parsed.program(db);

    let uri = file.uri(db).clone();
    tracing::debug!("Salsa: Extracting references from {}", uri);

    let references = Vec::new();

    // Walk the AST to find all identifier references
    // For now, we'll extract function calls as a starting point
    for item in program.items.iter() {
        if let parser::Item::Function {
            decl: func,
            location: _,
        } = item
        {
            // Scan function body for references
            // TODO: Implement proper AST walking
            // For now, we'll just note that references exist
            tracing::debug!("TODO: Scan function '{}' body for references", func.name);
        }
    }

    tracing::debug!("Found {} references in {}", references.len(), uri);
    ReferenceInfo::new(db, references)
}

// ============================================================================
// Code Actions & Refactorings
// ============================================================================

/// A code action for refactoring
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CodeAction {
    pub title: String,
    pub kind: CodeActionKind,
    pub edits: Vec<TextEdit>,
    pub is_preferred: bool,
}

/// Types of code actions
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CodeActionKind {
    /// Quick fix for a diagnostic
    QuickFix,
    /// Refactor: Extract function
    RefactorExtract,
    /// Refactor: Inline variable/function
    RefactorInline,
    /// Refactor: Rename
    RefactorRename,
    /// Refactor: Change signature
    RefactorChangeSignature,
    /// Refactor: Move item
    RefactorMove,
}

impl WindjammerDatabase {
    /// Get available code actions for a selection
    ///
    /// Returns code actions that can be applied at the given range.
    pub fn get_code_actions(
        &mut self,
        file: SourceFile,
        range: tower_lsp::lsp_types::Range,
    ) -> Vec<CodeAction> {
        let mut actions = Vec::new();

        // Try to extract function
        if let Some(action) = self.try_extract_function(file, range) {
            actions.push(action);
        }

        // Try to inline variable
        if let Some(action) = self.try_inline_variable(file, range) {
            actions.push(action);
        }

        // Try to inline function
        if let Some(action) = self.try_inline_function(file, range) {
            actions.push(action);
        }

        actions
    }

    /// Try to extract the selected code into a function
    fn try_extract_function(
        &mut self,
        file: SourceFile,
        range: tower_lsp::lsp_types::Range,
    ) -> Option<CodeAction> {
        let text = file.text(self);
        let lines: Vec<&str> = text.lines().collect();

        // Get selected text
        let start_line = range.start.line as usize;
        let end_line = range.end.line as usize;

        if start_line >= lines.len() || end_line >= lines.len() {
            return None;
        }

        // Extract the selected code
        let mut selected_code = String::new();
        for (idx, line) in lines
            .iter()
            .enumerate()
            .skip(start_line)
            .take(end_line - start_line + 1)
        {
            let line_idx = idx;
            if line_idx == start_line && line_idx == end_line {
                // Single line selection
                let start_char = range.start.character as usize;
                let end_char = range.end.character as usize;
                if start_char < line.len() && end_char <= line.len() {
                    selected_code.push_str(&line[start_char..end_char]);
                }
            } else if line_idx == start_line {
                // First line of multi-line selection
                let line = lines[line_idx];
                let start_char = range.start.character as usize;
                if start_char < line.len() {
                    selected_code.push_str(&line[start_char..]);
                    selected_code.push('\n');
                }
            } else if line_idx == end_line {
                // Last line of multi-line selection
                let line = lines[line_idx];
                let end_char = range.end.character as usize;
                if end_char <= line.len() {
                    selected_code.push_str(&line[..end_char]);
                }
            } else {
                // Middle lines
                selected_code.push_str(lines[line_idx]);
                selected_code.push('\n');
            }
        }

        if selected_code.trim().is_empty() {
            return None;
        }

        // Generate the extracted function
        let function_name = "extracted_function";
        let extracted_function = format!(
            "fn {}() {{\n    {}\n}}\n\n",
            function_name,
            selected_code.trim()
        );

        // Create edits
        let mut edits = Vec::new();

        // 1. Replace selection with function call
        edits.push(TextEdit {
            range,
            new_text: format!("{}()", function_name),
        });

        // 2. Insert function above current function
        // Find the start of the current function
        let insert_line = start_line.saturating_sub(1);
        edits.push(TextEdit {
            range: tower_lsp::lsp_types::Range {
                start: tower_lsp::lsp_types::Position {
                    line: insert_line as u32,
                    character: 0,
                },
                end: tower_lsp::lsp_types::Position {
                    line: insert_line as u32,
                    character: 0,
                },
            },
            new_text: extracted_function,
        });

        Some(CodeAction {
            title: "Extract function".to_string(),
            kind: CodeActionKind::RefactorExtract,
            edits,
            is_preferred: true,
        })
    }

    /// Try to inline a variable at the cursor
    fn try_inline_variable(
        &mut self,
        _file: SourceFile,
        _range: tower_lsp::lsp_types::Range,
    ) -> Option<CodeAction> {
        // TODO: Implement variable inlining
        // This requires:
        // 1. Identify the variable at the cursor
        // 2. Find all uses of the variable
        // 3. Replace uses with the variable's value
        None
    }

    /// Try to inline a function at the cursor
    fn try_inline_function(
        &mut self,
        _file: SourceFile,
        _range: tower_lsp::lsp_types::Range,
    ) -> Option<CodeAction> {
        // TODO: Implement function inlining
        // This requires:
        // 1. Identify the function call at the cursor
        // 2. Get the function body
        // 3. Replace call with inlined body
        None
    }
}

// ============================================================================
// Database API
// ============================================================================

impl WindjammerDatabase {
    /// Create a new database
    pub fn new() -> Self {
        Self {
            storage: Default::default(),
            symbol_cache: Default::default(),
            reference_cache: Default::default(),
        }
    }

    /// Check if symbols are loaded for a file
    pub fn are_symbols_loaded(&self, file: SourceFile) -> bool {
        let uri = file.uri(self);
        self.symbol_cache
            .lock()
            .unwrap()
            .get(uri)
            .copied()
            .unwrap_or(false)
    }

    /// Mark symbols as loaded for a file
    pub fn mark_symbols_loaded(&self, file: SourceFile) {
        let uri = file.uri(self).clone();
        self.symbol_cache.lock().unwrap().insert(uri, true);
    }

    /// Check if references are loaded for a file
    pub fn are_references_loaded(&self, file: SourceFile) -> bool {
        let uri = file.uri(self);
        self.reference_cache
            .lock()
            .unwrap()
            .get(uri)
            .copied()
            .unwrap_or(false)
    }

    /// Mark references as loaded for a file
    pub fn mark_references_loaded(&self, file: SourceFile) {
        let uri = file.uri(self).clone();
        self.reference_cache.lock().unwrap().insert(uri, true);
    }

    /// Get symbols with lazy loading
    pub fn get_symbols_lazy(&mut self, file: SourceFile) -> &Vec<Symbol> {
        if !self.are_symbols_loaded(file) {
            // Trigger computation
            let _symbols = self.get_symbols(file);
            self.mark_symbols_loaded(file);
        }
        self.get_symbols(file)
    }

    /// Get references with lazy loading
    pub fn get_references_lazy(&mut self, file: SourceFile) -> &Vec<SymbolReference> {
        if !self.are_references_loaded(file) {
            // Trigger computation
            let _refs = self.get_references(file);
            self.mark_references_loaded(file);
        }
        self.get_references(file)
    }

    /// Clear lazy loading caches (useful after file changes)
    pub fn clear_lazy_caches(&self) {
        self.symbol_cache.lock().unwrap().clear();
        self.reference_cache.lock().unwrap().clear();
    }

    /// Preload symbols for multiple files
    ///
    /// Note: This is sequential within the database context, but Salsa
    /// internally parallelizes computation across files.
    pub fn preload_symbols(&mut self, files: &[SourceFile]) {
        for file in files {
            if !self.are_symbols_loaded(*file) {
                let _ = self.get_symbols(*file);
                self.mark_symbols_loaded(*file);
            }
        }
    }

    /// Set the source text for a file
    ///
    /// Returns a SourceFile handle that can be used in queries.
    pub fn set_source_text(&mut self, uri: Url, text: String) -> SourceFile {
        SourceFile::new(self, uri, text)
    }

    /// Get the parsed program for a file
    pub fn get_program(&self, file: SourceFile) -> &parser::Program {
        let parsed = parse(self, file);
        parsed.program(self)
    }

    /// Get imports for a file
    pub fn get_imports(&self, file: SourceFile) -> &Vec<Url> {
        let import_info = imports(self, file);
        import_info.imports(self)
    }

    /// Get symbols for a file
    pub fn get_symbols(&self, file: SourceFile) -> &Vec<Symbol> {
        let symbol_table = extract_symbols(self, file);
        symbol_table.symbols(self)
    }

    /// Get references for a file
    pub fn get_references(&self, file: SourceFile) -> &Vec<SymbolReference> {
        let reference_info = extract_references(self, file);
        reference_info.references(self)
    }

    /// Find all references to a symbol across multiple files
    ///
    /// This searches through all provided files for references to the given symbol name.
    pub fn find_all_references(
        &self,
        symbol_name: &str,
        files: &[SourceFile],
    ) -> Vec<tower_lsp::lsp_types::Location> {
        let mut locations = Vec::new();

        // Search through all files
        for &file in files {
            let uri = file.uri(self).clone();

            // Check if symbol is defined in this file
            let symbols = self.get_symbols(file);
            for symbol in symbols {
                if symbol.name == symbol_name {
                    // Found definition
                    locations.push(tower_lsp::lsp_types::Location {
                        uri: uri.clone(),
                        range: tower_lsp::lsp_types::Range {
                            start: tower_lsp::lsp_types::Position {
                                line: symbol.line,
                                character: symbol.character,
                            },
                            end: tower_lsp::lsp_types::Position {
                                line: symbol.line,
                                character: symbol.character + symbol.name.len() as u32,
                            },
                        },
                    });
                }
            }

            // Check references in this file (when implemented)
            let references = self.get_references(file);
            for reference in references {
                if reference.name == symbol_name {
                    locations.push(tower_lsp::lsp_types::Location {
                        uri: reference.uri.clone(),
                        range: tower_lsp::lsp_types::Range {
                            start: tower_lsp::lsp_types::Position {
                                line: reference.line,
                                character: reference.character,
                            },
                            end: tower_lsp::lsp_types::Position {
                                line: reference.line,
                                character: reference.character + reference.name.len() as u32,
                            },
                        },
                    });
                }
            }
        }

        tracing::debug!(
            "Found {} references to '{}' across {} files",
            locations.len(),
            symbol_name,
            files.len()
        );

        locations
    }

    /// Find the definition of a symbol across multiple files
    ///
    /// Searches through all provided files for the definition of the given symbol.
    /// Returns the first matching definition found.
    pub fn find_definition(
        &self,
        symbol_name: &str,
        files: &[SourceFile],
    ) -> Option<tower_lsp::lsp_types::Location> {
        // Search through all files for the definition
        for &file in files {
            let uri = file.uri(self).clone();
            let symbols = self.get_symbols(file);

            for symbol in symbols {
                if symbol.name == symbol_name {
                    // Found definition!
                    tracing::debug!("Found definition of '{}' in {}", symbol_name, uri);
                    return Some(tower_lsp::lsp_types::Location {
                        uri,
                        range: tower_lsp::lsp_types::Range {
                            start: tower_lsp::lsp_types::Position {
                                line: symbol.line,
                                character: symbol.character,
                            },
                            end: tower_lsp::lsp_types::Position {
                                line: symbol.line,
                                character: symbol.character + symbol.name.len() as u32,
                            },
                        },
                    });
                }
            }
        }

        tracing::debug!("Definition of '{}' not found", symbol_name);
        None
    }
}

// ============================================================================
// Helper Functions
// ============================================================================

/// Resolve an import path to a URI
///
/// Given a source file and an import path like `utils.helpers`, resolves to the actual file URI.
///
/// Resolution strategy:
/// 1. Skip standard library imports (std.*)
/// 2. Check relative to current file
/// 3. Check relative to project root (look for Cargo.toml or wj.toml)
fn resolve_import(source_uri: &Url, import_path: &str) -> Option<Url> {
    tracing::debug!("Resolving import '{}' from {}", import_path, source_uri);

    // Skip standard library imports for now
    if import_path.starts_with("std.") {
        tracing::debug!("Skipping std library import: {}", import_path);
        return None;
    }

    // Convert dotted path to file path: utils.helpers -> utils/helpers.wj
    let file_path = import_path.replace('.', "/") + ".wj";

    // Try to get the directory of the source file
    let source_path = source_uri.to_file_path().ok()?;
    let source_dir = source_path.parent()?;

    // Strategy 1: Relative to current file
    let relative_path = source_dir.join(&file_path);
    if relative_path.exists() {
        let resolved_uri = Url::from_file_path(relative_path).ok()?;
        tracing::debug!("Resolved '{}' to {} (relative)", import_path, resolved_uri);
        return Some(resolved_uri);
    }

    // Strategy 2: Relative to project root (find Cargo.toml or wj.toml)
    let mut current_dir = source_dir;
    while let Some(parent) = current_dir.parent() {
        // Check for project root markers
        if parent.join("Cargo.toml").exists() || parent.join("wj.toml").exists() {
            let project_path = parent.join(&file_path);
            if project_path.exists() {
                let resolved_uri = Url::from_file_path(project_path).ok()?;
                tracing::debug!(
                    "Resolved '{}' to {} (project root)",
                    import_path,
                    resolved_uri
                );
                return Some(resolved_uri);
            }
            break;
        }
        current_dir = parent;
    }

    tracing::debug!("Could not resolve import: {}", import_path);
    None
}

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

    #[test]
    fn test_basic_parse() {
        let mut db = WindjammerDatabase::new();
        let uri = Url::parse("file:///test.wj").unwrap();

        let file = db.set_source_text(uri, "fn main() {}".to_string());

        let program = db.get_program(file);
        assert_eq!(program.items.len(), 1);

        // Verify it's a function
        if let parser::Item::Function { decl: func, .. } = &program.items[0] {
            assert_eq!(func.name, "main");
        } else {
            panic!("Expected function item");
        }
    }

    #[test]
    fn test_incremental_update() {
        let mut db = WindjammerDatabase::new();
        let uri = Url::parse("file:///test.wj").unwrap();

        // Initial parse
        let file1 = db.set_source_text(uri.clone(), "fn foo() {}".to_string());
        let program1 = db.get_program(file1);
        assert_eq!(program1.items.len(), 1);

        // Update source - creates a new SourceFile input
        let file2 = db.set_source_text(uri, "fn foo() {}\nfn bar() {}".to_string());
        let program2 = db.get_program(file2);
        assert_eq!(program2.items.len(), 2);
    }

    #[test]
    fn test_memoization() {
        let mut db = WindjammerDatabase::new();
        let uri = Url::parse("file:///test.wj").unwrap();

        let file = db.set_source_text(uri, "fn main() {}".to_string());

        // First parse
        let program1 = db.get_program(file);

        // Second parse (should be memoized - same pointer)
        let program2 = db.get_program(file);

        // Should return the same reference (memoized)
        assert!(std::ptr::eq(program1, program2));
    }

    #[test]
    fn test_parse_error_handling() {
        let mut db = WindjammerDatabase::new();
        let uri = Url::parse("file:///test.wj").unwrap();

        // Invalid syntax
        let file = db.set_source_text(uri, "fn }}}".to_string());

        // Should not panic, should return empty program
        let program = db.get_program(file);
        assert_eq!(program.items.len(), 0);
    }

    #[test]
    fn test_extract_imports() {
        let mut db = WindjammerDatabase::new();
        let uri = Url::parse("file:///test.wj").unwrap();

        let file = db.set_source_text(uri, "use std.fs\nuse std.http\nfn main() {}".to_string());

        let imports = db.get_imports(file);

        // For now, imports are empty until we implement resolution
        // But the function should not crash
        assert_eq!(imports.len(), 0);
    }
}

// ============================================================================
// Parallel Processing Utilities
// ============================================================================

/// Configuration for parallel processing
#[derive(Debug, Clone)]
pub struct ParallelConfig {
    /// Number of threads to use (0 = use all available cores)
    pub num_threads: usize,
    /// Minimum number of files to process in parallel (below this, use sequential)
    pub min_files_for_parallel: usize,
}

impl Default for ParallelConfig {
    fn default() -> Self {
        Self {
            num_threads: 0,            // Use all available cores
            min_files_for_parallel: 5, // Only parallelize if >= 5 files
        }
    }
}

impl WindjammerDatabase {
    /// Process multiple source files in parallel
    ///
    /// This is useful for initial project loading or when many files change at once.
    /// Uses rayon to parallelize parsing and symbol extraction.
    pub fn process_files_parallel(
        &mut self,
        files: Vec<(Url, String)>,
        config: &ParallelConfig,
    ) -> Vec<SourceFile> {
        // Configure rayon thread pool if specified
        if config.num_threads > 0 {
            rayon::ThreadPoolBuilder::new()
                .num_threads(config.num_threads)
                .build_global()
                .ok(); // Ignore error if already initialized
        }

        // If too few files, process sequentially
        if files.len() < config.min_files_for_parallel {
            return files
                .into_iter()
                .map(|(uri, text)| self.set_source_text(uri, text))
                .collect();
        }

        tracing::info!(
            "Processing {} files in parallel with {} threads",
            files.len(),
            rayon::current_num_threads()
        );

        // Process files in parallel
        // Note: We can't parallelize the actual Salsa operations due to &mut self,
        // but we can prepare the data in parallel
        files
            .into_iter()
            .map(|(uri, text)| self.set_source_text(uri, text))
            .collect()
    }

    /// Extract symbols from multiple files in parallel
    ///
    /// This leverages Salsa's caching - if files haven't changed, symbols are cached.
    pub fn extract_symbols_parallel(&mut self, files: &[SourceFile]) -> Vec<&[Symbol]> {
        tracing::debug!("Extracting symbols from {} files", files.len());

        // Salsa queries are already cached, so we can call them sequentially
        // The caching makes this very fast
        files
            .iter()
            .map(|file| {
                let symbols = self.get_symbols(*file);
                symbols.as_slice()
            })
            .collect()
    }

    /// Find all references across multiple files (optimized for parallel queries)
    ///
    /// This is the same as find_all_references but with additional logging
    /// and potential future optimizations for large file sets.
    pub fn find_all_references_parallel(
        &mut self,
        symbol_name: &str,
        files: &[SourceFile],
    ) -> Vec<tower_lsp::lsp_types::Location> {
        use tower_lsp::lsp_types::{Location, Position, Range};

        tracing::debug!(
            "Finding all references to '{}' across {} files (parallel-optimized)",
            symbol_name,
            files.len()
        );

        let mut locations = Vec::new();

        for file in files {
            let uri = file.uri(self);
            let symbols = self.get_symbols(*file); // Cached by Salsa

            for symbol in symbols.iter() {
                if symbol.name == symbol_name {
                    locations.push(Location {
                        uri: uri.clone(),
                        range: Range {
                            start: Position {
                                line: symbol.line,
                                character: symbol.character,
                            },
                            end: Position {
                                line: symbol.line,
                                character: symbol.character + symbol.name.len() as u32,
                            },
                        },
                    });
                }
            }
        }

        tracing::debug!("Found {} locations for '{}'", locations.len(), symbol_name);
        locations
    }

    /// Find all implementations of a trait
    ///
    /// Returns impl blocks that implement the specified trait.
    pub fn find_trait_implementations(
        &mut self,
        trait_name: &str,
        files: &[SourceFile],
    ) -> Vec<TraitImplementation> {
        tracing::debug!("Finding implementations of trait '{}'", trait_name);

        let mut implementations = Vec::new();

        for file in files {
            let uri = file.uri(self);
            let symbols = self.get_symbols(*file);

            for symbol in symbols.iter() {
                if symbol.kind == SymbolKind::Impl {
                    // Impl names are formatted as "impl Trait for Type"
                    if symbol.name.contains(trait_name) {
                        implementations.push(TraitImplementation {
                            trait_name: trait_name.to_string(),
                            type_name: self.extract_type_from_impl(&symbol.name),
                            location: tower_lsp::lsp_types::Location {
                                uri: uri.clone(),
                                range: tower_lsp::lsp_types::Range {
                                    start: tower_lsp::lsp_types::Position {
                                        line: symbol.line,
                                        character: symbol.character,
                                    },
                                    end: tower_lsp::lsp_types::Position {
                                        line: symbol.line,
                                        character: symbol.character + symbol.name.len() as u32,
                                    },
                                },
                            },
                        });
                    }
                }
            }
        }

        tracing::debug!(
            "Found {} implementations of '{}'",
            implementations.len(),
            trait_name
        );
        implementations
    }

    /// Extract type name from impl block name
    fn extract_type_from_impl(&self, impl_name: &str) -> String {
        // Parse "impl Trait for Type" or "impl Type"
        if let Some(for_pos) = impl_name.find(" for ") {
            impl_name[for_pos + 5..].trim().to_string()
        } else if let Some(impl_pos) = impl_name.find("impl ") {
            impl_name[impl_pos + 5..].trim().to_string()
        } else {
            impl_name.to_string()
        }
    }

    /// Get hover information for a symbol
    ///
    /// Returns type information, documentation, etc.
    /// Note: This requires the file to already be loaded via set_source_text
    pub fn get_hover_info(
        &mut self,
        file: SourceFile,
        line: u32,
        character: u32,
    ) -> Option<HoverInfo> {
        let symbols = self.get_symbols(file);

        // Find symbol at position
        for symbol in symbols.iter() {
            if symbol.line == line
                && character >= symbol.character
                && character <= symbol.character + symbol.name.len() as u32
            {
                return Some(HoverInfo {
                    name: symbol.name.clone(),
                    kind: format!("{:?}", symbol.kind),
                    type_info: symbol.type_info.clone(),
                    documentation: symbol.doc.clone(),
                });
            }
        }

        None
    }
}

/// Information about a trait implementation
#[derive(Debug, Clone)]
pub struct TraitImplementation {
    pub trait_name: String,
    pub type_name: String,
    pub location: tower_lsp::lsp_types::Location,
}

/// Hover information for a symbol
#[derive(Debug, Clone)]
pub struct HoverInfo {
    pub name: String,
    pub kind: String,
    pub type_info: Option<String>,
    pub documentation: Option<String>,
}

// ============================================================================
// Code Lens Support
// ============================================================================

/// A code lens item that can be displayed above a symbol
#[derive(Debug, Clone)]
pub struct CodeLens {
    pub range: tower_lsp::lsp_types::Range,
    pub command: Option<CodeLensCommand>,
    pub data: Option<serde_json::Value>,
}

/// A command that can be executed from a code lens
#[derive(Debug, Clone)]
pub struct CodeLensCommand {
    pub title: String,
    pub command: String,
    pub arguments: Vec<serde_json::Value>,
}

impl WindjammerDatabase {
    /// Generate code lenses for a file
    ///
    /// Returns code lenses showing:
    /// - Reference counts for functions, structs, traits
    /// - Implementation counts for traits
    /// - Test run commands for test functions
    pub fn get_code_lenses(&mut self, file: SourceFile, all_files: &[SourceFile]) -> Vec<CodeLens> {
        let mut lenses = Vec::new();
        let file_uri = file.uri(self).clone();

        // Clone symbols to avoid borrow checker issues
        let symbols: Vec<Symbol> = self.get_symbols(file).to_vec();

        for symbol in symbols.iter() {
            // Skip symbols without ranges
            let range = match &symbol.range {
                Some(r) => tower_lsp::lsp_types::Range {
                    start: tower_lsp::lsp_types::Position {
                        line: r.start_line,
                        character: r.start_character,
                    },
                    end: tower_lsp::lsp_types::Position {
                        line: r.end_line,
                        character: r.end_character,
                    },
                },
                None => continue,
            };

            match symbol.kind {
                SymbolKind::Function | SymbolKind::Struct | SymbolKind::Trait => {
                    // Count references across all files
                    let ref_count = self.count_references(&symbol.name, all_files);

                    // Create reference count lens
                    let title = if ref_count == 1 {
                        format!("{} reference", ref_count)
                    } else {
                        format!("{} references", ref_count)
                    };

                    lenses.push(CodeLens {
                        range,
                        command: Some(CodeLensCommand {
                            title,
                            command: "windjammer.showReferences".to_string(),
                            arguments: vec![
                                serde_json::json!(symbol.name),
                                serde_json::json!(file_uri.to_string()),
                            ],
                        }),
                        data: None,
                    });

                    // For traits, also show implementation count
                    if symbol.kind == SymbolKind::Trait {
                        let impls = self.find_trait_implementations(&symbol.name, all_files);
                        let impl_count = impls.len();

                        let title = if impl_count == 1 {
                            format!("{} implementation", impl_count)
                        } else {
                            format!("{} implementations", impl_count)
                        };

                        lenses.push(CodeLens {
                            range,
                            command: Some(CodeLensCommand {
                                title,
                                command: "windjammer.showImplementations".to_string(),
                                arguments: vec![
                                    serde_json::json!(symbol.name),
                                    serde_json::json!(file_uri.to_string()),
                                ],
                            }),
                            data: None,
                        });
                    }
                }
                _ => {
                    // Other symbol kinds don't get code lenses for now
                }
            }
        }

        tracing::debug!("Generated {} code lenses for {}", lenses.len(), file_uri);
        lenses
    }

    /// Count references to a symbol across all files
    ///
    /// This is a helper for code lens generation.
    fn count_references(&mut self, symbol_name: &str, files: &[SourceFile]) -> usize {
        let mut count = 0;

        for file in files {
            let symbols = self.get_symbols(*file);
            count += symbols.iter().filter(|s| s.name == symbol_name).count();
        }

        count
    }
}

// ============================================================================
// Inlay Hints Support
// ============================================================================

/// An inlay hint that can be displayed inline in the editor
#[derive(Debug, Clone)]
pub struct InlayHint {
    pub position: tower_lsp::lsp_types::Position,
    pub label: String,
    pub kind: InlayHintKind,
    pub tooltip: Option<String>,
}

/// The kind of inlay hint
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InlayHintKind {
    /// Type annotation (e.g., `: string`)
    Type,
    /// Parameter name (e.g., `x: `)
    Parameter,
}

impl WindjammerDatabase {
    /// Generate inlay hints for a file
    ///
    /// Returns inlay hints showing:
    /// - Type annotations for variables and return values
    /// - Parameter names in function calls
    pub fn get_inlay_hints(&mut self, file: SourceFile) -> Vec<InlayHint> {
        let mut hints = Vec::new();
        let symbols = self.get_symbols(file);

        for symbol in symbols.iter() {
            // Add type hints for symbols with type information
            if let Some(type_info) = &symbol.type_info {
                // Only add hints for functions (return types)
                if symbol.kind == SymbolKind::Function {
                    // Position hint after the function signature
                    if let Some(range) = &symbol.range {
                        hints.push(InlayHint {
                            position: tower_lsp::lsp_types::Position {
                                line: range.end_line,
                                character: range.end_character,
                            },
                            label: format!(": {}", type_info),
                            kind: InlayHintKind::Type,
                            tooltip: Some(format!("Return type of {}", symbol.name)),
                        });
                    }
                }
            }
        }

        tracing::debug!(
            "Generated {} inlay hints for {}",
            hints.len(),
            file.uri(self)
        );
        hints
    }

    /// Generate parameter hints for function calls
    ///
    /// This would analyze function call sites and show parameter names.
    /// For now, this is a placeholder that returns empty hints.
    pub fn get_parameter_hints(
        &mut self,
        _file: SourceFile,
        _line: u32,
        _character: u32,
    ) -> Vec<InlayHint> {
        // TODO: Implement parameter hint generation
        // This requires:
        // 1. Finding function call expressions in the AST
        // 2. Looking up the function definition
        // 3. Matching arguments to parameters
        // 4. Generating hints for each argument
        Vec::new()
    }
}

// ============================================================================
// Call Hierarchy Support
// ============================================================================

/// A call hierarchy item representing a function or method
#[derive(Debug, Clone)]
pub struct CallHierarchyItem {
    pub name: String,
    pub kind: SymbolKind,
    pub uri: Url,
    pub range: tower_lsp::lsp_types::Range,
    pub selection_range: tower_lsp::lsp_types::Range,
}

/// An incoming call (who calls this function)
#[derive(Debug, Clone)]
pub struct IncomingCall {
    pub from: CallHierarchyItem,
    pub from_ranges: Vec<tower_lsp::lsp_types::Range>,
}

/// An outgoing call (what this function calls)
#[derive(Debug, Clone)]
pub struct OutgoingCall {
    pub to: CallHierarchyItem,
    pub from_ranges: Vec<tower_lsp::lsp_types::Range>,
}

impl WindjammerDatabase {
    /// Prepare call hierarchy for a symbol at a position
    ///
    /// Returns the call hierarchy item if the position is on a function.
    pub fn prepare_call_hierarchy(
        &mut self,
        file: SourceFile,
        line: u32,
        character: u32,
    ) -> Option<CallHierarchyItem> {
        let symbols = self.get_symbols(file);
        let uri = file.uri(self).clone();

        // Find the symbol at the given position
        for symbol in symbols.iter() {
            if symbol.kind == SymbolKind::Function && symbol.line == line {
                // Check if character is within the symbol
                if character >= symbol.character
                    && character <= symbol.character + symbol.name.len() as u32
                {
                    let range = symbol.range.as_ref().map(|r| tower_lsp::lsp_types::Range {
                        start: tower_lsp::lsp_types::Position {
                            line: r.start_line,
                            character: r.start_character,
                        },
                        end: tower_lsp::lsp_types::Position {
                            line: r.end_line,
                            character: r.end_character,
                        },
                    })?;

                    let selection_range = symbol
                        .name_range
                        .as_ref()
                        .map(|r| tower_lsp::lsp_types::Range {
                            start: tower_lsp::lsp_types::Position {
                                line: r.start_line,
                                character: r.start_character,
                            },
                            end: tower_lsp::lsp_types::Position {
                                line: r.end_line,
                                character: r.end_character,
                            },
                        })
                        .unwrap_or(range);

                    return Some(CallHierarchyItem {
                        name: symbol.name.clone(),
                        kind: symbol.kind,
                        uri,
                        range,
                        selection_range,
                    });
                }
            }
        }

        None
    }

    /// Get incoming calls for a function
    ///
    /// Returns all places where this function is called.
    pub fn incoming_calls(
        &mut self,
        item: &CallHierarchyItem,
        all_files: &[SourceFile],
    ) -> Vec<IncomingCall> {
        let mut calls = Vec::new();

        // Find all references to this function
        for file in all_files {
            let symbols = self.get_symbols(*file);
            let uri = file.uri(self).clone();

            // Look for symbols that might call this function
            for symbol in symbols.iter() {
                if symbol.kind == SymbolKind::Function && symbol.name != item.name {
                    // This is a different function - it might call our target
                    // For now, we'll use a simple heuristic: if the function exists,
                    // assume it might be called
                    // TODO: Implement proper call graph analysis

                    // Create a call hierarchy item for the caller
                    if let (Some(range), Some(selection_range)) =
                        (&symbol.range, &symbol.name_range)
                    {
                        let from = CallHierarchyItem {
                            name: symbol.name.clone(),
                            kind: symbol.kind,
                            uri: uri.clone(),
                            range: tower_lsp::lsp_types::Range {
                                start: tower_lsp::lsp_types::Position {
                                    line: range.start_line,
                                    character: range.start_character,
                                },
                                end: tower_lsp::lsp_types::Position {
                                    line: range.end_line,
                                    character: range.end_character,
                                },
                            },
                            selection_range: tower_lsp::lsp_types::Range {
                                start: tower_lsp::lsp_types::Position {
                                    line: selection_range.start_line,
                                    character: selection_range.start_character,
                                },
                                end: tower_lsp::lsp_types::Position {
                                    line: selection_range.end_line,
                                    character: selection_range.end_character,
                                },
                            },
                        };

                        // For now, use the function's range as the call site
                        calls.push(IncomingCall {
                            from,
                            from_ranges: vec![tower_lsp::lsp_types::Range {
                                start: tower_lsp::lsp_types::Position {
                                    line: symbol.line,
                                    character: symbol.character,
                                },
                                end: tower_lsp::lsp_types::Position {
                                    line: symbol.line,
                                    character: symbol.character + symbol.name.len() as u32,
                                },
                            }],
                        });
                    }
                }
            }
        }

        tracing::debug!("Found {} incoming calls to '{}'", calls.len(), item.name);
        calls
    }

    /// Get outgoing calls from a function
    ///
    /// Returns all functions that this function calls.
    pub fn outgoing_calls(
        &mut self,
        item: &CallHierarchyItem,
        all_files: &[SourceFile],
    ) -> Vec<OutgoingCall> {
        let mut calls = Vec::new();

        // Find all functions that might be called by this function
        // For now, we'll use a simple heuristic: list all other functions
        // TODO: Implement proper call graph analysis by parsing function bodies

        for file in all_files {
            let symbols = self.get_symbols(*file);
            let uri = file.uri(self).clone();

            for symbol in symbols.iter() {
                if symbol.kind == SymbolKind::Function && symbol.name != item.name {
                    // This is a different function - it might be called by our target
                    if let (Some(range), Some(selection_range)) =
                        (&symbol.range, &symbol.name_range)
                    {
                        let to = CallHierarchyItem {
                            name: symbol.name.clone(),
                            kind: symbol.kind,
                            uri: uri.clone(),
                            range: tower_lsp::lsp_types::Range {
                                start: tower_lsp::lsp_types::Position {
                                    line: range.start_line,
                                    character: range.start_character,
                                },
                                end: tower_lsp::lsp_types::Position {
                                    line: range.end_line,
                                    character: range.end_character,
                                },
                            },
                            selection_range: tower_lsp::lsp_types::Range {
                                start: tower_lsp::lsp_types::Position {
                                    line: selection_range.start_line,
                                    character: selection_range.start_character,
                                },
                                end: tower_lsp::lsp_types::Position {
                                    line: selection_range.end_line,
                                    character: selection_range.end_character,
                                },
                            },
                        };

                        // Use the target function's range as the call site
                        calls.push(OutgoingCall {
                            to,
                            from_ranges: vec![tower_lsp::lsp_types::Range {
                                start: tower_lsp::lsp_types::Position {
                                    line: symbol.line,
                                    character: symbol.character,
                                },
                                end: tower_lsp::lsp_types::Position {
                                    line: symbol.line,
                                    character: symbol.character + symbol.name.len() as u32,
                                },
                            }],
                        });
                    }
                }
            }
        }

        tracing::debug!("Found {} outgoing calls from '{}'", calls.len(), item.name);
        calls
    }
}

// ============================================================================
// Unused Code Detection
// ============================================================================

/// Information about an unused symbol
#[derive(Debug, Clone)]
pub struct UnusedSymbol {
    pub name: String,
    pub kind: SymbolKind,
    pub location: tower_lsp::lsp_types::Location,
    pub reason: UnusedReason,
}

/// Reason why a symbol is considered unused
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnusedReason {
    /// Symbol is never referenced
    NeverReferenced,
    /// Symbol is only referenced in dead code
    OnlyInDeadCode,
    /// Symbol is exported but never used
    ExportedButUnused,
}

impl WindjammerDatabase {
    /// Find all unused symbols in the workspace
    ///
    /// Returns symbols that are defined but never referenced.
    pub fn find_unused_symbols(&mut self, files: &[SourceFile]) -> Vec<UnusedSymbol> {
        let mut unused = Vec::new();

        // Build a set of all referenced symbol names
        let mut referenced_symbols = std::collections::HashSet::new();
        for file in files {
            let symbols = self.get_symbols(*file);
            for symbol in symbols.iter() {
                // Count how many times this symbol appears across all files
                let mut ref_count = 0;
                for other_file in files {
                    let other_symbols = self.get_symbols(*other_file);
                    ref_count += other_symbols
                        .iter()
                        .filter(|s| s.name == symbol.name)
                        .count();
                }

                // If it appears more than once, it's referenced somewhere
                if ref_count > 1 {
                    referenced_symbols.insert(symbol.name.clone());
                }
            }
        }

        // Find symbols that are defined but not referenced
        for file in files {
            let uri = file.uri(self).clone();
            let symbols = self.get_symbols(*file);

            for symbol in symbols.iter() {
                // Skip certain kinds that are typically entry points
                match symbol.kind {
                    SymbolKind::Const | SymbolKind::Static => continue, // May be used externally
                    _ => {}
                }

                // Check if this symbol is referenced
                if !referenced_symbols.contains(&symbol.name) {
                    // Only report if we have location information
                    if let Some(range) = &symbol.range {
                        unused.push(UnusedSymbol {
                            name: symbol.name.clone(),
                            kind: symbol.kind,
                            location: tower_lsp::lsp_types::Location {
                                uri: uri.clone(),
                                range: tower_lsp::lsp_types::Range {
                                    start: tower_lsp::lsp_types::Position {
                                        line: range.start_line,
                                        character: range.start_character,
                                    },
                                    end: tower_lsp::lsp_types::Position {
                                        line: range.end_line,
                                        character: range.end_character,
                                    },
                                },
                            },
                            reason: UnusedReason::NeverReferenced,
                        });
                    }
                }
            }
        }

        tracing::debug!("Found {} unused symbols", unused.len());
        unused
    }

    /// Find unused functions specifically
    ///
    /// This is a specialized version that only looks for unused functions.
    pub fn find_unused_functions(&mut self, files: &[SourceFile]) -> Vec<UnusedSymbol> {
        self.find_unused_symbols(files)
            .into_iter()
            .filter(|u| u.kind == SymbolKind::Function)
            .collect()
    }

    /// Find unused structs specifically
    pub fn find_unused_structs(&mut self, files: &[SourceFile]) -> Vec<UnusedSymbol> {
        self.find_unused_symbols(files)
            .into_iter()
            .filter(|u| u.kind == SymbolKind::Struct)
            .collect()
    }
}

// ============================================================================
// Dependency Analysis
// ============================================================================

/// A dependency between two files
#[derive(Debug, Clone)]
pub struct FileDependency {
    pub from: Url,
    pub to: Url,
    pub kind: DependencyKind,
}

/// The kind of dependency
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DependencyKind {
    /// Direct import
    Import,
    /// Symbol reference
    SymbolReference,
    /// Type reference
    TypeReference,
}

/// Dependency graph for the workspace
#[derive(Debug, Clone)]
pub struct DependencyGraph {
    pub dependencies: Vec<FileDependency>,
    pub files: Vec<Url>,
}

impl DependencyGraph {
    /// Check if there are circular dependencies
    pub fn has_circular_dependencies(&self) -> bool {
        // Simple cycle detection using DFS
        let mut visited = std::collections::HashSet::new();
        let mut rec_stack = std::collections::HashSet::new();

        for file in &self.files {
            if self.has_cycle_util(file, &mut visited, &mut rec_stack) {
                return true;
            }
        }

        false
    }

    fn has_cycle_util(
        &self,
        file: &Url,
        visited: &mut std::collections::HashSet<Url>,
        rec_stack: &mut std::collections::HashSet<Url>,
    ) -> bool {
        if rec_stack.contains(file) {
            return true;
        }

        if visited.contains(file) {
            return false;
        }

        visited.insert(file.clone());
        rec_stack.insert(file.clone());

        // Check all dependencies
        for dep in &self.dependencies {
            if dep.from == *file && self.has_cycle_util(&dep.to, visited, rec_stack) {
                return true;
            }
        }

        rec_stack.remove(file);
        false
    }

    /// Get all dependencies of a file
    pub fn get_dependencies(&self, file: &Url) -> Vec<&FileDependency> {
        self.dependencies
            .iter()
            .filter(|d| d.from == *file)
            .collect()
    }

    /// Get all dependents of a file (who depends on this file)
    pub fn get_dependents(&self, file: &Url) -> Vec<&FileDependency> {
        self.dependencies.iter().filter(|d| d.to == *file).collect()
    }
}

impl WindjammerDatabase {
    /// Build a dependency graph for the workspace
    ///
    /// Analyzes imports and symbol references to build a complete dependency graph.
    pub fn build_dependency_graph(&mut self, files: &[SourceFile]) -> DependencyGraph {
        let mut dependencies = Vec::new();
        let file_uris: Vec<Url> = files.iter().map(|f| f.uri(self).clone()).collect();

        // Build import-based dependencies
        for file in files {
            let uri = file.uri(self).clone();
            let imports = self.get_imports(*file);

            for import_uri in imports.iter() {
                dependencies.push(FileDependency {
                    from: uri.clone(),
                    to: import_uri.clone(),
                    kind: DependencyKind::Import,
                });
            }
        }

        // Build symbol-based dependencies
        for file in files {
            let uri = file.uri(self).clone();
            let symbols = self.get_symbols(*file);

            // For each symbol in this file, check if it's used in other files
            for symbol in symbols.iter() {
                for other_file in files {
                    let other_uri = other_file.uri(self).clone();
                    if uri != other_uri {
                        let other_symbols = self.get_symbols(*other_file);
                        // Check if other file references this symbol
                        if other_symbols.iter().any(|s| s.name == symbol.name) {
                            dependencies.push(FileDependency {
                                from: other_uri.clone(),
                                to: uri.clone(),
                                kind: DependencyKind::SymbolReference,
                            });
                        }
                    }
                }
            }
        }

        tracing::debug!(
            "Built dependency graph with {} dependencies for {} files",
            dependencies.len(),
            files.len()
        );

        DependencyGraph {
            dependencies,
            files: file_uris,
        }
    }

    /// Find circular dependencies in the workspace
    pub fn find_circular_dependencies(&mut self, files: &[SourceFile]) -> Vec<Vec<Url>> {
        let graph = self.build_dependency_graph(files);
        let cycles = Vec::new();

        if graph.has_circular_dependencies() {
            // For now, just report that cycles exist
            // A full implementation would extract the actual cycles
            tracing::warn!("Circular dependencies detected in workspace");
        }

        cycles
    }

    /// Calculate coupling metrics for files
    ///
    /// Returns (afferent coupling, efferent coupling) for each file.
    /// Afferent = number of files that depend on this file
    /// Efferent = number of files this file depends on
    pub fn calculate_coupling(&mut self, files: &[SourceFile]) -> Vec<(Url, usize, usize)> {
        let graph = self.build_dependency_graph(files);
        let mut metrics = Vec::new();

        for file_uri in &graph.files {
            let afferent = graph.get_dependents(file_uri).len();
            let efferent = graph.get_dependencies(file_uri).len();
            metrics.push((file_uri.clone(), afferent, efferent));
        }

        metrics
    }
}

// ============================================================================
// Code Metrics
// ============================================================================

/// Metrics for a single file
#[derive(Debug, Clone)]
pub struct FileMetrics {
    pub uri: Url,
    pub lines_of_code: usize,
    pub num_functions: usize,
    pub num_structs: usize,
    pub num_enums: usize,
    pub num_traits: usize,
    pub avg_function_length: f64,
    pub max_function_length: usize,
    pub complexity_score: usize,
}

/// Metrics for the entire workspace
#[derive(Debug, Clone)]
pub struct WorkspaceMetrics {
    pub total_files: usize,
    pub total_lines: usize,
    pub total_functions: usize,
    pub total_structs: usize,
    pub total_enums: usize,
    pub total_traits: usize,
    pub avg_file_size: f64,
    pub largest_file: Option<(Url, usize)>,
}

impl WindjammerDatabase {
    /// Calculate metrics for a single file
    pub fn calculate_file_metrics(&mut self, file: SourceFile) -> FileMetrics {
        let uri = file.uri(self).clone();
        let text = file.text(self);
        let symbols = self.get_symbols(file);

        // Count lines of code (non-empty, non-comment lines)
        let lines_of_code = text
            .lines()
            .filter(|line| {
                let trimmed = line.trim();
                !trimmed.is_empty() && !trimmed.starts_with("//")
            })
            .count();

        // Count symbol types
        let num_functions = symbols
            .iter()
            .filter(|s| s.kind == SymbolKind::Function)
            .count();
        let num_structs = symbols
            .iter()
            .filter(|s| s.kind == SymbolKind::Struct)
            .count();
        let num_enums = symbols
            .iter()
            .filter(|s| s.kind == SymbolKind::Enum)
            .count();
        let num_traits = symbols
            .iter()
            .filter(|s| s.kind == SymbolKind::Trait)
            .count();

        // Calculate function lengths (approximate based on line count)
        let mut function_lengths = Vec::new();
        for symbol in symbols.iter() {
            if symbol.kind == SymbolKind::Function {
                if let Some(range) = &symbol.range {
                    let length = (range.end_line - range.start_line) as usize;
                    function_lengths.push(length);
                }
            }
        }

        let avg_function_length = if function_lengths.is_empty() {
            0.0
        } else {
            function_lengths.iter().sum::<usize>() as f64 / function_lengths.len() as f64
        };

        let max_function_length = function_lengths.iter().max().copied().unwrap_or(0);

        // Simple complexity score (based on number of symbols and LOC)
        let complexity_score = num_functions * 2 + num_structs + num_enums + num_traits;

        FileMetrics {
            uri,
            lines_of_code,
            num_functions,
            num_structs,
            num_enums,
            num_traits,
            avg_function_length,
            max_function_length,
            complexity_score,
        }
    }

    /// Calculate metrics for the entire workspace
    pub fn calculate_workspace_metrics(&mut self, files: &[SourceFile]) -> WorkspaceMetrics {
        let file_metrics: Vec<FileMetrics> = files
            .iter()
            .map(|f| self.calculate_file_metrics(*f))
            .collect();

        let total_files = file_metrics.len();
        let total_lines: usize = file_metrics.iter().map(|m| m.lines_of_code).sum();
        let total_functions: usize = file_metrics.iter().map(|m| m.num_functions).sum();
        let total_structs: usize = file_metrics.iter().map(|m| m.num_structs).sum();
        let total_enums: usize = file_metrics.iter().map(|m| m.num_enums).sum();
        let total_traits: usize = file_metrics.iter().map(|m| m.num_traits).sum();

        let avg_file_size = if total_files > 0 {
            total_lines as f64 / total_files as f64
        } else {
            0.0
        };

        let largest_file = file_metrics
            .iter()
            .max_by_key(|m| m.lines_of_code)
            .map(|m| (m.uri.clone(), m.lines_of_code));

        WorkspaceMetrics {
            total_files,
            total_lines,
            total_functions,
            total_structs,
            total_enums,
            total_traits,
            avg_file_size,
            largest_file,
        }
    }

    /// Find files that exceed size thresholds
    pub fn find_large_files(
        &mut self,
        files: &[SourceFile],
        threshold: usize,
    ) -> Vec<(Url, usize)> {
        files
            .iter()
            .map(|f| {
                let metrics = self.calculate_file_metrics(*f);
                (metrics.uri, metrics.lines_of_code)
            })
            .filter(|(_, loc)| *loc > threshold)
            .collect()
    }

    /// Find functions that exceed length thresholds
    pub fn find_long_functions(
        &mut self,
        files: &[SourceFile],
        threshold: usize,
    ) -> Vec<(Url, String, usize)> {
        let mut long_functions = Vec::new();

        for file in files {
            let uri = file.uri(self).clone();
            let symbols = self.get_symbols(*file);

            for symbol in symbols.iter() {
                if symbol.kind == SymbolKind::Function {
                    if let Some(range) = &symbol.range {
                        let length = (range.end_line - range.start_line) as usize;
                        if length > threshold {
                            long_functions.push((uri.clone(), symbol.name.clone(), length));
                        }
                    }
                }
            }
        }

        long_functions
    }
}

// ============================================================================
// Diagnostics & Linting Engine
// ============================================================================

/// Diagnostic severity levels
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiagnosticSeverity {
    Error,
    Warning,
    Info,
    Hint,
}

/// Diagnostic category (inspired by golangci-lint)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiagnosticCategory {
    // Code Quality
    CodeComplexity,
    CodeStyle,
    CodeSmell,

    // Error Detection
    BugRisk,
    ErrorHandling,
    NilCheck,

    // Performance
    Performance,
    Memory,

    // Security
    Security,

    // Maintainability
    Naming,
    Documentation,
    Unused,

    // Dependencies
    Import,
    Dependency,
}

/// A diagnostic message
#[derive(Debug, Clone)]
pub struct Diagnostic {
    pub severity: DiagnosticSeverity,
    pub category: DiagnosticCategory,
    pub message: String,
    pub location: tower_lsp::lsp_types::Location,
    pub rule: String,
    pub suggestion: Option<String>,
    pub fix: Option<AutoFix>,
}

/// An automatic fix for a diagnostic
#[derive(Debug, Clone)]
pub struct AutoFix {
    pub description: String,
    pub edits: Vec<TextEdit>,
}

/// A text edit for auto-fixing
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TextEdit {
    pub range: tower_lsp::lsp_types::Range,
    pub new_text: String,
}

/// Configuration for the linting engine
#[derive(Debug, Clone)]
pub struct LintConfig {
    pub max_function_length: usize,
    pub max_file_length: usize,
    pub max_complexity: usize,
    pub check_unused: bool,
    pub check_style: bool,
    pub check_performance: bool,
    pub check_security: bool,
    pub check_error_handling: bool,
    pub enable_autofix: bool,
}

impl Default for LintConfig {
    fn default() -> Self {
        Self {
            max_function_length: 50,
            max_file_length: 500,
            max_complexity: 10,
            check_unused: true,
            check_style: true,
            check_performance: true,
            check_security: true,
            check_error_handling: true,
            enable_autofix: false,
        }
    }
}

impl WindjammerDatabase {
    /// Run all linting checks on a workspace
    pub fn lint_workspace(&mut self, files: &[SourceFile], config: &LintConfig) -> Vec<Diagnostic> {
        let mut diagnostics = Vec::new();

        // Check for unused code
        if config.check_unused {
            diagnostics.extend(self.check_unused_code(files, config));
        }

        // Check code complexity
        diagnostics.extend(self.check_complexity(files, config));

        // Check code style
        if config.check_style {
            diagnostics.extend(self.check_style(files, config));
        }

        // Check error handling
        if config.check_error_handling {
            diagnostics.extend(self.check_error_handling(files, config));
        }

        // Check performance
        if config.check_performance {
            diagnostics.extend(self.check_performance(files, config));
        }

        // Check security
        if config.check_security {
            diagnostics.extend(self.check_security(files, config));
        }

        // Check circular dependencies
        diagnostics.extend(self.check_circular_deps(files));

        tracing::info!("Linting complete: {} diagnostics found", diagnostics.len());
        diagnostics
    }

    /// Check for unused code (similar to unused, deadcode, varcheck)
    fn check_unused_code(&mut self, files: &[SourceFile], config: &LintConfig) -> Vec<Diagnostic> {
        let mut diagnostics = Vec::new();
        let unused = self.find_unused_symbols(files);

        for symbol in unused {
            // Auto-fix: Can add #[allow(dead_code)] attribute
            let fix = if config.enable_autofix {
                Some(AutoFix {
                    description: format!("Add #[allow(dead_code)] to {}", symbol.name),
                    edits: vec![TextEdit {
                        range: symbol.location.range,
                        new_text: format!("#[allow(dead_code)]\n{}", symbol.name),
                    }],
                })
            } else {
                None
            };

            diagnostics.push(Diagnostic {
                severity: DiagnosticSeverity::Warning,
                category: DiagnosticCategory::Unused,
                message: format!(
                    "Unused {}: '{}'",
                    format!("{:?}", symbol.kind).to_lowercase(),
                    symbol.name
                ),
                location: symbol.location,
                rule: "unused-code".to_string(),
                suggestion: Some(format!(
                    "Remove unused {} or mark with #[allow(dead_code)]",
                    format!("{:?}", symbol.kind).to_lowercase()
                )),
                fix,
            });
        }

        diagnostics
    }

    /// Check code complexity (similar to gocyclo, gocognit, cyclop)
    fn check_complexity(&mut self, files: &[SourceFile], config: &LintConfig) -> Vec<Diagnostic> {
        let mut diagnostics = Vec::new();

        // Check function length
        let long_funcs = self.find_long_functions(files, config.max_function_length);
        for (uri, name, length) in long_funcs {
            diagnostics.push(Diagnostic {
                severity: DiagnosticSeverity::Warning,
                category: DiagnosticCategory::CodeComplexity,
                message: format!(
                    "Function '{}' is too long ({} lines, max {})",
                    name, length, config.max_function_length
                ),
                location: tower_lsp::lsp_types::Location {
                    uri,
                    range: tower_lsp::lsp_types::Range::default(),
                },
                rule: "function-length".to_string(),
                suggestion: Some(
                    "Consider breaking this function into smaller functions".to_string(),
                ),
                fix: None, // Complex refactoring, no auto-fix
            });
        }

        // Check file length
        let large_files = self.find_large_files(files, config.max_file_length);
        for (uri, loc) in large_files {
            diagnostics.push(Diagnostic {
                severity: DiagnosticSeverity::Info,
                category: DiagnosticCategory::CodeComplexity,
                message: format!(
                    "File is large ({} lines, max {})",
                    loc, config.max_file_length
                ),
                location: tower_lsp::lsp_types::Location {
                    uri,
                    range: tower_lsp::lsp_types::Range::default(),
                },
                rule: "file-length".to_string(),
                suggestion: Some("Consider splitting this file into multiple modules".to_string()),
                fix: None, // Complex refactoring, no auto-fix
            });
        }

        diagnostics
    }

    /// Check code style (similar to golint, revive, stylecheck)
    fn check_style(&mut self, files: &[SourceFile], config: &LintConfig) -> Vec<Diagnostic> {
        let mut diagnostics = Vec::new();

        for file in files {
            let uri = file.uri(self).clone();
            let symbols = self.get_symbols(*file);

            for symbol in symbols.iter() {
                // Check naming conventions
                if symbol.kind == SymbolKind::Struct
                    && !symbol.name.chars().next().unwrap_or('a').is_uppercase()
                {
                    if let Some(range) = &symbol.name_range {
                        let capitalized = capitalize_first(&symbol.name);

                        // Auto-fix: Can rename the struct
                        let fix = if config.enable_autofix {
                            Some(AutoFix {
                                description: format!(
                                    "Rename '{}' to '{}'",
                                    symbol.name, capitalized
                                ),
                                edits: vec![TextEdit {
                                    range: tower_lsp::lsp_types::Range {
                                        start: tower_lsp::lsp_types::Position {
                                            line: range.start_line,
                                            character: range.start_character,
                                        },
                                        end: tower_lsp::lsp_types::Position {
                                            line: range.end_line,
                                            character: range.end_character,
                                        },
                                    },
                                    new_text: capitalized.clone(),
                                }],
                            })
                        } else {
                            None
                        };

                        diagnostics.push(Diagnostic {
                            severity: DiagnosticSeverity::Warning,
                            category: DiagnosticCategory::Naming,
                            message: format!(
                                "Struct name '{}' should start with uppercase",
                                symbol.name
                            ),
                            location: tower_lsp::lsp_types::Location {
                                uri: uri.clone(),
                                range: tower_lsp::lsp_types::Range {
                                    start: tower_lsp::lsp_types::Position {
                                        line: range.start_line,
                                        character: range.start_character,
                                    },
                                    end: tower_lsp::lsp_types::Position {
                                        line: range.end_line,
                                        character: range.end_character,
                                    },
                                },
                            },
                            rule: "naming-convention".to_string(),
                            suggestion: Some(format!("Rename to '{}'", capitalized)),
                            fix,
                        });
                    }
                }

                // Check for documentation
                if (symbol.kind == SymbolKind::Function || symbol.kind == SymbolKind::Struct)
                    && symbol.doc.is_none()
                {
                    if let Some(range) = &symbol.range {
                        diagnostics.push(Diagnostic {
                            severity: DiagnosticSeverity::Info,
                            category: DiagnosticCategory::Documentation,
                            message: format!(
                                "{:?} '{}' is missing documentation",
                                symbol.kind, symbol.name
                            ),
                            location: tower_lsp::lsp_types::Location {
                                uri: uri.clone(),
                                range: tower_lsp::lsp_types::Range {
                                    start: tower_lsp::lsp_types::Position {
                                        line: range.start_line,
                                        character: range.start_character,
                                    },
                                    end: tower_lsp::lsp_types::Position {
                                        line: range.end_line,
                                        character: range.end_character,
                                    },
                                },
                            },
                            rule: "missing-docs".to_string(),
                            suggestion: Some(format!(
                                "Add documentation comment above {}",
                                symbol.name
                            )),
                            fix: None, // Cannot auto-generate meaningful docs
                        });
                    }
                }
            }
        }

        diagnostics
    }

    /// Check error handling (similar to errcheck, err113, errorlint)
    fn check_error_handling(
        &mut self,
        files: &[SourceFile],
        _config: &LintConfig,
    ) -> Vec<Diagnostic> {
        let mut diagnostics = Vec::new();

        for file in files {
            let uri = file.uri(self).clone();
            let text = file.text(self);

            // Check for ignored errors (Result without .expect() or ?)
            if text.contains("Result<") && !text.contains("?") && !text.contains(".expect(") {
                diagnostics.push(Diagnostic {
                    severity: DiagnosticSeverity::Warning,
                    category: DiagnosticCategory::ErrorHandling,
                    message: "Potential unchecked Result type".to_string(),
                    location: tower_lsp::lsp_types::Location {
                        uri: uri.clone(),
                        range: tower_lsp::lsp_types::Range::default(),
                    },
                    rule: "unchecked-result".to_string(),
                    suggestion: Some(
                        "Use '?' operator or '.expect()' to handle errors".to_string(),
                    ),
                    fix: None, // Context-dependent
                });
            }

            // Check for panic! usage
            if text.contains("panic!(") {
                diagnostics.push(Diagnostic {
                    severity: DiagnosticSeverity::Warning,
                    category: DiagnosticCategory::BugRisk,
                    message: "Use of panic! can crash the program".to_string(),
                    location: tower_lsp::lsp_types::Location {
                        uri: uri.clone(),
                        range: tower_lsp::lsp_types::Range::default(),
                    },
                    rule: "avoid-panic".to_string(),
                    suggestion: Some("Consider returning Result<T, E> instead".to_string()),
                    fix: None, // Complex refactoring
                });
            }

            // Check for unwrap() usage
            if text.contains(".unwrap()") {
                diagnostics.push(Diagnostic {
                    severity: DiagnosticSeverity::Warning,
                    category: DiagnosticCategory::BugRisk,
                    message: "Use of .unwrap() can panic at runtime".to_string(),
                    location: tower_lsp::lsp_types::Location {
                        uri: uri.clone(),
                        range: tower_lsp::lsp_types::Range::default(),
                    },
                    rule: "avoid-unwrap".to_string(),
                    suggestion: Some(
                        "Use pattern matching or .expect() with a message".to_string(),
                    ),
                    fix: None, // Context-dependent
                });
            }
        }

        diagnostics
    }

    /// Check performance issues (similar to prealloc, perfsprint)
    fn check_performance(&mut self, files: &[SourceFile], config: &LintConfig) -> Vec<Diagnostic> {
        let mut diagnostics = Vec::new();

        for file in files {
            let uri = file.uri(self).clone();
            let text = file.text(self);

            // Check for Vec without capacity hint
            if text.contains("Vec::new()") && text.contains("push(") {
                // Auto-fix: Can suggest with_capacity
                let fix = if config.enable_autofix {
                    Some(AutoFix {
                        description: "Use Vec::with_capacity() for better performance".to_string(),
                        edits: vec![TextEdit {
                            range: tower_lsp::lsp_types::Range::default(),
                            new_text: "Vec::with_capacity(capacity)".to_string(),
                        }],
                    })
                } else {
                    None
                };

                diagnostics.push(Diagnostic {
                    severity: DiagnosticSeverity::Info,
                    category: DiagnosticCategory::Performance,
                    message: "Vec::new() followed by push() - consider pre-allocation".to_string(),
                    location: tower_lsp::lsp_types::Location {
                        uri: uri.clone(),
                        range: tower_lsp::lsp_types::Range::default(),
                    },
                    rule: "vec-prealloc".to_string(),
                    suggestion: Some("Use Vec::with_capacity(n) if you know the size".to_string()),
                    fix,
                });
            }

            // Check for inefficient string concatenation
            if text.contains("+ \"") || text.contains("+ '") {
                diagnostics.push(Diagnostic {
                    severity: DiagnosticSeverity::Info,
                    category: DiagnosticCategory::Performance,
                    message: "String concatenation with + creates temporary allocations"
                        .to_string(),
                    location: tower_lsp::lsp_types::Location {
                        uri: uri.clone(),
                        range: tower_lsp::lsp_types::Range::default(),
                    },
                    rule: "string-concat".to_string(),
                    suggestion: Some("Consider using format!() or String::push_str()".to_string()),
                    fix: None, // Complex refactoring
                });
            }

            // Check for clone() in loops
            if text.contains("for ") && text.contains(".clone()") {
                diagnostics.push(Diagnostic {
                    severity: DiagnosticSeverity::Warning,
                    category: DiagnosticCategory::Performance,
                    message: "Cloning inside a loop can be expensive".to_string(),
                    location: tower_lsp::lsp_types::Location {
                        uri: uri.clone(),
                        range: tower_lsp::lsp_types::Range::default(),
                    },
                    rule: "clone-in-loop".to_string(),
                    suggestion: Some("Consider borrowing instead of cloning".to_string()),
                    fix: None, // Context-dependent
                });
            }
        }

        diagnostics
    }

    /// Check security issues (similar to gosec)
    fn check_security(&mut self, files: &[SourceFile], _config: &LintConfig) -> Vec<Diagnostic> {
        let mut diagnostics = Vec::new();

        for file in files {
            let uri = file.uri(self).clone();
            let text = file.text(self);

            // Check for unsafe blocks
            if text.contains("unsafe {") || text.contains("unsafe{") {
                diagnostics.push(Diagnostic {
                    severity: DiagnosticSeverity::Warning,
                    category: DiagnosticCategory::Security,
                    message: "Unsafe block detected - requires careful review".to_string(),
                    location: tower_lsp::lsp_types::Location {
                        uri: uri.clone(),
                        range: tower_lsp::lsp_types::Range::default(),
                    },
                    rule: "unsafe-block".to_string(),
                    suggestion: Some(
                        "Ensure all unsafe operations are properly documented and justified"
                            .to_string(),
                    ),
                    fix: None, // Manual review required
                });
            }

            // Check for hardcoded credentials
            let sensitive_patterns = ["password", "secret", "api_key", "token"];
            for pattern in &sensitive_patterns {
                if text.to_lowercase().contains(&format!("\"{}\"", pattern))
                    || text.to_lowercase().contains(&format!("'{}'", pattern))
                {
                    diagnostics.push(Diagnostic {
                        severity: DiagnosticSeverity::Error,
                        category: DiagnosticCategory::Security,
                        message: format!("Potential hardcoded sensitive data: '{}'", pattern),
                        location: tower_lsp::lsp_types::Location {
                            uri: uri.clone(),
                            range: tower_lsp::lsp_types::Range::default(),
                        },
                        rule: "hardcoded-secret".to_string(),
                        suggestion: Some(
                            "Use environment variables or secure configuration".to_string(),
                        ),
                        fix: None, // Requires manual intervention
                    });
                }
            }

            // Check for SQL query concatenation
            if text.contains("\"SELECT ") && text.contains(" + ") {
                diagnostics.push(Diagnostic {
                    severity: DiagnosticSeverity::Error,
                    category: DiagnosticCategory::Security,
                    message: "Potential SQL injection vulnerability".to_string(),
                    location: tower_lsp::lsp_types::Location {
                        uri: uri.clone(),
                        range: tower_lsp::lsp_types::Range::default(),
                    },
                    rule: "sql-injection".to_string(),
                    suggestion: Some(
                        "Use parameterized queries or prepared statements".to_string(),
                    ),
                    fix: None, // Complex refactoring
                });
            }
        }

        diagnostics
    }

    /// Check for circular dependencies (similar to import-cycle)
    fn check_circular_deps(&mut self, files: &[SourceFile]) -> Vec<Diagnostic> {
        let mut diagnostics = Vec::new();
        let graph = self.build_dependency_graph(files);

        if graph.has_circular_dependencies() {
            // For now, just report that cycles exist
            // A full implementation would extract the actual cycle paths
            for file_uri in &graph.files {
                diagnostics.push(Diagnostic {
                    severity: DiagnosticSeverity::Error,
                    category: DiagnosticCategory::Dependency,
                    message: "Circular dependency detected in project".to_string(),
                    location: tower_lsp::lsp_types::Location {
                        uri: file_uri.clone(),
                        range: tower_lsp::lsp_types::Range::default(),
                    },
                    rule: "circular-dependency".to_string(),
                    suggestion: Some(
                        "Break the circular dependency by refactoring imports".to_string(),
                    ),
                    fix: None, // Complex refactoring
                });
            }
        }

        diagnostics
    }
}

/// Helper function to capitalize first letter
fn capitalize_first(s: &str) -> String {
    let mut chars = s.chars();
    match chars.next() {
        None => String::new(),
        Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
    }
}

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

    #[test]
    fn test_parallel_config_default() {
        let config = ParallelConfig::default();
        assert_eq!(config.num_threads, 0); // Use all cores
        assert_eq!(config.min_files_for_parallel, 5);
    }

    #[test]
    fn test_process_files_parallel_sequential() {
        let mut db = WindjammerDatabase::new();
        let config = ParallelConfig::default();

        // Less than min_files_for_parallel, should process sequentially
        let files = vec![
            (
                Url::parse("file:///test1.wj").unwrap(),
                "fn test1() {}".to_string(),
            ),
            (
                Url::parse("file:///test2.wj").unwrap(),
                "fn test2() {}".to_string(),
            ),
        ];

        let source_files = db.process_files_parallel(files, &config);
        assert_eq!(source_files.len(), 2);
    }

    #[test]
    fn test_process_files_parallel() {
        let mut db = WindjammerDatabase::new();
        let config = ParallelConfig {
            num_threads: 2,
            min_files_for_parallel: 3,
        };

        // Enough files to trigger parallel processing
        let files = vec![
            (
                Url::parse("file:///test1.wj").unwrap(),
                "fn test1() {}".to_string(),
            ),
            (
                Url::parse("file:///test2.wj").unwrap(),
                "fn test2() {}".to_string(),
            ),
            (
                Url::parse("file:///test3.wj").unwrap(),
                "fn test3() {}".to_string(),
            ),
            (
                Url::parse("file:///test4.wj").unwrap(),
                "fn test4() {}".to_string(),
            ),
        ];

        let source_files = db.process_files_parallel(files, &config);
        assert_eq!(source_files.len(), 4);

        // Verify symbols were extracted
        for file in &source_files {
            let symbols = db.get_symbols(*file);
            assert_eq!(symbols.len(), 1); // Each file has one function
        }
    }

    #[test]
    fn test_extract_symbols_parallel() {
        let mut db = WindjammerDatabase::new();

        let files: Vec<_> = (0..10)
            .map(|i| {
                let uri = Url::parse(&format!("file:///test{}.wj", i)).unwrap();
                let text = format!("fn test{}() {{}}", i);
                db.set_source_text(uri, text)
            })
            .collect();

        let symbols_list = db.extract_symbols_parallel(&files);
        assert_eq!(symbols_list.len(), 10);

        for symbols in symbols_list {
            assert_eq!(symbols.len(), 1);
        }
    }

    #[test]
    fn test_find_all_references_parallel() {
        let mut db = WindjammerDatabase::new();

        // Create multiple files with the same function name
        let files: Vec<_> = (0..5)
            .map(|i| {
                let uri = Url::parse(&format!("file:///test{}.wj", i)).unwrap();
                let text = "fn calculate() {}".to_string();
                db.set_source_text(uri, text)
            })
            .collect();

        let locations = db.find_all_references_parallel("calculate", &files);

        // Should find 5 instances (one per file)
        assert_eq!(locations.len(), 5);

        // All should have the same function name
        for location in &locations {
            assert!(location.uri.as_str().starts_with("file:///test"));
        }
    }

    #[test]
    fn test_parallel_performance_benefit() {
        let mut db = WindjammerDatabase::new();

        // Create 20 files
        let files: Vec<_> = (0..20)
            .map(|i| {
                (
                    Url::parse(&format!("file:///test{}.wj", i)).unwrap(),
                    format!("fn test{}() {{}}", i),
                )
            })
            .collect();

        let config = ParallelConfig {
            num_threads: 4,
            min_files_for_parallel: 10,
        };

        let start = std::time::Instant::now();
        let source_files = db.process_files_parallel(files, &config);
        let elapsed = start.elapsed();

        assert_eq!(source_files.len(), 20);
        println!("Processed 20 files in {:?}", elapsed);

        // Second query should be cached (verify it works, don't assert on timing)
        let start = std::time::Instant::now();
        for file in &source_files {
            let _symbols = db.get_symbols(*file);
        }
        let cached_elapsed = start.elapsed();

        println!("Cached query for 20 files in {:?}", cached_elapsed);

        // In tests, cached queries might be slower due to overhead
        // Just verify it completes successfully
        println!(
            "Speedup: {:.2}x (note: may be slower in debug builds)",
            elapsed.as_nanos() as f64 / cached_elapsed.as_nanos().max(1) as f64
        );
    }
}

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

    #[test]
    fn test_find_trait_implementations() {
        let mut db = WindjammerDatabase::new();

        // Create files with trait implementations
        let files: Vec<_> = vec![
            (
                Url::parse("file:///traits.wj").unwrap(),
                "trait Display {}".to_string(),
            ),
            (
                Url::parse("file:///impl1.wj").unwrap(),
                "impl Display for String {}".to_string(),
            ),
            (
                Url::parse("file:///impl2.wj").unwrap(),
                "impl Display for Int {}".to_string(),
            ),
        ]
        .into_iter()
        .map(|(uri, text)| db.set_source_text(uri, text))
        .collect();

        let implementations = db.find_trait_implementations("Display", &files);

        // Should find implementations (may be 0 or 2 depending on parsing)
        // Just verify it doesn't panic
        for impl_info in implementations {
            assert_eq!(impl_info.trait_name, "Display");
            assert!(impl_info.type_name.contains("String") || impl_info.type_name.contains("Int"));
        }
    }

    #[test]
    fn test_extract_type_from_impl() {
        let db = WindjammerDatabase::new();

        // Test "impl Trait for Type"
        let type1 = db.extract_type_from_impl("impl Display for String");
        assert_eq!(type1, "String");

        // Test "impl Type"
        let type2 = db.extract_type_from_impl("impl MyStruct");
        assert_eq!(type2, "MyStruct");

        // Test with extra spaces
        let type3 = db.extract_type_from_impl("impl  Display  for  Int  ");
        assert_eq!(type3, "Int");
    }

    #[test]
    fn test_get_hover_info() {
        let mut db = WindjammerDatabase::new();

        let uri = Url::parse("file:///test.wj").unwrap();
        let text = "fn calculate(x: int) -> int { x * 2 }";
        let file = db.set_source_text(uri, text.to_string());

        // Try to get hover info at the function position (line 0, character 3)
        let hover = db.get_hover_info(file, 0, 3);

        // May or may not find it depending on exact position
        if let Some(info) = hover {
            assert_eq!(info.name, "calculate");
            assert_eq!(info.kind, "Function");
        }
    }

    #[test]
    fn test_hover_info_not_found() {
        let mut db = WindjammerDatabase::new();

        let uri = Url::parse("file:///test.wj").unwrap();
        let text = "fn test() {}";
        let file = db.set_source_text(uri, text.to_string());

        // Try to get hover info at a position with no symbol
        let hover = db.get_hover_info(file, 10, 50);
        assert!(hover.is_none());
    }

    #[test]
    fn test_hover_info_with_type() {
        let mut db = WindjammerDatabase::new();

        let uri = Url::parse("file:///test.wj").unwrap();
        let text = "fn typed() -> string { \"hello\" }";
        let file = db.set_source_text(uri, text.to_string());

        // The function should have type information
        let hover = db.get_hover_info(file, 0, 3);

        if let Some(info) = hover {
            assert_eq!(info.name, "typed");
            assert!(info.type_info.is_some());
        }
    }

    #[test]
    fn test_trait_implementations_empty() {
        let mut db = WindjammerDatabase::new();

        // Create file with no implementations
        let files: Vec<_> = vec![(
            Url::parse("file:///test.wj").unwrap(),
            "fn test() {}".to_string(),
        )]
        .into_iter()
        .map(|(uri, text)| db.set_source_text(uri, text))
        .collect();

        let implementations = db.find_trait_implementations("NonExistent", &files);
        assert_eq!(implementations.len(), 0);
    }
}

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

    #[test]
    fn test_get_code_lenses_function() {
        let mut db = WindjammerDatabase::new();

        let uri = Url::parse("file:///test.wj").unwrap();
        let text = "fn calculate(x: int) -> int { x * 2 }";
        let file = db.set_source_text(uri, text.to_string());

        let lenses = db.get_code_lenses(file, &[file]);

        // Code lenses require symbols to have ranges
        // If parsing doesn't extract ranges, lenses will be empty
        if !lenses.is_empty() {
            // First lens should be a reference count
            let first = &lenses[0];
            assert!(first.command.is_some());
            let cmd = first.command.as_ref().unwrap();
            assert!(cmd.title.contains("reference"));
            assert_eq!(cmd.command, "windjammer.showReferences");
        }
    }

    #[test]
    fn test_get_code_lenses_trait() {
        let mut db = WindjammerDatabase::new();

        let files: Vec<_> = vec![
            (
                Url::parse("file:///trait.wj").unwrap(),
                "trait Display {}".to_string(),
            ),
            (
                Url::parse("file:///impl.wj").unwrap(),
                "impl Display for String {}".to_string(),
            ),
        ]
        .into_iter()
        .map(|(uri, text)| db.set_source_text(uri, text))
        .collect();

        let lenses = db.get_code_lenses(files[0], &files);

        // Should have lenses for the trait
        // Note: May be empty if parsing doesn't extract ranges
        if !lenses.is_empty() {
            // Look for implementation count lens
            let impl_lens = lenses.iter().find(|l| {
                l.command
                    .as_ref()
                    .map(|c| c.title.contains("implementation"))
                    .unwrap_or(false)
            });

            if let Some(lens) = impl_lens {
                let cmd = lens.command.as_ref().unwrap();
                assert_eq!(cmd.command, "windjammer.showImplementations");
            }
        }
    }

    #[test]
    fn test_get_code_lenses_multiple_references() {
        let mut db = WindjammerDatabase::new();

        let files: Vec<_> = vec![
            (
                Url::parse("file:///def.wj").unwrap(),
                "fn helper() {}".to_string(),
            ),
            (
                Url::parse("file:///use1.wj").unwrap(),
                "fn helper() {}".to_string(), // Another definition
            ),
            (
                Url::parse("file:///use2.wj").unwrap(),
                "fn helper() {}".to_string(), // Yet another
            ),
        ]
        .into_iter()
        .map(|(uri, text)| db.set_source_text(uri, text))
        .collect();

        let lenses = db.get_code_lenses(files[0], &files);

        // Should show multiple references
        if !lenses.is_empty() {
            let first = &lenses[0];
            if let Some(cmd) = &first.command {
                // Should say "3 references" (plural)
                assert!(cmd.title.contains("reference"));
            }
        }
    }

    #[test]
    fn test_count_references() {
        let mut db = WindjammerDatabase::new();

        let files: Vec<_> = vec![
            (
                Url::parse("file:///file1.wj").unwrap(),
                "fn test() {}".to_string(),
            ),
            (
                Url::parse("file:///file2.wj").unwrap(),
                "fn test() {}".to_string(),
            ),
            (
                Url::parse("file:///file3.wj").unwrap(),
                "fn other() {}".to_string(),
            ),
        ]
        .into_iter()
        .map(|(uri, text)| db.set_source_text(uri, text))
        .collect();

        let count = db.count_references("test", &files);
        assert_eq!(count, 2); // "test" appears in 2 files

        let count_other = db.count_references("other", &files);
        assert_eq!(count_other, 1); // "other" appears in 1 file

        let count_none = db.count_references("nonexistent", &files);
        assert_eq!(count_none, 0); // "nonexistent" doesn't appear
    }

    #[test]
    fn test_code_lens_range() {
        let mut db = WindjammerDatabase::new();

        let uri = Url::parse("file:///test.wj").unwrap();
        let text = "fn test() {}";
        let file = db.set_source_text(uri, text.to_string());

        let lenses = db.get_code_lenses(file, &[file]);

        // Verify ranges are valid
        for lens in lenses {
            assert!(lens.range.start.line <= lens.range.end.line);
            if lens.range.start.line == lens.range.end.line {
                assert!(lens.range.start.character <= lens.range.end.character);
            }
        }
    }

    #[test]
    fn test_code_lens_empty_file() {
        let mut db = WindjammerDatabase::new();

        let uri = Url::parse("file:///empty.wj").unwrap();
        let text = "";
        let file = db.set_source_text(uri, text.to_string());

        let lenses = db.get_code_lenses(file, &[file]);

        // Empty file should have no lenses
        assert_eq!(lenses.len(), 0);
    }

    #[test]
    fn test_code_lens_no_range_symbols() {
        let mut db = WindjammerDatabase::new();

        let uri = Url::parse("file:///test.wj").unwrap();
        let text = "fn test() {}";
        let file = db.set_source_text(uri, text.to_string());

        // If symbols don't have ranges, code lenses should handle gracefully
        let _lenses = db.get_code_lenses(file, &[file]);

        // Should not panic - test passes if we get here
    }
}

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

    #[test]
    fn test_get_inlay_hints_function_with_type() {
        let mut db = WindjammerDatabase::new();

        let uri = Url::parse("file:///test.wj").unwrap();
        let text = "fn calculate(x: int) -> int { x * 2 }";
        let file = db.set_source_text(uri, text.to_string());

        let hints = db.get_inlay_hints(file);

        // May have hints if type info is extracted
        // Just verify it doesn't panic
        for hint in hints {
            assert!(hint.label.contains(":"));
            assert_eq!(hint.kind, InlayHintKind::Type);
        }
    }

    #[test]
    fn test_get_inlay_hints_empty_file() {
        let mut db = WindjammerDatabase::new();

        let uri = Url::parse("file:///empty.wj").unwrap();
        let text = "";
        let file = db.set_source_text(uri, text.to_string());

        let hints = db.get_inlay_hints(file);

        // Empty file should have no hints
        assert_eq!(hints.len(), 0);
    }

    #[test]
    fn test_get_inlay_hints_no_types() {
        let mut db = WindjammerDatabase::new();

        let uri = Url::parse("file:///test.wj").unwrap();
        let text = "fn test() {}";
        let file = db.set_source_text(uri, text.to_string());

        let _hints = db.get_inlay_hints(file);

        // Function without explicit return type may have no hints
        // Just verify it doesn't panic - test passes if we get here
    }

    #[test]
    fn test_get_parameter_hints_placeholder() {
        let mut db = WindjammerDatabase::new();

        let uri = Url::parse("file:///test.wj").unwrap();
        let text = "fn test(x: int) {}";
        let file = db.set_source_text(uri, text.to_string());

        // Parameter hints are not yet implemented
        let hints = db.get_parameter_hints(file, 0, 0);
        assert_eq!(hints.len(), 0);
    }

    #[test]
    fn test_inlay_hint_kind() {
        // Test that InlayHintKind enum works correctly
        assert_eq!(InlayHintKind::Type, InlayHintKind::Type);
        assert_eq!(InlayHintKind::Parameter, InlayHintKind::Parameter);
        assert_ne!(InlayHintKind::Type, InlayHintKind::Parameter);
    }

    #[test]
    fn test_inlay_hint_structure() {
        let hint = InlayHint {
            position: tower_lsp::lsp_types::Position {
                line: 0,
                character: 10,
            },
            label: ": string".to_string(),
            kind: InlayHintKind::Type,
            tooltip: Some("Return type".to_string()),
        };

        assert_eq!(hint.position.line, 0);
        assert_eq!(hint.position.character, 10);
        assert_eq!(hint.label, ": string");
        assert_eq!(hint.kind, InlayHintKind::Type);
        assert_eq!(hint.tooltip, Some("Return type".to_string()));
    }

    #[test]
    fn test_inlay_hints_multiple_functions() {
        let mut db = WindjammerDatabase::new();

        let uri = Url::parse("file:///test.wj").unwrap();
        let text = r#"
fn add(a: int, b: int) -> int { a + b }
fn greet(name: string) -> string { "Hello" }
"#;
        let file = db.set_source_text(uri, text.to_string());

        let hints = db.get_inlay_hints(file);

        // May have hints for both functions if types are extracted
        // Just verify structure is correct
        for hint in hints {
            assert!(hint.label.starts_with(":"));
            assert_eq!(hint.kind, InlayHintKind::Type);
            assert!(hint.tooltip.is_some());
        }
    }
}

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

    #[test]
    fn test_prepare_call_hierarchy() {
        let mut db = WindjammerDatabase::new();

        let uri = Url::parse("file:///test.wj").unwrap();
        let text = "fn calculate(x: int) -> int { x * 2 }";
        let file = db.set_source_text(uri, text.to_string());

        // Try to prepare call hierarchy at the function name position
        let item = db.prepare_call_hierarchy(file, 0, 3);

        // May return None if ranges aren't extracted
        if let Some(item) = item {
            assert_eq!(item.name, "calculate");
            assert_eq!(item.kind, SymbolKind::Function);
        }
    }

    #[test]
    fn test_prepare_call_hierarchy_not_found() {
        let mut db = WindjammerDatabase::new();

        let uri = Url::parse("file:///test.wj").unwrap();
        let text = "fn test() {}";
        let file = db.set_source_text(uri, text.to_string());

        // Try at a position with no symbol
        let item = db.prepare_call_hierarchy(file, 10, 50);
        assert!(item.is_none());
    }

    #[test]
    fn test_incoming_calls() {
        let mut db = WindjammerDatabase::new();

        let files: Vec<_> = vec![
            (
                Url::parse("file:///main.wj").unwrap(),
                "fn main() {}".to_string(),
            ),
            (
                Url::parse("file:///helper.wj").unwrap(),
                "fn helper() {}".to_string(),
            ),
        ]
        .into_iter()
        .map(|(uri, text)| db.set_source_text(uri, text))
        .collect();

        // Create a call hierarchy item for helper
        let item = CallHierarchyItem {
            name: "helper".to_string(),
            kind: SymbolKind::Function,
            uri: Url::parse("file:///helper.wj").unwrap(),
            range: tower_lsp::lsp_types::Range {
                start: tower_lsp::lsp_types::Position {
                    line: 0,
                    character: 0,
                },
                end: tower_lsp::lsp_types::Position {
                    line: 0,
                    character: 10,
                },
            },
            selection_range: tower_lsp::lsp_types::Range {
                start: tower_lsp::lsp_types::Position {
                    line: 0,
                    character: 3,
                },
                end: tower_lsp::lsp_types::Position {
                    line: 0,
                    character: 9,
                },
            },
        };

        let calls = db.incoming_calls(&item, &files);

        // May have calls if ranges are extracted
        // Just verify it doesn't panic
        for call in calls {
            assert_ne!(call.from.name, "helper"); // Should be from other functions
        }
    }

    #[test]
    fn test_outgoing_calls() {
        let mut db = WindjammerDatabase::new();

        let files: Vec<_> = vec![
            (
                Url::parse("file:///main.wj").unwrap(),
                "fn main() {}".to_string(),
            ),
            (
                Url::parse("file:///helper.wj").unwrap(),
                "fn helper() {}".to_string(),
            ),
        ]
        .into_iter()
        .map(|(uri, text)| db.set_source_text(uri, text))
        .collect();

        // Create a call hierarchy item for main
        let item = CallHierarchyItem {
            name: "main".to_string(),
            kind: SymbolKind::Function,
            uri: Url::parse("file:///main.wj").unwrap(),
            range: tower_lsp::lsp_types::Range {
                start: tower_lsp::lsp_types::Position {
                    line: 0,
                    character: 0,
                },
                end: tower_lsp::lsp_types::Position {
                    line: 0,
                    character: 10,
                },
            },
            selection_range: tower_lsp::lsp_types::Range {
                start: tower_lsp::lsp_types::Position {
                    line: 0,
                    character: 3,
                },
                end: tower_lsp::lsp_types::Position {
                    line: 0,
                    character: 7,
                },
            },
        };

        let calls = db.outgoing_calls(&item, &files);

        // May have calls if ranges are extracted
        // Just verify it doesn't panic
        for call in calls {
            assert_ne!(call.to.name, "main"); // Should be to other functions
        }
    }

    #[test]
    fn test_call_hierarchy_item_structure() {
        let item = CallHierarchyItem {
            name: "test".to_string(),
            kind: SymbolKind::Function,
            uri: Url::parse("file:///test.wj").unwrap(),
            range: tower_lsp::lsp_types::Range {
                start: tower_lsp::lsp_types::Position {
                    line: 0,
                    character: 0,
                },
                end: tower_lsp::lsp_types::Position {
                    line: 5,
                    character: 1,
                },
            },
            selection_range: tower_lsp::lsp_types::Range {
                start: tower_lsp::lsp_types::Position {
                    line: 0,
                    character: 3,
                },
                end: tower_lsp::lsp_types::Position {
                    line: 0,
                    character: 7,
                },
            },
        };

        assert_eq!(item.name, "test");
        assert_eq!(item.kind, SymbolKind::Function);
        assert_eq!(item.range.start.line, 0);
        assert_eq!(item.selection_range.start.character, 3);
    }

    #[test]
    fn test_incoming_call_structure() {
        let from = CallHierarchyItem {
            name: "caller".to_string(),
            kind: SymbolKind::Function,
            uri: Url::parse("file:///test.wj").unwrap(),
            range: tower_lsp::lsp_types::Range {
                start: tower_lsp::lsp_types::Position {
                    line: 0,
                    character: 0,
                },
                end: tower_lsp::lsp_types::Position {
                    line: 5,
                    character: 1,
                },
            },
            selection_range: tower_lsp::lsp_types::Range {
                start: tower_lsp::lsp_types::Position {
                    line: 0,
                    character: 3,
                },
                end: tower_lsp::lsp_types::Position {
                    line: 0,
                    character: 9,
                },
            },
        };

        let call = IncomingCall {
            from: from.clone(),
            from_ranges: vec![tower_lsp::lsp_types::Range {
                start: tower_lsp::lsp_types::Position {
                    line: 2,
                    character: 4,
                },
                end: tower_lsp::lsp_types::Position {
                    line: 2,
                    character: 10,
                },
            }],
        };

        assert_eq!(call.from.name, "caller");
        assert_eq!(call.from_ranges.len(), 1);
        assert_eq!(call.from_ranges[0].start.line, 2);
    }

    #[test]
    fn test_outgoing_call_structure() {
        let to = CallHierarchyItem {
            name: "callee".to_string(),
            kind: SymbolKind::Function,
            uri: Url::parse("file:///test.wj").unwrap(),
            range: tower_lsp::lsp_types::Range {
                start: tower_lsp::lsp_types::Position {
                    line: 10,
                    character: 0,
                },
                end: tower_lsp::lsp_types::Position {
                    line: 15,
                    character: 1,
                },
            },
            selection_range: tower_lsp::lsp_types::Range {
                start: tower_lsp::lsp_types::Position {
                    line: 10,
                    character: 3,
                },
                end: tower_lsp::lsp_types::Position {
                    line: 10,
                    character: 9,
                },
            },
        };

        let call = OutgoingCall {
            to: to.clone(),
            from_ranges: vec![tower_lsp::lsp_types::Range {
                start: tower_lsp::lsp_types::Position {
                    line: 2,
                    character: 4,
                },
                end: tower_lsp::lsp_types::Position {
                    line: 2,
                    character: 10,
                },
            }],
        };

        assert_eq!(call.to.name, "callee");
        assert_eq!(call.from_ranges.len(), 1);
        assert_eq!(call.from_ranges[0].start.line, 2);
    }

    #[test]
    fn test_call_hierarchy_empty_project() {
        let mut db = WindjammerDatabase::new();

        let uri = Url::parse("file:///empty.wj").unwrap();
        let text = "";
        let file = db.set_source_text(uri, text.to_string());

        let item = db.prepare_call_hierarchy(file, 0, 0);
        assert!(item.is_none());
    }
}

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

    #[test]
    fn test_find_unused_symbols_empty() {
        let mut db = WindjammerDatabase::new();

        let uri = Url::parse("file:///empty.wj").unwrap();
        let text = "";
        let file = db.set_source_text(uri, text.to_string());

        let unused = db.find_unused_symbols(&[file]);
        assert_eq!(unused.len(), 0);
    }

    #[test]
    fn test_find_unused_symbols_all_used() {
        let mut db = WindjammerDatabase::new();

        let files: Vec<_> = vec![
            (
                Url::parse("file:///main.wj").unwrap(),
                "fn main() { helper() }".to_string(),
            ),
            (
                Url::parse("file:///helper.wj").unwrap(),
                "fn helper() {}".to_string(),
            ),
        ]
        .into_iter()
        .map(|(uri, text)| db.set_source_text(uri, text))
        .collect();

        let _unused = db.find_unused_symbols(&files);

        // Both functions reference each other, so none should be unused
        // (This is a simplified check - actual usage would need AST analysis)
        // Test passes if no panic occurs
    }

    #[test]
    fn test_find_unused_functions() {
        let mut db = WindjammerDatabase::new();

        let files: Vec<_> = vec![
            (
                Url::parse("file:///main.wj").unwrap(),
                "fn main() {}".to_string(),
            ),
            (
                Url::parse("file:///unused.wj").unwrap(),
                "fn unused_func() {}".to_string(),
            ),
        ]
        .into_iter()
        .map(|(uri, text)| db.set_source_text(uri, text))
        .collect();

        let unused = db.find_unused_functions(&files);

        // Should find functions that are never called
        for u in &unused {
            assert_eq!(u.kind, SymbolKind::Function);
            assert_eq!(u.reason, UnusedReason::NeverReferenced);
        }
    }

    #[test]
    fn test_find_unused_structs() {
        let mut db = WindjammerDatabase::new();

        let files: Vec<_> = vec![(
            Url::parse("file:///structs.wj").unwrap(),
            "struct UsedStruct {} struct UnusedStruct {}".to_string(),
        )]
        .into_iter()
        .map(|(uri, text)| db.set_source_text(uri, text))
        .collect();

        let unused = db.find_unused_structs(&files);

        // Should only return structs
        for u in &unused {
            assert_eq!(u.kind, SymbolKind::Struct);
        }
    }

    #[test]
    fn test_unused_reason() {
        // Test the UnusedReason enum
        assert_eq!(UnusedReason::NeverReferenced, UnusedReason::NeverReferenced);
        assert_ne!(UnusedReason::NeverReferenced, UnusedReason::OnlyInDeadCode);
    }

    #[test]
    fn test_unused_symbol_structure() {
        let unused = UnusedSymbol {
            name: "test".to_string(),
            kind: SymbolKind::Function,
            location: tower_lsp::lsp_types::Location {
                uri: Url::parse("file:///test.wj").unwrap(),
                range: tower_lsp::lsp_types::Range {
                    start: tower_lsp::lsp_types::Position {
                        line: 0,
                        character: 0,
                    },
                    end: tower_lsp::lsp_types::Position {
                        line: 5,
                        character: 1,
                    },
                },
            },
            reason: UnusedReason::NeverReferenced,
        };

        assert_eq!(unused.name, "test");
        assert_eq!(unused.kind, SymbolKind::Function);
        assert_eq!(unused.reason, UnusedReason::NeverReferenced);
    }

    #[test]
    fn test_find_unused_with_duplicates() {
        let mut db = WindjammerDatabase::new();

        // Create files where the same function name appears multiple times
        let files: Vec<_> = vec![
            (
                Url::parse("file:///file1.wj").unwrap(),
                "fn duplicate() {}".to_string(),
            ),
            (
                Url::parse("file:///file2.wj").unwrap(),
                "fn duplicate() {}".to_string(),
            ),
        ]
        .into_iter()
        .map(|(uri, text)| db.set_source_text(uri, text))
        .collect();

        let unused = db.find_unused_symbols(&files);

        // Duplicates should not be marked as unused (they reference each other)
        let duplicate_unused = unused.iter().filter(|u| u.name == "duplicate").count();
        assert_eq!(duplicate_unused, 0);
    }
}

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

    #[test]
    fn test_build_dependency_graph_empty() {
        let mut db = WindjammerDatabase::new();

        let uri = Url::parse("file:///empty.wj").unwrap();
        let text = "";
        let file = db.set_source_text(uri, text.to_string());

        let graph = db.build_dependency_graph(&[file]);
        assert_eq!(graph.files.len(), 1);
        assert_eq!(graph.dependencies.len(), 0);
    }

    #[test]
    fn test_dependency_graph_no_cycles() {
        let mut db = WindjammerDatabase::new();

        let files: Vec<_> = vec![
            (
                Url::parse("file:///main.wj").unwrap(),
                "fn main() {}".to_string(),
            ),
            (
                Url::parse("file:///helper.wj").unwrap(),
                "fn helper() {}".to_string(),
            ),
        ]
        .into_iter()
        .map(|(uri, text)| db.set_source_text(uri, text))
        .collect();

        let graph = db.build_dependency_graph(&files);
        assert!(!graph.has_circular_dependencies());
    }

    #[test]
    fn test_get_dependencies() {
        let mut db = WindjammerDatabase::new();

        let files: Vec<_> = vec![
            (
                Url::parse("file:///main.wj").unwrap(),
                "fn main() {}".to_string(),
            ),
            (
                Url::parse("file:///helper.wj").unwrap(),
                "fn helper() {}".to_string(),
            ),
        ]
        .into_iter()
        .map(|(uri, text)| db.set_source_text(uri, text))
        .collect();

        let graph = db.build_dependency_graph(&files);
        let main_uri = Url::parse("file:///main.wj").unwrap();
        let _deps = graph.get_dependencies(&main_uri);

        // Verify we can get dependencies (may be empty)
        // Test passes if no panic occurs
    }

    #[test]
    fn test_calculate_coupling() {
        let mut db = WindjammerDatabase::new();

        let files: Vec<_> = vec![
            (
                Url::parse("file:///main.wj").unwrap(),
                "fn main() {}".to_string(),
            ),
            (
                Url::parse("file:///helper.wj").unwrap(),
                "fn helper() {}".to_string(),
            ),
        ]
        .into_iter()
        .map(|(uri, text)| db.set_source_text(uri, text))
        .collect();

        let metrics = db.calculate_coupling(&files);
        assert_eq!(metrics.len(), 2);

        for (uri, _afferent, _efferent) in metrics {
            assert!(uri.as_str().starts_with("file:///"));
            // assert!(afferent >= 0); // Always true for usize
            // assert!(efferent >= 0); // Always true for usize
        }
    }

    #[test]
    fn test_dependency_kind() {
        assert_eq!(DependencyKind::Import, DependencyKind::Import);
        assert_ne!(DependencyKind::Import, DependencyKind::SymbolReference);
    }

    #[test]
    fn test_file_dependency_structure() {
        let dep = FileDependency {
            from: Url::parse("file:///a.wj").unwrap(),
            to: Url::parse("file:///b.wj").unwrap(),
            kind: DependencyKind::Import,
        };

        assert_eq!(dep.from.as_str(), "file:///a.wj");
        assert_eq!(dep.to.as_str(), "file:///b.wj");
        assert_eq!(dep.kind, DependencyKind::Import);
    }

    #[test]
    fn test_find_circular_dependencies() {
        let mut db = WindjammerDatabase::new();

        let files: Vec<_> = vec![
            (Url::parse("file:///a.wj").unwrap(), "fn a() {}".to_string()),
            (Url::parse("file:///b.wj").unwrap(), "fn b() {}".to_string()),
        ]
        .into_iter()
        .map(|(uri, text)| db.set_source_text(uri, text))
        .collect();

        let _cycles = db.find_circular_dependencies(&files);
        // Should not panic, may be empty
        // Test passes if no panic occurs
    }
}

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

    #[test]
    fn test_calculate_file_metrics_empty() {
        let mut db = WindjammerDatabase::new();

        let uri = Url::parse("file:///empty.wj").unwrap();
        let text = "";
        let file = db.set_source_text(uri, text.to_string());

        let metrics = db.calculate_file_metrics(file);
        assert_eq!(metrics.lines_of_code, 0);
        assert_eq!(metrics.num_functions, 0);
        assert_eq!(metrics.num_structs, 0);
    }

    #[test]
    fn test_calculate_file_metrics_with_content() {
        let mut db = WindjammerDatabase::new();

        let uri = Url::parse("file:///test.wj").unwrap();
        let text = r#"
// Comment
fn main() {
    println("Hello");
}

struct Point {
    x: i32,
    y: i32,
}
"#;
        let file = db.set_source_text(uri, text.to_string());

        let metrics = db.calculate_file_metrics(file);
        assert!(metrics.lines_of_code > 0);
        // Parser may not extract all symbols, just check that we got some data
        // assert!(metrics.complexity_score >= 0); // Always true for usize
    }

    #[test]
    fn test_calculate_workspace_metrics() {
        let mut db = WindjammerDatabase::new();

        let files: Vec<_> = vec![
            (
                Url::parse("file:///main.wj").unwrap(),
                "fn main() {}".to_string(),
            ),
            (
                Url::parse("file:///helper.wj").unwrap(),
                "fn helper() {}".to_string(),
            ),
        ]
        .into_iter()
        .map(|(uri, text)| db.set_source_text(uri, text))
        .collect();

        let metrics = db.calculate_workspace_metrics(&files);
        assert_eq!(metrics.total_files, 2);
        assert!(metrics.total_lines > 0);
        assert!(metrics.total_functions >= 2);
    }

    #[test]
    fn test_find_large_files() {
        let mut db = WindjammerDatabase::new();

        let files: Vec<_> = vec![
            (
                Url::parse("file:///small.wj").unwrap(),
                "fn f() {}".to_string(),
            ),
            (
                Url::parse("file:///large.wj").unwrap(),
                "fn f1() {}\nfn f2() {}\nfn f3() {}\nfn f4() {}\nfn f5() {}".to_string(),
            ),
        ]
        .into_iter()
        .map(|(uri, text)| db.set_source_text(uri, text))
        .collect();

        let large = db.find_large_files(&files, 2);
        assert!(!large.is_empty());
        assert!(large.iter().any(|(uri, _)| uri.as_str().contains("large")));
    }

    #[test]
    fn test_find_long_functions() {
        let mut db = WindjammerDatabase::new();

        let files: Vec<_> = vec![(
            Url::parse("file:///test.wj").unwrap(),
            "fn short() {}\nfn long() {\n  // line 1\n  // line 2\n  // line 3\n}".to_string(),
        )]
        .into_iter()
        .map(|(uri, text)| db.set_source_text(uri, text))
        .collect();

        let _long = db.find_long_functions(&files, 3);
        // May or may not find long functions depending on AST parsing
        // assert!(long.len() >= 0); // Always true for usize
    }

    #[test]
    fn test_file_metrics_structure() {
        let mut db = WindjammerDatabase::new();

        let uri = Url::parse("file:///test.wj").unwrap();
        let text = "fn main() {}";
        let file = db.set_source_text(uri.clone(), text.to_string());

        let metrics = db.calculate_file_metrics(file);
        assert_eq!(metrics.uri, uri);
        assert!(metrics.avg_function_length >= 0.0);
        // assert!(metrics.complexity_score >= 0); // Always true for usize
    }

    #[test]
    fn test_workspace_metrics_largest_file() {
        let mut db = WindjammerDatabase::new();

        let files: Vec<_> = vec![
            (
                Url::parse("file:///small.wj").unwrap(),
                "fn f() {}".to_string(),
            ),
            (
                Url::parse("file:///large.wj").unwrap(),
                "fn f1() {}\nfn f2() {}\nfn f3() {}".to_string(),
            ),
        ]
        .into_iter()
        .map(|(uri, text)| db.set_source_text(uri, text))
        .collect();

        let metrics = db.calculate_workspace_metrics(&files);
        assert!(metrics.largest_file.is_some());

        if let Some((uri, size)) = metrics.largest_file {
            assert!(uri.as_str().contains("large"));
            assert!(size > 0);
        }
    }
}

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

    #[test]
    fn test_lint_config_default() {
        let config = LintConfig::default();
        assert_eq!(config.max_function_length, 50);
        assert_eq!(config.max_file_length, 500);
        assert!(config.check_unused);
        assert!(config.check_style);
    }

    #[test]
    fn test_lint_workspace_empty() {
        let mut db = WindjammerDatabase::new();
        let config = LintConfig::default();

        let uri = Url::parse("file:///empty.wj").unwrap();
        let text = "";
        let file = db.set_source_text(uri, text.to_string());

        let diagnostics = db.lint_workspace(&[file], &config);
        assert_eq!(diagnostics.len(), 0);
    }

    #[test]
    fn test_check_unused_code() {
        let mut db = WindjammerDatabase::new();

        let files: Vec<_> = vec![
            (
                Url::parse("file:///main.wj").unwrap(),
                "fn main() {}".to_string(),
            ),
            (
                Url::parse("file:///unused.wj").unwrap(),
                "fn unused_func() {}".to_string(),
            ),
        ]
        .into_iter()
        .map(|(uri, text)| db.set_source_text(uri, text))
        .collect();

        let config = LintConfig::default();
        let diagnostics = db.check_unused_code(&files, &config);
        // May find unused functions
        for diag in &diagnostics {
            assert_eq!(diag.category, DiagnosticCategory::Unused);
            assert_eq!(diag.severity, DiagnosticSeverity::Warning);
            assert!(diag.suggestion.is_some());
        }
    }

    #[test]
    fn test_check_complexity() {
        let mut db = WindjammerDatabase::new();
        let config = LintConfig {
            max_function_length: 2,
            max_file_length: 5,
            ..Default::default()
        };

        let files: Vec<_> = vec![(
            Url::parse("file:///test.wj").unwrap(),
            "fn long() {\n  line1();\n  line2();\n  line3();\n  line4();\n}".to_string(),
        )]
        .into_iter()
        .map(|(uri, text)| db.set_source_text(uri, text))
        .collect();

        let diagnostics = db.check_complexity(&files, &config);
        // May find complexity issues
        for diag in &diagnostics {
            assert_eq!(diag.category, DiagnosticCategory::CodeComplexity);
            assert!(
                diag.severity == DiagnosticSeverity::Warning
                    || diag.severity == DiagnosticSeverity::Info
            );
        }
    }

    #[test]
    fn test_diagnostic_severity() {
        assert_ne!(DiagnosticSeverity::Error, DiagnosticSeverity::Warning);
        assert_ne!(DiagnosticSeverity::Warning, DiagnosticSeverity::Info);
    }

    #[test]
    fn test_diagnostic_category() {
        assert_ne!(
            DiagnosticCategory::Unused,
            DiagnosticCategory::CodeComplexity
        );
        assert_ne!(
            DiagnosticCategory::Naming,
            DiagnosticCategory::Documentation
        );
    }

    #[test]
    fn test_capitalize_first() {
        assert_eq!(capitalize_first("hello"), "Hello");
        assert_eq!(capitalize_first("world"), "World");
        assert_eq!(capitalize_first(""), "");
        assert_eq!(capitalize_first("A"), "A");
    }

    #[test]
    fn test_lint_workspace_with_config() {
        let mut db = WindjammerDatabase::new();
        let config = LintConfig {
            max_function_length: 100,
            max_file_length: 1000,
            check_unused: false,
            check_style: false,
            check_performance: true,
            check_security: true,
            ..Default::default()
        };

        let files: Vec<_> = vec![(
            Url::parse("file:///test.wj").unwrap(),
            "fn main() {}".to_string(),
        )]
        .into_iter()
        .map(|(uri, text)| db.set_source_text(uri, text))
        .collect();

        let _diagnostics = db.lint_workspace(&files, &config);
        // Should return some diagnostics
        // assert!(diagnostics.len() >= 0); // Always true for Vec
    }

    #[test]
    fn test_autofix_enabled() {
        let mut db = WindjammerDatabase::new();
        let config = LintConfig {
            enable_autofix: true,
            ..Default::default()
        };

        let files: Vec<_> = vec![(
            Url::parse("file:///test.wj").unwrap(),
            "fn unused() {}".to_string(),
        )]
        .into_iter()
        .map(|(uri, text)| db.set_source_text(uri, text))
        .collect();

        let diagnostics = db.check_unused_code(&files, &config);
        // Check that auto-fixes are provided when enabled
        for diag in &diagnostics {
            // Auto-fix may or may not be available depending on the diagnostic
            if diag.fix.is_some() {
                assert!(!diag.fix.as_ref().unwrap().description.is_empty());
            }
        }
    }

    #[test]
    fn test_check_error_handling() {
        let mut db = WindjammerDatabase::new();
        let config = LintConfig::default();

        let files: Vec<_> = vec![(
            Url::parse("file:///test.wj").unwrap(),
            "fn test() -> Result<i32> { panic!(\"error\") }".to_string(),
        )]
        .into_iter()
        .map(|(uri, text)| db.set_source_text(uri, text))
        .collect();

        let diagnostics = db.check_error_handling(&files, &config);
        // Should find panic usage
        assert!(diagnostics.iter().any(|d| d.rule == "avoid-panic"));
    }

    #[test]
    fn test_check_performance() {
        let mut db = WindjammerDatabase::new();
        let config = LintConfig::default();

        let files: Vec<_> = vec![(
            Url::parse("file:///test.wj").unwrap(),
            "fn test() { let v = Vec::new(); v.push(1); }".to_string(),
        )]
        .into_iter()
        .map(|(uri, text)| db.set_source_text(uri, text))
        .collect();

        let diagnostics = db.check_performance(&files, &config);
        // Should find vec prealloc issue
        assert!(diagnostics
            .iter()
            .any(|d| d.category == DiagnosticCategory::Performance));
    }

    #[test]
    fn test_check_security() {
        let mut db = WindjammerDatabase::new();
        let config = LintConfig::default();

        let files: Vec<_> = vec![(
            Url::parse("file:///test.wj").unwrap(),
            "fn test() { unsafe { do_something(); } }".to_string(),
        )]
        .into_iter()
        .map(|(uri, text)| db.set_source_text(uri, text))
        .collect();

        let diagnostics = db.check_security(&files, &config);
        // Should find unsafe block
        assert!(diagnostics.iter().any(|d| d.rule == "unsafe-block"));
    }

    #[test]
    fn test_autofix_structure() {
        let fix = AutoFix {
            description: "Test fix".to_string(),
            edits: vec![TextEdit {
                range: tower_lsp::lsp_types::Range::default(),
                new_text: "fixed".to_string(),
            }],
        };

        assert_eq!(fix.description, "Test fix");
        assert_eq!(fix.edits.len(), 1);
        assert_eq!(fix.edits[0].new_text, "fixed");
    }
}

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

    #[test]
    fn test_lazy_loading_initial_state() {
        let mut db = WindjammerDatabase::new();
        let uri = Url::parse("file:///test.wj").unwrap();
        let file = db.set_source_text(uri, "fn test() {}".to_string());

        // Symbols should not be loaded initially
        assert!(!db.are_symbols_loaded(file));
        assert!(!db.are_references_loaded(file));
    }

    #[test]
    fn test_lazy_loading_mark_loaded() {
        let mut db = WindjammerDatabase::new();
        let uri = Url::parse("file:///test.wj").unwrap();
        let file = db.set_source_text(uri, "fn test() {}".to_string());

        // Mark as loaded
        db.mark_symbols_loaded(file);
        assert!(db.are_symbols_loaded(file));

        db.mark_references_loaded(file);
        assert!(db.are_references_loaded(file));
    }

    #[test]
    fn test_lazy_loading_get_symbols() {
        let mut db = WindjammerDatabase::new();
        let uri = Url::parse("file:///test.wj").unwrap();
        let file = db.set_source_text(uri, "fn test() {}".to_string());

        // Get symbols with lazy loading
        let _symbols = db.get_symbols_lazy(file);
        // assert!(symbols.len() >= 0); // Always true for Vec

        // Should be marked as loaded now
        assert!(db.are_symbols_loaded(file));
    }

    #[test]
    fn test_lazy_loading_clear_caches() {
        let mut db = WindjammerDatabase::new();
        let uri = Url::parse("file:///test.wj").unwrap();
        let file = db.set_source_text(uri, "fn test() {}".to_string());

        db.mark_symbols_loaded(file);
        db.mark_references_loaded(file);

        assert!(db.are_symbols_loaded(file));
        assert!(db.are_references_loaded(file));

        // Clear caches
        db.clear_lazy_caches();

        assert!(!db.are_symbols_loaded(file));
        assert!(!db.are_references_loaded(file));
    }

    #[test]
    fn test_lazy_loading_preload() {
        let mut db = WindjammerDatabase::new();

        let files: Vec<_> = vec![
            (Url::parse("file:///a.wj").unwrap(), "fn a() {}".to_string()),
            (Url::parse("file:///b.wj").unwrap(), "fn b() {}".to_string()),
        ]
        .into_iter()
        .map(|(uri, text)| db.set_source_text(uri, text))
        .collect();

        // Preload symbols
        db.preload_symbols(&files);

        // All files should have symbols loaded
        for file in &files {
            assert!(db.are_symbols_loaded(*file));
        }
    }

    #[test]
    fn test_lazy_loading_multiple_files() {
        let mut db = WindjammerDatabase::new();

        let files: Vec<_> = vec![
            (Url::parse("file:///a.wj").unwrap(), "fn a() {}".to_string()),
            (Url::parse("file:///b.wj").unwrap(), "fn b() {}".to_string()),
            (Url::parse("file:///c.wj").unwrap(), "fn c() {}".to_string()),
        ]
        .into_iter()
        .map(|(uri, text)| db.set_source_text(uri, text))
        .collect();

        // Mark only some as loaded
        db.mark_symbols_loaded(files[0]);
        db.mark_symbols_loaded(files[2]);

        assert!(db.are_symbols_loaded(files[0]));
        assert!(!db.are_symbols_loaded(files[1]));
        assert!(db.are_symbols_loaded(files[2]));
    }
}

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

    #[test]
    fn test_extract_function_single_line() {
        let mut db = WindjammerDatabase::new();
        let uri = Url::parse("file:///test.wj").unwrap();
        let code = "fn main() {\n    let x = 1 + 2;\n    println(x);\n}";
        let file = db.set_source_text(uri, code.to_string());

        // Select "1 + 2"
        let range = tower_lsp::lsp_types::Range {
            start: tower_lsp::lsp_types::Position {
                line: 1,
                character: 12,
            },
            end: tower_lsp::lsp_types::Position {
                line: 1,
                character: 17,
            },
        };

        let actions = db.get_code_actions(file, range);
        assert!(!actions.is_empty());

        let extract_action = actions
            .iter()
            .find(|a| a.kind == CodeActionKind::RefactorExtract);
        assert!(extract_action.is_some());

        let action = extract_action.unwrap();
        assert_eq!(action.title, "Extract function");
        assert!(action.is_preferred);
        assert_eq!(action.edits.len(), 2);
    }

    #[test]
    fn test_extract_function_multi_line() {
        let mut db = WindjammerDatabase::new();
        let uri = Url::parse("file:///test.wj").unwrap();
        let code = "fn main() {\n    let x = 1;\n    let y = 2;\n    println(x + y);\n}";
        let file = db.set_source_text(uri, code.to_string());

        // Select lines 2-3
        let range = tower_lsp::lsp_types::Range {
            start: tower_lsp::lsp_types::Position {
                line: 1,
                character: 4,
            },
            end: tower_lsp::lsp_types::Position {
                line: 2,
                character: 18,
            },
        };

        let actions = db.get_code_actions(file, range);
        let extract_action = actions
            .iter()
            .find(|a| a.kind == CodeActionKind::RefactorExtract);
        assert!(extract_action.is_some());
    }

    #[test]
    fn test_extract_function_empty_selection() {
        let mut db = WindjammerDatabase::new();
        let uri = Url::parse("file:///test.wj").unwrap();
        let code = "fn main() {\n    let x = 1;\n}";
        let file = db.set_source_text(uri, code.to_string());

        // Empty selection
        let range = tower_lsp::lsp_types::Range {
            start: tower_lsp::lsp_types::Position {
                line: 1,
                character: 4,
            },
            end: tower_lsp::lsp_types::Position {
                line: 1,
                character: 4,
            },
        };

        let actions = db.get_code_actions(file, range);
        // Should not offer extract function for empty selection
        let extract_action = actions
            .iter()
            .find(|a| a.kind == CodeActionKind::RefactorExtract);
        assert!(extract_action.is_none());
    }

    #[test]
    fn test_code_action_kind() {
        assert_ne!(CodeActionKind::QuickFix, CodeActionKind::RefactorExtract);
        assert_ne!(
            CodeActionKind::RefactorInline,
            CodeActionKind::RefactorRename
        );
    }

    #[test]
    fn test_code_action_structure() {
        let action = CodeAction {
            title: "Test action".to_string(),
            kind: CodeActionKind::QuickFix,
            edits: vec![],
            is_preferred: false,
        };

        assert_eq!(action.title, "Test action");
        assert_eq!(action.kind, CodeActionKind::QuickFix);
        assert!(!action.is_preferred);
    }
}