nvim-mcp 0.7.2

MCP server for Neovim
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
#![allow(rustdoc::invalid_codeblock_attributes)]

use std::collections::HashMap;
use std::fmt::{self, Display};
use std::marker::PhantomData;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::Arc;

use async_trait::async_trait;
use nvim_rs::{Handler, Neovim, create::tokio as create};
use rmpv::Value;
use serde::de::{self, MapAccess, Visitor};
use serde::{Deserialize, Deserializer};
use tokio::{
    io::AsyncWrite,
    net::TcpStream,
    sync::Mutex,
    time::{Duration, timeout},
};
use tracing::{debug, info, instrument};

use super::{connection::NeovimConnection, error::NeovimError};

/// Common trait for Neovim client operations
#[async_trait]
pub trait NeovimClientTrait: Sync {
    /// Get the target of the Neovim connection
    fn target(&self) -> Option<String>;

    /// Disconnect from the current Neovim instance
    async fn disconnect(&mut self) -> Result<String, NeovimError>;

    /// Get information about all buffers
    async fn get_buffers(&self) -> Result<Vec<BufferInfo>, NeovimError>;

    /// Execute Lua code in Neovim
    async fn execute_lua(&self, code: &str) -> Result<Value, NeovimError>;

    /// Set up diagnostics changed autocmd
    async fn setup_autocmd(&self) -> Result<(), NeovimError>;

    /// Wait for a specific notification with timeout
    async fn wait_for_notification(
        &self,
        notification_name: &str,
        timeout_ms: u64,
    ) -> Result<Notification, NeovimError>;

    /// Wait for LSP client to be ready and attached
    async fn wait_for_lsp_ready(
        &self,
        client_name: Option<&str>,
        timeout_ms: u64,
    ) -> Result<(), NeovimError>;

    /// Wait for diagnostics to be available for a specific buffer or workspace
    async fn wait_for_diagnostics(
        &self,
        buffer_id: Option<u64>,
        timeout_ms: u64,
    ) -> Result<Vec<Diagnostic>, NeovimError>;

    /// Get diagnostics for a specific buffer
    async fn get_buffer_diagnostics(&self, buffer_id: u64) -> Result<Vec<Diagnostic>, NeovimError>;

    /// Get diagnostics for the entire workspace
    async fn get_workspace_diagnostics(&self) -> Result<Vec<Diagnostic>, NeovimError>;

    /// Get LSP clients
    async fn lsp_get_clients(&self) -> Result<Vec<LspClient>, NeovimError>;

    /// Get LSP code actions
    async fn lsp_get_code_actions(
        &self,
        client_name: &str,
        document: DocumentIdentifier,
        range: Range,
    ) -> Result<Vec<CodeAction>, NeovimError>;

    /// Get LSP hover information for a specific position
    async fn lsp_hover(
        &self,
        client_name: &str,
        document: DocumentIdentifier,
        position: Position,
    ) -> Result<HoverResult, NeovimError>;

    /// Get document symbols for a specific buffer or document
    async fn lsp_document_symbols(
        &self,
        client_name: &str,
        document: DocumentIdentifier,
    ) -> Result<Option<DocumentSymbolResult>, NeovimError>;

    /// Search for workspace symbols by query
    async fn lsp_workspace_symbols(
        &self,
        client_name: &str,
        query: &str,
    ) -> Result<Option<DocumentSymbolResult>, NeovimError>;

    /// Get references for a symbol at a specific position
    async fn lsp_references(
        &self,
        client_name: &str,
        document: DocumentIdentifier,
        position: Position,
        include_declaration: bool,
    ) -> Result<Vec<Location>, NeovimError>;

    /// Get definition(s) of a symbol
    async fn lsp_definition(
        &self,
        client_name: &str,
        document: DocumentIdentifier,
        position: Position,
    ) -> Result<Option<LocateResult>, NeovimError>;

    /// Get type definition(s) of a symbol
    async fn lsp_type_definition(
        &self,
        client_name: &str,
        document: DocumentIdentifier,
        position: Position,
    ) -> Result<Option<LocateResult>, NeovimError>;

    /// Get implementation(s) of a symbol
    async fn lsp_implementation(
        &self,
        client_name: &str,
        document: DocumentIdentifier,
        position: Position,
    ) -> Result<Option<LocateResult>, NeovimError>;

    /// Get declaration(s) of a symbol
    async fn lsp_declaration(
        &self,
        client_name: &str,
        document: DocumentIdentifier,
        position: Position,
    ) -> Result<Option<LocateResult>, NeovimError>;

    /// Resolve a code action that may have incomplete data
    async fn lsp_resolve_code_action(
        &self,
        client_name: &str,
        code_action: CodeAction,
    ) -> Result<CodeAction, NeovimError>;

    /// Apply a workspace edit using the LSP workspace/applyEdit method
    async fn lsp_apply_workspace_edit(
        &self,
        client_name: &str,
        workspace_edit: WorkspaceEdit,
    ) -> Result<(), NeovimError>;

    /// Prepare rename operation to validate position and get range/placeholder
    async fn lsp_prepare_rename(
        &self,
        client_name: &str,
        document: DocumentIdentifier,
        position: Position,
    ) -> Result<Option<PrepareRenameResult>, NeovimError>;

    /// Rename symbol across workspace
    async fn lsp_rename(
        &self,
        client_name: &str,
        document: DocumentIdentifier,
        position: Position,
        new_name: &str,
    ) -> Result<Option<WorkspaceEdit>, NeovimError>;

    /// Format document using LSP
    async fn lsp_formatting(
        &self,
        client_name: &str,
        document: DocumentIdentifier,
        options: FormattingOptions,
    ) -> Result<Vec<TextEdit>, NeovimError>;

    /// Format document range using LSP
    async fn lsp_range_formatting(
        &self,
        client_name: &str,
        document: DocumentIdentifier,
        range: Range,
        options: FormattingOptions,
    ) -> Result<Vec<TextEdit>, NeovimError>;

    /// Get organize imports code actions for entire document
    async fn lsp_get_organize_imports_actions(
        &self,
        client_name: &str,
        document: DocumentIdentifier,
    ) -> Result<Vec<CodeAction>, NeovimError>;

    /// Apply text edits to a document
    async fn lsp_apply_text_edits(
        &self,
        client_name: &str,
        document: DocumentIdentifier,
        text_edits: Vec<TextEdit>,
    ) -> Result<(), NeovimError>;
    /// Navigate to a specific position in a document
    async fn navigate(
        &self,
        document: DocumentIdentifier,
        position: Position,
    ) -> Result<NavigateResult, NeovimError>;

    /// Prepare call hierarchy for a symbol at a specific position
    async fn lsp_call_hierarchy_prepare(
        &self,
        client_name: &str,
        document: DocumentIdentifier,
        position: Position,
    ) -> Result<Option<Vec<CallHierarchyItem>>, NeovimError>;

    /// Get incoming calls for a call hierarchy item
    async fn lsp_call_hierarchy_incoming_calls(
        &self,
        client_name: &str,
        item: CallHierarchyItem,
    ) -> Result<Option<Vec<CallHierarchyIncomingCall>>, NeovimError>;

    /// Get outgoing calls for a call hierarchy item
    async fn lsp_call_hierarchy_outgoing_calls(
        &self,
        client_name: &str,
        item: CallHierarchyItem,
    ) -> Result<Option<Vec<CallHierarchyOutgoingCall>>, NeovimError>;

    /// Prepare type hierarchy for a symbol at a specific position
    async fn lsp_type_hierarchy_prepare(
        &self,
        client_name: &str,
        document: DocumentIdentifier,
        position: Position,
    ) -> Result<Option<Vec<TypeHierarchyItem>>, NeovimError>;

    /// Get supertypes for a type hierarchy item
    async fn lsp_type_hierarchy_supertypes(
        &self,
        client_name: &str,
        item: TypeHierarchyItem,
    ) -> Result<Option<Vec<TypeHierarchyItem>>, NeovimError>;

    /// Get subtypes for a type hierarchy item
    async fn lsp_type_hierarchy_subtypes(
        &self,
        client_name: &str,
        item: TypeHierarchyItem,
    ) -> Result<Option<Vec<TypeHierarchyItem>>, NeovimError>;

    /// Read document content by DocumentIdentifier with optional line range
    async fn read_document(
        &self,
        document: DocumentIdentifier,
        start: i64,
        end: i64,
    ) -> Result<String, NeovimError>;
}

/// Notification tracking structure
#[derive(Debug, Clone)]
pub struct Notification {
    pub name: String,
    pub args: Vec<Value>,
    pub timestamp: std::time::SystemTime,
}

/// Shared state for notification tracking
#[derive(Clone, Default)]
pub struct NotificationTracker {
    notifications: Arc<Mutex<Vec<Notification>>>,
    notify_wakers: Arc<Mutex<HashMap<String, Vec<tokio::sync::oneshot::Sender<Notification>>>>>,
}

/// Configuration for notification cleanup
const MAX_STORED_NOTIFICATIONS: usize = 100;
const NOTIFICATION_EXPIRY_SECONDS: u64 = 30;

impl NotificationTracker {
    /// Clean up expired and excess notifications
    async fn cleanup_notifications(&self) {
        let mut notifications = self.notifications.lock().await;

        // Remove expired notifications
        let now = std::time::SystemTime::now();
        notifications.retain(|n| {
            now.duration_since(n.timestamp)
                .map(|d| d.as_secs() < NOTIFICATION_EXPIRY_SECONDS)
                .unwrap_or(false)
        });

        // If still too many notifications, keep only the most recent ones
        if notifications.len() > MAX_STORED_NOTIFICATIONS {
            let excess = notifications.len() - MAX_STORED_NOTIFICATIONS;
            notifications.drain(0..excess);
        }
    }

    /// Record a notification
    pub async fn record_notification(&self, name: String, args: Vec<Value>) {
        let notification = Notification {
            name: name.clone(),
            args,
            timestamp: std::time::SystemTime::now(),
        };

        // Notify any waiting tasks for this specific notification name first
        let mut wakers = self.notify_wakers.lock().await;
        if let Some(waiters) = wakers.get_mut(&name) {
            while let Some(waker) = waiters.pop() {
                let _ = waker.send(notification.clone());
            }
        }

        // Clean up wakers with no waiters
        wakers.retain(|_, waiters| !waiters.is_empty());
        drop(wakers); // Release lock early

        // Always store recent notifications for potential future requests
        // but clean up old/excess ones to prevent memory leaks
        {
            let mut notifications = self.notifications.lock().await;
            notifications.push(notification);

            // Trigger cleanup if we're approaching the limit
            if notifications.len() > MAX_STORED_NOTIFICATIONS * 3 / 4 {
                drop(notifications); // Release lock before calling cleanup
                self.cleanup_notifications().await;
            }
        }
    }

    /// Wait for a specific notification with timeout
    pub async fn wait_for_notification(
        &self,
        notification_name: &str,
        timeout_duration: Duration,
    ) -> Result<Notification, NeovimError> {
        // First check if a recent (non-expired) notification already exists
        {
            let notifications = self.notifications.lock().await;
            let now = std::time::SystemTime::now();

            if let Some(notification) = notifications
                .iter()
                .rev() // Check most recent first
                .find(|n| {
                    n.name == notification_name
                        && now
                            .duration_since(n.timestamp)
                            .map(|d| d.as_secs() < NOTIFICATION_EXPIRY_SECONDS)
                            .unwrap_or(false)
                })
            {
                return Ok(notification.clone());
            }
        }

        // Create a oneshot channel to wait for the notification
        let (tx, rx) = tokio::sync::oneshot::channel();

        // Register our interest in this notification
        let mut wakers = self.notify_wakers.lock().await;
        wakers
            .entry(notification_name.to_string())
            .or_insert_with(Vec::new)
            .push(tx);

        // Wait for the notification with timeout
        drop(wakers); // Release the lock before awaiting

        match timeout(timeout_duration, rx).await {
            Ok(Ok(notification)) => Ok(notification),
            Ok(Err(_)) => Err(NeovimError::Api(
                "Notification channel closed unexpectedly".to_string(),
            )),
            Err(_) => Err(NeovimError::Api(format!(
                "Timeout waiting for notification: {}",
                notification_name
            ))),
        }
    }

    /// Clear all recorded notifications
    pub async fn clear_notifications(&self) {
        let mut notifications = self.notifications.lock().await;
        notifications.clear();
    }

    /// Manually trigger cleanup of expired notifications
    #[allow(dead_code)]
    pub(crate) async fn cleanup_expired_notifications(&self) {
        self.cleanup_notifications().await;
    }

    /// Get current notification statistics (for debugging/monitoring)
    #[allow(dead_code)]
    pub(crate) async fn get_stats(&self) -> (usize, usize) {
        let notifications = self.notifications.lock().await;
        let wakers = self.notify_wakers.lock().await;
        (notifications.len(), wakers.len())
    }
}

pub struct NeovimHandler<T> {
    _marker: std::marker::PhantomData<T>,
    notification_tracker: NotificationTracker,
}

impl<T> NeovimHandler<T> {
    pub fn new() -> Self {
        NeovimHandler {
            _marker: std::marker::PhantomData,
            notification_tracker: NotificationTracker::default(),
        }
    }

    pub fn notification_tracker(&self) -> NotificationTracker {
        self.notification_tracker.clone()
    }
}

impl<T> Clone for NeovimHandler<T> {
    fn clone(&self) -> Self {
        NeovimHandler {
            _marker: std::marker::PhantomData,
            notification_tracker: self.notification_tracker.clone(),
        }
    }
}

#[async_trait]
impl<T> Handler for NeovimHandler<T>
where
    T: futures::AsyncWrite + Send + Sync + Unpin + 'static,
{
    type Writer = T;

    async fn handle_notify(&self, name: String, args: Vec<Value>, _neovim: Neovim<T>) {
        info!("handling notification: {name:?}, {args:?}");
        self.notification_tracker
            .record_notification(name, args)
            .await;
    }

    async fn handle_request(
        &self,
        name: String,
        args: Vec<Value>,
        _neovim: Neovim<T>,
    ) -> Result<Value, Value> {
        info!("handling request: {name:?}, {args:?}");
        match name.as_ref() {
            "ping" => Ok(Value::from("pong")),
            _ => Ok(Value::Nil),
        }
    }
}

#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct Diagnostic {
    pub message: String,
    pub code: Option<serde_json::Value>,
    pub severity: u8,
    pub lnum: u64,
    pub col: u64,
    pub source: String,
    pub bufnr: u64,
    pub end_lnum: u64,
    pub end_col: u64,
    pub namespace: u64,
    pub user_data: Option<UserData>,
}

#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct UserData {
    pub lsp: LSPDiagnostic,
    #[serde(flatten)]
    pub unknowns: HashMap<String, serde_json::Value>,
}

#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
pub struct LSPDiagnostic {
    pub code: Option<serde_json::Value>,
    pub message: String,
    pub range: Range,
    pub severity: u8,
    pub source: String,
}

#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct LspClient {
    pub id: u64,
    pub name: String,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct BufferInfo {
    pub id: u64,
    pub name: String,
    pub line_count: u64,
}

/// Text documents are identified using a URI.
/// On the protocol level, URIs are passed as strings.
#[derive(Debug, serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
pub struct TextDocumentIdentifier {
    /// The text document's URI.
    uri: String,
    /// The version number of this document. If an optional versioned text document
    /// identifier is sent from the server to the client and the file is not
    /// open in the editor (the server has not received an open notification
    /// before) the server can send `null` to indicate that the version is
    /// known and the content on disk is the master (as specified with document
    /// content ownership).
    ///
    /// The version number of a document will increase after each change,
    /// including undo/redo. The number doesn't need to be consecutive.
    version: Option<i32>,
}

/// This is a Visitor that forwards string types to T's `FromStr` impl and
/// forwards map types to T's `Deserialize` impl. The `PhantomData` is to
/// keep the compiler from complaining about T being an unused generic type
/// parameter. We need T in order to know the Value type for the Visitor
/// impl.
struct StringOrStruct<T>(PhantomData<fn() -> T>);

impl<'de, T> Visitor<'de> for StringOrStruct<T>
where
    T: Deserialize<'de> + FromStr,
    <T as FromStr>::Err: Display,
{
    type Value = T;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("string or map")
    }

    fn visit_str<E>(self, value: &str) -> Result<T, E>
    where
        E: de::Error,
    {
        FromStr::from_str(value).map_err(de::Error::custom)
    }

    fn visit_map<M>(self, map: M) -> Result<T, M::Error>
    where
        M: MapAccess<'de>,
    {
        // `MapAccessDeserializer` is a wrapper that turns a `MapAccess`
        // into a `Deserializer`, allowing it to be used as the input to T's
        // `Deserialize` implementation. T then deserializes itself using
        // the entries from the map visitor.
        Deserialize::deserialize(de::value::MapAccessDeserializer::new(map))
    }
}

/// Custom deserializer function that handles both formats
pub fn string_or_struct<'de, T, D>(deserializer: D) -> Result<T, D::Error>
where
    D: Deserializer<'de>,
    T: Deserialize<'de> + FromStr,
    <T as FromStr>::Err: Display,
{
    deserializer.deserialize_any(StringOrStruct(PhantomData))
}

/// Universal identifier for text documents supporting multiple reference types
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum DocumentIdentifier {
    /// Reference by Neovim buffer ID (for currently open files)
    BufferId(u64),
    /// Reference by project-relative path
    ProjectRelativePath(PathBuf),
    /// Reference by absolute file path
    AbsolutePath(PathBuf),
}

macro_rules! impl_fromstr_serde_json {
    ($type:ty) => {
        impl FromStr for $type {
            type Err = serde_json::Error;

            fn from_str(s: &str) -> Result<Self, Self::Err> {
                serde_json::from_str(s)
            }
        }
    };
}

impl_fromstr_serde_json!(DocumentIdentifier);

impl DocumentIdentifier {
    /// Create from buffer ID
    pub fn from_buffer_id(buffer_id: u64) -> Self {
        Self::BufferId(buffer_id)
    }

    /// Create from project-relative path
    pub fn from_project_path<P: Into<PathBuf>>(path: P) -> Self {
        Self::ProjectRelativePath(path.into())
    }

    /// Create from absolute path
    pub fn from_absolute_path<P: Into<PathBuf>>(path: P) -> Self {
        Self::AbsolutePath(path.into())
    }
}

/// Position in a text document expressed as zero-based line and zero-based character offset.
/// A position is between two characters like an 'insert' cursor in an editor.
#[derive(Debug, Clone, Default, serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
pub struct Position {
    /// Line position in a document (zero-based).
    pub line: u64,
    /// Character offset on a line in a document (zero-based).
    pub character: u64,
}

#[derive(Debug, Clone, Default, serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
pub struct Range {
    /// The range's start position.
    pub start: Position,
    /// The range's end position.
    pub end: Position,
}

/// The kind of a code action.
///
/// Kinds are a hierarchical list of identifiers separated by `.`,
/// e.g. `"refactor.extract.function"`.
///
/// The set of kinds is open and client needs to announce the kinds it supports
/// to the server during initialization.
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, schemars::JsonSchema, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum CodeActionKind {
    /// Empty kind.
    #[serde(rename = "")]
    Empty,
    /// Base kind for quickfix actions: 'quickfix'.
    #[serde(rename = "quickfix")]
    Quickfix,
    /// Base kind for refactoring actions: 'refactor'.
    Refactor,
    /// Base kind for refactoring extraction actions: 'refactor.extract'.
    ///
    /// Example extract actions:
    ///
    /// - Extract method
    /// - Extract function
    /// - Extract variable
    /// - Extract interface from class
    /// - ...
    #[serde(rename = "refactor.extract")]
    RefactorExtract,
    /// Base kind for refactoring inline actions: 'refactor.inline'.
    ///
    /// Example inline actions:
    ///
    /// - Inline function
    /// - Inline variable
    /// - Inline constant
    /// - ...
    #[serde(rename = "refactor.inline")]
    RefactorInline,
    /// Base kind for refactoring rewrite actions: 'refactor.rewrite'.
    ///
    /// Example rewrite actions:
    ///
    /// - Convert JavaScript function to class
    /// - Add or remove parameter
    /// - Encapsulate field
    /// - Make method static
    /// - Move method to base class
    /// - ...
    #[serde(rename = "refactor.rewrite")]
    RefactorRewrite,
    /// Base kind for source actions: `source`.
    ///
    /// Source code actions apply to the entire file.
    Source,
    /// Base kind for an organize imports source action:
    /// `source.organizeImports`.
    #[serde(rename = "source.organizeImports")]
    SourceOrganizeImports,
    /// Base kind for a 'fix all' source action: `source.fixAll`.
    ///
    /// 'Fix all' actions automatically fix errors that have a clear fix that
    /// do not require user input. They should not suppress errors or perform
    /// unsafe fixes such as generating new types or classes.
    ///
    /// @since 3.17.0
    #[serde(rename = "source.fixAll")]
    SourceFixAll,

    #[serde(untagged)]
    Unknown(String),
}

/// The reason why code actions were requested.
///
/// @since 3.17.0
#[derive(Debug, serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
pub enum CodeActionTriggerKind {
    /// Code actions were explicitly requested by the user or by an extension.
    Invoked = 1,
    /// Code actions were requested automatically.
    ///
    /// This typically happens when current selection in a file changes, but can
    /// also be triggered when file content changes.
    Automatic = 2,
}
/// Contains additional diagnostic information about the context in which
/// a code action is run.
#[derive(Debug, serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct CodeActionContext {
    /// Requested kind of actions to return.
    ///
    /// Actions not of this kind are filtered out by the client before being
    /// shown. So servers can omit computing them.
    only: Option<Vec<CodeActionKind>>,
    /// An array of diagnostics known on the client side overlapping the range
    /// provided to the `textDocument/codeAction` request. They are provided so
    /// that the server knows which errors are currently presented to the user
    /// for the given range. There is no guarantee that these accurately reflect
    /// the error state of the resource. The primary parameter
    /// to compute code actions is the provided range.
    diagnostics: Vec<LSPDiagnostic>,
    /// The reason why code actions were requested.
    ///
    /// @since 3.17.0
    trigger_kind: Option<CodeActionTriggerKind>,
}

/// Params for the CodeActionRequest
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CodeActionParams {
    /// The document in which the command was invoked.
    pub text_document: TextDocumentIdentifier,
    /// The range for which the command was invoked.
    pub range: Range,
    /// Context carrying additional information.
    pub context: CodeActionContext,
}

#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
pub struct Disabled {
    /// Human readable description of why the code action is currently
    /// disabled.
    ///
    /// This is displayed in the code actions UI.
    reason: String,
}

/// A textual edit applicable to a text document.
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct TextEdit {
    /// The range of the text document to be manipulated. To insert
    /// text into a document create a range where start === end.
    range: Range,
    /// The string to be inserted. For delete operations use an
    /// empty string.
    new_text: String,
    /// The actual annotation identifier.
    annotation_id: Option<String>,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct WorkspaceEdit {
    /// Holds changes to existing resources.
    #[serde(skip_serializing_if = "Option::is_none")]
    changes: Option<std::collections::HashMap<String, Vec<TextEdit>>>,

    /// Depending on the client capability
    /// `workspace.workspaceEdit.resourceOperations` document changes are either
    /// an array of `TextDocumentEdit`s to express changes to n different text
    /// documents where each text document edit addresses a specific version of
    /// a text document. Or it can contain above `TextDocumentEdit`s mixed with
    /// create, rename and delete file / folder operations.
    ///
    /// Whether a client supports versioned document edits is expressed via
    /// `workspace.workspaceEdit.documentChanges` client capability.
    ///
    /// If a client neither supports `documentChanges` nor
    /// `workspace.workspaceEdit.resourceOperations` then only plain `TextEdit`s
    /// using the `changes` property are supported.
    #[serde(skip_serializing_if = "Option::is_none")]
    document_changes: Option<Vec<serde_json::Value>>,
    /// A map of change annotations that can be referenced in
    /// `AnnotatedTextEdit`s or create, rename and delete file / folder
    /// operations.
    ///
    /// Whether clients honor this property depends on the client capability
    /// `workspace.changeAnnotationSupport`.
    ///
    /// @since 3.16.0
    #[serde(skip_serializing_if = "Option::is_none")]
    change_annotations: Option<HashMap<String, serde_json::Value>>,
}

impl_fromstr_serde_json!(WorkspaceEdit);

/// Formatting options for LSP document formatting
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct FormattingOptions {
    /// Size of a tab in spaces
    pub tab_size: u32,
    /// Prefer spaces over tabs
    pub insert_spaces: bool,
    /// Trim trailing whitespace on a line (since LSP 3.15.0)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trim_trailing_whitespace: Option<bool>,
    /// Insert a newline character at the end of the file if one does not exist (since LSP 3.15.0)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub insert_final_newline: Option<bool>,
    /// Trim all newlines after the final newline at the end of the file (since LSP 3.15.0)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trim_final_newlines: Option<bool>,
    /// For further properties.
    #[serde(flatten)]
    pub extras: HashMap<String, serde_json::Value>,
}

impl_fromstr_serde_json!(FormattingOptions);

#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
pub struct Command {
    /// Title of the command, like `save`.
    title: String,
    /// The identifier of the actual command handler.
    command: String,
    /// Arguments that the command handler should be
    /// invoked with.
    arguments: Vec<serde_json::Value>,
}

/// A code action represents a change that can be performed in code, e.g. to fix
/// a problem or to refactor code.
///
/// A CodeAction must set either `edit` and/or a `command`. If both are supplied,
/// the `edit` is applied first, then the `command` is executed.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct CodeAction {
    /// A short, human-readable, title for this code action.
    title: String,

    /// The kind of the code action.
    ///
    /// Used to filter code actions.
    kind: Option<CodeActionKind>,

    /// The diagnostics that this code action resolves.
    diagnostics: Option<Vec<LSPDiagnostic>>,
    /// Marks this as a preferred action. Preferred actions are used by the
    /// `auto fix` command and can be targeted by keybindings.
    ///
    /// A quick fix should be marked preferred if it properly addresses the
    /// underlying error. A refactoring should be marked preferred if it is the
    /// most reasonable choice of actions to take.
    ///
    /// @since 3.15.0
    is_preferred: Option<bool>,
    /// Marks that the code action cannot currently be applied.
    ///
    /// Clients should follow the following guidelines regarding disabled code
    /// actions:
    ///
    /// - Disabled code actions are not shown in automatic lightbulbs code
    ///   action menus.
    ///
    /// - Disabled actions are shown as faded out in the code action menu when
    ///   the user request a more specific type of code action, such as
    ///   refactorings.
    ///
    /// - If the user has a keybinding that auto applies a code action and only
    ///   a disabled code actions are returned, the client should show the user
    ///   an error message with `reason` in the editor.
    ///
    /// @since 3.16.0
    disabled: Option<Disabled>,

    /// The workspace edit this code action performs.
    edit: Option<WorkspaceEdit>,

    /// A command this code action executes. If a code action
    /// provides an edit and a command, first the edit is
    /// executed and then the command.
    command: Option<Command>,

    /// A data entry field that is preserved on a code action between
    /// a `textDocument/codeAction` and a `codeAction/resolve` request.
    ///
    /// @since 3.16.0
    data: Option<serde_json::Value>,
}

impl CodeAction {
    /// Get the title of the code action
    pub fn title(&self) -> &str {
        &self.title
    }

    /// Get the workspace edit if available
    pub fn edit(&self) -> Option<&WorkspaceEdit> {
        self.edit.as_ref()
    }

    /// Check if this code action has a workspace edit
    pub fn has_edit(&self) -> bool {
        self.edit.is_some()
    }
}

impl_fromstr_serde_json!(CodeAction);

#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TextDocumentPositionParams {
    pub text_document: TextDocumentIdentifier,
    pub position: Position,
}

#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ReferenceParams {
    pub text_document: TextDocumentIdentifier,
    pub position: Position,
    pub context: ReferenceContext,
}

#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ReferenceContext {
    /// Include the declaration of the current symbol.
    pub include_declaration: bool,
}

#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct HoverResult {
    /// The hover's content
    pub contents: HoverContents,
    /// An optional range is a range inside a text document
    /// that is used to visualize a hover, e.g. by changing the background color.
    pub range: Option<Range>,
}

#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(untagged)]
pub enum HoverContents {
    String(MarkedString),
    Strings(Vec<MarkedString>),
    Content(MarkupContent),
}

/// MarkedString can be used to render human readable text. It is either a
/// markdown string or a code-block that provides a language and a code snippet.
/// The language identifier is semantically equal to the optional language
/// identifier in fenced code blocks in GitHub issues.
///
/// The pair of a language and a value is an equivalent to markdown:
/// ```${language}
/// ${value}
/// ```
///
/// Note that markdown strings will be sanitized - that means html will be
/// escaped.
///
/// @deprecated use MarkupContent instead.
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub enum MarkedString {
    String(String),
    Markup { lang: String, value: String },
}

/// A `MarkupContent` literal represents a string value which content is
/// interpreted base on its kind flag. Currently the protocol supports
/// `plaintext` and `markdown` as markup kinds.
///
/// If the kind is `markdown` then the value can contain fenced code blocks like
/// in GitHub issues.
///
/// *Please Note* that clients might sanitize the return markdown. A client could
/// decide to remove HTML from the markdown to avoid script execution.
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct MarkupContent {
    /// The type of the Markup
    pub kind: MarkupKind,
    /// The content itself
    pub value: String,
}

/// Describes the content type that a client supports in various
/// result literals like `Hover`, `ParameterInfo` or `CompletionItem`.
///
/// Please note that `MarkupKinds` must not start with a `$`. This kinds
/// are reserved for internal usage.
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub enum MarkupKind {
    /// Plain text is supported as a content format
    #[serde(rename = "plaintext")]
    PlainText,
    /// Markdown is supported as a content format
    #[serde(rename = "markdown")]
    Markdown,
}

#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct CodeActionResult {
    #[serde(default)]
    pub result: Vec<CodeAction>,
}

#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct NavigateResult {
    pub success: bool,
    pub buffer_name: String,
    pub line: String,
}

/// A symbol kind.
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
#[serde(into = "u8", from = "u8")]
pub enum SymbolKind {
    File = 1,
    Module = 2,
    Namespace = 3,
    Package = 4,
    Class = 5,
    Method = 6,
    Property = 7,
    Field = 8,
    Constructor = 9,
    Enum = 10,
    Interface = 11,
    Function = 12,
    Variable = 13,
    Constant = 14,
    String = 15,
    Number = 16,
    Boolean = 17,
    Array = 18,
    Object = 19,
    Key = 20,
    Null = 21,
    EnumMember = 22,
    Struct = 23,
    Event = 24,
    Operator = 25,
    TypeParameter = 26,
}

impl From<SymbolKind> for u8 {
    fn from(kind: SymbolKind) -> u8 {
        kind as u8
    }
}

impl From<u8> for SymbolKind {
    fn from(value: u8) -> SymbolKind {
        match value {
            1 => SymbolKind::File,
            2 => SymbolKind::Module,
            3 => SymbolKind::Namespace,
            4 => SymbolKind::Package,
            5 => SymbolKind::Class,
            6 => SymbolKind::Method,
            7 => SymbolKind::Property,
            8 => SymbolKind::Field,
            9 => SymbolKind::Constructor,
            10 => SymbolKind::Enum,
            11 => SymbolKind::Interface,
            12 => SymbolKind::Function,
            13 => SymbolKind::Variable,
            14 => SymbolKind::Constant,
            15 => SymbolKind::String,
            16 => SymbolKind::Number,
            17 => SymbolKind::Boolean,
            18 => SymbolKind::Array,
            19 => SymbolKind::Object,
            20 => SymbolKind::Key,
            21 => SymbolKind::Null,
            22 => SymbolKind::EnumMember,
            23 => SymbolKind::Struct,
            24 => SymbolKind::Event,
            25 => SymbolKind::Operator,
            26 => SymbolKind::TypeParameter,
            _ => SymbolKind::Variable, // Default fallback
        }
    }
}

/// Symbol tags are extra annotations that tweak the rendering of a symbol.
///
/// @since 3.16
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
#[serde(into = "u8", from = "u8")]
pub enum SymbolTag {
    /// Render a symbol as obsolete, usually using a strike-out.
    Deprecated = 1,
}

impl From<SymbolTag> for u8 {
    fn from(tag: SymbolTag) -> u8 {
        tag as u8
    }
}

impl From<u8> for SymbolTag {
    fn from(value: u8) -> SymbolTag {
        match value {
            1 => SymbolTag::Deprecated,
            _ => SymbolTag::Deprecated, // Default fallback
        }
    }
}

/// Represents a location inside a resource, such as a line inside a text file.
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct Location {
    pub uri: String,
    pub range: Range,
}

/// Represents a link between a source and a target location.
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LocationLink {
    /// Span of the origin of this link.
    /// Used as the underlined span for mouse interaction. Defaults to the word
    /// range at the definition position.
    pub origin_selection_range: Option<Range>,
    /// The target resource identifier of this link.
    pub target_uri: String,
    /// The full target range of this link. If the target for example is a symbol
    /// then target range is the range enclosing this symbol not including
    /// leading/trailing whitespace but everything else like comments. This
    /// information is typically used for highlighting the range in the editor.
    pub target_range: Range,
    /// The range that should be selected and revealed when this link is being
    /// followed, e.g the name of a function. Must be contained by the
    /// `target_range`. See also `DocumentSymbol#range`
    pub target_selection_range: Range,
}

/// The result of a textDocument/definition request.
/// Can be a single Location, a list of Locations, or a list of LocationLinks.
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(untagged)]
pub enum LocateResult {
    Single(Location),
    Locations(Vec<Location>),
    LocationLinks(Vec<LocationLink>),
}

/// Represents information about programming constructs like variables, classes, interfaces etc.
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SymbolInformation {
    /// The name of this symbol.
    pub name: String,
    /// The kind of this symbol.
    pub kind: SymbolKind,
    /// Tags for this symbol.
    ///
    /// @since 3.16.0
    pub tags: Option<Vec<SymbolTag>>,
    /// Indicates if this symbol is deprecated.
    ///
    /// @deprecated Use tags instead
    pub deprecated: Option<bool>,
    /// The location of this symbol. The location's range is used by a tool
    /// to reveal the location in the editor. If the symbol is selected in the
    /// tool the range's start information is used to position the cursor. So
    /// the range usually spans more than the actual symbol's name and does
    /// normally include things like visibility modifiers.
    ///
    /// The range doesn't have to denote a node range in the sense of an abstract
    /// syntax tree. It can therefore not be used to re-construct a hierarchy of
    /// the symbols.
    pub location: Location,
    /// The name of the symbol containing this symbol. This information is for
    /// user interface purposes (e.g. to render a qualifier in the user interface
    /// if necessary). It can't be used to re-infer a hierarchy for the document
    /// symbols.
    pub container_name: Option<String>,
}

/// Represents programming constructs like variables, classes, interfaces etc. that appear in a document.
/// Document symbols can be hierarchical and they have two ranges: one that encloses its definition and
/// one that points to its most interesting range, e.g. the range of an identifier.
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DocumentSymbol {
    /// The name of this symbol. Will be displayed in the user interface and therefore must not be
    /// an empty string or a string only consisting of white spaces.
    pub name: String,
    /// More detail for this symbol, e.g the signature of a function.
    pub detail: Option<String>,
    /// The kind of this symbol.
    pub kind: SymbolKind,
    /// Tags for this symbol.
    ///
    /// @since 3.16.0
    pub tags: Option<Vec<SymbolTag>>,
    /// Indicates if this symbol is deprecated.
    ///
    /// @deprecated Use tags instead
    pub deprecated: Option<bool>,
    /// The range enclosing this symbol not including leading/trailing whitespace but everything else
    /// like comments. This information is typically used to determine if the clients cursor is
    /// inside the symbol to reveal in the symbol in the UI.
    pub range: Range,
    /// The range that should be selected and revealed when this symbol is being picked, e.g the name of a function.
    /// Must be contained by the `range`.
    pub selection_range: Range,
    /// Children of this symbol, e.g. properties of a class.
    pub children: Option<Vec<DocumentSymbol>>,
}

/// Parameters for document symbol request
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DocumentSymbolParams {
    /// The text document.
    pub text_document: TextDocumentIdentifier,
}

/// Parameters for workspace symbol request
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct WorkspaceSymbolParams {
    /// A query string to filter symbols by. Clients may send an empty
    /// string here to request all symbols.
    pub query: String,
}

/// Represents a symbol in the call hierarchy.
///
/// @since 3.16.0
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct CallHierarchyItem {
    /// The name of this symbol.
    pub name: String,
    /// The kind of this symbol.
    pub kind: SymbolKind,
    /// Tags for this symbol.
    ///
    /// @since 3.16.0
    pub tags: Option<Vec<SymbolTag>>,
    /// More detail for this symbol, e.g the signature of a function.
    pub detail: Option<String>,
    /// The resource identifier of this symbol.
    pub uri: String,
    /// The range enclosing this symbol not including leading/trailing whitespace
    /// but everything else like comments. This information is typically used to
    /// determine if the clients cursor is inside the symbol to reveal in the
    /// symbol in the UI.
    pub range: Range,
    /// The range that should be selected and revealed when this symbol is being
    /// picked, e.g the name of a function. Must be contained by the `range`.
    pub selection_range: Range,
    /// A data entry field that is preserved on a call hierarchy item between
    /// a call hierarchy prepare and incoming calls or outgoing calls requests.
    pub data: Option<serde_json::Value>,
}

impl_fromstr_serde_json!(CallHierarchyItem);

/// Parameters for the call hierarchy prepare request.
///
/// @since 3.16.0
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CallHierarchyPrepareParams {
    /// The text document.
    pub text_document: TextDocumentIdentifier,
    /// The position inside the text document.
    pub position: Position,
}

/// Represents an incoming call, e.g. a caller of a method or constructor.
///
/// @since 3.16.0
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CallHierarchyIncomingCall {
    /// The item that makes the call.
    pub from: CallHierarchyItem,
    /// The ranges at which the calls appear. This is relative to the caller
    /// denoted by `from`.
    pub from_ranges: Vec<Range>,
}

/// Parameters for the incoming calls request.
///
/// @since 3.16.0
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CallHierarchyIncomingCallsParams {
    pub item: CallHierarchyItem,
}

/// Represents an outgoing call, e.g. calling a getter from a method or
/// a method from a constructor etc.
///
/// @since 3.16.0
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CallHierarchyOutgoingCall {
    /// The item that is called.
    pub to: CallHierarchyItem,
    /// The range at which this item is called. This is the range relative to
    /// the caller, e.g the item passed to `callHierarchy/outgoingCalls` request.
    pub from_ranges: Vec<Range>,
}

/// Parameters for the outgoing calls request.
///
/// @since 3.16.0
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CallHierarchyOutgoingCallsParams {
    pub item: CallHierarchyItem,
}

/// Represents a type hierarchy item.
///
/// @since 3.17.0
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct TypeHierarchyItem {
    /// The name of this symbol.
    pub name: String,
    /// The kind of this symbol.
    pub kind: SymbolKind,
    /// Tags for this symbol.
    ///
    /// @since 3.16.0
    pub tags: Option<Vec<SymbolTag>>,
    /// More detail for this symbol, e.g the signature of a function.
    pub detail: Option<String>,
    /// The resource identifier of this symbol.
    pub uri: String,
    /// The range enclosing this symbol not including leading/trailing whitespace
    /// but everything else like comments. This information is typically used to
    /// determine if the clients cursor is inside the symbol to reveal in the
    /// symbol in the UI.
    pub range: Range,
    /// The range that should be selected and revealed when this symbol is being
    /// picked, e.g the name of a function. Must be contained by the `range`.
    pub selection_range: Range,
    /// A data entry field that is preserved between a type hierarchy prepare and a
    /// supertypes or subtypes request. It could also be used to identify the
    /// type hierarchy in the server, helping improve the performance on
    /// resolving supertypes and subtypes.
    pub data: Option<serde_json::Value>,
}

impl_fromstr_serde_json!(TypeHierarchyItem);

/// Parameters for the type hierarchy prepare request.
///
/// @since 3.17.0
#[derive(Debug, serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct TypeHierarchyPrepareParams {
    /// The text document.
    pub text_document: TextDocumentIdentifier,
    /// The position inside the text document.
    pub position: Position,
}

/// Parameters for the supertypes request.
///
/// @since 3.17.0
#[derive(Debug, serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct TypeHierarchySupertypesParams {
    pub item: TypeHierarchyItem,
}

/// Parameters for the subtypes request.
///
/// @since 3.17.0
#[derive(Debug, serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct TypeHierarchySubtypesParams {
    pub item: TypeHierarchyItem,
}

/// Result type for document symbols request
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(untagged)]
pub enum DocumentSymbolResult {
    Symbols(Vec<DocumentSymbol>),
    Information(Vec<SymbolInformation>),
}

/// Prepare rename response variants
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(untagged)]
pub enum PrepareRenameResult {
    Range(Range),
    RangeWithPlaceholder {
        range: Range,
        placeholder: String,
    },
    DefaultBehavior {
        #[serde(rename = "defaultBehavior")]
        default_behavior: bool,
    },
}

/// Rename request parameters for LSP
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RenameRequestParams {
    pub text_document: TextDocumentIdentifier,
    pub position: Position,
    pub new_name: String,
}

/// Read document parameters
#[derive(Debug, serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct ReadDocumentParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub buffer_id: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file_path: Option<String>,
    pub start_line: i64,
    pub end_line: i64,
}

impl ReadDocumentParams {
    fn buffer_id(id: u64, start: i64, end: i64) -> Self {
        Self {
            buffer_id: Some(id),
            file_path: None,
            start_line: start,
            end_line: end,
        }
    }

    fn path<P: AsRef<Path>>(path: P, start: i64, end: i64) -> Self {
        Self {
            buffer_id: None,
            file_path: Some(path.as_ref().to_string_lossy().to_string()),
            start_line: start,
            end_line: end,
        }
    }
}

/// Configuration for Neovim client operations
#[derive(Debug, Clone)]
pub struct NeovimClientConfig {
    /// Timeout in milliseconds for LSP operations (default: 3000ms)
    pub lsp_timeout_ms: u64,
}

impl Default for NeovimClientConfig {
    fn default() -> Self {
        Self {
            lsp_timeout_ms: 3000,
        }
    }
}

pub struct NeovimClient<T>
where
    T: AsyncWrite + Send + 'static,
{
    connection: Option<NeovimConnection<T>>,
    notification_tracker: Option<NotificationTracker>,
    config: NeovimClientConfig,
}

impl<T> Default for NeovimClient<T>
where
    T: AsyncWrite + Send + 'static,
{
    fn default() -> Self {
        Self {
            connection: None,
            notification_tracker: None,
            config: NeovimClientConfig::default(),
        }
    }
}

#[cfg(unix)]
type Connection = tokio::net::UnixStream;
#[cfg(windows)]
type Connection = tokio::net::windows::named_pipe::NamedPipeClient;

/// Creates a TextDocumentIdentifier from a file path
/// This utility function works independently of Neovim buffers
#[allow(dead_code)]
pub fn make_text_document_identifier_from_path<P: AsRef<Path>>(
    file_path: P,
) -> Result<TextDocumentIdentifier, NeovimError> {
    let path = file_path.as_ref();

    // Convert to absolute path and canonicalize
    let absolute_path = path.canonicalize().map_err(|e| {
        NeovimError::Api(format!("Failed to resolve path {}: {}", path.display(), e))
    })?;

    // Convert to file:// URI
    let uri = format!("file://{}", absolute_path.display());

    Ok(TextDocumentIdentifier {
        uri,
        version: None, // No version for path-based identifiers
    })
}

/// Nvim execute_lua custom result type
#[derive(Debug, serde::Deserialize)]
pub enum NvimExecuteLuaResult<T> {
    #[serde(rename = "err_msg")]
    Error(String),
    #[serde(rename = "result")]
    Ok(T),
    #[serde(rename = "err")]
    LspError { message: String, code: i32 },
}

impl<T> From<NvimExecuteLuaResult<T>> for Result<T, NeovimError> {
    fn from(val: NvimExecuteLuaResult<T>) -> Self {
        use NvimExecuteLuaResult::*;
        match val {
            Ok(result) => Result::Ok(result),
            Error(msg) => Err(NeovimError::Api(msg)),
            LspError { message, code } => Err(NeovimError::Lsp { code, message }),
        }
    }
}

impl NeovimClient<Connection> {
    #[instrument(skip(self))]
    pub async fn connect_path(&mut self, path: &str) -> Result<(), NeovimError> {
        if self.connection.is_some() {
            return Err(NeovimError::Connection(format!(
                "Already connected to {}. Disconnect first.",
                self.connection.as_ref().unwrap().target()
            )));
        }

        debug!("Attempting to connect to Neovim at {}", path);
        let handler = NeovimHandler::new();
        let notification_tracker = handler.notification_tracker();
        match create::new_path(path, handler).await {
            Ok((nvim, io_handler)) => {
                let connection = NeovimConnection::new(
                    nvim,
                    tokio::spawn(async move {
                        let rv = io_handler.await;
                        info!("io_handler completed with result: {:?}", rv);
                        rv
                    }),
                    path.to_string(),
                );
                self.connection = Some(connection);
                self.notification_tracker = Some(notification_tracker);
                debug!("Successfully connected to Neovim at {}", path);
                Ok(())
            }
            Err(e) => {
                debug!("Failed to connect to Neovim at {}: {}", path, e);
                Err(NeovimError::Connection(format!("Connection failed: {e}")))
            }
        }
    }
}

impl NeovimClient<TcpStream> {
    #[instrument(skip(self))]
    pub async fn connect_tcp(&mut self, address: &str) -> Result<(), NeovimError> {
        if self.connection.is_some() {
            return Err(NeovimError::Connection(format!(
                "Already connected to {}. Disconnect first.",
                self.connection.as_ref().unwrap().target()
            )));
        }

        debug!("Attempting to connect to Neovim at {}", address);
        let handler = NeovimHandler::new();
        let notification_tracker = handler.notification_tracker();
        match create::new_tcp(address, handler).await {
            Ok((nvim, io_handler)) => {
                let connection = NeovimConnection::new(
                    nvim,
                    tokio::spawn(async move {
                        let rv = io_handler.await;
                        info!("io_handler completed with result: {:?}", rv);
                        rv
                    }),
                    address.to_string(),
                );
                self.connection = Some(connection);
                self.notification_tracker = Some(notification_tracker);
                debug!("Successfully connected to Neovim at {}", address);
                Ok(())
            }
            Err(e) => {
                debug!("Failed to connect to Neovim at {}: {}", address, e);
                Err(NeovimError::Connection(format!("Connection failed: {e}")))
            }
        }
    }
}

impl<T> NeovimClient<T>
where
    T: AsyncWrite + Send + 'static,
{
    /// Configure the Neovim client with custom settings
    #[allow(dead_code)]
    pub fn with_config(mut self, config: NeovimClientConfig) -> Self {
        self.config = config;
        self
    }

    #[instrument(skip(self))]
    async fn get_diagnostics(
        &self,
        buffer_id: Option<u64>,
    ) -> Result<Vec<Diagnostic>, NeovimError> {
        let conn = self.connection.as_ref().ok_or_else(|| {
            NeovimError::Connection("Not connected to any Neovim instance".to_string())
        })?;

        let args = if let Some(id) = buffer_id {
            vec![Value::from(id)]
        } else {
            vec![]
        };

        match conn
            .nvim
            .execute_lua("return vim.json.encode(vim.diagnostic.get(...))", args)
            .await
        {
            Ok(diagnostics) => {
                let diagnostics: Vec<Diagnostic> =
                    match serde_json::from_str(diagnostics.as_str().unwrap()) {
                        Ok(d) => d,
                        Err(e) => {
                            debug!("Failed to parse diagnostics: {}", e);
                            return Err(NeovimError::Api(format!(
                                "Failed to parse diagnostics: {e}"
                            )));
                        }
                    };
                debug!("Found {} diagnostics", diagnostics.len());
                Ok(diagnostics)
            }
            Err(e) => {
                debug!("Failed to get diagnostics: {}", e);
                Err(NeovimError::Api(format!("Failed to get diagnostics: {e}")))
            }
        }
    }

    #[instrument(skip(self))]
    async fn lsp_make_text_document_params(
        &self,
        buffer_id: u64,
    ) -> Result<TextDocumentIdentifier, NeovimError> {
        let conn = self.connection.as_ref().ok_or_else(|| {
            NeovimError::Connection("Not connected to any Neovim instance".to_string())
        })?;

        match conn
            .nvim
            .execute_lua(
                include_str!("lua/lsp_make_text_document_params.lua"),
                vec![Value::from(buffer_id)],
            )
            .await
        {
            Ok(raw) => {
                let doc = serde_json::from_str::<TextDocumentIdentifier>(raw.as_str().unwrap())
                    .map_err(|e| {
                        NeovimError::Api(format!("Failed to parse text document params: {e}"))
                    })?;
                info!("Created text document params {doc:?} for buffer {buffer_id}");
                Ok(doc)
            }
            Err(e) => {
                debug!("Failed to make text document params: {}", e);
                Err(NeovimError::Api(format!(
                    "Failed to make text document params: {e}"
                )))
            }
        }
    }

    /// Get project root directory from Neovim
    #[instrument(skip(self))]
    async fn get_project_root(&self) -> Result<PathBuf, NeovimError> {
        let conn = self.connection.as_ref().ok_or_else(|| {
            NeovimError::Connection("Not connected to any Neovim instance".to_string())
        })?;

        match conn
            .nvim
            .execute_lua("return vim.fn.getcwd()", vec![])
            .await
        {
            Ok(value) => {
                let cwd = value.as_str().ok_or_else(|| {
                    NeovimError::Api("Invalid working directory format".to_string())
                })?;
                Ok(PathBuf::from(cwd))
            }
            Err(e) => Err(NeovimError::Api(format!(
                "Failed to get working directory: {e}"
            ))),
        }
    }

    /// Universal resolver for converting any DocumentIdentifier to TextDocumentIdentifier
    #[instrument(skip(self))]
    async fn resolve_text_document_identifier(
        &self,
        identifier: &DocumentIdentifier,
    ) -> Result<TextDocumentIdentifier, NeovimError> {
        match identifier {
            DocumentIdentifier::BufferId(buffer_id) => {
                // Use existing buffer-based approach
                self.lsp_make_text_document_params(*buffer_id).await
            }
            DocumentIdentifier::ProjectRelativePath(rel_path) => {
                // Get project root from Neovim
                let project_root = self.get_project_root().await?;
                let absolute_path = project_root.join(rel_path);
                make_text_document_identifier_from_path(absolute_path)
            }
            DocumentIdentifier::AbsolutePath(abs_path) => {
                // Use the existing path-based helper function
                make_text_document_identifier_from_path(abs_path)
            }
        }
    }
}

#[async_trait]
impl<T> NeovimClientTrait for NeovimClient<T>
where
    T: AsyncWrite + Send + 'static,
{
    fn target(&self) -> Option<String> {
        self.connection.as_ref().map(|c| c.target().to_string())
    }

    #[instrument(skip(self))]
    async fn disconnect(&mut self) -> Result<String, NeovimError> {
        debug!("Attempting to disconnect from Neovim");

        if let Some(connection) = self.connection.take() {
            let target = connection.target().to_string();
            connection.io_handler.abort();

            // Clear notification tracker to free memory
            if let Some(tracker) = self.notification_tracker.take() {
                tracker.clear_notifications().await;
            }

            debug!("Successfully disconnected from Neovim at {}", target);
            Ok(target)
        } else {
            Err(NeovimError::Connection(
                "Not connected to any Neovim instance".to_string(),
            ))
        }
    }

    #[instrument(skip(self))]
    async fn get_buffers(&self) -> Result<Vec<BufferInfo>, NeovimError> {
        debug!("Getting buffer information");

        let lua_code = include_str!("lua/lsp_get_buffers.lua");

        match self.execute_lua(lua_code).await {
            Ok(buffers) => {
                debug!("Get buffers retrieved successfully");
                let buffers: Vec<BufferInfo> = match serde_json::from_str(buffers.as_str().unwrap())
                {
                    Ok(d) => d,
                    Err(e) => {
                        debug!("Failed to parse buffers: {}", e);
                        return Err(NeovimError::Api(format!("Failed to parse buffers: {e}")));
                    }
                };
                debug!("Found {} buffers", buffers.len());
                Ok(buffers)
            }
            Err(e) => {
                debug!("Failed to get buffer info: {}", e);
                Err(NeovimError::Api(format!("Failed to get buffer info: {e}")))
            }
        }
    }

    #[instrument(skip(self))]
    async fn execute_lua(&self, code: &str) -> Result<Value, NeovimError> {
        debug!("Executing Lua code: {}", code);

        if code.trim().is_empty() {
            return Err(NeovimError::Api("Lua code cannot be empty".to_string()));
        }

        let conn = self.connection.as_ref().ok_or_else(|| {
            NeovimError::Connection("Not connected to any Neovim instance".to_string())
        })?;

        let lua_args = Vec::<Value>::new();
        match conn.nvim.exec_lua(code, lua_args).await {
            Ok(result) => {
                debug!("Lua execution successful, result: {:?}", result);
                Ok(result)
            }
            Err(e) => {
                debug!("Lua execution failed: {e}");
                Err(NeovimError::Api(format!("Lua execution failed: {e}")))
            }
        }
    }

    #[instrument(skip(self))]
    async fn setup_autocmd(&self) -> Result<(), NeovimError> {
        debug!("Setting up autocmd");

        let conn = self.connection.as_ref().ok_or_else(|| {
            NeovimError::Connection("Not connected to any Neovim instance".to_string())
        })?;

        match conn
            .nvim
            .exec_lua(include_str!("lua/setup_autocmd.lua"), vec![])
            .await
        {
            Ok(_) => {
                debug!("autocmd set up successfully");
                Ok(())
            }
            Err(e) => {
                debug!("Failed to set up autocmd: {}", e);
                Err(NeovimError::Api(format!("Failed to set up autocmd: {e}")))
            }
        }
    }

    #[instrument(skip(self))]
    async fn get_buffer_diagnostics(&self, buffer_id: u64) -> Result<Vec<Diagnostic>, NeovimError> {
        self.get_diagnostics(Some(buffer_id)).await
    }

    #[instrument(skip(self))]
    async fn get_workspace_diagnostics(&self) -> Result<Vec<Diagnostic>, NeovimError> {
        self.get_diagnostics(None).await
    }

    #[instrument(skip(self))]
    async fn lsp_get_clients(&self) -> Result<Vec<LspClient>, NeovimError> {
        debug!("Getting LSP clients");

        let conn = self.connection.as_ref().ok_or_else(|| {
            NeovimError::Connection("Not connected to any Neovim instance".to_string())
        })?;

        match conn
            .nvim
            .execute_lua(include_str!("lua/lsp_get_clients.lua"), vec![])
            .await
        {
            Ok(clients) => {
                debug!("LSP clients retrieved successfully");
                let clients: Vec<LspClient> = match serde_json::from_str(clients.as_str().unwrap())
                {
                    Ok(d) => d,
                    Err(e) => {
                        debug!("Failed to parse clients: {}", e);
                        return Err(NeovimError::Api(format!("Failed to parse clients: {e}")));
                    }
                };
                debug!("Found {} clients", clients.len());
                Ok(clients)
            }
            Err(e) => {
                debug!("Failed to get LSP clients: {}", e);
                Err(NeovimError::Api(format!("Failed to get LSP clients: {e}")))
            }
        }
    }

    #[instrument(skip(self))]
    async fn lsp_get_code_actions(
        &self,
        client_name: &str,
        document: DocumentIdentifier,
        range: Range,
    ) -> Result<Vec<CodeAction>, NeovimError> {
        let text_document = self.resolve_text_document_identifier(&document).await?;

        let diagnostics = match &document {
            DocumentIdentifier::BufferId(buffer_id) => self
                .get_buffer_diagnostics(*buffer_id)
                .await
                .map_err(|e| NeovimError::Api(format!("Failed to get diagnostics: {e}")))?,
            _ => {
                // For path-based identifiers, diagnostics might not be available
                Vec::new()
            }
        };

        let conn = self.connection.as_ref().ok_or_else(|| {
            NeovimError::Connection("Not connected to any Neovim instance".to_string())
        })?;

        // Get buffer ID for Lua execution (needed for some LSP operations)
        let buffer_id = match &document {
            DocumentIdentifier::BufferId(id) => *id,
            _ => 0, // Use buffer 0 as fallback for path-based operations
        };

        match conn
            .nvim
            .execute_lua(
                include_str!("lua/lsp_client_get_code_actions.lua"),
                vec![
                    Value::from(client_name), // client_name
                    Value::from(
                        serde_json::to_string(&CodeActionParams {
                            text_document,
                            range,
                            context: CodeActionContext {
                                diagnostics: diagnostics
                                    .into_iter()
                                    .filter_map(|d| d.user_data.map(|u| u.lsp))
                                    .collect(),
                                only: None,
                                trigger_kind: None,
                            },
                        })
                        .unwrap(),
                    ), // params
                    Value::from(self.config.lsp_timeout_ms), // timeout_ms
                    Value::from(buffer_id),   // bufnr
                ],
            )
            .await
        {
            Ok(actions) => {
                let actions = serde_json::from_str::<CodeActionResult>(actions.as_str().unwrap())
                    .map_err(|e| {
                    NeovimError::Api(format!("Failed to parse code actions: {e}"))
                })?;
                debug!("Found {} code actions", actions.result.len());
                Ok(actions.result)
            }
            Err(e) => {
                debug!("Failed to get LSP code actions: {}", e);
                Err(NeovimError::Api(format!(
                    "Failed to get LSP code actions: {e}"
                )))
            }
        }
    }

    #[instrument(skip(self))]
    async fn lsp_hover(
        &self,
        client_name: &str,
        document: DocumentIdentifier,
        position: Position,
    ) -> Result<HoverResult, NeovimError> {
        let text_document = self.resolve_text_document_identifier(&document).await?;

        let conn = self.connection.as_ref().ok_or_else(|| {
            NeovimError::Connection("Not connected to any Neovim instance".to_string())
        })?;

        // Get buffer ID for Lua execution (needed for some LSP operations)
        let buffer_id = match &document {
            DocumentIdentifier::BufferId(id) => *id,
            _ => 0, // Use buffer 0 as fallback for path-based operations
        };

        match conn
            .nvim
            .execute_lua(
                include_str!("lua/lsp_hover.lua"),
                vec![
                    Value::from(client_name), // client_name
                    Value::from(
                        serde_json::to_string(&TextDocumentPositionParams {
                            text_document,
                            position,
                        })
                        .unwrap(),
                    ), // params
                    Value::from(self.config.lsp_timeout_ms), // timeout_ms
                    Value::from(buffer_id),   // bufnr
                ],
            )
            .await
        {
            Ok(result) => {
                match serde_json::from_str::<NvimExecuteLuaResult<HoverResult>>(
                    result.as_str().unwrap(),
                ) {
                    Ok(d) => d.into(),
                    Err(e) => {
                        debug!("Failed to parse hover result: {e}");
                        Err(NeovimError::Api(format!(
                            "Failed to parse hover result: {e}"
                        )))
                    }
                }
            }
            Err(e) => {
                debug!("Failed to get LSP hover: {}", e);
                Err(NeovimError::Api(format!("Failed to get LSP hover: {e}")))
            }
        }
    }

    #[instrument(skip(self))]
    async fn lsp_document_symbols(
        &self,
        client_name: &str,
        document: DocumentIdentifier,
    ) -> Result<Option<DocumentSymbolResult>, NeovimError> {
        let text_document = self.resolve_text_document_identifier(&document).await?;

        let conn = self.connection.as_ref().ok_or_else(|| {
            NeovimError::Connection("Not connected to any Neovim instance".to_string())
        })?;

        // Get buffer ID for Lua execution (needed for some LSP operations)
        let buffer_id = match &document {
            DocumentIdentifier::BufferId(id) => *id,
            _ => 0, // Use buffer 0 as fallback for path-based operations
        };

        match conn
            .nvim
            .execute_lua(
                include_str!("lua/lsp_document_symbols.lua"),
                vec![
                    Value::from(client_name), // client_name
                    Value::from(
                        serde_json::to_string(&DocumentSymbolParams { text_document }).unwrap(),
                    ), // params
                    Value::from(self.config.lsp_timeout_ms), // timeout_ms
                    Value::from(buffer_id),   // bufnr
                ],
            )
            .await
        {
            Ok(result) => {
                match serde_json::from_str::<NvimExecuteLuaResult<Option<DocumentSymbolResult>>>(
                    result.as_str().unwrap(),
                ) {
                    Ok(d) => d.into(),
                    Err(e) => {
                        debug!("Failed to parse document symbols result: {e}");
                        Err(NeovimError::Api(format!(
                            "Failed to parse document symbols result: {e}"
                        )))
                    }
                }
            }
            Err(e) => {
                debug!("Failed to get document symbols: {}", e);
                Err(NeovimError::Api(format!(
                    "Failed to get document symbols: {e}"
                )))
            }
        }
    }

    #[instrument(skip(self))]
    async fn lsp_workspace_symbols(
        &self,
        client_name: &str,
        query: &str,
    ) -> Result<Option<DocumentSymbolResult>, NeovimError> {
        let conn = self.connection.as_ref().ok_or_else(|| {
            NeovimError::Connection("Not connected to any Neovim instance".to_string())
        })?;

        match conn
            .nvim
            .execute_lua(
                include_str!("lua/lsp_workspace_symbols.lua"),
                vec![
                    Value::from(client_name), // client_name
                    Value::from(
                        serde_json::to_string(&WorkspaceSymbolParams {
                            query: query.to_string(),
                        })
                        .unwrap(),
                    ), // params
                    Value::from(self.config.lsp_timeout_ms), // timeout_ms
                ],
            )
            .await
        {
            Ok(result) => {
                match serde_json::from_str::<NvimExecuteLuaResult<Option<DocumentSymbolResult>>>(
                    result.as_str().unwrap(),
                ) {
                    Ok(d) => d.into(),
                    Err(e) => {
                        debug!("Failed to parse workspace symbols result: {e}");
                        Err(NeovimError::Api(format!(
                            "Failed to parse workspace symbols result: {e}"
                        )))
                    }
                }
            }
            Err(e) => {
                debug!("Failed to get workspace symbols: {}", e);
                Err(NeovimError::Api(format!(
                    "Failed to get workspace symbols: {e}"
                )))
            }
        }
    }

    #[instrument(skip(self))]
    async fn lsp_references(
        &self,
        client_name: &str,
        document: DocumentIdentifier,
        position: Position,
        include_declaration: bool,
    ) -> Result<Vec<Location>, NeovimError> {
        let text_document = self.resolve_text_document_identifier(&document).await?;

        let conn = self.connection.as_ref().ok_or_else(|| {
            NeovimError::Connection("Not connected to any Neovim instance".to_string())
        })?;

        // Get buffer ID for Lua execution (needed for some LSP operations)
        let buffer_id = match &document {
            DocumentIdentifier::BufferId(id) => *id,
            _ => 0, // Use buffer 0 as fallback for path-based operations
        };

        match conn
            .nvim
            .execute_lua(
                include_str!("lua/lsp_references.lua"),
                vec![
                    Value::from(client_name), // client_name
                    Value::from(
                        serde_json::to_string(&ReferenceParams {
                            text_document,
                            position,
                            context: ReferenceContext {
                                include_declaration,
                            },
                        })
                        .unwrap(),
                    ), // params
                    Value::from(self.config.lsp_timeout_ms), // timeout_ms
                    Value::from(buffer_id),   // bufnr
                ],
            )
            .await
        {
            Ok(result) => {
                match serde_json::from_str::<NvimExecuteLuaResult<Option<Vec<Location>>>>(
                    result.as_str().unwrap(),
                ) {
                    Ok(d) => {
                        let result: Result<Option<Vec<Location>>, NeovimError> = d.into();
                        result.map(|opt| opt.unwrap_or_default())
                    }
                    Err(e) => {
                        debug!("Failed to parse references result: {e}");
                        Err(NeovimError::Api(format!(
                            "Failed to parse references result: {e}"
                        )))
                    }
                }
            }
            Err(e) => {
                debug!("Failed to get LSP references: {}", e);
                Err(NeovimError::Api(format!(
                    "Failed to get LSP references: {e}"
                )))
            }
        }
    }

    #[instrument(skip(self))]
    async fn lsp_definition(
        &self,
        client_name: &str,
        document: DocumentIdentifier,
        position: Position,
    ) -> Result<Option<LocateResult>, NeovimError> {
        let text_document = self.resolve_text_document_identifier(&document).await?;

        let conn = self.connection.as_ref().ok_or_else(|| {
            NeovimError::Connection("Not connected to any Neovim instance".to_string())
        })?;

        match conn
            .nvim
            .execute_lua(
                include_str!("lua/lsp_definition.lua"),
                vec![
                    Value::from(client_name), // client_name
                    Value::from(
                        serde_json::to_string(&TextDocumentPositionParams {
                            text_document,
                            position,
                        })
                        .unwrap(),
                    ), // params
                    Value::from(self.config.lsp_timeout_ms), // timeout_ms
                ],
            )
            .await
        {
            Ok(result) => {
                match serde_json::from_str::<NvimExecuteLuaResult<Option<LocateResult>>>(
                    result.as_str().unwrap(),
                ) {
                    Ok(d) => d.into(),
                    Err(e) => {
                        debug!("Failed to parse definition result: {e}");
                        Err(NeovimError::Api(format!(
                            "Failed to parse definition result: {e}"
                        )))
                    }
                }
            }
            Err(e) => {
                debug!("Failed to get LSP definition: {}", e);
                Err(NeovimError::Api(format!(
                    "Failed to get LSP definition: {e}"
                )))
            }
        }
    }

    #[instrument(skip(self))]
    async fn lsp_type_definition(
        &self,
        client_name: &str,
        document: DocumentIdentifier,
        position: Position,
    ) -> Result<Option<LocateResult>, NeovimError> {
        let text_document = self.resolve_text_document_identifier(&document).await?;

        let conn = self.connection.as_ref().ok_or_else(|| {
            NeovimError::Connection("Not connected to any Neovim instance".to_string())
        })?;

        match conn
            .nvim
            .execute_lua(
                include_str!("lua/lsp_type_definition.lua"),
                vec![
                    Value::from(client_name), // client_name
                    Value::from(
                        serde_json::to_string(&TextDocumentPositionParams {
                            text_document,
                            position,
                        })
                        .unwrap(),
                    ), // params
                    Value::from(self.config.lsp_timeout_ms), // timeout_ms
                ],
            )
            .await
        {
            Ok(result) => {
                match serde_json::from_str::<NvimExecuteLuaResult<Option<LocateResult>>>(
                    result.as_str().unwrap(),
                ) {
                    Ok(d) => d.into(),
                    Err(e) => {
                        debug!("Failed to parse type definition result: {e}");
                        Err(NeovimError::Api(format!(
                            "Failed to parse type definition result: {e}"
                        )))
                    }
                }
            }
            Err(e) => {
                debug!("Failed to get LSP type definition: {}", e);
                Err(NeovimError::Api(format!(
                    "Failed to get LSP type definition: {e}"
                )))
            }
        }
    }

    #[instrument(skip(self))]
    async fn lsp_implementation(
        &self,
        client_name: &str,
        document: DocumentIdentifier,
        position: Position,
    ) -> Result<Option<LocateResult>, NeovimError> {
        let text_document = self.resolve_text_document_identifier(&document).await?;

        let conn = self.connection.as_ref().ok_or_else(|| {
            NeovimError::Connection("Not connected to any Neovim instance".to_string())
        })?;

        match conn
            .nvim
            .execute_lua(
                include_str!("lua/lsp_implementation.lua"),
                vec![
                    Value::from(client_name), // client_name
                    Value::from(
                        serde_json::to_string(&TextDocumentPositionParams {
                            text_document,
                            position,
                        })
                        .unwrap(),
                    ), // params
                    Value::from(self.config.lsp_timeout_ms), // timeout_ms
                ],
            )
            .await
        {
            Ok(result) => {
                match serde_json::from_str::<NvimExecuteLuaResult<Option<LocateResult>>>(
                    result.as_str().unwrap(),
                ) {
                    Ok(d) => d.into(),
                    Err(e) => {
                        debug!("Failed to parse implementation result: {e}");
                        Err(NeovimError::Api(format!(
                            "Failed to parse implementation result: {e}"
                        )))
                    }
                }
            }
            Err(e) => {
                debug!("Failed to get LSP implementation: {}", e);
                Err(NeovimError::Api(format!(
                    "Failed to get LSP implementation: {e}"
                )))
            }
        }
    }

    #[instrument(skip(self))]
    async fn lsp_declaration(
        &self,
        client_name: &str,
        document: DocumentIdentifier,
        position: Position,
    ) -> Result<Option<LocateResult>, NeovimError> {
        let text_document = self.resolve_text_document_identifier(&document).await?;

        let conn = self.connection.as_ref().ok_or_else(|| {
            NeovimError::Connection("Not connected to any Neovim instance".to_string())
        })?;

        match conn
            .nvim
            .execute_lua(
                include_str!("lua/lsp_declaration.lua"),
                vec![
                    Value::from(client_name), // client_name
                    Value::from(
                        serde_json::to_string(&TextDocumentPositionParams {
                            text_document,
                            position,
                        })
                        .unwrap(),
                    ), // params
                    Value::from(self.config.lsp_timeout_ms), // timeout_ms
                ],
            )
            .await
        {
            Ok(result) => {
                match serde_json::from_str::<NvimExecuteLuaResult<Option<LocateResult>>>(
                    result.as_str().unwrap(),
                ) {
                    Ok(d) => d.into(),
                    Err(e) => {
                        debug!("Failed to parse declaration result: {e}");
                        Err(NeovimError::Api(format!(
                            "Failed to parse declaration result: {e}"
                        )))
                    }
                }
            }
            Err(e) => {
                debug!("Failed to get LSP declaration: {}", e);
                Err(NeovimError::Api(format!(
                    "Failed to get LSP declaration: {e}"
                )))
            }
        }
    }

    #[instrument(skip(self))]
    async fn lsp_resolve_code_action(
        &self,
        client_name: &str,
        code_action: CodeAction,
    ) -> Result<CodeAction, NeovimError> {
        let conn = self.connection.as_ref().ok_or_else(|| {
            NeovimError::Connection("Not connected to any Neovim instance".to_string())
        })?;

        match conn
            .nvim
            .execute_lua(
                include_str!("lua/lsp_resolve_code_action.lua"),
                vec![
                    Value::from(client_name),
                    Value::from(serde_json::to_string(&code_action).map_err(|e| {
                        NeovimError::Api(format!("Failed to serialize code action: {e}"))
                    })?),
                    Value::from(5000), // timeout_ms
                    Value::from(0),    // bufnr (not needed for this request)
                ],
            )
            .await
        {
            Ok(result) => {
                match serde_json::from_str::<NvimExecuteLuaResult<CodeAction>>(
                    result.as_str().unwrap(),
                ) {
                    Ok(d) => d.into(),
                    Err(e) => {
                        debug!("Failed to parse resolve code action result: {e}");
                        Err(NeovimError::Api(format!(
                            "Failed to parse resolve code action result: {e}"
                        )))
                    }
                }
            }
            Err(e) => {
                debug!("Failed to resolve LSP code action: {}", e);
                Err(NeovimError::Api(format!(
                    "Failed to resolve LSP code action: {e}"
                )))
            }
        }
    }

    #[instrument(skip(self))]
    async fn lsp_apply_workspace_edit(
        &self,
        client_name: &str,
        workspace_edit: WorkspaceEdit,
    ) -> Result<(), NeovimError> {
        let conn = self.connection.as_ref().ok_or_else(|| {
            NeovimError::Connection("Not connected to any Neovim instance".to_string())
        })?;

        match conn
            .nvim
            .execute_lua(
                include_str!("lua/lsp_apply_workspace_edit.lua"),
                vec![
                    Value::from(client_name),
                    Value::from(serde_json::to_string(&workspace_edit).map_err(|e| {
                        NeovimError::Api(format!("Failed to serialize workspace edit: {e}"))
                    })?),
                ],
            )
            .await
        {
            Ok(result) => {
                match serde_json::from_str::<NvimExecuteLuaResult<()>>(result.as_str().unwrap()) {
                    Ok(rv) => rv.into(),
                    Err(e) => {
                        debug!("Failed to parse apply workspace edit result: {}", e);
                        Err(NeovimError::Api(format!(
                            "Failed to parse apply workspace edit result: {e}"
                        )))
                    }
                }
            }
            Err(e) => {
                debug!("Failed to apply LSP workspace edit: {}", e);
                Err(NeovimError::Api(format!(
                    "Failed to apply LSP workspace edit: {e}"
                )))
            }
        }
    }

    #[instrument(skip(self))]
    async fn lsp_prepare_rename(
        &self,
        client_name: &str,
        document: DocumentIdentifier,
        position: Position,
    ) -> Result<Option<PrepareRenameResult>, NeovimError> {
        let text_document = self.resolve_text_document_identifier(&document).await?;

        let conn = self.connection.as_ref().ok_or_else(|| {
            NeovimError::Connection("Not connected to any Neovim instance".to_string())
        })?;

        let buffer_id = match &document {
            DocumentIdentifier::BufferId(id) => *id,
            _ => 0,
        };

        match conn
            .nvim
            .execute_lua(
                include_str!("lua/lsp_prepare_rename.lua"),
                vec![
                    Value::from(client_name),
                    Value::from(
                        serde_json::to_string(&TextDocumentPositionParams {
                            text_document,
                            position,
                        })
                        .unwrap(),
                    ),
                    Value::from(self.config.lsp_timeout_ms),
                    Value::from(buffer_id),
                ],
            )
            .await
        {
            Ok(result) => {
                match serde_json::from_str::<NvimExecuteLuaResult<Option<PrepareRenameResult>>>(
                    result.as_str().unwrap(),
                ) {
                    Ok(d) => d.into(),
                    Err(e) => {
                        debug!("Failed to parse prepare rename result: {e}");
                        Err(NeovimError::Api(format!(
                            "Failed to parse prepare rename result: {e}"
                        )))
                    }
                }
            }
            Err(e) => {
                debug!("Failed to prepare rename: {}", e);
                Err(NeovimError::Api(format!("Failed to prepare rename: {e}")))
            }
        }
    }

    #[instrument(skip(self))]
    async fn lsp_rename(
        &self,
        client_name: &str,
        document: DocumentIdentifier,
        position: Position,
        new_name: &str,
    ) -> Result<Option<WorkspaceEdit>, NeovimError> {
        let text_document = self.resolve_text_document_identifier(&document).await?;

        let conn = self.connection.as_ref().ok_or_else(|| {
            NeovimError::Connection("Not connected to any Neovim instance".to_string())
        })?;

        let buffer_id = match &document {
            DocumentIdentifier::BufferId(id) => *id,
            _ => 0,
        };

        match conn
            .nvim
            .execute_lua(
                include_str!("lua/lsp_rename.lua"),
                vec![
                    Value::from(client_name),
                    Value::from(
                        serde_json::to_string(&RenameRequestParams {
                            text_document,
                            position,
                            new_name: new_name.to_string(),
                        })
                        .unwrap(),
                    ),
                    Value::from(5000), // Longer timeout for rename operations
                    Value::from(buffer_id),
                ],
            )
            .await
        {
            Ok(result) => {
                match serde_json::from_str::<NvimExecuteLuaResult<Option<WorkspaceEdit>>>(
                    result.as_str().unwrap(),
                ) {
                    Ok(d) => d.into(),
                    Err(e) => {
                        debug!("Failed to parse rename result: {e}");
                        Err(NeovimError::Api(format!(
                            "Failed to parse rename result: {e}"
                        )))
                    }
                }
            }
            Err(e) => {
                debug!("Failed to rename: {}", e);
                Err(NeovimError::Api(format!("Failed to rename: {e}")))
            }
        }
    }

    #[instrument(skip(self))]
    async fn lsp_formatting(
        &self,
        client_name: &str,
        document: DocumentIdentifier,
        options: FormattingOptions,
    ) -> Result<Vec<TextEdit>, NeovimError> {
        let text_document = self.resolve_text_document_identifier(&document).await?;

        let conn = self.connection.as_ref().ok_or_else(|| {
            NeovimError::Connection("Not connected to any Neovim instance".to_string())
        })?;

        #[derive(serde::Serialize)]
        #[serde(rename_all = "camelCase")]
        struct DocumentFormattingRequest {
            text_document: TextDocumentIdentifier,
            options: FormattingOptions,
        }

        match conn
            .nvim
            .execute_lua(
                include_str!("lua/lsp_formatting.lua"),
                vec![
                    Value::from(client_name), // client_name
                    Value::from(
                        serde_json::to_string(&DocumentFormattingRequest {
                            text_document,
                            options,
                        })
                        .unwrap(),
                    ),
                    Value::from(self.config.lsp_timeout_ms), // timeout_ms
                ],
            )
            .await
        {
            Ok(result) => {
                match serde_json::from_str::<NvimExecuteLuaResult<Option<Vec<TextEdit>>>>(
                    result.as_str().unwrap(),
                ) {
                    Ok(d) => {
                        let rv: Result<Option<Vec<TextEdit>>, NeovimError> = d.into();
                        rv.map(|x| x.unwrap_or_default())
                    }
                    Err(e) => {
                        debug!("Failed to parse formatting result: {e}");
                        Err(NeovimError::Api(format!(
                            "Failed to parse formatting result: {e}"
                        )))
                    }
                }
            }
            Err(e) => {
                debug!("Failed to format document: {}", e);
                Err(NeovimError::Api(format!("Failed to format document: {e}")))
            }
        }
    }

    #[instrument(skip(self))]
    async fn lsp_range_formatting(
        &self,
        client_name: &str,
        document: DocumentIdentifier,
        range: Range,
        options: FormattingOptions,
    ) -> Result<Vec<TextEdit>, NeovimError> {
        let text_document = self.resolve_text_document_identifier(&document).await?;

        let conn = self.connection.as_ref().ok_or_else(|| {
            NeovimError::Connection("Not connected to any Neovim instance".to_string())
        })?;

        #[derive(serde::Serialize)]
        #[serde(rename_all = "camelCase")]
        struct DocumentRangeFormattingRequest {
            text_document: TextDocumentIdentifier,
            range: Range,
            options: FormattingOptions,
        }

        match conn
            .nvim
            .execute_lua(
                include_str!("lua/lsp_range_formatting.lua"),
                vec![
                    Value::from(client_name), // client_name
                    Value::from(
                        serde_json::to_string(&DocumentRangeFormattingRequest {
                            text_document,
                            range,
                            options,
                        })
                        .unwrap(),
                    ),
                    Value::from(self.config.lsp_timeout_ms), // timeout_ms
                ],
            )
            .await
        {
            Ok(result) => {
                match serde_json::from_str::<NvimExecuteLuaResult<Option<Vec<TextEdit>>>>(
                    result.as_str().unwrap(),
                ) {
                    Ok(d) => {
                        let rv: Result<Option<Vec<TextEdit>>, NeovimError> = d.into();
                        rv.map(|x| x.unwrap_or_default())
                    }
                    Err(e) => {
                        debug!("Failed to parse range formatting result: {e}");
                        Err(NeovimError::Api(format!(
                            "Failed to parse range formatting result: {e}"
                        )))
                    }
                }
            }
            Err(e) => {
                debug!("Failed to format range: {}", e);
                Err(NeovimError::Api(format!("Failed to format range: {e}")))
            }
        }
    }

    #[instrument(skip(self))]
    async fn lsp_get_organize_imports_actions(
        &self,
        client_name: &str,
        document: DocumentIdentifier,
    ) -> Result<Vec<CodeAction>, NeovimError> {
        let text_document = self.resolve_text_document_identifier(&document).await?;

        // For document imports organization, we use an zero-value range
        let range = Range::default();

        // Request code actions with only source.organizeImports filter
        let context = CodeActionContext {
            diagnostics: Vec::new(), // No diagnostics needed for organize imports
            only: Some(vec![CodeActionKind::SourceOrganizeImports]),
            trigger_kind: None,
        };

        let conn = self.connection.as_ref().ok_or_else(|| {
            NeovimError::Connection("Not connected to any Neovim instance".to_string())
        })?;

        // Get buffer ID for Lua execution (needed for some LSP operations)
        let buffer_id = match &document {
            DocumentIdentifier::BufferId(id) => *id,
            _ => 0, // Use buffer 0 as fallback for path-based operations
        };

        match conn
            .nvim
            .execute_lua(
                include_str!("lua/lsp_client_get_code_actions.lua"),
                vec![
                    Value::from(client_name), // client_name
                    Value::from(
                        serde_json::to_string(&CodeActionParams {
                            text_document,
                            range,
                            context,
                        })
                        .unwrap(),
                    ), // params
                    Value::from(self.config.lsp_timeout_ms), // timeout_ms
                    Value::from(buffer_id),   // bufnr
                ],
            )
            .await
        {
            Ok(actions) => {
                let actions = serde_json::from_str::<CodeActionResult>(actions.as_str().unwrap())
                    .map_err(|e| {
                    NeovimError::Api(format!("Failed to parse code actions: {e}"))
                })?;
                debug!("Found {} organize imports actions", actions.result.len());
                Ok(actions.result)
            }
            Err(e) => {
                debug!("Failed to get organize imports actions: {}", e);
                Err(NeovimError::Api(format!(
                    "Failed to get organize imports actions: {e}"
                )))
            }
        }
    }

    #[instrument(skip(self))]
    async fn lsp_apply_text_edits(
        &self,
        client_name: &str,
        document: DocumentIdentifier,
        text_edits: Vec<TextEdit>,
    ) -> Result<(), NeovimError> {
        let text_document = self.resolve_text_document_identifier(&document).await?;
        let conn = self.connection.as_ref().ok_or_else(|| {
            NeovimError::Connection("Not connected to any Neovim instance".to_string())
        })?;

        match conn
            .nvim
            .execute_lua(
                include_str!("lua/lsp_apply_text_edits.lua"),
                vec![
                    Value::from(client_name),
                    Value::from(serde_json::to_string(&text_edits).map_err(|e| {
                        NeovimError::Api(format!("Failed to serialize text edits: {e}"))
                    })?),
                    Value::from(text_document.uri),
                ],
            )
            .await
        {
            Ok(result) => {
                match serde_json::from_str::<NvimExecuteLuaResult<()>>(result.as_str().unwrap()) {
                    Ok(rv) => rv.into(),
                    Err(e) => {
                        debug!("Failed to parse apply text edits result: {}", e);
                        Err(NeovimError::Api(format!(
                            "Failed to parse apply text edits result: {e}"
                        )))
                    }
                }
            }
            Err(e) => {
                debug!("Failed to apply text edits: {}", e);
                Err(NeovimError::Api(format!("Failed to apply text edits: {e}")))
            }
        }
    }

    #[instrument(skip(self))]
    async fn navigate(
        &self,
        document: DocumentIdentifier,
        position: Position,
    ) -> Result<NavigateResult, NeovimError> {
        let text_document = self.resolve_text_document_identifier(&document).await?;

        let conn = self.connection.as_ref().ok_or_else(|| {
            NeovimError::Connection("Not connected to any Neovim instance".to_string())
        })?;

        match conn
            .nvim
            .execute_lua(
                include_str!("lua/navigate.lua"),
                vec![Value::from(
                    serde_json::to_string(&TextDocumentPositionParams {
                        text_document,
                        position,
                    })
                    .unwrap(),
                )],
            )
            .await
        {
            Ok(result) => {
                match serde_json::from_str::<NvimExecuteLuaResult<NavigateResult>>(
                    result.as_str().unwrap(),
                ) {
                    Ok(rv) => rv.into(),
                    Err(e) => {
                        debug!("Failed to parse navigate result: {}", e);
                        Err(NeovimError::Api(format!(
                            "Failed to parse navigate result: {e}"
                        )))
                    }
                }
            }
            Err(e) => {
                debug!("Failed to navigate: {}", e);
                Err(NeovimError::Api(format!("Failed to navigate: {e}")))
            }
        }
    }

    #[instrument(skip(self))]
    async fn wait_for_notification(
        &self,
        notification_name: &str,
        timeout_ms: u64,
    ) -> Result<Notification, NeovimError> {
        debug!(
            "Waiting for notification: {} with timeout: {}ms",
            notification_name, timeout_ms
        );

        let tracker = self.notification_tracker.as_ref().ok_or_else(|| {
            NeovimError::Connection("Not connected to any Neovim instance".to_string())
        })?;

        tracker
            .wait_for_notification(notification_name, Duration::from_millis(timeout_ms))
            .await
    }

    #[instrument(skip(self))]
    async fn wait_for_lsp_ready(
        &self,
        client_name: Option<&str>,
        timeout_ms: u64,
    ) -> Result<(), NeovimError> {
        debug!(
            "Waiting for LSP client readiness: {:?} with timeout: {}ms",
            client_name, timeout_ms
        );

        // Wait for NVIM_MCP_LspAttach notification
        let notification = self
            .wait_for_notification("NVIM_MCP_LspAttach", timeout_ms)
            .await?;

        // If specific client name is requested, verify it matches
        if let Some(expected_client_name) = client_name {
            // Parse the notification args to check client name
            if let Some(attach_data) = notification.args.first() {
                // Extract client_name from the nvim_rs::Value
                if let Value::Map(map) = attach_data {
                    // Find the client_name key-value pair in the map
                    let client_name_key = Value::String("client_name".into());
                    let client_name_value = map
                        .iter()
                        .find(|(k, _)| k == &client_name_key)
                        .map(|(_, v)| v);

                    if let Some(Value::String(actual_client_name)) = client_name_value {
                        let actual_str = actual_client_name.as_str().unwrap_or("");
                        if actual_str != expected_client_name {
                            return Err(NeovimError::Api(format!(
                                "LSP client '{}' attached but expected '{}'",
                                actual_str, expected_client_name
                            )));
                        }
                    } else {
                        return Err(NeovimError::Api(
                            "LSP attach notification missing or invalid client_name".to_string(),
                        ));
                    }
                } else {
                    return Err(NeovimError::Api(
                        "LSP attach notification data is not a map".to_string(),
                    ));
                }
            } else {
                return Err(NeovimError::Api(
                    "LSP attach notification missing data".to_string(),
                ));
            }
        }

        debug!("LSP client readiness confirmed");
        Ok(())
    }

    #[instrument(skip(self))]
    async fn wait_for_diagnostics(
        &self,
        buffer_id: Option<u64>,
        timeout_ms: u64,
    ) -> Result<Vec<Diagnostic>, NeovimError> {
        debug!(
            "Waiting for diagnostics for buffer {:?} with timeout: {}ms",
            buffer_id, timeout_ms
        );

        // First try to get diagnostics immediately
        match self.get_diagnostics(buffer_id).await {
            Ok(diagnostics) if !diagnostics.is_empty() => {
                debug!("Found {} diagnostics immediately", diagnostics.len());
                return Ok(diagnostics);
            }
            Ok(_) => {
                // No diagnostics found, wait for diagnostic notification
                debug!("No diagnostics found, waiting for notification");
            }
            Err(e) => {
                debug!("Error getting diagnostics: {}, waiting for notification", e);
            }
        }

        // Wait for diagnostic notification
        let notification = self
            .wait_for_notification("NVIM_MCP_DiagnosticsChanged", timeout_ms)
            .await?;

        debug!("Received diagnostics notification: {:?}", notification);

        // After notification, try to get diagnostics again
        self.get_diagnostics(buffer_id).await
    }

    #[instrument(skip(self))]
    async fn lsp_call_hierarchy_prepare(
        &self,
        client_name: &str,
        document: DocumentIdentifier,
        position: Position,
    ) -> Result<Option<Vec<CallHierarchyItem>>, NeovimError> {
        let text_document = self.resolve_text_document_identifier(&document).await?;

        let conn = self.connection.as_ref().ok_or_else(|| {
            NeovimError::Connection("Not connected to any Neovim instance".to_string())
        })?;

        match conn
            .nvim
            .execute_lua(
                include_str!("lua/lsp_call_hierarchy_prepare.lua"),
                vec![
                    Value::from(client_name), // client_name
                    Value::from(
                        serde_json::to_string(&CallHierarchyPrepareParams {
                            text_document,
                            position,
                        })
                        .unwrap(),
                    ), // params
                    Value::from(self.config.lsp_timeout_ms), // timeout_ms
                ],
            )
            .await
        {
            Ok(result) => {
                match serde_json::from_str::<NvimExecuteLuaResult<Option<Vec<CallHierarchyItem>>>>(
                    result.as_str().unwrap(),
                ) {
                    Ok(rv) => rv.into(),
                    Err(e) => {
                        debug!("Failed to parse call hierarchy prepare result: {}", e);
                        Err(NeovimError::Api(format!(
                            "Failed to parse call hierarchy prepare result: {e}"
                        )))
                    }
                }
            }
            Err(e) => {
                debug!("Failed to prepare call hierarchy: {}", e);
                Err(NeovimError::Api(format!(
                    "Failed to prepare call hierarchy: {e}"
                )))
            }
        }
    }

    #[instrument(skip(self))]
    async fn lsp_call_hierarchy_incoming_calls(
        &self,
        client_name: &str,
        item: CallHierarchyItem,
    ) -> Result<Option<Vec<CallHierarchyIncomingCall>>, NeovimError> {
        let conn = self.connection.as_ref().ok_or_else(|| {
            NeovimError::Connection("Not connected to any Neovim instance".to_string())
        })?;

        match conn
            .nvim
            .execute_lua(
                include_str!("lua/lsp_call_hierarchy_incoming_calls.lua"),
                vec![
                    Value::from(client_name), // client_name
                    Value::from(
                        serde_json::to_string(&CallHierarchyIncomingCallsParams { item }).unwrap(),
                    ), // params
                    Value::from(self.config.lsp_timeout_ms), // timeout_ms
                ],
            )
            .await
        {
            Ok(result) => {
                match serde_json::from_str::<
                    NvimExecuteLuaResult<Option<Vec<CallHierarchyIncomingCall>>>,
                >(result.as_str().unwrap())
                {
                    Ok(rv) => rv.into(),
                    Err(e) => {
                        debug!(
                            "Failed to parse call hierarchy incoming calls result: {}",
                            e
                        );
                        Err(NeovimError::Api(format!(
                            "Failed to parse call hierarchy incoming calls result: {e}"
                        )))
                    }
                }
            }
            Err(e) => {
                debug!("Failed to get call hierarchy incoming calls: {}", e);
                Err(NeovimError::Api(format!(
                    "Failed to get call hierarchy incoming calls: {e}"
                )))
            }
        }
    }

    #[instrument(skip(self))]
    async fn lsp_call_hierarchy_outgoing_calls(
        &self,
        client_name: &str,
        item: CallHierarchyItem,
    ) -> Result<Option<Vec<CallHierarchyOutgoingCall>>, NeovimError> {
        let conn = self.connection.as_ref().ok_or_else(|| {
            NeovimError::Connection("Not connected to any Neovim instance".to_string())
        })?;

        match conn
            .nvim
            .execute_lua(
                include_str!("lua/lsp_call_hierarchy_outgoing_calls.lua"),
                vec![
                    Value::from(client_name), // client_name
                    Value::from(
                        serde_json::to_string(&CallHierarchyOutgoingCallsParams { item }).unwrap(),
                    ), // params
                    Value::from(self.config.lsp_timeout_ms), // timeout_ms
                ],
            )
            .await
        {
            Ok(result) => {
                match serde_json::from_str::<
                    NvimExecuteLuaResult<Option<Vec<CallHierarchyOutgoingCall>>>,
                >(result.as_str().unwrap())
                {
                    Ok(rv) => rv.into(),
                    Err(e) => {
                        debug!(
                            "Failed to parse call hierarchy outgoing calls result: {}",
                            e
                        );
                        Err(NeovimError::Api(format!(
                            "Failed to parse call hierarchy outgoing calls result: {e}"
                        )))
                    }
                }
            }
            Err(e) => {
                debug!("Failed to get call hierarchy outgoing calls: {}", e);
                Err(NeovimError::Api(format!(
                    "Failed to get call hierarchy outgoing calls: {e}"
                )))
            }
        }
    }

    #[instrument(skip(self))]
    async fn lsp_type_hierarchy_prepare(
        &self,
        client_name: &str,
        document: DocumentIdentifier,
        position: Position,
    ) -> Result<Option<Vec<TypeHierarchyItem>>, NeovimError> {
        let text_document = self.resolve_text_document_identifier(&document).await?;
        let conn = self.connection.as_ref().ok_or_else(|| {
            NeovimError::Connection("Not connected to any Neovim instance".to_string())
        })?;
        match conn
            .nvim
            .execute_lua(
                include_str!("lua/lsp_type_hierarchy_prepare.lua"),
                vec![
                    Value::from(client_name), // client_name
                    Value::from(
                        serde_json::to_string(&TypeHierarchyPrepareParams {
                            text_document,
                            position,
                        })
                        .unwrap(),
                    ), // params
                    Value::from(self.config.lsp_timeout_ms), // timeout_ms
                ],
            )
            .await
        {
            Ok(result) => {
                match serde_json::from_str::<NvimExecuteLuaResult<Option<Vec<TypeHierarchyItem>>>>(
                    result.as_str().unwrap(),
                ) {
                    Ok(rv) => rv.into(),
                    Err(e) => {
                        debug!("Failed to parse type hierarchy prepare result: {}", e);
                        Err(NeovimError::Api(format!(
                            "Failed to parse type hierarchy prepare result: {e}"
                        )))
                    }
                }
            }
            Err(e) => {
                debug!("Failed to prepare type hierarchy: {}", e);
                Err(NeovimError::Api(format!(
                    "Failed to prepare type hierarchy: {e}"
                )))
            }
        }
    }

    #[instrument(skip(self))]
    async fn lsp_type_hierarchy_supertypes(
        &self,
        client_name: &str,
        item: TypeHierarchyItem,
    ) -> Result<Option<Vec<TypeHierarchyItem>>, NeovimError> {
        let conn = self.connection.as_ref().ok_or_else(|| {
            NeovimError::Connection("Not connected to any Neovim instance".to_string())
        })?;
        match conn
            .nvim
            .execute_lua(
                include_str!("lua/lsp_type_hierarchy_supertypes.lua"),
                vec![
                    Value::from(client_name), // client_name
                    Value::from(
                        serde_json::to_string(&TypeHierarchySupertypesParams { item }).unwrap(),
                    ), // params
                    Value::from(self.config.lsp_timeout_ms), // timeout_ms
                ],
            )
            .await
        {
            Ok(result) => {
                match serde_json::from_str::<NvimExecuteLuaResult<Option<Vec<TypeHierarchyItem>>>>(
                    result.as_str().unwrap(),
                ) {
                    Ok(rv) => rv.into(),
                    Err(e) => {
                        debug!("Failed to parse type hierarchy supertypes result: {}", e);
                        Err(NeovimError::Api(format!(
                            "Failed to parse type hierarchy supertypes result: {e}"
                        )))
                    }
                }
            }
            Err(e) => {
                debug!("Failed to get type hierarchy supertypes: {}", e);
                Err(NeovimError::Api(format!(
                    "Failed to get type hierarchy supertypes: {e}"
                )))
            }
        }
    }

    #[instrument(skip(self))]
    async fn lsp_type_hierarchy_subtypes(
        &self,
        client_name: &str,
        item: TypeHierarchyItem,
    ) -> Result<Option<Vec<TypeHierarchyItem>>, NeovimError> {
        let conn = self.connection.as_ref().ok_or_else(|| {
            NeovimError::Connection("Not connected to any Neovim instance".to_string())
        })?;
        match conn
            .nvim
            .execute_lua(
                include_str!("lua/lsp_type_hierarchy_subtypes.lua"),
                vec![
                    Value::from(client_name), // client_name
                    Value::from(
                        serde_json::to_string(&TypeHierarchySubtypesParams { item }).unwrap(),
                    ), // params
                    Value::from(self.config.lsp_timeout_ms), // timeout_ms
                ],
            )
            .await
        {
            Ok(result) => {
                match serde_json::from_str::<NvimExecuteLuaResult<Option<Vec<TypeHierarchyItem>>>>(
                    result.as_str().unwrap(),
                ) {
                    Ok(rv) => rv.into(),
                    Err(e) => {
                        debug!("Failed to parse type hierarchy subtypes result: {}", e);
                        Err(NeovimError::Api(format!(
                            "Failed to parse type hierarchy subtypes result: {e}"
                        )))
                    }
                }
            }
            Err(e) => {
                debug!("Failed to get type hierarchy subtypes: {}", e);
                Err(NeovimError::Api(format!(
                    "Failed to get type hierarchy subtypes: {e}"
                )))
            }
        }
    }

    #[instrument(skip(self))]
    async fn read_document(
        &self,
        document: DocumentIdentifier,
        start: i64,
        end: i64,
    ) -> Result<String, NeovimError> {
        let conn = self.connection.as_ref().ok_or_else(|| {
            NeovimError::Connection("Not connected to any Neovim instance".to_string())
        })?;
        let params = match &document {
            DocumentIdentifier::BufferId(buffer_id) => {
                ReadDocumentParams::buffer_id(*buffer_id, start, end)
            }
            DocumentIdentifier::ProjectRelativePath(rel_path) => {
                // Get project root and construct absolute path
                let project_root = self.get_project_root().await?;
                let absolute_path = project_root.join(rel_path);
                ReadDocumentParams::path(absolute_path, start, end)
            }
            DocumentIdentifier::AbsolutePath(abs_path) => {
                ReadDocumentParams::path(abs_path, start, end)
            }
        };
        match conn
            .nvim
            .execute_lua(
                include_str!("lua/read_document.lua"),
                vec![
                    Value::from(serde_json::to_string(&params).unwrap()), // params
                ],
            )
            .await
        {
            Ok(result) => {
                match serde_json::from_str::<NvimExecuteLuaResult<String>>(result.as_str().unwrap())
                {
                    Ok(rv) => rv.into(),
                    Err(e) => {
                        debug!("Failed to parse read document result: {}", e);
                        Err(NeovimError::Api(format!(
                            "Failed to parse read document result: {e}"
                        )))
                    }
                }
            }
            Err(e) => {
                debug!("Failed to get read document: {}", e);
                Err(NeovimError::Api(format!(
                    "Failed to get read document: {e}"
                )))
            }
        }
    }
}

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

    #[test]
    fn test_symbol_kind_serialization() {
        assert_eq!(serde_json::to_value(SymbolKind::Function).unwrap(), 12);
        assert_eq!(serde_json::to_value(SymbolKind::Variable).unwrap(), 13);
        assert_eq!(serde_json::to_value(SymbolKind::Class).unwrap(), 5);
    }

    #[test]
    fn test_symbol_information_serialization() {
        let symbol = SymbolInformation {
            name: "test_function".to_string(),
            kind: SymbolKind::Function,
            tags: None,
            deprecated: None,
            location: Location {
                uri: "file:///test.rs".to_string(),
                range: Range {
                    start: Position {
                        line: 0,
                        character: 0,
                    },
                    end: Position {
                        line: 0,
                        character: 13,
                    },
                },
            },
            container_name: None,
        };

        let json = serde_json::to_string(&symbol).unwrap();
        assert!(json.contains("test_function"));
        assert!(json.contains("file:///test.rs"));
    }

    #[test]
    fn test_document_symbol_serialization() {
        let symbol = DocumentSymbol {
            name: "TestClass".to_string(),
            detail: Some("class TestClass".to_string()),
            kind: SymbolKind::Class,
            tags: None,
            deprecated: None,
            range: Range {
                start: Position {
                    line: 0,
                    character: 0,
                },
                end: Position {
                    line: 10,
                    character: 0,
                },
            },
            selection_range: Range {
                start: Position {
                    line: 0,
                    character: 6,
                },
                end: Position {
                    line: 0,
                    character: 15,
                },
            },
            children: None,
        };

        let json = serde_json::to_string(&symbol).unwrap();
        assert!(json.contains("TestClass"));
        assert!(json.contains("class TestClass"));
    }

    #[test]
    fn test_workspace_symbol_params_serialization() {
        let params = WorkspaceSymbolParams {
            query: "function".to_string(),
        };

        let json = serde_json::to_string(&params).unwrap();
        assert!(json.contains("function"));
    }

    #[test]
    fn test_reference_params_serialization() {
        let params = ReferenceParams {
            text_document: TextDocumentIdentifier {
                uri: "file:///test.rs".to_string(),
                version: Some(1),
            },
            position: Position {
                line: 10,
                character: 5,
            },
            context: ReferenceContext {
                include_declaration: true,
            },
        };

        let json = serde_json::to_string(&params).unwrap();
        assert!(json.contains("textDocument"));
        assert!(json.contains("position"));
        assert!(json.contains("context"));
        assert!(json.contains("includeDeclaration"));
        assert!(json.contains("true"));
    }

    #[derive(serde::Deserialize)]
    struct DocumentIdentifierWrapper {
        #[serde(deserialize_with = "string_or_struct")]
        pub identifier: DocumentIdentifier,
    }

    #[test]
    fn test_make_text_document_identifier_from_path() {
        // Test with current file (this source file should exist)
        let current_file = file!();
        let result = make_text_document_identifier_from_path(current_file);

        assert!(result.is_ok());
        let text_doc = result.unwrap();
        assert!(text_doc.uri.starts_with("file://"));
        assert!(text_doc.uri.ends_with("client.rs"));
        assert_eq!(text_doc.version, None);
    }

    #[test]
    fn test_make_text_document_identifier_from_path_invalid() {
        // Test with non-existent path
        let result = make_text_document_identifier_from_path("/nonexistent/path/file.rs");
        assert!(result.is_err());

        if let Err(NeovimError::Api(msg)) = result {
            assert!(msg.contains("Failed to resolve path"));
        } else {
            panic!("Expected NeovimError::Api");
        }
    }

    #[test]
    fn test_document_identifier_creation() {
        let buffer_id = DocumentIdentifier::from_buffer_id(42);
        assert_eq!(buffer_id, DocumentIdentifier::BufferId(42));

        let rel_path = DocumentIdentifier::from_project_path("src/lib.rs");
        assert_eq!(
            rel_path,
            DocumentIdentifier::ProjectRelativePath(PathBuf::from("src/lib.rs"))
        );

        let abs_path = DocumentIdentifier::from_absolute_path("/usr/src/lib.rs");
        assert_eq!(
            abs_path,
            DocumentIdentifier::AbsolutePath(PathBuf::from("/usr/src/lib.rs"))
        );
    }

    #[test]
    fn test_document_identifier_serde() {
        // Test BufferId serialization
        let buffer_id = DocumentIdentifier::from_buffer_id(123);
        let json = serde_json::to_string(&buffer_id).unwrap();
        assert!(json.contains("buffer_id"));
        assert!(json.contains("123"));

        let deserialized: DocumentIdentifier = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized, buffer_id);

        // Test ProjectRelativePath serialization
        let rel_path = DocumentIdentifier::from_project_path("src/main.rs");
        let json = serde_json::to_string(&rel_path).unwrap();
        assert!(json.contains("project_relative_path"));
        assert!(json.contains("src/main.rs"));

        let deserialized: DocumentIdentifier = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized, rel_path);

        // Test AbsolutePath serialization
        let abs_path = DocumentIdentifier::from_absolute_path("/tmp/test.rs");
        let json = serde_json::to_string(&abs_path).unwrap();
        assert!(json.contains("absolute_path"));
        assert!(json.contains("/tmp/test.rs"));

        let deserialized: DocumentIdentifier = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized, abs_path);
    }

    #[test]
    fn test_document_identifier_json_schema() {
        use schemars::schema_for;

        let schema = schema_for!(DocumentIdentifier);
        let schema_json = serde_json::to_string(&schema).unwrap();

        // Verify the schema contains the expected enum variants
        assert!(schema_json.contains("buffer_id"));
        assert!(schema_json.contains("project_relative_path"));
        assert!(schema_json.contains("absolute_path"));
    }

    #[test]
    fn test_document_identifier_string_deserializer_buffer_id() {
        // Test deserializing buffer_id from JSON string
        let json_str = r#"{"buffer_id": 42}"#;
        let result: Result<DocumentIdentifier, _> = serde_json::from_str(json_str);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), DocumentIdentifier::BufferId(42));

        // Test large buffer ID
        let json_str = r#"{"buffer_id": 18446744073709551615}"#;
        let result: Result<DocumentIdentifier, _> = serde_json::from_str(json_str);
        assert!(result.is_ok());
        assert_eq!(
            result.unwrap(),
            DocumentIdentifier::BufferId(18446744073709551615)
        );
    }

    #[test]
    fn test_document_identifier_string_deserializer_project_path() {
        // Test deserializing project_relative_path from JSON string
        let json_str = r#"{"project_relative_path": "src/main.rs"}"#;
        let result: Result<DocumentIdentifier, _> = serde_json::from_str(json_str);
        assert!(result.is_ok());
        assert_eq!(
            result.unwrap(),
            DocumentIdentifier::ProjectRelativePath(PathBuf::from("src/main.rs"))
        );

        // Test with nested path
        let json_str = r#"{"project_relative_path": "src/server/tools.rs"}"#;
        let result: Result<DocumentIdentifier, _> = serde_json::from_str(json_str);
        assert!(result.is_ok());
        assert_eq!(
            result.unwrap(),
            DocumentIdentifier::ProjectRelativePath(PathBuf::from("src/server/tools.rs"))
        );

        // Test with empty path
        let json_str = r#"{"project_relative_path": ""}"#;
        let result: Result<DocumentIdentifier, _> = serde_json::from_str(json_str);
        assert!(result.is_ok());
        assert_eq!(
            result.unwrap(),
            DocumentIdentifier::ProjectRelativePath(PathBuf::from(""))
        );
    }

    #[test]
    fn test_document_identifier_string_deserializer_absolute_path() {
        // Test deserializing absolute_path from JSON string
        let json_str = r#"{"absolute_path": "/usr/local/src/main.rs"}"#;
        let result: Result<DocumentIdentifier, _> = serde_json::from_str(json_str);
        assert!(result.is_ok());
        assert_eq!(
            result.unwrap(),
            DocumentIdentifier::AbsolutePath(PathBuf::from("/usr/local/src/main.rs"))
        );

        // Test Windows-style absolute path
        let json_str = r#"{"absolute_path": "C:\\Users\\test\\Documents\\file.rs"}"#;
        let result: Result<DocumentIdentifier, _> = serde_json::from_str(json_str);
        assert!(result.is_ok());
        assert_eq!(
            result.unwrap(),
            DocumentIdentifier::AbsolutePath(PathBuf::from("C:\\Users\\test\\Documents\\file.rs"))
        );
    }

    #[test]
    fn test_document_identifier_string_deserializer_error_cases() {
        // Test invalid JSON string format
        let invalid_json = r#"{"invalid_field": 42}"#;
        let result: Result<DocumentIdentifier, _> = serde_json::from_str(invalid_json);
        assert!(result.is_err());

        // Test empty JSON object
        let empty_json = r#"{}"#;
        let result: Result<DocumentIdentifier, _> = serde_json::from_str(empty_json);
        assert!(result.is_err());

        // Test malformed JSON
        let malformed_json = r#"{"buffer_id": invalid}"#;
        let result: Result<DocumentIdentifier, _> = serde_json::from_str(malformed_json);
        assert!(result.is_err());

        // Test negative buffer_id (should fail for u64)
        let negative_json = r#"{"buffer_id": -1}"#;
        let result: Result<DocumentIdentifier, _> = serde_json::from_str(negative_json);
        assert!(result.is_err());

        // Test string with malformed embedded JSON
        let malformed_embedded = r#""{\"buffer_id\": }"#;
        let result: Result<DocumentIdentifier, _> = serde_json::from_str(malformed_embedded);
        assert!(result.is_err());
    }

    #[test]
    fn test_document_identifier_string_deserializer_mixed_cases() {
        // Test with extra whitespace in JSON
        let json_str = r#"{ "buffer_id" : 999 }"#;
        let result: Result<DocumentIdentifier, _> = serde_json::from_str(json_str);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), DocumentIdentifier::BufferId(999));

        // Test with Unicode in paths
        let json_str = r#"{"project_relative_path": "src/测试.rs"}"#;
        let result: Result<DocumentIdentifier, _> = serde_json::from_str(json_str);
        assert!(result.is_ok());
        assert_eq!(
            result.unwrap(),
            DocumentIdentifier::ProjectRelativePath(PathBuf::from("src/测试.rs"))
        );

        // Test with special characters in paths
        let json_str = r#"{"absolute_path": "/tmp/test with spaces & symbols!.rs"}"#;
        let result: Result<DocumentIdentifier, _> = serde_json::from_str(json_str);
        assert!(result.is_ok());
        assert_eq!(
            result.unwrap(),
            DocumentIdentifier::AbsolutePath(PathBuf::from("/tmp/test with spaces & symbols!.rs"))
        );
    }

    #[test]
    fn test_document_identifier_round_trip_serialization() {
        // Test round-trip serialization/deserialization for all variants
        let test_cases = vec![
            DocumentIdentifier::BufferId(42),
            DocumentIdentifier::ProjectRelativePath(PathBuf::from("src/main.rs")),
            DocumentIdentifier::AbsolutePath(PathBuf::from("/usr/src/main.rs")),
        ];

        for original in test_cases {
            // Serialize to JSON
            let json = serde_json::to_string(&original).unwrap();

            // Deserialize back from JSON
            let deserialized: DocumentIdentifier = serde_json::from_str(&json).unwrap();

            // Verify round-trip equality
            assert_eq!(original, deserialized);

            // Test string-embedded JSON deserialization (Claude Code use case)
            let json_string = serde_json::to_string(&serde_json::json!( {
                "identifier": json,
            }))
            .unwrap();
            let from_string: DocumentIdentifierWrapper =
                serde_json::from_str(&json_string).unwrap();
            assert_eq!(original, from_string.identifier);
        }
    }

    #[test]
    fn test_code_action_serialization() {
        let code_action = CodeAction {
            title: "Fix this issue".to_string(),
            kind: Some(CodeActionKind::Quickfix),
            diagnostics: Some(vec![]),
            is_preferred: Some(true),
            disabled: None,
            edit: Some(WorkspaceEdit {
                changes: Some(std::collections::HashMap::new()),
                document_changes: None,
                change_annotations: None,
            }),
            command: None,
            data: None,
        };

        let json = serde_json::to_string(&code_action).unwrap();
        assert!(json.contains("Fix this issue"));
        assert!(json.contains("quickfix"));

        // Test round-trip
        let deserialized: CodeAction = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.title, "Fix this issue");
        assert_eq!(deserialized.kind, Some(CodeActionKind::Quickfix));
    }

    #[test]
    fn test_workspace_edit_serialization() {
        let mut changes = std::collections::HashMap::new();
        changes.insert(
            "file:///test.rs".to_string(),
            vec![TextEdit {
                range: Range {
                    start: Position {
                        line: 0,
                        character: 0,
                    },
                    end: Position {
                        line: 0,
                        character: 5,
                    },
                },
                new_text: "hello".to_string(),
                annotation_id: None,
            }],
        );

        let workspace_edit = WorkspaceEdit {
            changes: Some(changes),
            document_changes: None,
            change_annotations: None,
        };

        let json = serde_json::to_string(&workspace_edit).unwrap();
        assert!(json.contains("file:///test.rs"));
        assert!(json.contains("hello"));

        // Test round-trip
        let deserialized: WorkspaceEdit = serde_json::from_str(&json).unwrap();
        assert!(deserialized.changes.is_some());
    }

    #[derive(serde::Deserialize)]
    struct CodeActionWrapper {
        #[serde(deserialize_with = "string_or_struct")]
        pub code_action: CodeAction,
    }

    #[test]
    fn test_code_action_string_deserialization() {
        // Test that CodeAction can deserialize from both object and string formats
        let code_action = CodeAction {
            title: "Fix this issue".to_string(),
            kind: Some(CodeActionKind::Quickfix),
            diagnostics: None,
            is_preferred: Some(true),
            disabled: None,
            edit: None,
            command: None,
            data: None,
        };

        // Serialize to JSON string
        let json = serde_json::to_string(&code_action).unwrap();

        // Test direct object deserialization
        let deserialized_object: CodeAction = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized_object.title, "Fix this issue");
        assert_eq!(deserialized_object.kind, Some(CodeActionKind::Quickfix));

        // Test string-wrapped deserialization
        let json_string = serde_json::json!({
            "code_action": json
        });
        let deserialized: CodeActionWrapper = serde_json::from_value(json_string).unwrap();
        let deserialized = deserialized.code_action;
        assert_eq!(deserialized.title, "Fix this issue");
        assert_eq!(deserialized.kind, Some(CodeActionKind::Quickfix));
    }

    #[derive(serde::Deserialize)]
    struct WorkspaceEditWrapper {
        #[serde(deserialize_with = "string_or_struct")]
        pub workspace_edit: WorkspaceEdit,
    }

    #[test]
    fn test_workspace_edit_string_deserialization() {
        // Test that WorkspaceEdit can deserialize from both object and string formats
        let mut changes = std::collections::HashMap::new();
        changes.insert(
            "file:///test.rs".to_string(),
            vec![TextEdit {
                range: Range {
                    start: Position {
                        line: 0,
                        character: 0,
                    },
                    end: Position {
                        line: 0,
                        character: 5,
                    },
                },
                new_text: "hello".to_string(),
                annotation_id: None,
            }],
        );

        let workspace_edit = WorkspaceEdit {
            changes: Some(changes),
            document_changes: None,
            change_annotations: None,
        };

        // Serialize to JSON string
        let json = serde_json::to_string(&workspace_edit).unwrap();

        // Test direct object deserialization
        let deserialized_object: WorkspaceEdit = serde_json::from_str(&json).unwrap();
        assert!(deserialized_object.changes.is_some());

        // Test string-wrapped deserialization
        let json_string = serde_json::json!({
            "workspace_edit": json
        });
        let deserialized: WorkspaceEditWrapper = serde_json::from_value(json_string).unwrap();
        let deserialized = deserialized.workspace_edit;
        assert!(deserialized.changes.is_some());
    }

    #[tokio::test]
    async fn test_notification_tracker_basic() {
        let tracker = NotificationTracker::default();

        // Test recording a notification
        tracker
            .record_notification(
                "test_notification".to_string(),
                vec![Value::from("test_arg")],
            )
            .await;

        // Test waiting for the notification
        let result = tracker
            .wait_for_notification("test_notification", Duration::from_millis(100))
            .await;

        assert!(result.is_ok());
        let notification = result.unwrap();
        assert_eq!(notification.name, "test_notification");
        assert_eq!(notification.args.len(), 1);
        assert_eq!(notification.args[0].as_str().unwrap(), "test_arg");
    }

    #[tokio::test]
    async fn test_notification_tracker_timeout() {
        let tracker = NotificationTracker::default();

        // Test waiting for a notification that never comes (should timeout)
        let result = tracker
            .wait_for_notification("nonexistent_notification", Duration::from_millis(50))
            .await;

        assert!(result.is_err());
        let error = result.unwrap_err();
        assert!(matches!(error, NeovimError::Api(_)));
        assert!(
            error
                .to_string()
                .contains("Timeout waiting for notification")
        );
    }

    #[tokio::test]
    async fn test_notification_tracker_wait_then_send() {
        let tracker = NotificationTracker::default();

        // Spawn a task that will wait for a notification
        let wait_handle = tokio::spawn({
            let tracker = tracker.clone();
            async move {
                tracker
                    .wait_for_notification("test_async_notification", Duration::from_millis(500))
                    .await
            }
        });

        // Give the waiting task a moment to start waiting
        tokio::time::sleep(Duration::from_millis(10)).await;

        // Now send the notification
        tracker
            .record_notification(
                "test_async_notification".to_string(),
                vec![Value::from("async_test_arg")],
            )
            .await;

        // The waiting task should now receive the notification
        let result = wait_handle.await.unwrap();
        assert!(result.is_ok());
        let notification = result.unwrap();
        assert_eq!(notification.name, "test_async_notification");
        assert_eq!(notification.args.len(), 1);
        assert_eq!(notification.args[0].as_str().unwrap(), "async_test_arg");
    }

    #[tokio::test]
    async fn test_notification_cleanup_expired() {
        let tracker = NotificationTracker::default();

        // Record a notification with a modified timestamp (simulate old notification)
        let old_notification = Notification {
            name: "old_notification".to_string(),
            args: vec![Value::from("old_data")],
            timestamp: std::time::SystemTime::now()
                - Duration::from_secs(NOTIFICATION_EXPIRY_SECONDS + 1),
        };

        // Manually insert old notification to simulate existing data
        {
            let mut notifications = tracker.notifications.lock().await;
            notifications.push(old_notification);
        }

        // Record a fresh notification
        tracker
            .record_notification(
                "fresh_notification".to_string(),
                vec![Value::from("fresh_data")],
            )
            .await;

        // Check initial state
        let (count_before, _) = tracker.get_stats().await;
        assert_eq!(count_before, 2);

        // Trigger cleanup
        tracker.cleanup_expired_notifications().await;

        // Old notification should be removed, fresh one should remain
        let (count_after, _) = tracker.get_stats().await;
        assert_eq!(count_after, 1);

        // Verify the remaining notification is the fresh one
        let result = tracker
            .wait_for_notification("fresh_notification", Duration::from_millis(10))
            .await;
        assert!(result.is_ok());

        // Verify old notification is gone
        let result = tracker
            .wait_for_notification("old_notification", Duration::from_millis(10))
            .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_notification_cleanup_excess() {
        let tracker = NotificationTracker::default();

        // Record more than MAX_STORED_NOTIFICATIONS
        for i in 0..(MAX_STORED_NOTIFICATIONS + 10) {
            tracker
                .record_notification(format!("notification_{}", i), vec![Value::from(i as i64)])
                .await;
        }

        // Get current count
        let (count, _) = tracker.get_stats().await;

        // Should be limited to MAX_STORED_NOTIFICATIONS due to automatic cleanup
        assert!(count <= MAX_STORED_NOTIFICATIONS);

        // The most recent notifications should still be available
        let result = tracker
            .wait_for_notification(
                &format!("notification_{}", MAX_STORED_NOTIFICATIONS + 9),
                Duration::from_millis(10),
            )
            .await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_notification_expiry_in_wait() {
        let tracker = NotificationTracker::default();

        // Create an expired notification manually
        let expired_notification = Notification {
            name: "expired_test".to_string(),
            args: vec![Value::from("expired_data")],
            timestamp: std::time::SystemTime::now()
                - Duration::from_secs(NOTIFICATION_EXPIRY_SECONDS + 1),
        };

        // Manually insert expired notification
        {
            let mut notifications = tracker.notifications.lock().await;
            notifications.push(expired_notification);
        }

        // wait_for_notification should not return expired notification
        let result = tracker
            .wait_for_notification("expired_test", Duration::from_millis(50))
            .await;

        // Should timeout because expired notification is ignored
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Timeout waiting for notification")
        );
    }
}