deps-core 0.12.0

Core abstractions for deps-lsp: caching, errors, and traits
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
//! Core completion infrastructure for deps-lsp.
//!
//! This module provides generic completion functionality that works across
//! all package ecosystems (Cargo, npm, PyPI, etc.). It handles:
//!
//! - Context detection - determining what type of completion is appropriate
//! - Prefix extraction - getting the text typed so far
//! - CompletionItem builders - creating LSP completion responses
//!
//! # Architecture
//!
//! The completion system uses trait objects (`dyn Dependency`, `dyn ParseResult`,
//! `dyn Version`, `dyn Metadata`) to work generically across ecosystems.
//!
//! # Examples
//!
//! ```no_run
//! use deps_core::completion::{detect_completion_context, CompletionContext};
//! use tower_lsp_server::ls_types::Position;
//!
//! // In your ecosystem's generate_completions implementation:
//! async fn generate_completions(
//!     parse_result: &dyn deps_core::ParseResult,
//!     position: Position,
//!     content: &str,
//! ) -> Vec<tower_lsp_server::ls_types::CompletionItem> {
//!     let context = detect_completion_context(parse_result, position, content);
//!
//!     match context {
//!         CompletionContext::PackageName { prefix, range } => {
//!             // Search registry and build completions, replacing `range`
//!             vec![]
//!         }
//!         CompletionContext::Version { package_name, prefix } => {
//!             // Fetch versions and build completions
//!             vec![]
//!         }
//!         _ => vec![],
//!     }
//! }
//! ```

use crate::lsp_helpers::{escape_markdown, is_safe_version_string, warn_rejected_value};
use crate::{
    ConcreteVersion, FreshnessSettings, Metadata, PackageName, ParseResult, PublishTime, Version,
    format_relative_age,
};
use std::time::Duration;
use tower_lsp_server::ls_types::{
    CompletionItem, CompletionItemKind, CompletionItemLabelDetails, CompletionTextEdit,
    Documentation, MarkupContent, MarkupKind, Position, Range, TextEdit,
};

/// Wall-clock budget `deps-lsp`'s completion handler gives an ecosystem's
/// `generate_completions` before treating it as a timeout.
///
/// Past this, the handler skips the fallback search rather than treating a
/// fast-but-empty result as "genuinely no results"
/// (`crates/deps-lsp/src/handlers/completion.rs`).
///
/// A registry-backed completion path that retries internally on failure (e.g.
/// `deps-maven`'s `search_typed`, #274) must size its own total retry budget to
/// exceed this constant: finishing sooner with an empty/error result is
/// indistinguishable, at the call site, from a query that legitimately has no
/// matches, and triggers a wasted (and, for a struggling registry, likely to also
/// fail) fallback search rather than the handler's existing skip-on-timeout path.
pub const COMPLETION_SEARCH_TIMEOUT: Duration = Duration::from_secs(2);

/// Result of [`Ecosystem::generate_completions`](crate::Ecosystem::generate_completions).
///
/// Carries the completion items produced for this specific call, plus whether they are
/// a possibly-truncated view of a larger candidate set that the LSP client should
/// re-query for as the user keeps typing.
///
/// Supersedes the ecosystem-wide `Ecosystem::completions_are_incomplete()` flag (#419):
/// `is_incomplete` is computed per call from the actual completion context and result
/// set, so only the specific context that is genuinely truncated (e.g. PyPI's unranked,
/// index-backed package-name search) is flagged — a version completion, a comment
/// position, or any other exhaustive context in the same manifest correctly reports
/// `is_incomplete: false` instead of inheriting the worst case across the whole
/// ecosystem (#427).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Completions {
    /// The completion items for this call.
    pub items: Vec<CompletionItem>,
    /// Whether `items` is a possibly-truncated view of a larger candidate set.
    pub is_incomplete: bool,
}

impl From<Vec<CompletionItem>> for Completions {
    /// Wraps an always-exhaustive result set, i.e. `is_incomplete: false`.
    fn from(items: Vec<CompletionItem>) -> Self {
        Self {
            items,
            is_incomplete: false,
        }
    }
}

/// Context for completion request based on cursor position.
///
/// This enum represents what type of completion is appropriate at the
/// current cursor location within a manifest file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CompletionContext {
    /// Cursor is within or after a package name.
    ///
    /// Example: `serd|` or `tokio|` where | represents cursor position.
    PackageName {
        /// Partial package name typed so far (may be empty).
        prefix: String,
        /// Range of the full package-name token, to be replaced by the completion's
        /// `textEdit` (not just the already-typed prefix up to the cursor).
        range: Range,
    },

    /// Cursor is within a version string.
    ///
    /// Example: `"1.0|"` or `"^2.|"` where | represents cursor position.
    Version {
        /// Package name this version belongs to.
        package_name: PackageName,
        /// Partial version typed so far (may include operators like ^, ~).
        prefix: String,
    },

    /// Cursor is within a feature array.
    ///
    /// Example: `features = ["deri|"]` where | represents cursor position.
    Feature {
        /// Package name whose features are being completed.
        package_name: PackageName,
        /// Partial feature name typed so far (may be empty).
        prefix: String,
    },

    /// Cursor is not in a valid completion position.
    None,
}

/// Detects the completion context based on cursor position.
///
/// This function analyzes the cursor position relative to parsed dependencies
/// to determine what type of completion should be offered.
///
/// # Arguments
///
/// * `parse_result` - Parsed manifest with dependency information
/// * `position` - Cursor position in the document (LSP Position, 0-based line, 0-based character)
/// * `content` - Full document content for prefix extraction
///
/// # Returns
///
/// A `CompletionContext` indicating what type of completion is appropriate,
/// or `CompletionContext::None` if the cursor is not in a valid position.
///
/// # Examples
///
/// ```no_run
/// use deps_core::completion::detect_completion_context;
/// use tower_lsp_server::ls_types::Position;
///
/// # async fn example(parse_result: &dyn deps_core::ParseResult, content: &str) {
/// // Cursor at position after "ser" in "serde"
/// let position = Position { line: 5, character: 3 };
/// let context = detect_completion_context(parse_result, position, content);
/// # }
/// ```
pub fn detect_completion_context(
    parse_result: &dyn ParseResult,
    position: Position,
    content: &str,
) -> CompletionContext {
    let dependencies = parse_result.dependencies();

    for dep in dependencies {
        // Check if position is within the dependency name range
        let name_range = dep.name_range();
        // `position_in_range` tolerates a request position one column past
        // `name_range.end` (a convenience for firing completion right after the
        // last typed character), but the manifest text immediately following the
        // name is often structurally significant (a closing quote, the space
        // before `=`, ...). Widening the returned range to reach that far would
        // consume it once the client applies the edit. So this branch requires
        // *strict* containment (`position.character <= name_range.end.character`
        // on the end line) rather than reusing that tolerance — the boundary
        // case (cursor exactly at `name_range.end`) is already covered without
        // it, and a position one further past falls through to the checks below
        // instead of matching here.
        if position_in_range(position, name_range)
            && (name_range.end.line != position.line
                || position.character <= name_range.end.character)
        {
            let prefix = extract_prefix(content, position, name_range);
            return CompletionContext::PackageName {
                prefix,
                range: name_range,
            };
        }

        // Check if position is within the version range
        if let Some(version_range) = dep.version_range()
            && position_in_range(position, version_range)
        {
            let prefix = extract_prefix(content, position, version_range);
            return CompletionContext::Version {
                package_name: dep.name().clone(),
                prefix,
            };
        }

        // Check if position is within the features array range
        if let Some(features_range) = dep.features_range()
            && position_in_range(position, features_range)
        {
            let prefix = extract_feature_prefix(content, position);
            return CompletionContext::Feature {
                package_name: dep.name().clone(),
                prefix,
            };
        }
    }

    CompletionContext::None
}

/// Checks if a position is within or at the end of a range.
///
/// LSP ranges are inclusive of start, exclusive of end.
/// We also consider the position to be "in range" if it's immediately
/// after the range end (for completion after typing).
const fn position_in_range(position: Position, range: Range) -> bool {
    // Before range start
    if position.line < range.start.line {
        return false;
    }

    if position.line == range.start.line && position.character < range.start.character {
        return false;
    }

    // After range end (allow one position past for completion)
    if position.line > range.end.line {
        return false;
    }

    if position.line == range.end.line && position.character > range.end.character + 1 {
        return false;
    }

    true
}

/// Converts UTF-16 offset to byte offset in a string.
///
/// LSP uses UTF-16 code units for character positions (for compatibility with
/// JavaScript and other languages). This function converts from UTF-16 offset
/// to byte offset for Rust string indexing.
///
/// # Arguments
///
/// * `s` - The string to index into
/// * `utf16_offset` - UTF-16 code unit offset (from LSP Position.character)
///
/// # Returns
///
/// Byte offset if valid, `None` if the UTF-16 offset is out of bounds.
///
/// # Examples
///
/// ```
/// # use deps_core::completion::utf16_to_byte_offset;
/// // ASCII: UTF-16 offset equals byte offset
/// assert_eq!(utf16_to_byte_offset("hello", 2), Some(2));
///
/// // Unicode: "日本語" - each char is 3 bytes but 1 UTF-16 code unit
/// assert_eq!(utf16_to_byte_offset("日本語", 0), Some(0));
/// assert_eq!(utf16_to_byte_offset("日本語", 1), Some(3));
/// assert_eq!(utf16_to_byte_offset("日本語", 2), Some(6));
///
/// // Emoji: "😀" is 4 bytes but 2 UTF-16 code units (surrogate pair)
/// assert_eq!(utf16_to_byte_offset("😀test", 2), Some(4));
/// ```
pub fn utf16_to_byte_offset(s: &str, utf16_offset: u32) -> Option<usize> {
    let mut utf16_count = 0u32;
    for (byte_idx, ch) in s.char_indices() {
        if utf16_count >= utf16_offset {
            return Some(byte_idx);
        }
        utf16_count += ch.len_utf16() as u32;
    }
    if utf16_count == utf16_offset {
        return Some(s.len());
    }
    None
}

/// Converts a byte offset within `s` to a UTF-16 code unit offset (LSP `Position.character`).
///
/// `byte_offset` must fall on a UTF-8 char boundary of `s` (e.g. one produced by
/// `str::find`/`rfind`/slicing, never an arbitrary user-controlled value).
///
/// # Panics
///
/// Panics if `byte_offset` is out of bounds or does not fall on a UTF-8 char boundary of `s`.
///
/// # Examples
///
/// ```
/// # use deps_core::completion::byte_to_utf16_offset;
/// // ASCII: byte offset equals UTF-16 offset
/// assert_eq!(byte_to_utf16_offset("hello", 2), 2);
///
/// // Unicode: "日本語" - each char is 3 bytes but 1 UTF-16 code unit
/// assert_eq!(byte_to_utf16_offset("日本語", 0), 0);
/// assert_eq!(byte_to_utf16_offset("日本語", 3), 1);
/// assert_eq!(byte_to_utf16_offset("日本語", 6), 2);
///
/// // Emoji: "😀" is 4 bytes but 2 UTF-16 code units (surrogate pair)
/// assert_eq!(byte_to_utf16_offset("😀test", 4), 2);
/// ```
pub fn byte_to_utf16_offset(s: &str, byte_offset: usize) -> u32 {
    s[..byte_offset].encode_utf16().count() as u32
}

/// Extracts the prefix text from content at a position within a range.
///
/// This function finds the text from the start of the range up to the
/// cursor position, excluding any quote characters.
///
/// # Arguments
///
/// * `content` - Full document content
/// * `position` - Cursor position (LSP Position, 0-based line, UTF-16 character offset)
/// * `range` - Range containing the token (name, version, etc.)
///
/// # Returns
///
/// The prefix string typed so far, with quotes and extra whitespace removed.
///
/// # Examples
///
/// ```no_run
/// use deps_core::completion::extract_prefix;
/// use tower_lsp_server::ls_types::{Position, Range};
///
/// let content = r#"serde = "1.0""#;
/// let position = Position { line: 0, character: 11 }; // After "1."
/// let range = Range {
///     start: Position { line: 0, character: 9 },
///     end: Position { line: 0, character: 13 },
/// };
///
/// let prefix = extract_prefix(content, position, range);
/// assert_eq!(prefix, "1.");
/// ```
pub fn extract_prefix(content: &str, position: Position, range: Range) -> String {
    // Get the line at the position - use nth() instead of collecting all lines
    let line = match content.lines().nth(position.line as usize) {
        Some(l) => l,
        None => return String::new(),
    };

    // Convert UTF-16 positions to byte offsets
    let start_byte = if position.line == range.start.line {
        match utf16_to_byte_offset(line, range.start.character) {
            Some(offset) => offset,
            None => return String::new(),
        }
    } else {
        0
    };

    let cursor_byte = match utf16_to_byte_offset(line, position.character) {
        Some(offset) => offset,
        None => return String::new(),
    };

    // Safety: ensure byte offsets are within bounds
    if start_byte > line.len() || cursor_byte > line.len() || start_byte > cursor_byte {
        return String::new();
    }

    // Extract substring
    let prefix = &line[start_byte..cursor_byte];

    // Remove quotes and trim whitespace
    prefix
        .trim()
        .trim_matches('"')
        .trim_matches('\'')
        .trim()
        .to_string()
}

/// Extracts the partial feature name typed at the cursor position.
///
/// Scans backwards from the cursor on the current line to find the start of
/// the feature string being typed. Handles both inline and multi-line arrays.
///
/// Returns an empty string when the cursor is not inside a quoted string
/// (e.g. right after `[` or between `, ` and the next `"`).
///
/// # Examples
///
/// ```no_run
/// # use deps_core::completion::extract_feature_prefix;
/// # use tower_lsp_server::ls_types::Position;
/// // Cursor inside: features = ["derive", "std", "ser|"]
/// let content = r#"serde = { version = "1", features = ["derive", "std", "ser"] }"#;
/// // cursor_char = index after "ser" inside the last quoted element
/// let ser_start = content.find(r#""ser""#).unwrap() + 1; // skip opening quote
/// let pos = Position { line: 0, character: (ser_start + "ser".len()) as u32 };
/// let prefix = extract_feature_prefix(content, pos);
/// assert_eq!(prefix, "ser");
/// ```
pub fn extract_feature_prefix(content: &str, position: Position) -> String {
    let line = match content.lines().nth(position.line as usize) {
        Some(l) => l,
        None => return String::new(),
    };

    let cursor_byte = match utf16_to_byte_offset(line, position.character) {
        Some(offset) => offset.min(line.len()),
        None => return String::new(),
    };

    let before_cursor = &line[..cursor_byte];

    // Use the text after the last '[' on this line as the relevant segment
    // (handles inline arrays; for multi-line arrays there is no '[' and we
    // use the whole line up to the cursor).
    let segment_start = before_cursor.rfind('[').map_or(0, |i| i + 1);
    let segment = &before_cursor[segment_start..];

    // Count '"' characters to determine whether the cursor is inside a string.
    // An odd count means the cursor is inside an open string literal.
    let quote_count = segment.chars().filter(|&c| c == '"').count();
    if quote_count % 2 == 0 {
        return String::new();
    }

    // Find the last opening quote and return the text after it.
    match segment.rfind('"') {
        Some(pos) => segment[pos + 1..].to_string(),
        None => String::new(),
    }
}

/// Builds a completion item for a package name.
///
/// Creates a properly formatted LSP CompletionItem with documentation,
/// version information, and links to repository/docs.
///
/// # Arguments
///
/// * `metadata` - Package metadata from registry search
/// * `insert_range` - LSP range where the completion should be inserted
///
/// # Returns
///
/// `Some(CompletionItem)` ready to send to the LSP client, or `None` when
/// `metadata.name()` fails [`crate::is_safe_package_name`] — a malicious/compromised
/// registry search result must not reach the manifest as an unsanitized `label`,
/// `insert_text`, `text_edit`, `sort_text`, or `filter_text`, so the item is dropped
/// rather than built with unsafe text.
///
/// # Examples
///
/// ```no_run
/// use deps_core::completion::build_package_completion;
/// use tower_lsp_server::ls_types::Range;
///
/// # async fn example(metadata: &dyn deps_core::Metadata) {
/// let range = Range::default(); // Use actual range from context
/// let item = build_package_completion(metadata, range).unwrap();
/// assert_eq!(item.label, metadata.name().as_str());
/// # }
/// ```
pub fn build_package_completion(
    metadata: &dyn Metadata,
    insert_range: Range,
) -> Option<CompletionItem> {
    let name = metadata.name();
    if !crate::is_safe_package_name(name.as_str()) {
        warn_rejected_value(
            "is_safe_package_name",
            "primary completion path package name",
            name.as_str(),
        );
        return None;
    }
    let latest = metadata.latest_version().as_str();

    // Build markdown documentation
    let header = if latest.is_empty() {
        format!("**{}**", escape_markdown(name.as_str()))
    } else {
        format!(
            "**{}** v{}",
            escape_markdown(name.as_str()),
            escape_markdown(latest)
        )
    };
    let mut doc_parts = vec![header];

    if let Some(desc) = metadata.description() {
        doc_parts.push(String::new()); // Empty line
        // Truncate the raw description first, then escape — escaping first could
        // cut a `\`-escape sequence in half at the byte boundary.
        let truncated = if desc.len() > 200 {
            let end = desc.floor_char_boundary(200);
            format!("{}...", escape_markdown(&desc[..end]))
        } else {
            escape_markdown(desc)
        };
        doc_parts.push(truncated);
    }

    // Add links section if we have any links
    let mut links = Vec::new();
    if let Some(repo) = metadata.repository() {
        links.push(format!("[Repository]({})", escape_markdown(repo)));
    }
    if let Some(docs) = metadata.documentation() {
        links.push(format!("[Documentation]({})", escape_markdown(docs)));
    }

    if !links.is_empty() {
        doc_parts.push(String::new()); // Empty line
        doc_parts.push(links.join(" | "));
    }

    Some(CompletionItem {
        label: name.to_string(),
        kind: Some(CompletionItemKind::MODULE),
        detail: if latest.is_empty() {
            None
        } else {
            Some(format!("v{}", latest))
        },
        documentation: Some(Documentation::MarkupContent(MarkupContent {
            kind: MarkupKind::Markdown,
            value: doc_parts.join("\n"),
        })),
        insert_text: Some(name.to_string()),
        text_edit: Some(CompletionTextEdit::Edit(TextEdit {
            range: insert_range,
            new_text: name.to_string(),
        })),
        sort_text: Some(name.to_string()),
        filter_text: Some(name.to_string()),
        ..Default::default()
    })
}

/// Builds a completion item for a version string.
///
/// Creates a properly formatted LSP CompletionItem with version metadata
/// in a simplified format matching Code Actions (Cmd+.) style.
///
/// # Arguments
///
/// * `display_item` - Version display metadata with label, description, and flags
/// * `insert_range` - Optional LSP range where the completion should replace text.
///   If `None`, the completion will insert at cursor position without replacing.
/// * `now` - Current instant, injected explicitly rather than read internally, so every
///   item in the same completion response has its age computed against one consistent
///   instant instead of drifting mid-request.
///
/// # Returns
///
/// A complete `CompletionItem` with simple index-based sorting and preselect.
///
/// # Format
///
/// - Label: `"version"` or `"version (latest)"` for the latest version
/// - Detail: `"Update package_name to version"`
/// - Label details: a greyed-out relative age (e.g. `"2 hours ago"`) when
///   `display_item.published_at` is known and `freshness_enabled` is `true`; omitted
///   entirely otherwise
/// - Preselect: `true` for latest version, `false` otherwise
/// - Sort: Index-based (00000, 00001, etc.)
///
/// # Examples
///
/// ```no_run
/// use deps_core::completion::{build_version_completion, VersionDisplayItem};
/// use deps_core::PackageName;
/// use tower_lsp_server::ls_types::Range;
///
/// # async fn example(version: &dyn deps_core::Version) {
/// let now = deps_core::PublishTime::now();
///
/// // Without range - insert at cursor
/// let display_item = VersionDisplayItem::new(version, &PackageName::new("serde"), 0, true);
/// let item = build_version_completion(&display_item, None, now, true);
/// assert_eq!(item.label, display_item.label);
///
/// // With range - replace existing text
/// let range = Range::default();
/// let item = build_version_completion(&display_item, Some(range), now, true);
/// # }
/// ```
pub fn build_version_completion(
    display_item: &VersionDisplayItem,
    insert_range: Option<Range>,
    now: PublishTime,
    freshness_enabled: bool,
) -> CompletionItem {
    // Simple index-based sorting (00000, 00001, etc.)
    let sort_text = format!("{:05}", display_item.index);

    // Greyed-out label suffix; unlike `label`, it never participates in filter matching,
    // so adding it cannot change which items match a typed prefix (FR-006).
    let label_details = freshness_enabled
        .then_some(display_item.published_at)
        .flatten()
        .map(|published_at| CompletionItemLabelDetails {
            detail: Some(format!(
                "  {}",
                format_relative_age(published_at.age_secs_from(now))
            )),
            description: None,
        });

    CompletionItem {
        label: display_item.label.clone(),
        kind: Some(CompletionItemKind::VALUE),
        detail: Some(display_item.description.clone()),
        documentation: None,
        insert_text: Some(display_item.version.to_string()),
        text_edit: insert_range.map(|range| {
            CompletionTextEdit::Edit(TextEdit {
                range,
                new_text: display_item.version.to_string(),
            })
        }),
        sort_text: Some(sort_text),
        preselect: Some(display_item.is_latest),
        label_details,
        ..Default::default()
    }
}

/// Display metadata for a single version in LSP responses.
///
/// Captures common formatting logic shared between completion items and code actions.
#[derive(Debug, Clone)]
pub struct VersionDisplayItem {
    /// Raw version string (e.g., "1.0.0")
    pub version: ConcreteVersion,
    /// Display label with "(latest)" suffix for first item
    pub label: String,
    /// Action description (e.g., "Update serde to 1.0.0")
    pub description: String,
    /// Zero-based index for sorting
    pub index: usize,
    /// True if this is the latest non-yanked version
    pub is_latest: bool,
    /// When this version was published, if the registry exposes it.
    ///
    /// `None` for ecosystems without publish metadata (see
    /// [`Version::published_at`]) — callers must degrade gracefully rather than
    /// rendering a placeholder age.
    pub published_at: Option<PublishTime>,
}

impl VersionDisplayItem {
    /// Creates a display item from version metadata.
    pub fn new(
        version: &dyn Version,
        package_name: &PackageName,
        index: usize,
        is_latest: bool,
    ) -> Self {
        let version_str = version.version_string();
        let label = if is_latest {
            format!("{} (latest)", version_str)
        } else {
            version_str.to_string()
        };
        let description = format!("Update {} to {}", package_name, version_str);

        Self {
            version: version_str.clone(),
            label,
            description,
            index,
            is_latest,
            published_at: version.published_at(),
        }
    }
}

/// Filters and formats versions for LSP display.
///
/// Returns up to 5 non-yanked versions with display metadata. An
/// advisory-deprecated version (e.g. an abandoned Composer package, a
/// deprecated npm package) is not excluded here — only a hard yank is
/// (#347): excluding advisory-only flags would leave a deprecated-but-
/// installable package with zero version completions.
pub fn prepare_version_display_items<V: AsRef<dyn Version>>(
    versions: &[V],
    package_name: &PackageName,
) -> Vec<VersionDisplayItem> {
    versions
        .iter()
        .map(|v| v.as_ref())
        .filter(|v| !v.removal_status().blocks_resolution())
        .take(MAX_COMPLETION_VERSIONS)
        .enumerate()
        .map(|(index, version)| VersionDisplayItem::new(version, package_name, index, index == 0))
        .collect()
}

/// Builds a completion item for a feature flag.
///
/// Creates a properly formatted LSP CompletionItem for feature flag names.
/// Only applicable to ecosystems that support features (e.g., Cargo).
///
/// # Arguments
///
/// * `feature_name` - Name of the feature flag
/// * `package_name` - Name of the package this feature belongs to
/// * `insert_range` - LSP range where the completion should be inserted, or `None` to omit
///   `textEdit` and let the client insert at cursor position via `insertText`
///
/// # Returns
///
/// A complete `CompletionItem` for the feature flag.
///
/// # Examples
///
/// ```no_run
/// use deps_core::completion::build_feature_completion;
///
/// let item = build_feature_completion("derive", &deps_core::PackageName::new("serde"), None);
/// assert_eq!(item.label, "derive");
/// ```
pub fn build_feature_completion(
    feature_name: &str,
    package_name: &PackageName,
    insert_range: Option<Range>,
) -> CompletionItem {
    CompletionItem {
        label: feature_name.to_string(),
        kind: Some(CompletionItemKind::PROPERTY),
        detail: Some(format!("Feature of {}", package_name)),
        documentation: None,
        insert_text: Some(feature_name.to_string()),
        text_edit: insert_range.map(|range| {
            CompletionTextEdit::Edit(TextEdit {
                range,
                new_text: feature_name.to_string(),
            })
        }),
        sort_text: Some(feature_name.to_string()),
        ..Default::default()
    }
}

/// Maximum number of version completions to show (matches Code Actions limit).
const MAX_COMPLETION_VERSIONS: usize = 5;

/// Checks whether `prefix` has an acceptable length (2 to 200 characters, inclusive) for
/// triggering a package-name completion search.
///
/// Length is measured in Unicode scalar values (`chars().count()`), not bytes, so a
/// multi-byte prefix (e.g. CJK) is bounded by how many characters the user typed rather
/// than how many bytes those characters happen to occupy.
///
/// # Examples
///
/// ```
/// # use deps_core::completion::is_valid_completion_prefix_len;
/// assert!(!is_valid_completion_prefix_len("a")); // 1 char, too short
/// assert!(is_valid_completion_prefix_len("ab")); // 2 chars, accepted
///
/// // "日" is 1 char / 3 bytes: rejected despite being >= 2 bytes.
/// assert!(!is_valid_completion_prefix_len("日"));
/// // "日本" is 2 chars / 6 bytes: accepted.
/// assert!(is_valid_completion_prefix_len("日本"));
/// ```
#[must_use]
pub fn is_valid_completion_prefix_len(prefix: &str) -> bool {
    (2..=200).contains(&prefix.chars().count())
}

/// Generic package name completion using any `Registry` implementation.
///
/// Searches the registry for packages matching `prefix` and returns up to `limit`
/// completion items, each with its `textEdit` set to replace `insert_range`. Returns
/// empty vec if `prefix` is shorter than 2 characters or longer than 200 characters.
/// A result whose name fails [`build_package_completion`]'s [`crate::is_safe_package_name`]
/// gate is silently dropped rather than surfaced as an error, matching the fallback-search
/// completion builder's convention (`create_package_completion_item` in `deps-lsp`).
pub async fn complete_package_names_generic(
    registry: &dyn crate::Registry,
    prefix: &str,
    limit: usize,
    insert_range: Range,
) -> Vec<CompletionItem> {
    if !is_valid_completion_prefix_len(prefix) {
        return vec![];
    }

    let results = match registry.search(prefix, limit).await {
        Ok(r) => r,
        Err(e) => {
            tracing::warn!("Registry search failed for '{}': {}", prefix, e);
            return vec![];
        }
    };

    results
        .into_iter()
        .filter_map(|metadata| build_package_completion(metadata.as_ref(), insert_range))
        .collect()
}

/// Generic version completion logic used by all ecosystems.
///
/// Filters versions by prefix (stripping ecosystem-specific operators),
/// hides yanked/deprecated versions, returns up to 5 completion items.
///
/// # Arguments
///
/// * `registry` - Package registry to fetch versions from
/// * `package_name` - Name of the package
/// * `prefix` - Partial version string typed by user (may include operators)
/// * `operator_chars` - Ecosystem-specific version operators to strip (e.g., `&['^', '~']`)
///
/// # Returns
///
/// Up to 5 completion items for non-yanked versions, filtered by prefix.
/// If no versions match the prefix, returns up to 5 non-yanked versions.
/// The first item (latest version) is marked with "(latest)" suffix and preselected.
///
/// # Examples
///
/// ```no_run
/// use deps_core::completion::complete_versions_generic;
/// use deps_core::PackageName;
///
/// # async fn example(registry: &dyn deps_core::Registry) {
/// let freshness = deps_core::FreshnessSettings::default();
///
/// // Cargo: strip ^, ~, =, <, > operators
/// let items = complete_versions_generic(
///     registry,
///     &PackageName::new("serde"),
///     "^1.0",
///     &['^', '~', '=', '<', '>'],
///     freshness,
/// ).await;
///
/// // Go: no operators to strip
/// let items = complete_versions_generic(
///     registry,
///     &PackageName::new("github.com/gin-gonic/gin"),
///     "v1.9",
///     &[],
///     freshness,
/// ).await;
/// # }
/// ```
pub async fn complete_versions_generic(
    registry: &dyn crate::Registry,
    package_name: &PackageName,
    prefix: &str,
    operator_chars: &[char],
    freshness: FreshnessSettings,
) -> Vec<CompletionItem> {
    let versions = match registry.get_versions_with(package_name, freshness).await {
        Ok(v) => v,
        Err(e) => {
            tracing::warn!("Failed to fetch versions for '{}': {}", package_name, e);
            return vec![];
        }
    };

    let clean_prefix = prefix.trim_start_matches(operator_chars).trim();

    // Filter versions by prefix first
    let filtered_versions: Vec<_> = versions
        .iter()
        .filter(|v| v.version_string().as_str().starts_with(clean_prefix))
        .collect();

    // Use filtered or all versions, prepare_version_display_items will handle yanked filtering
    let display_items = if filtered_versions.is_empty() {
        prepare_version_display_items(&versions, package_name)
    } else {
        prepare_version_display_items(&filtered_versions, package_name)
    };

    // Don't provide text_edit range - let LSP client insert at cursor position
    let now = PublishTime::now();
    display_items
        .iter()
        // A registry-reported version is exactly as untrusted as the one fed into
        // `format_version_replacing`/`format_version_for_text_edit` (see
        // `is_safe_version_string`'s doc comment) — a completion item's
        // `insert_text`/`text_edit` is a manifest-write sink too, and fires on
        // ordinary typing rather than a quickfix click.
        .filter(|item| {
            let safe = is_safe_version_string(item.version.as_str());
            if !safe {
                warn_rejected_value(
                    "is_safe_version_string",
                    "version completion item",
                    item.version.as_str(),
                );
            }
            safe
        })
        .map(|item| build_version_completion(item, None, now, freshness.enabled))
        .collect()
}

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

    fn pkg(s: &str) -> PackageName {
        PackageName::new(s)
    }

    // Mock implementations for testing

    struct MockDependency {
        name: crate::PackageName,
        name_range: Range,
        version_range: Option<Range>,
        features_range: Option<Range>,
    }

    impl crate::ecosystem::Dependency for MockDependency {
        fn name(&self) -> &crate::PackageName {
            &self.name
        }

        fn name_range(&self) -> Range {
            self.name_range
        }

        fn version_requirement(&self) -> Option<&crate::VersionReq> {
            static VERSION_REQ: std::sync::LazyLock<crate::VersionReq> =
                std::sync::LazyLock::new(|| crate::VersionReq::new("1.0"));
            Some(&VERSION_REQ)
        }

        fn version_range(&self) -> Option<Range> {
            self.version_range
        }

        fn features_range(&self) -> Option<Range> {
            self.features_range
        }

        fn source(&self) -> crate::parser::DependencySource {
            crate::parser::DependencySource::Registry
        }

        fn as_any(&self) -> &dyn Any {
            self
        }
    }

    struct MockParseResult {
        dependencies: Vec<MockDependency>,
    }

    impl ParseResult for MockParseResult {
        fn dependencies(&self) -> Vec<&dyn crate::ecosystem::Dependency> {
            self.dependencies
                .iter()
                .map(|d| d as &dyn crate::ecosystem::Dependency)
                .collect()
        }

        fn workspace_root(&self) -> Option<&std::path::Path> {
            None
        }

        fn uri(&self) -> &tower_lsp_server::ls_types::Uri {
            static URL: std::sync::LazyLock<tower_lsp_server::ls_types::Uri> =
                std::sync::LazyLock::new(|| "file:///test/Cargo.toml".parse().unwrap());
            &URL
        }

        fn as_any(&self) -> &dyn Any {
            self
        }
    }

    struct MockVersion {
        version: ConcreteVersion,
        yanked: bool,
        prerelease: bool,
    }

    impl crate::registry::Version for MockVersion {
        fn version_string(&self) -> &ConcreteVersion {
            &self.version
        }

        fn removal_status(&self) -> crate::RemovalStatus {
            crate::RemovalStatus::from_yanked(self.yanked)
        }

        fn is_prerelease(&self) -> bool {
            self.prerelease
        }

        fn as_any(&self) -> &dyn Any {
            self
        }
    }

    /// A [`MockVersion`] variant that reports a `published_at`, used only by the
    /// freshness-specific tests below — kept separate so the many pre-existing
    /// `MockVersion` literals do not need a new field added to every call site.
    struct MockVersionWithAge {
        version: ConcreteVersion,
        published_at: Option<PublishTime>,
    }

    impl crate::registry::Version for MockVersionWithAge {
        fn version_string(&self) -> &ConcreteVersion {
            &self.version
        }

        fn published_at(&self) -> Option<PublishTime> {
            self.published_at
        }

        fn as_any(&self) -> &dyn Any {
            self
        }
    }

    #[derive(Clone)]
    struct MockMetadata {
        name: crate::PackageName,
        description: Option<String>,
        repository: Option<String>,
        documentation: Option<String>,
        latest_version: ConcreteVersion,
    }

    impl crate::registry::Metadata for MockMetadata {
        fn name(&self) -> &crate::PackageName {
            &self.name
        }

        fn description(&self) -> Option<&str> {
            self.description.as_deref()
        }

        fn repository(&self) -> Option<&str> {
            self.repository.as_deref()
        }

        fn documentation(&self) -> Option<&str> {
            self.documentation.as_deref()
        }

        fn latest_version(&self) -> &ConcreteVersion {
            &self.latest_version
        }

        fn as_any(&self) -> &dyn Any {
            self
        }
    }

    struct MockRegistry {
        versions: Vec<MockVersion>,
    }

    impl crate::Registry for MockRegistry {
        fn get_versions<'a>(
            &'a self,
            _package_name: &'a crate::PackageName,
        ) -> crate::ecosystem::BoxFuture<'a, crate::error::Result<Vec<Box<dyn crate::Version>>>>
        {
            let versions: Vec<Box<dyn crate::Version>> = self
                .versions
                .iter()
                .map(|v| {
                    Box::new(MockVersion {
                        version: v.version.clone(),
                        yanked: v.yanked,
                        prerelease: v.prerelease,
                    }) as Box<dyn crate::Version>
                })
                .collect();
            Box::pin(async move { Ok(versions) })
        }

        fn get_latest_matching<'a>(
            &'a self,
            _name: &'a crate::PackageName,
            _req: &'a crate::VersionReq,
        ) -> crate::ecosystem::BoxFuture<'a, crate::error::Result<Option<Box<dyn crate::Version>>>>
        {
            Box::pin(async move { Ok(None) })
        }

        fn search<'a>(
            &'a self,
            _query: &'a str,
            _limit: usize,
        ) -> crate::ecosystem::BoxFuture<'a, crate::error::Result<Vec<Box<dyn crate::Metadata>>>>
        {
            Box::pin(async move { Ok(vec![]) })
        }

        fn as_any(&self) -> &dyn Any {
            self
        }
    }

    /// Registry stub whose `search` returns preconfigured metadata, used to verify
    /// [`complete_package_names_generic`] threads its `insert_range` into every
    /// returned item's `text_edit` instead of defaulting to a placeholder range.
    struct MockSearchRegistry {
        results: Vec<MockMetadata>,
    }

    impl crate::Registry for MockSearchRegistry {
        fn get_versions<'a>(
            &'a self,
            _package_name: &'a crate::PackageName,
        ) -> crate::ecosystem::BoxFuture<'a, crate::error::Result<Vec<Box<dyn crate::Version>>>>
        {
            Box::pin(async move { Ok(vec![]) })
        }

        fn get_latest_matching<'a>(
            &'a self,
            _name: &'a crate::PackageName,
            _req: &'a crate::VersionReq,
        ) -> crate::ecosystem::BoxFuture<'a, crate::error::Result<Option<Box<dyn crate::Version>>>>
        {
            Box::pin(async move { Ok(None) })
        }

        fn search<'a>(
            &'a self,
            _query: &'a str,
            _limit: usize,
        ) -> crate::ecosystem::BoxFuture<'a, crate::error::Result<Vec<Box<dyn crate::Metadata>>>>
        {
            let results: Vec<Box<dyn crate::Metadata>> = self
                .results
                .iter()
                .cloned()
                .map(|m| Box::new(m) as Box<dyn crate::Metadata>)
                .collect();
            Box::pin(async move { Ok(results) })
        }

        fn as_any(&self) -> &dyn Any {
            self
        }
    }

    #[tokio::test]
    async fn test_complete_package_names_generic_uses_insert_range() {
        let registry = MockSearchRegistry {
            results: vec![MockMetadata {
                name: pkg("serde"),
                description: None,
                repository: None,
                documentation: None,
                latest_version: "1.0.0".into(),
            }],
        };

        let insert_range = Range {
            start: Position {
                line: 3,
                character: 4,
            },
            end: Position {
                line: 3,
                character: 7,
            },
        };

        let items = complete_package_names_generic(&registry, "ser", 5, insert_range).await;

        assert_eq!(items.len(), 1);
        assert_ne!(insert_range, Range::default());
        match &items[0].text_edit {
            Some(CompletionTextEdit::Edit(edit)) => {
                assert_eq!(edit.range, insert_range);
                assert_eq!(edit.new_text, "serde");
            }
            other => panic!("Expected a textEdit::Edit, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn test_complete_package_names_generic_short_prefix_empty() {
        let registry = MockSearchRegistry {
            results: vec![MockMetadata {
                name: pkg("serde"),
                description: None,
                repository: None,
                documentation: None,
                latest_version: "1.0.0".into(),
            }],
        };

        let items = complete_package_names_generic(&registry, "s", 5, Range::default()).await;
        assert!(items.is_empty());
    }

    #[tokio::test]
    async fn test_complete_package_names_generic_drops_unsafe_names() {
        // A registry search can return a mix of safe and malicious/compromised
        // results (e.g. a Gradle Groovy breakout name); only the safe ones should
        // survive into the returned completion list.
        let registry = MockSearchRegistry {
            results: vec![
                MockMetadata {
                    name: pkg("serde"),
                    description: None,
                    repository: None,
                    documentation: None,
                    latest_version: "1.0.0".into(),
                },
                MockMetadata {
                    name: pkg("guava'); System.exit(1); //"),
                    description: None,
                    repository: None,
                    documentation: None,
                    latest_version: "1.0.0".into(),
                },
            ],
        };

        let items = complete_package_names_generic(&registry, "gua", 5, Range::default()).await;

        assert_eq!(items.len(), 1);
        assert_eq!(items[0].label, "serde");
    }

    #[test]
    fn test_is_valid_completion_prefix_len_ascii_short_rejected() {
        assert!(!is_valid_completion_prefix_len("a"));
    }

    #[test]
    fn test_is_valid_completion_prefix_len_one_char_cjk_rejected() {
        // "日" is 1 char but 3 bytes — a byte-length guard would wrongly accept it.
        assert!(!is_valid_completion_prefix_len("日"));
    }

    #[test]
    fn test_is_valid_completion_prefix_len_two_char_cjk_accepted() {
        // "日本" is 2 chars but 6 bytes — must be accepted under char-count semantics.
        assert!(is_valid_completion_prefix_len("日本"));
    }

    #[tokio::test]
    async fn test_complete_package_names_generic_one_char_cjk_prefix_empty() {
        // "日" is 1 char but 3 bytes — a byte-length guard would wrongly accept it.
        let registry = MockSearchRegistry {
            results: vec![MockMetadata {
                name: pkg("serde"),
                description: None,
                repository: None,
                documentation: None,
                latest_version: "1.0.0".into(),
            }],
        };

        let items = complete_package_names_generic(&registry, "日", 5, Range::default()).await;
        assert!(items.is_empty());
    }

    #[tokio::test]
    async fn test_complete_package_names_generic_two_char_cjk_prefix_accepted() {
        // "日本" is 2 chars / 6 bytes — must pass the guard and reach the registry search.
        let registry = MockSearchRegistry {
            results: vec![MockMetadata {
                name: pkg("serde"),
                description: None,
                repository: None,
                documentation: None,
                latest_version: "1.0.0".into(),
            }],
        };

        let items = complete_package_names_generic(&registry, "日本", 5, Range::default()).await;
        assert_eq!(items.len(), 1);
    }

    // Context detection tests

    #[test]
    fn test_detect_package_name_context_at_start() {
        let parse_result = MockParseResult {
            dependencies: vec![MockDependency {
                name: "serde".into(),
                name_range: Range {
                    start: Position {
                        line: 0,
                        character: 0,
                    },
                    end: Position {
                        line: 0,
                        character: 5,
                    },
                },
                version_range: None,
                features_range: None,
            }],
        };

        let content = "serde";
        let position = Position {
            line: 0,
            character: 0,
        };

        let context = detect_completion_context(&parse_result, position, content);

        match context {
            CompletionContext::PackageName { prefix, range } => {
                assert_eq!(prefix, "");
                assert_eq!(
                    range,
                    Range {
                        start: Position {
                            line: 0,
                            character: 0
                        },
                        end: Position {
                            line: 0,
                            character: 5
                        },
                    }
                );
            }
            _ => panic!("Expected PackageName context, got {:?}", context),
        }
    }

    #[test]
    fn test_detect_package_name_context_partial() {
        let parse_result = MockParseResult {
            dependencies: vec![MockDependency {
                name: "serde".into(),
                name_range: Range {
                    start: Position {
                        line: 0,
                        character: 0,
                    },
                    end: Position {
                        line: 0,
                        character: 5,
                    },
                },
                version_range: None,
                features_range: None,
            }],
        };

        let content = "serde";
        let position = Position {
            line: 0,
            character: 3,
        };

        let context = detect_completion_context(&parse_result, position, content);

        match context {
            CompletionContext::PackageName { prefix, range } => {
                assert_eq!(prefix, "ser");
                assert_eq!(
                    range,
                    Range {
                        start: Position {
                            line: 0,
                            character: 0
                        },
                        end: Position {
                            line: 0,
                            character: 5
                        },
                    }
                );
            }
            _ => panic!("Expected PackageName context, got {:?}", context),
        }
    }

    #[test]
    fn test_detect_package_name_context_one_past_end_does_not_widen_range() {
        // `position_in_range` tolerates a request one column past `name_range.end`,
        // but the text right after a name is often structurally significant (a
        // closing quote, the space before `=`, ...) — widening the range to reach
        // a position past the name would consume that character once a client
        // applies the edit, corrupting the manifest. So a one-past-end position
        // must NOT produce a PackageName context (there is nothing else on this
        // line for it to match either, so it falls through to `None`).
        let parse_result = MockParseResult {
            dependencies: vec![MockDependency {
                name: "serde".into(),
                name_range: Range {
                    start: Position {
                        line: 0,
                        character: 0,
                    },
                    end: Position {
                        line: 0,
                        character: 5,
                    },
                },
                version_range: None,
                features_range: None,
            }],
        };

        let content = "serde";
        let position = Position {
            line: 0,
            character: 6,
        };

        let context = detect_completion_context(&parse_result, position, content);

        assert_eq!(context, CompletionContext::None);
    }

    #[test]
    fn test_detect_package_name_context_exactly_at_end_matches_unwidened_range() {
        // The cursor sitting exactly at `name_range.end` (right after the last
        // typed character, no tolerance needed) must still fire PackageName with
        // the name's own unwidened range.
        let parse_result = MockParseResult {
            dependencies: vec![MockDependency {
                name: "serde".into(),
                name_range: Range {
                    start: Position {
                        line: 0,
                        character: 0,
                    },
                    end: Position {
                        line: 0,
                        character: 5,
                    },
                },
                version_range: None,
                features_range: None,
            }],
        };

        let content = "serde";
        let position = Position {
            line: 0,
            character: 5,
        };

        let context = detect_completion_context(&parse_result, position, content);

        match context {
            CompletionContext::PackageName { prefix, range } => {
                assert_eq!(prefix, "serde");
                assert_eq!(
                    range,
                    Range {
                        start: Position {
                            line: 0,
                            character: 0
                        },
                        end: Position {
                            line: 0,
                            character: 5
                        },
                    }
                );
            }
            _ => panic!("Expected PackageName context, got {:?}", context),
        }
    }

    #[test]
    fn test_detect_package_name_context_fires_for_ecosystem_supplied_partial_name() {
        // #310 (deps-deno): a scheme-prefixed but structurally incomplete specifier value
        // ("jsr:", "jsr:@", "jsr:@std", "jsr:@std/") has no complete name to parse, yet
        // completion must still fire while the user is mid-keystroke. This is deliberately
        // NOT solved by adding jsr:/npm:-specific logic here — `detect_completion_context`
        // stays ecosystem-agnostic. Instead, `deps-deno`'s parser (mirroring `deps-npm`,
        // which always builds a `Dependency` from a `dependencies` object key regardless of
        // scope completeness) supplies a `Dependency` whose `name`/`name_range` cover the
        // partial text directly; the existing range-containment check below requires no
        // change to handle it. This test documents and locks in that consistency.
        let parse_result = MockParseResult {
            dependencies: vec![MockDependency {
                name: "jsr:@std/".into(),
                name_range: Range {
                    start: Position {
                        line: 0,
                        character: 0,
                    },
                    end: Position {
                        line: 0,
                        character: 9,
                    },
                },
                version_range: None,
                features_range: None,
            }],
        };

        let content = "jsr:@std/";
        let position = Position {
            line: 0,
            character: 9,
        };

        let context = detect_completion_context(&parse_result, position, content);

        match context {
            CompletionContext::PackageName { prefix, range } => {
                assert_eq!(prefix, "jsr:@std/");
                assert_eq!(range, parse_result.dependencies[0].name_range);
            }
            other => panic!("Expected PackageName context, got {other:?}"),
        }
    }

    #[test]
    fn test_detect_version_context() {
        let parse_result = MockParseResult {
            dependencies: vec![MockDependency {
                name: "serde".into(),
                name_range: Range {
                    start: Position {
                        line: 0,
                        character: 0,
                    },
                    end: Position {
                        line: 0,
                        character: 5,
                    },
                },
                version_range: Some(Range {
                    start: Position {
                        line: 0,
                        character: 9,
                    },
                    end: Position {
                        line: 0,
                        character: 14,
                    },
                }),
                features_range: None,
            }],
        };

        let content = r#"serde = "1.0.1""#;
        let position = Position {
            line: 0,
            character: 11,
        };

        let context = detect_completion_context(&parse_result, position, content);

        match context {
            CompletionContext::Version {
                package_name,
                prefix,
            } => {
                assert_eq!(package_name, "serde");
                assert_eq!(prefix, "1.");
            }
            _ => panic!("Expected Version context, got {:?}", context),
        }
    }

    #[test]
    fn test_detect_no_context_before_dependencies() {
        let parse_result = MockParseResult {
            dependencies: vec![MockDependency {
                name: "serde".into(),
                name_range: Range {
                    start: Position {
                        line: 5,
                        character: 0,
                    },
                    end: Position {
                        line: 5,
                        character: 5,
                    },
                },
                version_range: None,
                features_range: None,
            }],
        };

        let content = "[dependencies]\nserde";
        let position = Position {
            line: 0,
            character: 10,
        };

        let context = detect_completion_context(&parse_result, position, content);

        assert_eq!(context, CompletionContext::None);
    }

    #[test]
    fn test_detect_no_context_invalid_position() {
        let parse_result = MockParseResult {
            dependencies: vec![],
        };

        let content = "";
        let position = Position {
            line: 100,
            character: 100,
        };

        let context = detect_completion_context(&parse_result, position, content);

        assert_eq!(context, CompletionContext::None);
    }

    // Prefix extraction tests

    #[test]
    fn test_extract_prefix_at_start() {
        let content = "serde";
        let position = Position {
            line: 0,
            character: 0,
        };
        let range = Range {
            start: Position {
                line: 0,
                character: 0,
            },
            end: Position {
                line: 0,
                character: 5,
            },
        };

        let prefix = extract_prefix(content, position, range);
        assert_eq!(prefix, "");
    }

    #[test]
    fn test_extract_prefix_partial() {
        let content = "serde";
        let position = Position {
            line: 0,
            character: 3,
        };
        let range = Range {
            start: Position {
                line: 0,
                character: 0,
            },
            end: Position {
                line: 0,
                character: 5,
            },
        };

        let prefix = extract_prefix(content, position, range);
        assert_eq!(prefix, "ser");
    }

    #[test]
    fn test_extract_prefix_with_quotes() {
        let content = r#"serde = "1.0""#;
        let position = Position {
            line: 0,
            character: 11,
        };
        let range = Range {
            start: Position {
                line: 0,
                character: 9,
            },
            end: Position {
                line: 0,
                character: 13,
            },
        };

        let prefix = extract_prefix(content, position, range);
        assert_eq!(prefix, "1.");
    }

    #[test]
    fn test_extract_prefix_empty() {
        let content = r#"serde = """#;
        let position = Position {
            line: 0,
            character: 9,
        };
        let range = Range {
            start: Position {
                line: 0,
                character: 9,
            },
            end: Position {
                line: 0,
                character: 11,
            },
        };

        let prefix = extract_prefix(content, position, range);
        assert_eq!(prefix, "");
    }

    #[test]
    fn test_extract_prefix_version_with_operator() {
        let content = r#"serde = "^1.0""#;
        let position = Position {
            line: 0,
            character: 12,
        };
        let range = Range {
            start: Position {
                line: 0,
                character: 9,
            },
            end: Position {
                line: 0,
                character: 14,
            },
        };

        let prefix = extract_prefix(content, position, range);
        assert_eq!(prefix, "^1.");
    }

    // CompletionItem builder tests

    #[test]
    fn test_build_package_completion_full() {
        let metadata = MockMetadata {
            name: "serde".into(),
            description: Some("Serialization framework".to_string()),
            repository: Some("https://github.com/serde-rs/serde".to_string()),
            documentation: Some("https://docs.rs/serde".to_string()),
            latest_version: "1.0.214".into(),
        };

        let range = Range::default();
        let item = build_package_completion(&metadata, range).unwrap();

        assert_eq!(item.label, "serde");
        assert_eq!(item.kind, Some(CompletionItemKind::MODULE));
        assert_eq!(item.detail, Some("v1.0.214".to_string()));
        assert!(matches!(
            item.documentation,
            Some(Documentation::MarkupContent(_))
        ));

        if let Some(Documentation::MarkupContent(content)) = item.documentation {
            assert!(content.value.contains("**serde** v1\\.0\\.214"));
            assert!(content.value.contains("Serialization framework"));
            assert!(content.value.contains("Repository"));
            assert!(content.value.contains("Documentation"));
        }
    }

    #[test]
    fn test_build_package_completion_minimal() {
        let metadata = MockMetadata {
            name: "test-pkg".into(),
            description: None,
            repository: None,
            documentation: None,
            latest_version: "0.1.0".into(),
        };

        let range = Range::default();
        let item = build_package_completion(&metadata, range).unwrap();

        assert_eq!(item.label, "test-pkg");
        assert_eq!(item.detail, Some("v0.1.0".to_string()));

        if let Some(Documentation::MarkupContent(content)) = item.documentation {
            assert!(content.value.contains("**test\\-pkg** v0\\.1\\.0"));
            assert!(!content.value.contains("Repository"));
        }
    }

    #[test]
    fn test_build_package_completion_empty_latest_version() {
        let metadata = MockMetadata {
            name: "swift-nio".into(),
            description: None,
            repository: None,
            documentation: None,
            latest_version: String::new().into(),
        };

        let range = Range::default();
        let item = build_package_completion(&metadata, range).unwrap();

        assert_eq!(item.detail, None);

        if let Some(Documentation::MarkupContent(content)) = item.documentation {
            assert!(content.value.contains("**swift\\-nio**"));
            assert!(!content.value.trim_end().ends_with('v'));
        }
    }

    #[test]
    fn test_build_package_completion_escapes_description_markdown() {
        let metadata = MockMetadata {
            name: "test-pkg".into(),
            description: Some("Fast *bold* _italic_ [link](evil) `code`".to_string()),
            repository: None,
            documentation: None,
            latest_version: "1.0.0".into(),
        };

        let range = Range::default();
        let item = build_package_completion(&metadata, range).unwrap();

        if let Some(Documentation::MarkupContent(content)) = item.documentation {
            assert!(!content.value.contains("*bold*"));
            assert!(!content.value.contains("_italic_"));
            assert!(!content.value.contains("[link](evil)"));
            assert!(content.value.contains(r"\*bold\*"));
            assert!(content.value.contains(r"\[link\]\(evil\)"));
        } else {
            panic!("Expected MarkupContent documentation");
        }
    }

    #[test]
    fn test_build_package_completion_escapes_repository_link_breakout() {
        // A malicious repository URL that attempts to close the `[Repository](...)`
        // link early and splice in a new, attacker-controlled markdown link.
        let malicious_repo = "https://legit.example)[Click here](https://evil.example";
        let metadata = MockMetadata {
            name: "test-pkg".into(),
            description: None,
            repository: Some(malicious_repo.to_string()),
            documentation: None,
            latest_version: "1.0.0".into(),
        };

        let range = Range::default();
        let item = build_package_completion(&metadata, range).unwrap();

        if let Some(Documentation::MarkupContent(content)) = item.documentation {
            assert!(!content.value.contains(")[Click here]("));
            assert!(content.value.contains(r"\)\[Click here\]\("));
        } else {
            panic!("Expected MarkupContent documentation");
        }
    }

    #[test]
    fn test_build_package_completion_escapes_documentation_link_breakout() {
        let malicious_docs = "https://legit.example)[Click here](https://evil.example";
        let metadata = MockMetadata {
            name: "test-pkg".into(),
            description: None,
            repository: None,
            documentation: Some(malicious_docs.to_string()),
            latest_version: "1.0.0".into(),
        };

        let range = Range::default();
        let item = build_package_completion(&metadata, range).unwrap();

        if let Some(Documentation::MarkupContent(content)) = item.documentation {
            assert!(!content.value.contains(")[Click here]("));
            assert!(content.value.contains(r"\)\[Click here\]\("));
        } else {
            panic!("Expected MarkupContent documentation");
        }
    }

    #[test]
    fn test_build_package_completion_truncate_then_escape_no_dangling_backslash() {
        // A special character sitting right at the 200-char truncation boundary:
        // truncating BEFORE escaping (correct order) keeps the escape sequence
        // whole; escaping before truncating would risk cutting between the
        // backslash and the character it escapes, leaving a dangling `\`.
        let mut desc = "a".repeat(199);
        desc.push('*');
        desc.push_str(&"b".repeat(50));

        let metadata = MockMetadata {
            name: "test-pkg".into(),
            description: Some(desc),
            repository: None,
            documentation: None,
            latest_version: "1.0.0".into(),
        };

        let range = Range::default();
        let item = build_package_completion(&metadata, range).unwrap();

        if let Some(Documentation::MarkupContent(content)) = item.documentation {
            let lines: Vec<_> = content.value.lines().collect();
            let desc_line = lines[2];
            assert!(desc_line.ends_with(r"\*..."), "got: {desc_line}");
            assert!(
                !desc_line.ends_with(r"\..."),
                "dangling backslash: {desc_line}"
            );
        } else {
            panic!("Expected MarkupContent documentation");
        }
    }

    #[test]
    fn test_build_package_completion_escapes_malicious_version_link_breakout() {
        // A crafted latest-version string attempting to close the leading bold span
        // and splice in a live, attacker-controlled markdown link — same injection
        // class as description/repository/documentation. `latest_version` isn't
        // gated by `is_safe_package_name` (that only guards `name`), so it must
        // still be escaped in the rendered documentation.
        let malicious_latest = "1.0.0)[click](https://evil.example";
        let metadata = MockMetadata {
            name: "test-pkg".into(),
            description: None,
            repository: None,
            documentation: None,
            latest_version: malicious_latest.into(),
        };

        let range = Range::default();
        let item = build_package_completion(&metadata, range).unwrap();

        if let Some(Documentation::MarkupContent(content)) = item.documentation {
            assert!(!content.value.contains(")[click]("));
            assert!(
                content
                    .value
                    .contains(r"1\.0\.0\)\[click\]\(https\:\/\/evil\.example")
            );
        } else {
            panic!("Expected MarkupContent documentation");
        }
    }

    #[test]
    fn test_build_package_completion_rejects_unsafe_name() {
        // A crafted package name attempting to close the leading bold span and
        // splice in a live, attacker-controlled markdown link — reachable simply
        // by typing a package-name prefix (no malicious manifest required). Such
        // a name fails `is_safe_package_name` (structural characters like `[`,
        // `]`, `(`, `)`, `*`, and space are not in its allowlist), so the whole
        // completion item must be dropped rather than built with unsafe text.
        let malicious_name = "a** [Official Download](https://evil.example) **b";
        let metadata = MockMetadata {
            name: malicious_name.into(),
            description: None,
            repository: None,
            documentation: None,
            latest_version: "1.0.0".into(),
        };

        let range = Range::default();
        assert!(build_package_completion(&metadata, range).is_none());
    }

    #[test]
    fn test_build_package_completion_benign_repository_url_round_trips() {
        // Backslash-escaping ASCII punctuation is visually inert on render (CommonMark
        // strips the backslash for the literal character), so a normal URL must still
        // render as the same, unmangled link once those escapes are stripped.
        let metadata = MockMetadata {
            name: "test-pkg".into(),
            description: None,
            repository: Some("https://github.com/owner/repo".to_string()),
            documentation: None,
            latest_version: "1.0.0".into(),
        };

        let range = Range::default();
        let item = build_package_completion(&metadata, range).unwrap();

        if let Some(Documentation::MarkupContent(content)) = item.documentation {
            let unescaped: String = content.value.chars().filter(|&c| c != '\\').collect();
            assert!(unescaped.contains("[Repository](https://github.com/owner/repo)"));
        } else {
            panic!("Expected MarkupContent documentation");
        }
    }

    #[test]
    fn test_build_package_completion_escapes_html_in_description() {
        let metadata = MockMetadata {
            name: "test-pkg".into(),
            description: Some("<img src=x onerror=alert(1)>".to_string()),
            repository: None,
            documentation: None,
            latest_version: "1.0.0".into(),
        };

        let range = Range::default();
        let item = build_package_completion(&metadata, range).unwrap();

        if let Some(Documentation::MarkupContent(content)) = item.documentation {
            assert!(!content.value.contains("<img src=x onerror=alert(1)>"));
            assert!(
                content
                    .value
                    .contains(r"\<img src\=x onerror\=alert\(1\)\>")
            );
        } else {
            panic!("Expected MarkupContent documentation");
        }
    }

    #[test]
    fn test_build_package_completion_empty_description() {
        let metadata = MockMetadata {
            name: "test-pkg".into(),
            description: Some(String::new()),
            repository: None,
            documentation: None,
            latest_version: "1.0.0".into(),
        };

        let range = Range::default();
        let item = build_package_completion(&metadata, range).unwrap();

        if let Some(Documentation::MarkupContent(content)) = item.documentation {
            assert!(content.value.starts_with(r"**test\-pkg** v1\.0\.0"));
        } else {
            panic!("Expected MarkupContent documentation");
        }
    }

    #[test]
    fn test_build_package_completion_truncate_snaps_multibyte_boundary() {
        // A 3-byte character straddling the 200-byte truncation boundary: truncation
        // must snap back to a valid char boundary rather than panicking mid-codepoint,
        // proving `floor_char_boundary` is exercised as a genuine non-identity op
        // (unlike an all-ASCII description, where every byte offset is already a
        // char boundary).
        let mut desc = "a".repeat(199);
        desc.push('日'); // 3 bytes, occupies byte offsets 199..202 — straddles byte 200
        desc.push('*');
        desc.push_str(&"b".repeat(50));

        let metadata = MockMetadata {
            name: "test-pkg".into(),
            description: Some(desc),
            repository: None,
            documentation: None,
            latest_version: "1.0.0".into(),
        };

        let range = Range::default();
        let item = build_package_completion(&metadata, range).unwrap();

        if let Some(Documentation::MarkupContent(content)) = item.documentation {
            let lines: Vec<_> = content.value.lines().collect();
            let desc_line = lines[2];
            assert!(!desc_line.contains('日'));
            assert!(desc_line.ends_with("..."));
        } else {
            panic!("Expected MarkupContent documentation");
        }
    }

    #[test]
    fn test_build_version_completion_stable() {
        let version = MockVersion {
            version: "1.0.0".into(),
            yanked: false,
            prerelease: false,
        };

        let now = PublishTime::now();
        let display_item = VersionDisplayItem::new(&version, &pkg("serde"), 0, false);
        let item = build_version_completion(&display_item, None, now, true);

        assert_eq!(item.label, "1.0.0");
        assert_eq!(item.kind, Some(CompletionItemKind::VALUE));
        assert_eq!(item.detail, Some("Update serde to 1.0.0".to_string()));
        assert_eq!(item.documentation, None);
        assert_eq!(item.preselect, Some(false));
        assert_eq!(item.sort_text, Some("00000".to_string()));
        assert_eq!(item.text_edit, None); // No text_edit when range is None
    }

    #[test]
    fn test_build_version_completion_latest() {
        let version = MockVersion {
            version: "1.0.0".into(),
            yanked: false,
            prerelease: false,
        };

        let now = PublishTime::now();
        let display_item = VersionDisplayItem::new(&version, &pkg("serde"), 0, true);
        let item = build_version_completion(&display_item, None, now, true);

        assert_eq!(item.label, "1.0.0 (latest)");
        assert_eq!(item.kind, Some(CompletionItemKind::VALUE));
        assert_eq!(item.detail, Some("Update serde to 1.0.0".to_string()));
        assert_eq!(item.documentation, None);
        assert_eq!(item.preselect, Some(true));
        assert_eq!(item.sort_text, Some("00000".to_string()));
        assert_eq!(item.text_edit, None); // No text_edit when range is None
    }

    #[test]
    fn test_build_version_completion_not_latest() {
        let version = MockVersion {
            version: "0.9.0".into(),
            yanked: false,
            prerelease: false,
        };

        let now = PublishTime::now();
        let display_item = VersionDisplayItem::new(&version, &pkg("tokio"), 1, false);
        let item = build_version_completion(&display_item, None, now, true);

        assert_eq!(item.label, "0.9.0");
        assert_eq!(item.detail, Some("Update tokio to 0.9.0".to_string()));
        assert_eq!(item.documentation, None);
        assert_eq!(item.preselect, Some(false));
        assert_eq!(item.sort_text, Some("00001".to_string()));
        assert_eq!(item.text_edit, None); // No text_edit when range is None
    }

    #[test]
    fn test_build_version_completion_sort_order() {
        let v1 = MockVersion {
            version: "1.0.0".into(),
            yanked: false,
            prerelease: false,
        };
        let v2 = MockVersion {
            version: "0.9.0".into(),
            yanked: false,
            prerelease: false,
        };
        let v3 = MockVersion {
            version: "0.8.0".into(),
            yanked: false,
            prerelease: false,
        };

        let display_item1 = VersionDisplayItem::new(&v1, &pkg("test"), 0, true);
        let display_item2 = VersionDisplayItem::new(&v2, &pkg("test"), 1, false);
        let display_item3 = VersionDisplayItem::new(&v3, &pkg("test"), 2, false);
        let now = PublishTime::now();
        let item1 = build_version_completion(&display_item1, None, now, true);
        let item2 = build_version_completion(&display_item2, None, now, true);
        let item3 = build_version_completion(&display_item3, None, now, true);

        // Simple index-based sorting
        assert_eq!(item1.sort_text.as_ref().unwrap(), "00000");
        assert_eq!(item2.sort_text.as_ref().unwrap(), "00001");
        assert_eq!(item3.sort_text.as_ref().unwrap(), "00002");

        // First item should be preselected
        assert_eq!(item1.preselect, Some(true));
        assert_eq!(item2.preselect, Some(false));
        assert_eq!(item3.preselect, Some(false));
    }

    #[test]
    fn test_version_completion_semantic_ordering() {
        let versions = [
            MockVersion {
                version: "0.14.0".into(),
                yanked: false,
                prerelease: false,
            },
            MockVersion {
                version: "0.8.0".into(),
                yanked: false,
                prerelease: false,
            },
            MockVersion {
                version: "0.2.0".into(),
                yanked: false,
                prerelease: false,
            },
        ];

        let now = PublishTime::now();
        let items: Vec<_> = versions
            .iter()
            .enumerate()
            .map(|(idx, v)| {
                let display_item = VersionDisplayItem::new(v, &pkg("test"), idx, idx == 0);
                build_version_completion(&display_item, None, now, true)
            })
            .collect();

        assert_eq!(items[0].sort_text.as_ref().unwrap(), "00000");
        assert_eq!(items[1].sort_text.as_ref().unwrap(), "00001");
        assert_eq!(items[2].sort_text.as_ref().unwrap(), "00002");

        let mut sorted_items = items;
        sorted_items.sort_by(|a, b| {
            a.sort_text
                .as_ref()
                .unwrap()
                .cmp(b.sort_text.as_ref().unwrap())
        });

        assert_eq!(sorted_items[0].label, "0.14.0 (latest)");
        assert_eq!(sorted_items[1].label, "0.8.0");
        assert_eq!(sorted_items[2].label, "0.2.0");
    }

    #[test]
    fn test_version_completion_index_ordering() {
        let versions = ["1.20.0", "1.9.0", "1.2.0", "0.99.0", "0.50.0"];

        let now = PublishTime::now();
        let items: Vec<_> = versions
            .iter()
            .enumerate()
            .map(|(idx, ver)| {
                let v = MockVersion {
                    version: (*ver).into(),
                    yanked: false,
                    prerelease: false,
                };
                let display_item = VersionDisplayItem::new(&v, &pkg("test"), idx, idx == 0);
                build_version_completion(&display_item, None, now, true)
            })
            .collect();

        assert_eq!(items[0].sort_text.as_ref().unwrap(), "00000");
        assert_eq!(items[1].sort_text.as_ref().unwrap(), "00001");
        assert_eq!(items[2].sort_text.as_ref().unwrap(), "00002");
        assert_eq!(items[3].sort_text.as_ref().unwrap(), "00003");
        assert_eq!(items[4].sort_text.as_ref().unwrap(), "00004");

        let mut sorted_items = items;
        sorted_items.sort_by(|a, b| {
            a.sort_text
                .as_ref()
                .unwrap()
                .cmp(b.sort_text.as_ref().unwrap())
        });

        assert_eq!(sorted_items[0].label, "1.20.0 (latest)");
        assert_eq!(sorted_items[1].label, "1.9.0");
        assert_eq!(sorted_items[2].label, "1.2.0");
        assert_eq!(sorted_items[3].label, "0.99.0");
        assert_eq!(sorted_items[4].label, "0.50.0");
    }

    #[test]
    fn test_version_display_item_latest() {
        let version = MockVersion {
            version: "1.0.0".into(),
            yanked: false,
            prerelease: false,
        };

        let item = VersionDisplayItem::new(&version, &pkg("serde"), 0, true);

        assert_eq!(item.version, "1.0.0");
        assert_eq!(item.label, "1.0.0 (latest)");
        assert_eq!(item.description, "Update serde to 1.0.0");
        assert_eq!(item.index, 0);
        assert!(item.is_latest);
    }

    #[test]
    fn test_version_display_item_not_latest() {
        let version = MockVersion {
            version: "0.9.0".into(),
            yanked: false,
            prerelease: false,
        };

        let item = VersionDisplayItem::new(&version, &pkg("tokio"), 1, false);

        assert_eq!(item.version, "0.9.0");
        assert_eq!(item.label, "0.9.0");
        assert_eq!(item.description, "Update tokio to 0.9.0");
        assert_eq!(item.index, 1);
        assert!(!item.is_latest);
    }

    #[test]
    fn test_prepare_version_display_items_filters_yanked() {
        let versions: Vec<std::sync::Arc<dyn crate::Version>> = vec![
            std::sync::Arc::new(MockVersion {
                version: "1.0.0".into(),
                yanked: false,
                prerelease: false,
            }),
            std::sync::Arc::new(MockVersion {
                version: "0.9.0".into(),
                yanked: true,
                prerelease: false,
            }),
            std::sync::Arc::new(MockVersion {
                version: "0.8.0".into(),
                yanked: false,
                prerelease: false,
            }),
        ];

        let items = prepare_version_display_items(&versions, &pkg("test"));

        assert_eq!(items.len(), 2);
        assert_eq!(items[0].version, "1.0.0");
        assert_eq!(items[0].label, "1.0.0 (latest)");
        assert!(items[0].is_latest);
        assert_eq!(items[1].version, "0.8.0");
        assert_eq!(items[1].label, "0.8.0");
        assert!(!items[1].is_latest);
    }

    #[test]
    fn test_prepare_version_display_items_limits_to_5() {
        let versions: Vec<std::sync::Arc<dyn crate::Version>> = (0..10)
            .map(|i| {
                std::sync::Arc::new(MockVersion {
                    version: format!("1.0.{}", i).into(),
                    yanked: false,
                    prerelease: false,
                }) as std::sync::Arc<dyn crate::Version>
            })
            .collect();

        let items = prepare_version_display_items(&versions, &pkg("test"));

        assert_eq!(items.len(), 5);
        assert_eq!(items[0].version, "1.0.0");
        assert_eq!(items[0].label, "1.0.0 (latest)");
        assert_eq!(items[4].version, "1.0.4");
        assert_eq!(items[4].label, "1.0.4");
    }

    #[test]
    fn test_prepare_version_display_items_empty() {
        let versions: Vec<std::sync::Arc<dyn crate::Version>> = vec![];

        let items = prepare_version_display_items(&versions, &pkg("test"));

        assert_eq!(items.len(), 0);
    }

    #[test]
    fn test_prepare_version_display_items_all_yanked() {
        let versions: Vec<std::sync::Arc<dyn crate::Version>> = vec![
            std::sync::Arc::new(MockVersion {
                version: "1.0.0".into(),
                yanked: true,
                prerelease: false,
            }),
            std::sync::Arc::new(MockVersion {
                version: "0.9.0".into(),
                yanked: true,
                prerelease: false,
            }),
        ];

        let items = prepare_version_display_items(&versions, &pkg("test"));

        assert_eq!(items.len(), 0);
    }

    #[test]
    fn test_build_feature_completion() {
        let item = build_feature_completion("derive", &pkg("serde"), None);

        assert_eq!(item.label, "derive");
        assert_eq!(item.kind, Some(CompletionItemKind::PROPERTY));
        assert_eq!(item.detail, Some("Feature of serde".to_string()));
        assert!(item.documentation.is_none());
        assert!(item.text_edit.is_none());
        assert_eq!(item.sort_text, Some("derive".to_string()));
    }

    #[test]
    fn test_build_feature_completion_with_range() {
        let range = Range::default();
        let item = build_feature_completion("derive", &pkg("serde"), Some(range));

        assert_eq!(item.label, "derive");
        assert!(item.text_edit.is_some());
    }

    #[test]
    fn test_position_in_range_within() {
        let range = Range {
            start: Position {
                line: 0,
                character: 5,
            },
            end: Position {
                line: 0,
                character: 10,
            },
        };

        let position = Position {
            line: 0,
            character: 7,
        };

        assert!(position_in_range(position, range));
    }

    #[test]
    fn test_position_in_range_at_start() {
        let range = Range {
            start: Position {
                line: 0,
                character: 5,
            },
            end: Position {
                line: 0,
                character: 10,
            },
        };

        let position = Position {
            line: 0,
            character: 5,
        };

        assert!(position_in_range(position, range));
    }

    #[test]
    fn test_position_in_range_at_end() {
        let range = Range {
            start: Position {
                line: 0,
                character: 5,
            },
            end: Position {
                line: 0,
                character: 10,
            },
        };

        let position = Position {
            line: 0,
            character: 10,
        };

        assert!(position_in_range(position, range));
    }

    #[test]
    fn test_position_in_range_one_past_end() {
        let range = Range {
            start: Position {
                line: 0,
                character: 5,
            },
            end: Position {
                line: 0,
                character: 10,
            },
        };

        // Allow one character past end for completion
        let position = Position {
            line: 0,
            character: 11,
        };

        assert!(position_in_range(position, range));
    }

    #[test]
    fn test_position_in_range_before() {
        let range = Range {
            start: Position {
                line: 0,
                character: 5,
            },
            end: Position {
                line: 0,
                character: 10,
            },
        };

        let position = Position {
            line: 0,
            character: 4,
        };

        assert!(!position_in_range(position, range));
    }

    #[test]
    fn test_position_in_range_after() {
        let range = Range {
            start: Position {
                line: 0,
                character: 5,
            },
            end: Position {
                line: 0,
                character: 10,
            },
        };

        let position = Position {
            line: 0,
            character: 12,
        };

        assert!(!position_in_range(position, range));
    }

    // UTF-16 to byte offset conversion tests

    #[test]
    fn test_utf16_to_byte_offset_ascii() {
        let s = "hello";
        assert_eq!(utf16_to_byte_offset(s, 0), Some(0));
        assert_eq!(utf16_to_byte_offset(s, 2), Some(2));
        assert_eq!(utf16_to_byte_offset(s, 5), Some(5));
    }

    #[test]
    fn test_utf16_to_byte_offset_multibyte() {
        // "日本語" - each character is 3 bytes, 1 UTF-16 code unit
        let s = "日本語";
        assert_eq!(utf16_to_byte_offset(s, 0), Some(0));
        assert_eq!(utf16_to_byte_offset(s, 1), Some(3));
        assert_eq!(utf16_to_byte_offset(s, 2), Some(6));
        assert_eq!(utf16_to_byte_offset(s, 3), Some(9));
    }

    #[test]
    fn test_utf16_to_byte_offset_emoji() {
        // "😀" is 4 bytes but 2 UTF-16 code units (surrogate pair)
        let s = "😀test";
        assert_eq!(utf16_to_byte_offset(s, 0), Some(0));
        assert_eq!(utf16_to_byte_offset(s, 2), Some(4)); // After emoji
        assert_eq!(utf16_to_byte_offset(s, 3), Some(5)); // After 't'
    }

    #[test]
    fn test_utf16_to_byte_offset_mixed() {
        // Mix of ASCII, multi-byte, and emoji
        let s = "hello 世界 😀!";
        assert_eq!(utf16_to_byte_offset(s, 0), Some(0)); // 'h'
        assert_eq!(utf16_to_byte_offset(s, 6), Some(6)); // '世'
        assert_eq!(utf16_to_byte_offset(s, 7), Some(9)); // '界'
        assert_eq!(utf16_to_byte_offset(s, 9), Some(13)); // '😀' (2 UTF-16 units)
        assert_eq!(utf16_to_byte_offset(s, 11), Some(17)); // '!'
    }

    #[test]
    fn test_utf16_to_byte_offset_out_of_bounds() {
        let s = "hello";
        assert_eq!(utf16_to_byte_offset(s, 100), None);
    }

    #[test]
    fn test_utf16_to_byte_offset_empty() {
        let s = "";
        assert_eq!(utf16_to_byte_offset(s, 0), Some(0));
        assert_eq!(utf16_to_byte_offset(s, 1), None);
    }

    // Byte to UTF-16 offset conversion tests

    #[test]
    fn test_byte_to_utf16_offset_ascii() {
        let s = "hello";
        assert_eq!(byte_to_utf16_offset(s, 0), 0);
        assert_eq!(byte_to_utf16_offset(s, 2), 2);
        assert_eq!(byte_to_utf16_offset(s, 5), 5);
    }

    #[test]
    fn test_byte_to_utf16_offset_multibyte() {
        // "日本語" - each character is 3 bytes, 1 UTF-16 code unit
        let s = "日本語";
        assert_eq!(byte_to_utf16_offset(s, 0), 0);
        assert_eq!(byte_to_utf16_offset(s, 3), 1);
        assert_eq!(byte_to_utf16_offset(s, 6), 2);
        assert_eq!(byte_to_utf16_offset(s, 9), 3);
    }

    #[test]
    fn test_byte_to_utf16_offset_emoji() {
        // "😀" is 4 bytes but 2 UTF-16 code units (surrogate pair)
        let s = "😀test";
        assert_eq!(byte_to_utf16_offset(s, 0), 0);
        assert_eq!(byte_to_utf16_offset(s, 4), 2); // After emoji
        assert_eq!(byte_to_utf16_offset(s, 5), 3); // After 't'
    }

    #[test]
    fn test_byte_to_utf16_offset_mixed() {
        // Mix of ASCII, multi-byte, and emoji
        let s = "hello 世界 😀!";
        assert_eq!(byte_to_utf16_offset(s, 0), 0); // 'h'
        assert_eq!(byte_to_utf16_offset(s, 6), 6); // '世'
        assert_eq!(byte_to_utf16_offset(s, 9), 7); // '界'
        assert_eq!(byte_to_utf16_offset(s, 13), 9); // '😀' (2 UTF-16 units)
        assert_eq!(byte_to_utf16_offset(s, 17), 11); // '!'
    }

    #[test]
    fn test_byte_to_utf16_offset_empty() {
        let s = "";
        assert_eq!(byte_to_utf16_offset(s, 0), 0);
    }

    // Unicode truncation tests

    #[test]
    fn test_build_package_completion_long_description_ascii() {
        let long_desc = "a".repeat(250);
        let metadata = MockMetadata {
            name: "test-pkg".into(),
            description: Some(long_desc),
            repository: None,
            documentation: None,
            latest_version: "1.0.0".into(),
        };

        let range = Range::default();
        let item = build_package_completion(&metadata, range).unwrap();

        if let Some(Documentation::MarkupContent(content)) = item.documentation {
            // Should be truncated to 200 chars + "..."
            let lines: Vec<_> = content.value.lines().collect();
            assert!(lines[2].ends_with("..."));
            assert!(lines[2].len() <= 203); // 200 + "..."
        } else {
            panic!("Expected MarkupContent documentation");
        }
    }

    #[test]
    fn test_build_package_completion_long_description_unicode() {
        // Create description with Unicode chars at the boundary
        // Each '日' is 3 bytes, so 67 chars = 201 bytes
        let mut long_desc = String::new();
        for _ in 0..67 {
            long_desc.push('日');
        }

        let metadata = MockMetadata {
            name: "test-pkg".into(),
            description: Some(long_desc),
            repository: None,
            documentation: None,
            latest_version: "1.0.0".into(),
        };

        let range = Range::default();
        let item = build_package_completion(&metadata, range).unwrap();

        // Should not panic on truncation
        if let Some(Documentation::MarkupContent(content)) = item.documentation {
            let lines: Vec<_> = content.value.lines().collect();
            assert!(lines[2].ends_with("..."));
            // Truncation should happen at a char boundary
            assert!(lines[2].is_char_boundary(lines[2].len()));
        } else {
            panic!("Expected MarkupContent documentation");
        }
    }

    #[test]
    fn test_build_package_completion_long_description_emoji() {
        // Emoji "😀" is 4 bytes each
        // 51 emoji = 204 bytes
        let long_desc = "😀".repeat(51);

        let metadata = MockMetadata {
            name: "test-pkg".into(),
            description: Some(long_desc),
            repository: None,
            documentation: None,
            latest_version: "1.0.0".into(),
        };

        let range = Range::default();
        let item = build_package_completion(&metadata, range).unwrap();

        // Should not panic on truncation
        if let Some(Documentation::MarkupContent(content)) = item.documentation {
            let lines: Vec<_> = content.value.lines().collect();
            assert!(lines[2].ends_with("..."));
            // Truncation should happen at a char boundary
            assert!(lines[2].is_char_boundary(lines[2].len()));
        } else {
            panic!("Expected MarkupContent documentation");
        }
    }

    #[test]
    fn test_extract_prefix_unicode_package_name() {
        // Package name with Unicode characters
        let content = "日本語-crate = \"1.0\"";
        let position = Position {
            line: 0,
            character: 3, // UTF-16 offset after "日本語"
        };
        let range = Range {
            start: Position {
                line: 0,
                character: 0,
            },
            end: Position {
                line: 0,
                character: 10,
            },
        };

        let prefix = extract_prefix(content, position, range);
        assert_eq!(prefix, "日本語");
    }

    #[test]
    fn test_extract_prefix_emoji_in_content() {
        // Content with emoji (rare but should handle gracefully)
        let content = "emoji-😀-crate = \"1.0\"";
        let position = Position {
            line: 0,
            character: 8, // UTF-16 offset after "emoji-😀"
        };
        let range = Range {
            start: Position {
                line: 0,
                character: 0,
            },
            end: Position {
                line: 0,
                character: 14,
            },
        };

        let prefix = extract_prefix(content, position, range);
        assert_eq!(prefix, "emoji-😀");
    }

    // Generic version completion tests

    #[tokio::test]
    async fn test_complete_versions_generic_operator_stripping() {
        let registry = MockRegistry {
            versions: vec![
                MockVersion {
                    version: "1.0.0".into(),
                    yanked: false,
                    prerelease: false,
                },
                MockVersion {
                    version: "1.0.1".into(),
                    yanked: false,
                    prerelease: false,
                },
                MockVersion {
                    version: "1.1.0".into(),
                    yanked: false,
                    prerelease: false,
                },
                MockVersion {
                    version: "2.0.0".into(),
                    yanked: false,
                    prerelease: false,
                },
            ],
        };

        // Test with Cargo-style operators (^, ~, =, <, >)
        let items = complete_versions_generic(
            &registry,
            &pkg("test-pkg"),
            "^1.0",
            &['^', '~', '=', '<', '>'],
            FreshnessSettings::default(),
        )
        .await;

        // Should return versions starting with "1.0" (after stripping ^)
        assert_eq!(items.len(), 2);
        assert_eq!(items[0].label, "1.0.0 (latest)");
        assert_eq!(items[1].label, "1.0.1");

        // Test with tilde operator
        let items = complete_versions_generic(
            &registry,
            &pkg("test-pkg"),
            "~1.1",
            &['^', '~', '=', '<', '>'],
            FreshnessSettings::default(),
        )
        .await;

        assert_eq!(items.len(), 1);
        assert_eq!(items[0].label, "1.1.0 (latest)");

        // Test with equals operator
        let items = complete_versions_generic(
            &registry,
            &pkg("test-pkg"),
            "=2.0",
            &['^', '~', '=', '<', '>'],
            FreshnessSettings::default(),
        )
        .await;

        assert_eq!(items.len(), 1);
        assert_eq!(items[0].label, "2.0.0 (latest)");

        // Test with no operator (should work the same)
        let items = complete_versions_generic(
            &registry,
            &pkg("test-pkg"),
            "1.0",
            &['^', '~', '=', '<', '>'],
            FreshnessSettings::default(),
        )
        .await;

        assert_eq!(items.len(), 2);
        assert_eq!(items[0].label, "1.0.0 (latest)");
        assert_eq!(items[1].label, "1.0.1");
    }

    #[tokio::test]
    async fn test_complete_versions_generic_fallback_when_no_prefix_match() {
        let registry = MockRegistry {
            versions: vec![
                MockVersion {
                    version: "1.0.0".into(),
                    yanked: false,
                    prerelease: false,
                },
                MockVersion {
                    version: "1.1.0".into(),
                    yanked: false,
                    prerelease: false,
                },
                MockVersion {
                    version: "2.0.0".into(),
                    yanked: false,
                    prerelease: false,
                },
                MockVersion {
                    version: "2.1.0".into(),
                    yanked: true, // Yanked version
                    prerelease: false,
                },
            ],
        };

        // Test with prefix that doesn't match any version
        let items = complete_versions_generic(
            &registry,
            &pkg("test-pkg"),
            "3.0",
            &['^', '~', '=', '<', '>'],
            FreshnessSettings::default(),
        )
        .await;

        // Should fallback to showing all non-yanked versions
        assert_eq!(items.len(), 3);
        assert_eq!(items[0].label, "1.0.0 (latest)");
        assert_eq!(items[1].label, "1.1.0");
        assert_eq!(items[2].label, "2.0.0");

        // Yanked version should not be included in fallback
        assert!(!items.iter().any(|item| item.label == "2.1.0"));

        // Test with empty prefix (should show all non-yanked)
        let items = complete_versions_generic(
            &registry,
            &pkg("test-pkg"),
            "",
            &[],
            FreshnessSettings::default(),
        )
        .await;

        assert_eq!(items.len(), 3);
        assert_eq!(items[0].label, "1.0.0 (latest)");
        assert_eq!(items[1].label, "1.1.0");
        assert_eq!(items[2].label, "2.0.0");
    }

    #[tokio::test]
    async fn test_complete_versions_generic_filters_yanked_in_prefix_match() {
        let registry = MockRegistry {
            versions: vec![
                MockVersion {
                    version: "1.0.0".into(),
                    yanked: false,
                    prerelease: false,
                },
                MockVersion {
                    version: "1.0.1".into(),
                    yanked: true, // Yanked version
                    prerelease: false,
                },
                MockVersion {
                    version: "1.0.2".into(),
                    yanked: false,
                    prerelease: false,
                },
            ],
        };

        // Test that yanked versions are filtered out even when prefix matches
        let items = complete_versions_generic(
            &registry,
            &pkg("test-pkg"),
            "1.0",
            &[],
            FreshnessSettings::default(),
        )
        .await;

        // Should only include non-yanked versions
        assert_eq!(items.len(), 2);
        assert_eq!(items[0].label, "1.0.0 (latest)");
        assert_eq!(items[1].label, "1.0.2");

        // Yanked version 1.0.1 should not be included
        assert!(!items.iter().any(|item| item.label == "1.0.1"));
    }

    #[tokio::test]
    async fn test_complete_versions_generic_filters_unsafe_version_string() {
        // Regression (critic S3): `build_version_completion` writes `insert_text`/
        // `text_edit.new_text` straight from a registry-reported version, the same
        // untrusted data source as the REFACTOR code-action loop. An unsafe
        // registry version must never surface as a completion item, while an
        // ordinary safe version alongside it must still be offered.
        let registry = MockRegistry {
            versions: vec![
                MockVersion {
                    version: "1.0.0".into(),
                    yanked: false,
                    prerelease: false,
                },
                MockVersion {
                    version: "1.0.1\", \"evil\": \"true".into(),
                    yanked: false,
                    prerelease: false,
                },
            ],
        };

        let items = complete_versions_generic(
            &registry,
            &pkg("test-pkg"),
            "1.0",
            &[],
            FreshnessSettings::default(),
        )
        .await;

        assert!(
            !items.iter().any(|item| item.label.contains("evil")),
            "an unsafe version string must never be offered as a completion item: {items:?}"
        );
        assert!(
            items.iter().any(|item| item.label.starts_with("1.0.0")),
            "a safe version must still be offered: {items:?}"
        );
    }

    #[tokio::test]
    async fn test_complete_versions_generic_limit_5() {
        // Create more than 5 versions
        let versions: Vec<_> = (0..10)
            .map(|i| MockVersion {
                version: format!("1.0.{}", i).into(),
                yanked: false,
                prerelease: false,
            })
            .collect();

        let registry = MockRegistry { versions };

        // Test that we only return 5 items
        let items = complete_versions_generic(
            &registry,
            &pkg("test-pkg"),
            "1.0",
            &[],
            FreshnessSettings::default(),
        )
        .await;

        assert_eq!(items.len(), 5);
        assert_eq!(items[0].label, "1.0.0 (latest)");
        assert_eq!(items[4].label, "1.0.4");
    }

    #[tokio::test]
    async fn test_complete_versions_generic_go_no_operators() {
        let registry = MockRegistry {
            versions: vec![
                MockVersion {
                    version: "v1.9.0".into(),
                    yanked: false,
                    prerelease: false,
                },
                MockVersion {
                    version: "v1.9.1".into(),
                    yanked: false,
                    prerelease: false,
                },
                MockVersion {
                    version: "v1.10.0".into(),
                    yanked: false,
                    prerelease: false,
                },
            ],
        };

        // Go has no operators, so empty array
        let items = complete_versions_generic(
            &registry,
            &pkg("github.com/gin-gonic/gin"),
            "v1.9",
            &[],
            FreshnessSettings::default(),
        )
        .await;

        assert_eq!(items.len(), 2);
        assert_eq!(items[0].label, "v1.9.0 (latest)");
        assert_eq!(items[1].label, "v1.9.1");
    }

    // --- Feature completion detection tests ---

    fn make_dep_with_features_range(
        name: &str,
        name_range: Range,
        features_range: Range,
    ) -> MockDependency {
        MockDependency {
            name: name.into(),
            name_range,
            version_range: None,
            features_range: Some(features_range),
        }
    }

    #[test]
    fn test_detect_feature_context_inline() {
        // serde = { version = "1", features = ["derive", "std"] }
        // col:                                 36              52
        let features_range = Range {
            start: Position {
                line: 0,
                character: 36,
            },
            end: Position {
                line: 0,
                character: 52,
            },
        };
        let dep = make_dep_with_features_range(
            "serde",
            Range {
                start: Position {
                    line: 0,
                    character: 0,
                },
                end: Position {
                    line: 0,
                    character: 5,
                },
            },
            features_range,
        );
        let parse_result = MockParseResult {
            dependencies: vec![dep],
        };

        let content = r#"serde = { version = "1", features = ["derive", "std"] }"#;

        // Content: ...["derive",...  => '"' is at char 37, 'd'=38, 'e'=39, 'r'=40
        // Cursor after 'r' (insertion point) = character 41
        let position = Position {
            line: 0,
            character: 41,
        };
        let context = detect_completion_context(&parse_result, position, content);
        assert!(
            matches!(context, CompletionContext::Feature { ref package_name, ref prefix }
                if package_name == "serde" && prefix == "der"),
            "Expected Feature context with prefix 'der', got {context:?}"
        );
    }

    #[test]
    fn test_detect_feature_context_empty_prefix() {
        // Cursor right after opening quote: features = ["|"]
        let features_range = Range {
            start: Position {
                line: 0,
                character: 11,
            },
            end: Position {
                line: 0,
                character: 15,
            },
        };
        let dep = make_dep_with_features_range(
            "tokio",
            Range {
                start: Position {
                    line: 0,
                    character: 0,
                },
                end: Position {
                    line: 0,
                    character: 5,
                },
            },
            features_range,
        );
        let parse_result = MockParseResult {
            dependencies: vec![dep],
        };

        let content = r#"features = [""]"#;
        // Cursor between the two quotes: position character 13
        let position = Position {
            line: 0,
            character: 13,
        };
        let context = detect_completion_context(&parse_result, position, content);
        assert!(
            matches!(context, CompletionContext::Feature { ref package_name, ref prefix }
                if package_name == "tokio" && prefix.is_empty()),
            "Expected Feature context with empty prefix, got {context:?}"
        );
    }

    #[test]
    fn test_detect_feature_context_second_item() {
        // features = ["full", "rt-|"]
        let features_range = Range {
            start: Position {
                line: 0,
                character: 11,
            },
            end: Position {
                line: 0,
                character: 28,
            },
        };
        let dep = make_dep_with_features_range(
            "tokio",
            Range {
                start: Position {
                    line: 0,
                    character: 0,
                },
                end: Position {
                    line: 0,
                    character: 5,
                },
            },
            features_range,
        );
        let parse_result = MockParseResult {
            dependencies: vec![dep],
        };

        let content = r#"features = ["full", "rt-"]"#;
        // Cursor after "rt-": character 24
        let position = Position {
            line: 0,
            character: 24,
        };
        let context = detect_completion_context(&parse_result, position, content);
        assert!(
            matches!(context, CompletionContext::Feature { ref package_name, ref prefix }
                if package_name == "tokio" && prefix == "rt-"),
            "Expected Feature context with prefix 'rt-', got {context:?}"
        );
    }

    #[test]
    fn test_detect_no_feature_context_outside_range() {
        let features_range = Range {
            start: Position {
                line: 2,
                character: 11,
            },
            end: Position {
                line: 2,
                character: 20,
            },
        };
        let dep = make_dep_with_features_range(
            "serde",
            Range {
                start: Position {
                    line: 2,
                    character: 0,
                },
                end: Position {
                    line: 2,
                    character: 5,
                },
            },
            features_range,
        );
        let parse_result = MockParseResult {
            dependencies: vec![dep],
        };

        // Cursor is on line 0, not line 2 where features are
        let content = "[package]\nname = \"test\"\nfeatures = [\"full\"]";
        let position = Position {
            line: 0,
            character: 5,
        };
        let context = detect_completion_context(&parse_result, position, content);
        assert_eq!(context, CompletionContext::None);
    }

    #[test]
    fn test_extract_feature_prefix_basic() {
        let content = r#"serde = { features = ["derive"] }"#;
        // '"' is at char 22, 'd'=23, 'e'=24, 'r'=25, 'i'=26
        // Cursor after 'i' (insertion point) = character 27
        let position = Position {
            line: 0,
            character: 27,
        };
        let prefix = extract_feature_prefix(content, position);
        assert_eq!(prefix, "deri");
    }

    #[test]
    fn test_extract_feature_prefix_empty() {
        let content = r#"features = [""]"#;
        // Cursor between opening and closing quote at character 13
        let position = Position {
            line: 0,
            character: 13,
        };
        let prefix = extract_feature_prefix(content, position);
        assert_eq!(prefix, "");
    }

    #[test]
    fn test_extract_feature_prefix_multiline() {
        let content = "features = [\n    \"rt-multi-thread\",\n    \"mac\"\n]";
        // Line 2: `    "mac"` — '"' at char 4, 'm'=5, 'a'=6, 'c'=7
        // Cursor after 'c' (insertion point) = character 8
        let position = Position {
            line: 2,
            character: 8,
        };
        let prefix = extract_feature_prefix(content, position);
        assert_eq!(prefix, "mac");
    }

    #[test]
    fn test_extract_feature_prefix_no_quote() {
        let content = "features = [\n    \n]";
        // Cursor on blank line inside array
        let position = Position {
            line: 1,
            character: 4,
        };
        let prefix = extract_feature_prefix(content, position);
        assert_eq!(prefix, "");
    }

    #[test]
    fn test_extract_feature_prefix_between_items_no_quote() {
        // Cursor between a comma and the next opening quote: ["full", |]
        // After "full" the quote count is 2 (even) → not inside a string → empty prefix
        let content = r#"features = ["full", ]"#;
        // Cursor after ", " at character 19 (before `]`)
        let position = Position {
            line: 0,
            character: 19,
        };
        let prefix = extract_feature_prefix(content, position);
        assert_eq!(prefix, "");
    }

    #[test]
    fn test_extract_feature_prefix_cursor_after_opening_bracket() {
        // Cursor right after `[`, before any quote: features = [|]
        let content = "features = []";
        let position = Position {
            line: 0,
            character: 12,
        };
        let prefix = extract_feature_prefix(content, position);
        assert_eq!(prefix, "");
    }

    // --- Release-freshness signal (issue #145): VersionDisplayItem.published_at,
    // build_version_completion's label_details ---

    #[test]
    fn test_version_display_item_captures_published_at() {
        let version = MockVersionWithAge {
            version: "1.0.0".into(),
            published_at: Some(PublishTime::from_unix_secs(1_000)),
        };

        let item = VersionDisplayItem::new(&version, &pkg("serde"), 0, true);

        assert_eq!(item.published_at, Some(PublishTime::from_unix_secs(1_000)));
    }

    #[test]
    fn test_version_display_item_published_at_none_when_unavailable() {
        // Plain `MockVersion` doesn't override `published_at`, so it falls back to
        // the `Version` trait's default `None` — the ecosystems-without-metadata case.
        let version = MockVersion {
            version: "1.0.0".into(),
            yanked: false,
            prerelease: false,
        };

        let item = VersionDisplayItem::new(&version, &pkg("serde"), 0, true);

        assert_eq!(item.published_at, None);
    }

    #[test]
    fn test_build_version_completion_label_details_present_when_published_at_known() {
        let now = PublishTime::from_unix_secs(10_000);
        let published_two_hours_ago = PublishTime::from_unix_secs(10_000 - 2 * 3600);
        let version = MockVersionWithAge {
            version: "1.2.3".into(),
            published_at: Some(published_two_hours_ago),
        };
        let display_item = VersionDisplayItem::new(&version, &pkg("serde"), 0, true);

        let item = build_version_completion(&display_item, None, now, true);

        let details = item
            .label_details
            .expect("label_details must be set when published_at is known");
        assert_eq!(details.detail, Some("  2 hours ago".to_string()));
        assert_eq!(details.description, None);
    }

    #[test]
    fn test_build_version_completion_label_details_absent_when_freshness_disabled() {
        // `freshness.enabled: false` must suppress label_details even when
        // published_at is known — the escape hatch must be all-or-nothing.
        let now = PublishTime::from_unix_secs(10_000);
        let published_two_hours_ago = PublishTime::from_unix_secs(10_000 - 2 * 3600);
        let version = MockVersionWithAge {
            version: "1.2.3".into(),
            published_at: Some(published_two_hours_ago),
        };
        let display_item = VersionDisplayItem::new(&version, &pkg("serde"), 0, true);

        let item = build_version_completion(&display_item, None, now, false);

        assert!(item.label_details.is_none());
    }

    #[test]
    fn test_build_version_completion_label_details_absent_when_published_at_unknown() {
        let version = MockVersion {
            version: "1.2.3".into(),
            yanked: false,
            prerelease: false,
        };
        let display_item = VersionDisplayItem::new(&version, &pkg("serde"), 0, true);

        let item = build_version_completion(&display_item, None, PublishTime::now(), true);

        assert!(item.label_details.is_none());
    }

    /// FR-006 regression guard: when freshness data is absent (the pre-feature and
    /// 5-deferred-ecosystem case), `label`, `sort_text`, `preselect`, and the item
    /// count/order out of `prepare_version_display_items` must stay byte-identical to
    /// what this suite asserted before `published_at`/`label_details` existed.
    #[test]
    fn test_build_version_completion_byte_identical_output_without_freshness_data() {
        let versions: Vec<std::sync::Arc<dyn crate::Version>> = vec![
            std::sync::Arc::new(MockVersion {
                version: "1.0.0".into(),
                yanked: false,
                prerelease: false,
            }),
            std::sync::Arc::new(MockVersion {
                version: "0.9.0".into(),
                yanked: true,
                prerelease: false,
            }),
            std::sync::Arc::new(MockVersion {
                version: "0.8.0".into(),
                yanked: false,
                prerelease: false,
            }),
        ];

        let display_items = prepare_version_display_items(&versions, &pkg("test"));
        assert_eq!(display_items.len(), 2, "yanked filtering must be unchanged");

        let now = PublishTime::now();
        let items: Vec<_> = display_items
            .iter()
            .map(|item| build_version_completion(item, None, now, true))
            .collect();

        assert_eq!(items[0].label, "1.0.0 (latest)");
        assert_eq!(items[0].sort_text, Some("00000".to_string()));
        assert_eq!(items[0].preselect, Some(true));
        assert_eq!(items[0].label_details, None);

        assert_eq!(items[1].label, "0.8.0");
        assert_eq!(items[1].sort_text, Some("00001".to_string()));
        assert_eq!(items[1].preselect, Some(false));
        assert_eq!(items[1].label_details, None);
    }
}