agent-file-tools 0.35.4

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

use std::ops::Range;

use tree_sitter::{Node, Parser, Tree};

use crate::parser::{grammar_for, LangId};

mod c;
pub(crate) use c::{classify_group_c_import_kind, normalize_include_module};
mod csharp;
mod java;
mod kotlin;
mod lua;
mod perl;
mod php;
pub(crate) use php::{php_grouped_use_matches_module, php_grouped_use_shares_prefix};
mod ruby;
mod scala;
pub(crate) use scala::scala_block_uses_scala2_dialect;
mod swift;

// ---------------------------------------------------------------------------
// Shared types
// ---------------------------------------------------------------------------

/// What kind of import this is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImportKind {
    /// `import { X } from 'y'` or `import X from 'y'`
    Value,
    /// `import type { X } from 'y'`
    Type,
    /// `import './side-effect'`
    SideEffect,
}

/// Which logical group an import belongs to (language-specific).
///
/// Ordering matches conventional import group sorting:
///   Stdlib (first) < External < Internal (last)
///
/// Language mapping:
///   - TS/JS/TSX: External (no `.` prefix), Internal (`.`/`..` prefix)
///   - Python:    Stdlib, External (third-party), Internal (relative `.`/`..`)
///   - Rust:      Stdlib (std/core/alloc), External (crates), Internal (crate/self/super)
///   - Go:        Stdlib (no dots in path), External (dots in path)
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ImportGroup {
    /// Standard library (Python stdlib, Rust std/core/alloc, Go stdlib).
    /// TS/JS don't use this group.
    Stdlib,
    /// External/third-party packages.
    External,
    /// Internal/relative imports (TS relative, Python local, Rust crate/self/super).
    Internal,
}

impl ImportGroup {
    /// Human-readable label for the group.
    pub fn label(&self) -> &'static str {
        match self {
            ImportGroup::Stdlib => "stdlib",
            ImportGroup::External => "external",
            ImportGroup::Internal => "internal",
        }
    }
}

/// Structured, language-honest representation of a single import's shape.
///
/// This is the migration target that replaces the TS-shaped flat fields
/// (`names`/`default_import`/`namespace_import`) and their per-language
/// overloads (Rust packs `"pub"` into `default_import`; Go packs the alias
/// there). It is introduced additively alongside the flat fields (Stream M of
/// the imports-refactor plan): parsers populate BOTH, readers migrate onto
/// `form` one at a time behind the golden-parity gate, and the flat fields are
/// removed once no reader depends on them. New-language variants (Static,
/// Include, RuntimeRequire, …) are added when their engines land — only the
/// variants the existing engines produce exist today.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ImportForm {
    /// ES modules: TypeScript, TSX, JavaScript.
    /// `named` holds verbatim specifiers (`"useState"`, `"stdin as input"`,
    /// `"type Foo"`, `"type Foo as Bar"`) — see [`specifier_imported_name`].
    Es {
        default_import: Option<String>,
        namespace_import: Option<String>,
        named: Vec<String>,
        /// Statement-level `import type { ... }`.
        type_only: bool,
        /// Side-effect-only `import "mod"` (no bindings).
        side_effect: bool,
    },
    /// Python `import module` (`from_import = false`) or
    /// `from module import a, b` (`from_import = true`).
    Python {
        from_import: bool,
        named: Vec<String>,
    },
    /// Rust `use path;` / `pub use path;`. `visibility` replaces the
    /// `default_import == "pub"` overload (`Some("pub")`, `Some("pub(crate)")`,
    /// …). The brace/use-tree text remains carried by `module_path` per the
    /// lossless-round-trip decision; `named` holds extracted use-list names.
    RustUse {
        visibility: Option<String>,
        named: Vec<String>,
    },
    /// Go import. `alias` replaces the `default_import` overload, including the
    /// blank (`_`) and dot (`.`) import bindings.
    Go { alias: Option<String> },
    /// Solidity import, in one of four forms:
    /// - side-effect: `import "x";` (all empty)
    /// - named: `import { A, B as C } from "x";` (`named`)
    /// - namespace: `import * as A from "x";` (`namespace`)
    /// - whole-file alias: `import "x" as A;` (`alias`)
    ///
    /// `named` holds verbatim specifiers (`"A"`, `"B as C"`) like the ES form,
    /// so [`specifier_imported_name`] / [`specifier_local_name`] apply.
    Solidity {
        named: Vec<String>,
        namespace: Option<String>,
        alias: Option<String>,
    },
    /// Generic structured form shared by the Phase-1 engines (Java, C#, PHP,
    /// Kotlin, Scala, Swift, …). Carries the full schema field set so a new
    /// engine does not need its own enum variant; `module_path` (on the parent
    /// `ImportStatement`) holds the path/FQN. `named` uses the verbatim
    /// specifier convention.
    Structured {
        named: Vec<String>,
        namespace: Option<String>,
        alias: Option<String>,
        modifiers: Vec<String>,
        import_kind: Option<String>,
    },
}

/// Structured request to generate a single import line. Superset of the fields
/// the public `aft_import` schema exposes; each engine reads only the subset it
/// supports. New languages add fields here rather than growing positional
/// parameters on every generator signature.
#[derive(Debug, Clone)]
pub struct ImportRequest<'a> {
    pub module_path: &'a str,
    pub names: &'a [String],
    pub default_import: Option<&'a str>,
    /// ES `* as ns` / Solidity `* as A`.
    pub namespace: Option<&'a str>,
    /// Whole-module local alias (Solidity `import "x" as A`).
    pub alias: Option<&'a str>,
    pub type_only: bool,
    /// Statement-level modifier tokens (Java/C# `static`, C# `global`/`unsafe`,
    /// `wildcard`, Swift `@testable`, …). Empty for the legacy engines.
    pub modifiers: &'a [String],
    /// Symbol-kind-specific import (PHP `function`/`const`, Swift `struct`/…,
    /// Scala `given`). Absent for the legacy engines.
    pub import_kind: Option<&'a str>,
}

/// Empty default for the `modifiers` slice so legacy callers need not allocate.
const NO_MODIFIERS: &[String] = &[];

impl<'a> ImportRequest<'a> {
    /// Construct a request carrying only the legacy positional fields; the
    /// structured fields (alias/modifiers/import_kind) default to absent. Used
    /// by the back-compat free-function wrappers.
    pub fn legacy(
        module_path: &'a str,
        names: &'a [String],
        default_import: Option<&'a str>,
        namespace: Option<&'a str>,
        type_only: bool,
    ) -> Self {
        ImportRequest {
            module_path,
            names,
            default_import,
            namespace,
            alias: None,
            type_only,
            modifiers: NO_MODIFIERS,
            import_kind: None,
        }
    }
}

/// A single parsed import statement.
#[derive(Debug, Clone)]
pub struct ImportStatement {
    /// The module path (e.g., `react`, `./utils`, `../config`).
    pub module_path: String,
    /// Named imports (e.g., `["useState", "useEffect"]`).
    pub names: Vec<String>,
    /// Default import name (e.g., `React` from `import React from 'react'`).
    pub default_import: Option<String>,
    /// Namespace import name (e.g., `path` from `import * as path from 'path'`).
    pub namespace_import: Option<String>,
    /// What kind: value, type, or side-effect.
    pub kind: ImportKind,
    /// Which group this import belongs to.
    pub group: ImportGroup,
    /// Byte range in the original source.
    pub byte_range: Range<usize>,
    /// Raw text of the import statement.
    pub raw_text: String,
    /// Structured, de-overloaded representation (Stream M migration target).
    /// Populated by every parser alongside the flat fields above; readers
    /// migrate onto this incrementally behind the golden-parity gate.
    pub form: ImportForm,
}

/// A block of parsed imports from a file.
#[derive(Debug, Clone)]
pub struct ImportBlock {
    /// All parsed import statements, in source order.
    pub imports: Vec<ImportStatement>,
    /// Overall byte range covering all import statements (start of first to end of last).
    /// `None` if no imports found.
    pub byte_range: Option<Range<usize>>,
}

impl ImportBlock {
    pub fn empty() -> Self {
        ImportBlock {
            imports: Vec::new(),
            byte_range: None,
        }
    }
}

pub(crate) fn import_byte_range(imports: &[ImportStatement]) -> Option<Range<usize>> {
    imports.first().zip(imports.last()).map(|(first, last)| {
        let start = first.byte_range.start;
        let end = last.byte_range.end;
        start..end
    })
}

// ---------------------------------------------------------------------------
// Specifier helpers (TS/JS verbatim-string format)
// ---------------------------------------------------------------------------

/// Return the local binding name for a TS/JS named-import specifier stored in
/// `ImportStatement::names`. Specifiers are stored verbatim — e.g.
/// `"stdin as input"`, `"type Foo"`, `"type Foo as Bar"`, `"useState"` — so
/// callers that want the name actually introduced into scope must strip the
/// optional `type ` prefix and prefer the post-`as` identifier when present.
///
/// Examples:
///   `"useState"`            → `"useState"`
///   `"stdin as input"`      → `"input"`
///   `"type Foo"`            → `"Foo"`
///   `"type Foo as Bar"`     → `"Bar"`
pub fn specifier_local_name(spec: &str) -> &str {
    let trimmed = spec.trim();
    let after_type = trimmed
        .strip_prefix("type ")
        .unwrap_or(trimmed)
        .trim_start();
    if let Some(idx) = after_type.find(" as ") {
        after_type[idx + 4..].trim()
    } else {
        after_type
    }
}

/// Return the imported (pre-`as`) name for a TS/JS named-import specifier.
/// Used by dedup, remove, and any caller that needs the source-side name.
///
/// Examples:
///   `"useState"`            → `"useState"`
///   `"stdin as input"`      → `"stdin"`
///   `"type Foo"`            → `"Foo"`
///   `"type Foo as Bar"`     → `"Foo"`
pub fn specifier_imported_name(spec: &str) -> &str {
    let trimmed = spec.trim();
    let after_type = trimmed
        .strip_prefix("type ")
        .unwrap_or(trimmed)
        .trim_start();
    after_type
        .find(" as ")
        .map(|idx| after_type[..idx].trim())
        .unwrap_or(after_type)
}

/// Whether a stored specifier matches a target name. Matches against either
/// the imported name or the local binding so callers can pass whichever name
/// they observed in source. Useful for `remove_import` where the agent may
/// reference an aliased import by either name.
pub fn specifier_matches(spec: &str, target: &str) -> bool {
    specifier_imported_name(spec) == target || specifier_local_name(spec) == target
}

// ---------------------------------------------------------------------------
// Per-language engine: the ImportSyntax trait + registry
// ---------------------------------------------------------------------------

/// Per-language import engine. One impl per supported language; [`syntax_for`]
/// maps a [`LangId`] to its `&'static dyn ImportSyntax`. This is the single
/// plug-in point that replaces the scattered `match lang` dispatch in
/// `parse_imports` / `generate_import_line_with_namespace` / `classify_group` /
/// `is_supported`. Adding a language is a new impl + one registry arm.
///
/// The existing engines are thin wrappers over the free functions they already
/// used, so routing through the trait is behavior-preserving (golden-gated).
pub trait ImportSyntax: Sync {
    /// Parse all imports from a file's already-parsed tree.
    fn parse(&self, source: &str, tree: &Tree) -> ImportBlock;

    /// Generate a single import line from a structured [`ImportRequest`].
    /// Engines read only the fields they support and ignore the rest.
    fn generate_line(&self, req: &ImportRequest) -> String;

    /// Classify a module path into stdlib / external / internal.
    fn classify_group(&self, module_path: &str) -> ImportGroup;
}

/// ES modules engine: TypeScript, TSX, JavaScript.
struct EsSyntax;
impl ImportSyntax for EsSyntax {
    fn parse(&self, source: &str, tree: &Tree) -> ImportBlock {
        parse_ts_imports(source, tree)
    }
    fn generate_line(&self, req: &ImportRequest) -> String {
        generate_ts_import_line(
            req.module_path,
            req.names,
            req.default_import,
            req.namespace,
            req.type_only,
        )
    }
    fn classify_group(&self, module_path: &str) -> ImportGroup {
        classify_group_ts(module_path)
    }
}

struct PythonSyntax;
impl ImportSyntax for PythonSyntax {
    fn parse(&self, source: &str, tree: &Tree) -> ImportBlock {
        parse_py_imports(source, tree)
    }
    fn generate_line(&self, req: &ImportRequest) -> String {
        generate_py_import_line(req.module_path, req.names, req.default_import)
    }
    fn classify_group(&self, module_path: &str) -> ImportGroup {
        classify_group_py(module_path)
    }
}

struct RustSyntax;
impl ImportSyntax for RustSyntax {
    fn parse(&self, source: &str, tree: &Tree) -> ImportBlock {
        parse_rs_imports(source, tree)
    }
    fn generate_line(&self, req: &ImportRequest) -> String {
        generate_rs_import_line(req.module_path, req.names, req.type_only)
    }
    fn classify_group(&self, module_path: &str) -> ImportGroup {
        classify_group_rs(module_path)
    }
}

struct GoSyntax;
impl ImportSyntax for GoSyntax {
    fn parse(&self, source: &str, tree: &Tree) -> ImportBlock {
        parse_go_imports(source, tree)
    }
    fn generate_line(&self, req: &ImportRequest) -> String {
        generate_go_import_line(req.module_path, req.default_import, false)
    }
    fn classify_group(&self, module_path: &str) -> ImportGroup {
        classify_group_go(module_path)
    }
}

/// Solidity import engine. Supports named / namespace / whole-file-alias /
/// side-effect forms (Phase 1: first new language onto the registry).
struct SoliditySyntax;
impl ImportSyntax for SoliditySyntax {
    fn parse(&self, source: &str, tree: &Tree) -> ImportBlock {
        parse_solidity_imports(source, tree)
    }
    fn generate_line(&self, req: &ImportRequest) -> String {
        generate_solidity_import_line(req)
    }
    fn classify_group(&self, module_path: &str) -> ImportGroup {
        classify_group_solidity(module_path)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum VueScriptRangeError {
    MissingScript,
    MultipleScripts,
}

impl VueScriptRangeError {
    pub(crate) fn code(self) -> &'static str {
        match self {
            VueScriptRangeError::MissingScript => "missing_vue_script",
            VueScriptRangeError::MultipleScripts => "ambiguous_vue_script",
        }
    }

    pub(crate) fn message(self, command: &str) -> String {
        match self {
            VueScriptRangeError::MissingScript => format!(
                "{command}: Vue import management requires exactly one <script> block; found none"
            ),
            VueScriptRangeError::MultipleScripts => format!(
                "{command}: Vue import management requires exactly one <script> block; found multiple"
            ),
        }
    }
}

/// Locate the byte range of the single `<script>` block's inner content in a
/// Vue Single-File Component. tree-sitter-vue exposes the script body as a
/// single `raw_text` node; this returns `(start, end)` of that node, or — for an
/// empty `<script></script>` with no `raw_text` child — a zero-width range right
/// after the start tag. Multiple scripts are ambiguous for byte-level edits and
/// no-script SFCs have no safe insertion region, so callers should surface the
/// returned error instead of silently editing byte 0 or the first script.
pub(crate) fn vue_single_script_content_range(
    tree: &Tree,
) -> Result<(usize, usize), VueScriptRangeError> {
    let root = tree.root_node();
    let mut ranges = Vec::new();
    let mut cursor = root.walk();
    for child in root.named_children(&mut cursor) {
        if child.kind() == "script_element" {
            ranges.push(vue_script_element_content_range(&child));
        }
    }

    match ranges.len() {
        0 => Err(VueScriptRangeError::MissingScript),
        1 => Ok(ranges[0]),
        _ => Err(VueScriptRangeError::MultipleScripts),
    }
}

/// Back-compat convenience wrapper for callers that only need the safe single
/// script range and intentionally treat missing/ambiguous scripts as absent.
pub(crate) fn vue_script_content_range(tree: &Tree) -> Option<(usize, usize)> {
    vue_single_script_content_range(tree).ok()
}

fn vue_script_element_content_range(child: &Node) -> (usize, usize) {
    let mut inner = child.walk();
    for sub in child.named_children(&mut inner) {
        if sub.kind() == "raw_text" {
            return (sub.start_byte(), sub.end_byte());
        }
    }

    // Empty `<script></script>`: insert right after the start tag.
    let mut inner2 = child.walk();
    for sub in child.named_children(&mut inner2) {
        if sub.kind() == "start_tag" {
            return (sub.end_byte(), sub.end_byte());
        }
    }

    (child.end_byte(), child.end_byte())
}

/// Parse imports from a Vue SFC `<script>` block. The script body is re-parsed
/// with the TypeScript grammar (which covers both `lang="ts"` and plain JS
/// import syntax), then every byte offset is remapped from script-relative to
/// whole-file positions so insertion, removal, and organize operate correctly.
fn parse_vue_imports(source: &str, tree: &Tree) -> ImportBlock {
    let Ok((start, end)) = vue_single_script_content_range(tree) else {
        return ImportBlock {
            imports: Vec::new(),
            byte_range: None,
        };
    };
    let inner = &source[start..end];
    let mut parser = Parser::new();
    if parser
        .set_language(&grammar_for(LangId::TypeScript))
        .is_err()
    {
        return ImportBlock {
            imports: Vec::new(),
            byte_range: None,
        };
    }
    let Some(inner_tree) = parser.parse(inner, None) else {
        return ImportBlock {
            imports: Vec::new(),
            byte_range: None,
        };
    };
    let mut block = parse_ts_imports(inner, &inner_tree);
    for imp in &mut block.imports {
        imp.byte_range = (imp.byte_range.start + start)..(imp.byte_range.end + start);
    }
    block.byte_range = block.byte_range.map(|r| (r.start + start)..(r.end + start));
    block
}

/// Vue Single-File Component import engine. The `<script>` body is exposed by
/// tree-sitter-vue as a single `raw_text` node, so we re-parse it with the
/// TypeScript grammar and remap the resulting byte offsets back to whole-file
/// positions. Generation and grouping reuse the ES (TS/JS) engine, since Vue
/// script imports are TypeScript/JavaScript.
struct VueSyntax;
impl ImportSyntax for VueSyntax {
    fn parse(&self, source: &str, tree: &Tree) -> ImportBlock {
        parse_vue_imports(source, tree)
    }
    fn generate_line(&self, req: &ImportRequest) -> String {
        generate_ts_import_line(
            req.module_path,
            req.names,
            req.default_import,
            req.namespace,
            req.type_only,
        )
    }
    fn classify_group(&self, module_path: &str) -> ImportGroup {
        classify_group_ts(module_path)
    }
}

static ES_SYNTAX: EsSyntax = EsSyntax;
static PYTHON_SYNTAX: PythonSyntax = PythonSyntax;
static RUST_SYNTAX: RustSyntax = RustSyntax;
static GO_SYNTAX: GoSyntax = GoSyntax;
static SOLIDITY_SYNTAX: SoliditySyntax = SoliditySyntax;
static VUE_SYNTAX: VueSyntax = VueSyntax;

/// Map a language to its import engine, or `None` when imports are unsupported.
pub fn syntax_for(lang: LangId) -> Option<&'static dyn ImportSyntax> {
    match lang {
        LangId::TypeScript | LangId::Tsx | LangId::JavaScript => Some(&ES_SYNTAX),
        LangId::Python => Some(&PYTHON_SYNTAX),
        LangId::Rust => Some(&RUST_SYNTAX),
        LangId::Go => Some(&GO_SYNTAX),
        LangId::Solidity => Some(&SOLIDITY_SYNTAX),
        LangId::Vue => Some(&VUE_SYNTAX),
        LangId::C => Some(&c::C_SYNTAX),
        LangId::Cpp => Some(&c::C_SYNTAX),
        LangId::Java => Some(&java::JAVA_SYNTAX),
        LangId::Kotlin => Some(&kotlin::KOTLIN_SYNTAX),
        LangId::Lua => Some(&lua::LUA_SYNTAX),
        LangId::CSharp => Some(&csharp::CSHARP_SYNTAX),
        LangId::Php => Some(&php::PHP_SYNTAX),
        LangId::Perl => Some(&perl::PERL_SYNTAX),
        LangId::Ruby => Some(&ruby::RUBY_SYNTAX),
        LangId::Scala => Some(&scala::SCALA_SYNTAX),
        LangId::Swift => Some(&swift::SWIFT_SYNTAX),
        LangId::Zig
        | LangId::Bash
        | LangId::Scss
        | LangId::Json
        | LangId::Html
        | LangId::Markdown
        | LangId::Yaml => None,
    }
}

// ---------------------------------------------------------------------------
// Core API
// ---------------------------------------------------------------------------

/// Parse imports from source using the provided tree-sitter tree.
pub fn parse_imports(source: &str, tree: &Tree, lang: LangId) -> ImportBlock {
    match syntax_for(lang) {
        Some(engine) => engine.parse(source, tree),
        None => ImportBlock::empty(),
    }
}

/// Check if an import with the given module + name combination already exists.
///
/// For dedup: same module path and matching binding shape. Side-effect imports
/// are only duplicates of side-effect imports; namespace imports are distinct
/// from side-effect imports and from other namespace aliases.
pub fn is_duplicate(
    block: &ImportBlock,
    module_path: &str,
    names: &[String],
    default_import: Option<&str>,
    type_only: bool,
) -> bool {
    is_duplicate_with_namespace(block, module_path, names, default_import, None, type_only)
}

/// Check if an import with the given module + complete binding shape already exists.
pub fn is_duplicate_with_namespace(
    block: &ImportBlock,
    module_path: &str,
    names: &[String],
    default_import: Option<&str>,
    namespace_import: Option<&str>,
    type_only: bool,
) -> bool {
    let target_kind = if type_only {
        ImportKind::Type
    } else {
        ImportKind::Value
    };

    for imp in &block.imports {
        if imp.module_path != module_path {
            continue;
        }

        // For side-effect imports (no names/default/namespace): module path
        // match is sufficient only when the existing import is also a
        // side-effect import. Namespace imports like `import * as fs from 'fs'`
        // are distinct local bindings and must not be conflated with
        // `import 'fs'`.
        if names.is_empty()
            && default_import.is_none()
            && namespace_import.is_none()
            && imp.names.is_empty()
            && imp.default_import.is_none()
            && imp.namespace_import.is_none()
        {
            return true;
        }

        // For side-effect imports specifically (TS/JS): module match is enough
        if names.is_empty()
            && default_import.is_none()
            && namespace_import.is_none()
            && imp.kind == ImportKind::SideEffect
        {
            return true;
        }

        // Kind must match for dedup (value imports don't dedup against type imports)
        if imp.kind != target_kind && imp.kind != ImportKind::SideEffect {
            continue;
        }

        // Default+namespace imports are one ES binding shape. A plain default
        // import must not satisfy a request for `default, * as ns`, and a
        // different namespace alias must not either.
        if let (Some(def), Some(namespace)) = (default_import, namespace_import) {
            if imp.default_import.as_deref() == Some(def)
                && imp.namespace_import.as_deref() == Some(namespace)
                && names
                    .iter()
                    .all(|n| imp.names.iter().any(|stored| specifier_matches(stored, n)))
            {
                return true;
            }
            continue;
        }

        // Namespace-only requests are satisfied by any existing same-module
        // import that already binds that namespace alias, even if it also has a
        // default binding.
        if names.is_empty()
            && default_import.is_none()
            && namespace_import.is_some()
            && imp.namespace_import.as_deref() == namespace_import
        {
            return true;
        }

        // Check default import match. This branch only handles requests that do
        // not also ask for a namespace; that combined shape is checked above.
        if let Some(def) = default_import {
            if namespace_import.is_none() && imp.default_import.as_deref() == Some(def) {
                return true;
            }
        }

        // Check named imports — if ALL requested names already exist.
        // Compare on the imported (pre-`as`) name so adding `Foo` is a
        // no-op when `Foo as Bar` is already imported, but adding
        // `Foo as Bar` is NOT a duplicate of bare `Foo` (different
        // local bindings).
        if !names.is_empty()
            && names
                .iter()
                .all(|n| imp.names.iter().any(|stored| specifier_matches(stored, n)))
        {
            return true;
        }
    }

    false
}

/// Check whether a fully structured add-import request is already present.
///
/// Legacy ES/Python/Rust/Go callers intentionally keep the historical
/// subset/dominance semantics (`import { a, b }` satisfies adding `{ a }`). The
/// newer engines carry language-specific shape in `ImportForm::Structured` (or
/// Solidity's dedicated form), where module path alone is not enough: include
/// delimiters, statement kinds, modifiers, aliases, and runtime import flavors
/// all affect the generated source. Those languages deduplicate on a canonical
/// full-form key so `#include <x>` does not block `#include "x"`, `load` does
/// not block `require`, and side-effect Solidity imports do not block aliases.
pub(crate) fn is_duplicate_import_request(
    lang: LangId,
    block: &ImportBlock,
    req: &ImportRequest<'_>,
) -> bool {
    if !uses_form_aware_dedup(lang) {
        return is_duplicate_with_namespace(
            block,
            req.module_path,
            req.names,
            req.default_import,
            req.namespace,
            req.type_only,
        );
    }

    let target = request_dedup_key(lang, req);
    block
        .imports
        .iter()
        .map(|imp| statement_dedup_key(lang, imp))
        .any(|key| key == target)
}

fn uses_form_aware_dedup(lang: LangId) -> bool {
    matches!(
        lang,
        LangId::Solidity
            | LangId::C
            | LangId::Cpp
            | LangId::Java
            | LangId::CSharp
            | LangId::Php
            | LangId::Kotlin
            | LangId::Scala
            | LangId::Swift
            | LangId::Ruby
            | LangId::Lua
            | LangId::Perl
    )
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct ImportDedupKey {
    module_path: String,
    kind: ImportKind,
    form: ImportForm,
}

fn statement_dedup_key(lang: LangId, imp: &ImportStatement) -> ImportDedupKey {
    canonical_dedup_key(
        lang,
        ImportDedupKey {
            module_path: imp.module_path.clone(),
            kind: imp.kind,
            form: imp.form.clone(),
        },
    )
}

fn request_dedup_key(lang: LangId, req: &ImportRequest<'_>) -> ImportDedupKey {
    let key = match lang {
        LangId::Solidity => {
            let kind = if req.names.is_empty() && req.namespace.is_none() && req.alias.is_none() {
                ImportKind::SideEffect
            } else {
                ImportKind::Value
            };
            ImportDedupKey {
                module_path: req.module_path.to_string(),
                kind,
                form: ImportForm::Solidity {
                    named: req.names.to_vec(),
                    namespace: req.namespace.map(str::to_string),
                    alias: req.alias.map(str::to_string),
                },
            }
        }
        LangId::C | LangId::Cpp => structured_dedup_key(
            req.module_path,
            ImportKind::SideEffect,
            &[],
            None,
            None,
            &[],
            Some(req.import_kind.or(req.default_import).unwrap_or("system")),
        ),
        LangId::Java => {
            let (mut module_path, modifiers) = wildcard_suffix_request(
                req.module_path,
                req.modifiers,
                req.default_import == Some("*"),
            );
            let mut names = req.names.to_vec();
            normalize_java_static_member_key(&mut module_path, &modifiers, &mut names);
            structured_dedup_key(
                &module_path,
                ImportKind::Value,
                &names,
                None,
                None,
                &modifiers,
                None,
            )
        }
        LangId::CSharp => structured_dedup_key(
            req.module_path,
            ImportKind::Value,
            &[],
            None,
            req.alias,
            req.modifiers,
            None,
        ),
        LangId::Php => structured_dedup_key(
            req.module_path,
            ImportKind::Value,
            &[],
            None,
            req.alias,
            req.modifiers,
            req.import_kind,
        ),
        LangId::Kotlin => {
            let wildcard = req.default_import == Some("*") || req.module_path.ends_with(".*");
            let (module_path, modifiers) =
                wildcard_suffix_request(req.module_path, req.modifiers, wildcard);
            let alias = req
                .alias
                .or(req.default_import.filter(|value| *value != "*"));
            structured_dedup_key(
                &module_path,
                ImportKind::Value,
                &[],
                None,
                alias,
                &modifiers,
                None,
            )
        }
        LangId::Scala => scala_request_dedup_key(req),
        LangId::Swift => structured_dedup_key(
            req.module_path,
            ImportKind::Value,
            &[],
            None,
            None,
            req.modifiers,
            req.import_kind,
        ),
        LangId::Ruby => {
            let mut modifiers = req.modifiers.to_vec();
            if !modifiers
                .iter()
                .any(|modifier| modifier == "quote:single" || modifier == "quote:double")
            {
                modifiers.push("quote:single".to_string());
            }
            structured_dedup_key(
                req.module_path,
                ImportKind::SideEffect,
                &[],
                None,
                None,
                &modifiers,
                Some(req.import_kind.unwrap_or("require")),
            )
        }
        LangId::Lua => {
            let alias = req.default_import.or(req.alias);
            let kind = if alias.is_some() {
                ImportKind::Value
            } else {
                ImportKind::SideEffect
            };
            structured_dedup_key(req.module_path, kind, &[], None, alias, req.modifiers, None)
        }
        LangId::Perl => structured_dedup_key(
            req.module_path,
            ImportKind::SideEffect,
            &[],
            None,
            None,
            req.modifiers,
            Some(req.import_kind.unwrap_or("use")),
        ),
        _ => structured_dedup_key(
            req.module_path,
            if req.type_only {
                ImportKind::Type
            } else {
                ImportKind::Value
            },
            req.names,
            req.namespace,
            req.alias,
            req.modifiers,
            req.import_kind,
        ),
    };

    canonical_dedup_key(lang, key)
}

fn structured_dedup_key(
    module_path: &str,
    kind: ImportKind,
    named: &[String],
    namespace: Option<&str>,
    alias: Option<&str>,
    modifiers: &[String],
    import_kind: Option<&str>,
) -> ImportDedupKey {
    ImportDedupKey {
        module_path: module_path.to_string(),
        kind,
        form: ImportForm::Structured {
            named: named.to_vec(),
            namespace: namespace.map(str::to_string),
            alias: alias.map(str::to_string),
            modifiers: modifiers.to_vec(),
            import_kind: import_kind.map(str::to_string),
        },
    }
}

fn wildcard_suffix_request(
    module_path: &str,
    modifiers: &[String],
    wildcard: bool,
) -> (String, Vec<String>) {
    let stripped = module_path.strip_suffix(".*").unwrap_or(module_path);
    let mut modifiers = modifiers.to_vec();
    if (wildcard || stripped.len() != module_path.len())
        && !modifiers.iter().any(|modifier| modifier == "wildcard")
    {
        modifiers.push("wildcard".to_string());
    }
    (stripped.to_string(), modifiers)
}

fn normalize_java_static_member_key(
    module_path: &mut String,
    modifiers: &[String],
    names: &mut Vec<String>,
) {
    let is_static = modifiers.iter().any(|modifier| modifier == "static");
    let is_wildcard = modifiers.iter().any(|modifier| modifier == "wildcard");
    if !is_static || is_wildcard || !names.is_empty() {
        return;
    }

    if let Some((prefix, member)) = module_path.rsplit_once('.') {
        if !prefix.is_empty() && !member.is_empty() {
            names.push(member.to_string());
            *module_path = prefix.to_string();
        }
    }
}

fn scala_request_dedup_key(req: &ImportRequest<'_>) -> ImportDedupKey {
    let mut module_path = req.module_path.to_string();
    let mut names: Vec<String> = req
        .names
        .iter()
        .map(|name| normalize_scala_selector_for_dedup(name))
        .collect();
    let mut modifiers = req.modifiers.to_vec();
    let mut import_kind = req.import_kind.map(str::to_string);

    if req.default_import == Some("given") || module_path.ends_with(".given") {
        import_kind.get_or_insert_with(|| "given".to_string());
        if let Some(stripped) = module_path.strip_suffix(".given") {
            module_path = stripped.to_string();
        }
    }

    if matches!(req.default_import, Some("*") | Some("_"))
        || matches!(req.namespace, Some("*") | Some("_"))
        || module_path.ends_with(".*")
        || module_path.ends_with("._")
    {
        if !modifiers.iter().any(|modifier| modifier == "wildcard") {
            modifiers.push("wildcard".to_string());
        }
        module_path = module_path
            .strip_suffix(".*")
            .or_else(|| module_path.strip_suffix("._"))
            .unwrap_or(&module_path)
            .to_string();
    }

    if names.is_empty() {
        if let Some(alias) = req.alias.filter(|alias| !alias.is_empty()) {
            if let Some((prefix, leaf)) = module_path.rsplit_once('.') {
                names.push(format!("{leaf} as {alias}"));
                module_path = prefix.to_string();
            }
        }
    }

    structured_dedup_key(
        &module_path,
        ImportKind::Value,
        &names,
        None,
        None,
        &modifiers,
        import_kind.as_deref(),
    )
}

fn normalize_scala_selector_for_dedup(name: &str) -> String {
    let trimmed = name.trim();
    if let Some((from, to)) = trimmed.split_once("=>") {
        format!("{} as {}", from.trim(), to.trim())
    } else {
        trimmed.to_string()
    }
}

fn canonical_dedup_key(lang: LangId, mut key: ImportDedupKey) -> ImportDedupKey {
    match &mut key.form {
        ImportForm::Structured { named, .. } | ImportForm::Solidity { named, .. } => {
            sort_named_specifiers(named);
        }
        ImportForm::Es { named, .. } | ImportForm::Python { named, .. } => {
            sort_named_specifiers(named);
        }
        ImportForm::RustUse { named, .. } => {
            sort_named_specifiers(named);
        }
        ImportForm::Go { .. } => {}
    }

    if matches!(lang, LangId::Java | LangId::Kotlin) {
        if let Some(stripped) = key.module_path.strip_suffix(".*") {
            key.module_path = stripped.to_string();
        }
        if matches!(lang, LangId::Java) {
            if let ImportForm::Structured {
                named, modifiers, ..
            } = &mut key.form
            {
                normalize_java_static_member_key(&mut key.module_path, modifiers, named);
            }
        }
    } else if matches!(lang, LangId::Scala) {
        key.module_path = key
            .module_path
            .strip_suffix(".given")
            .or_else(|| key.module_path.strip_suffix(".*"))
            .or_else(|| key.module_path.strip_suffix("._"))
            .unwrap_or(&key.module_path)
            .to_string();
    }

    key
}

fn sort_named_specifiers(names: &mut [String]) {
    names.sort_by(|a, b| {
        specifier_imported_name(a)
            .cmp(specifier_imported_name(b))
            .then_with(|| a.cmp(b))
    });
}

/// Find the byte offset where a new import should be inserted.
///
/// Strategy:
/// - Find all existing imports in the same group.
/// - Within that group, find the alphabetical position by module path.
/// - Type imports sort after value imports within the same group and module-sort position.
/// - If no imports exist in the target group, insert after the last import of the
///   nearest preceding group (or before the first import of the nearest following
///   group, or at file start if no groups exist).
/// - Returns (byte_offset, needs_newline_before, needs_newline_after)
pub fn find_insertion_point(
    source: &str,
    block: &ImportBlock,
    group: ImportGroup,
    module_path: &str,
    type_only: bool,
) -> (usize, bool, bool) {
    if block.imports.is_empty() {
        // No imports at all — insert at start of file
        return (0, false, source.is_empty().then_some(false).unwrap_or(true));
    }

    let target_kind = if type_only {
        ImportKind::Type
    } else {
        ImportKind::Value
    };

    // Collect imports in the target group
    let group_imports: Vec<&ImportStatement> =
        block.imports.iter().filter(|i| i.group == group).collect();

    if group_imports.is_empty() {
        // No imports in this group yet — find nearest neighbor group
        // Try preceding groups (lower ordinal) first
        let preceding_last = block.imports.iter().filter(|i| i.group < group).last();

        if let Some(last) = preceding_last {
            let end = last.byte_range.end;
            let insert_at = skip_newline(source, end);
            return (insert_at, true, true);
        }

        // No preceding group — try following groups (higher ordinal)
        let following_first = block.imports.iter().find(|i| i.group > group);

        if let Some(first) = following_first {
            return (first.byte_range.start, false, true);
        }

        // Shouldn't reach here if block is non-empty, but handle gracefully
        let first_byte = import_byte_range(&block.imports)
            .map(|range| range.start)
            .unwrap_or(0);
        return (first_byte, false, true);
    }

    // Find position within the group (alphabetical by module path, type after value)
    for imp in &group_imports {
        let cmp = module_path.cmp(&imp.module_path);
        match cmp {
            std::cmp::Ordering::Less => {
                // Insert before this import
                return (imp.byte_range.start, false, false);
            }
            std::cmp::Ordering::Equal => {
                // Same module — type imports go after value imports
                if target_kind == ImportKind::Type && imp.kind == ImportKind::Value {
                    // Insert after this value import
                    let end = imp.byte_range.end;
                    let insert_at = skip_newline(source, end);
                    return (insert_at, false, false);
                }
                // Insert before (or it's a duplicate, caller should have checked)
                return (imp.byte_range.start, false, false);
            }
            std::cmp::Ordering::Greater => continue,
        }
    }

    // Module path sorts after all existing imports in this group — insert at end
    let Some(last) = group_imports.last() else {
        return (
            import_byte_range(&block.imports)
                .map(|range| range.end)
                .unwrap_or(0),
            false,
            false,
        );
    };
    let end = last.byte_range.end;
    let insert_at = skip_newline(source, end);
    (insert_at, false, false)
}

/// Generate a single import line from a structured [`ImportRequest`]. The full
/// entry point — engines read the fields they support; unsupported languages
/// yield an empty string.
pub fn generate_import(lang: LangId, req: &ImportRequest) -> String {
    match syntax_for(lang) {
        Some(engine) => engine.generate_line(req),
        None => String::new(),
    }
}

/// Generate an import line for the given language. Back-compat wrapper over
/// [`generate_import`] for callers that pass only the legacy positional fields.
pub fn generate_import_line(
    lang: LangId,
    module_path: &str,
    names: &[String],
    default_import: Option<&str>,
    type_only: bool,
) -> String {
    generate_import(
        lang,
        &ImportRequest::legacy(module_path, names, default_import, None, type_only),
    )
}

/// Generate an import line including namespace imports
/// (`import * as ns from 'mod'`). Back-compat wrapper over [`generate_import`].
pub fn generate_import_line_with_namespace(
    lang: LangId,
    module_path: &str,
    names: &[String],
    default_import: Option<&str>,
    namespace_import: Option<&str>,
    type_only: bool,
) -> String {
    generate_import(
        lang,
        &ImportRequest::legacy(
            module_path,
            names,
            default_import,
            namespace_import,
            type_only,
        ),
    )
}

/// Check if the given language is supported by the import engine.
pub fn is_supported(lang: LangId) -> bool {
    syntax_for(lang).is_some()
}

/// Classify a module path into a group for TS/JS/TSX.
pub fn classify_group_ts(module_path: &str) -> ImportGroup {
    if module_path.starts_with('.') {
        ImportGroup::Internal
    } else {
        ImportGroup::External
    }
}

/// Classify a module path into a group for the given language.
pub fn classify_group(lang: LangId, module_path: &str) -> ImportGroup {
    match syntax_for(lang) {
        Some(engine) => engine.classify_group(module_path),
        // Unsupported languages have no grouping policy; External is the
        // historical neutral default.
        None => ImportGroup::External,
    }
}

/// Parse a file from disk and return its import block.
/// Convenience wrapper that handles parsing.
pub fn parse_file_imports(
    path: &std::path::Path,
    lang: LangId,
) -> Result<(String, Tree, ImportBlock), crate::error::AftError> {
    let source =
        std::fs::read_to_string(path).map_err(|e| crate::error::AftError::FileNotFound {
            path: format!("{}: {}", path.display(), e),
        })?;

    let grammar = grammar_for(lang);
    let mut parser = Parser::new();
    parser
        .set_language(&grammar)
        .map_err(|e| crate::error::AftError::ParseError {
            message: format!("grammar init failed for {:?}: {}", lang, e),
        })?;

    let tree = parser
        .parse(&source, None)
        .ok_or_else(|| crate::error::AftError::ParseError {
            message: format!("tree-sitter parse returned None for {}", path.display()),
        })?;

    let block = parse_imports(&source, &tree, lang);
    Ok((source, tree, block))
}

// ---------------------------------------------------------------------------
// TS/JS/TSX implementation
// ---------------------------------------------------------------------------

/// Parse imports from a TS/JS/TSX file.
///
/// Walks the AST root's direct children looking for `import_statement` nodes (D041).
fn parse_ts_imports(source: &str, tree: &Tree) -> ImportBlock {
    let root = tree.root_node();
    let mut imports = Vec::new();

    let mut cursor = root.walk();
    if !cursor.goto_first_child() {
        return ImportBlock::empty();
    }

    loop {
        let node = cursor.node();
        if node.kind() == "import_statement" {
            if let Some(imp) = parse_single_ts_import(source, &node) {
                imports.push(imp);
            }
        }
        if !cursor.goto_next_sibling() {
            break;
        }
    }

    let byte_range = import_byte_range(&imports);

    ImportBlock {
        imports,
        byte_range,
    }
}

/// Parse a single `import_statement` node into an `ImportStatement`.
fn parse_single_ts_import(source: &str, node: &Node) -> Option<ImportStatement> {
    let raw_text = source[node.byte_range()].to_string();
    let byte_range = node.byte_range();

    // Find the source module (string/string_fragment child of the import)
    let module_path = extract_module_path(source, node)?;

    // Determine if this is a type-only import: `import type ...`
    let is_type_only = has_type_keyword(node);

    // Extract import clause details
    let mut names = Vec::new();
    let mut default_import = None;
    let mut namespace_import = None;

    let mut child_cursor = node.walk();
    if child_cursor.goto_first_child() {
        loop {
            let child = child_cursor.node();
            match child.kind() {
                "import_clause" => {
                    extract_import_clause(
                        source,
                        &child,
                        &mut names,
                        &mut default_import,
                        &mut namespace_import,
                    );
                }
                // In some grammars, the default import is a direct identifier child
                "identifier" => {
                    let text = &source[child.byte_range()];
                    if text != "import" && text != "from" && text != "type" {
                        default_import = Some(text.to_string());
                    }
                }
                _ => {}
            }
            if !child_cursor.goto_next_sibling() {
                break;
            }
        }
    }

    // Classify kind
    let kind = if names.is_empty() && default_import.is_none() && namespace_import.is_none() {
        ImportKind::SideEffect
    } else if is_type_only {
        ImportKind::Type
    } else {
        ImportKind::Value
    };

    let group = classify_group_ts(&module_path);

    let form = ImportForm::Es {
        default_import: default_import.clone(),
        namespace_import: namespace_import.clone(),
        named: names.clone(),
        type_only: is_type_only,
        side_effect: matches!(kind, ImportKind::SideEffect),
    };

    Some(ImportStatement {
        module_path,
        names,
        default_import,
        namespace_import,
        kind,
        group,
        byte_range,
        raw_text,
        form,
    })
}

/// Extract the module path string from an import_statement node.
///
/// Looks for a `string` child node and extracts the content without quotes.
fn extract_module_path(source: &str, node: &Node) -> Option<String> {
    let mut cursor = node.walk();
    if !cursor.goto_first_child() {
        return None;
    }

    loop {
        let child = cursor.node();
        if child.kind() == "string" {
            // Get the text and strip quotes
            let text = &source[child.byte_range()];
            let stripped = text
                .trim_start_matches(|c| c == '\'' || c == '"')
                .trim_end_matches(|c| c == '\'' || c == '"');
            return Some(stripped.to_string());
        }
        if !cursor.goto_next_sibling() {
            break;
        }
    }
    None
}

/// Check if the import_statement has a `type` keyword (import type ...).
///
/// In tree-sitter-typescript, `import type { X } from 'y'` produces a `type`
/// node as a direct child of `import_statement`, between `import` and `import_clause`.
fn has_type_keyword(node: &Node) -> bool {
    let mut cursor = node.walk();
    if !cursor.goto_first_child() {
        return false;
    }

    loop {
        let child = cursor.node();
        if child.kind() == "type" {
            return true;
        }
        if !cursor.goto_next_sibling() {
            break;
        }
    }

    false
}

/// Extract named imports, default import, and namespace import from an import_clause.
fn extract_import_clause(
    source: &str,
    node: &Node,
    names: &mut Vec<String>,
    default_import: &mut Option<String>,
    namespace_import: &mut Option<String>,
) {
    let mut cursor = node.walk();
    if !cursor.goto_first_child() {
        return;
    }

    loop {
        let child = cursor.node();
        match child.kind() {
            "identifier" => {
                // This is a default import: `import Foo from 'bar'`
                let text = &source[child.byte_range()];
                if text != "type" {
                    *default_import = Some(text.to_string());
                }
            }
            "named_imports" => {
                // `{ name1, name2 }`
                extract_named_imports(source, &child, names);
            }
            "namespace_import" => {
                // `* as name`
                extract_namespace_import(source, &child, namespace_import);
            }
            _ => {}
        }
        if !cursor.goto_next_sibling() {
            break;
        }
    }
}

/// Extract individual names from a named_imports node (`{ a, b, c }`).
///
/// Each name is stored verbatim including any alias and per-name `type`
/// modifier so the regenerator can round-trip them losslessly. Examples of
/// captured forms:
///
/// - `useState`               (plain)
/// - `stdin as input`         (renamed)
/// - `type Foo`               (per-specifier type-only)
/// - `type Foo as Bar`        (per-specifier type-only with rename)
///
/// **Why verbatim strings instead of a struct field per attribute:** dedup,
/// sort, dropping a single import, and the regenerator are all driven by
/// `Vec<String>` today. Encoding the alias inside the string preserves the
/// shape so the rest of the pipeline (organize, remove_import, move_symbol)
/// keeps working without a workspace-wide refactor. The cost is that callers
/// who want the canonical name (e.g. dedup) must compare on the leading
/// identifier only — see `extract_canonical_name` if you need that.
fn extract_named_imports(source: &str, node: &Node, names: &mut Vec<String>) {
    let mut cursor = node.walk();
    if !cursor.goto_first_child() {
        return;
    }

    loop {
        let child = cursor.node();
        if child.kind() == "import_specifier" {
            // Capture the full text of the specifier so per-name `type` markers
            // and `as alias` clauses are preserved across organize/regenerate
            // round-trips. Falls back to the imported name if the specifier
            // text is empty for any reason.
            let raw = source[child.byte_range()].trim().to_string();
            if !raw.is_empty() {
                names.push(raw);
            } else if let Some(name_node) = child.child_by_field_name("name") {
                names.push(source[name_node.byte_range()].to_string());
            }
        }
        if !cursor.goto_next_sibling() {
            break;
        }
    }
}

/// Extract the alias name from a namespace_import node (`* as name`).
fn extract_namespace_import(source: &str, node: &Node, namespace_import: &mut Option<String>) {
    let mut cursor = node.walk();
    if !cursor.goto_first_child() {
        return;
    }

    loop {
        let child = cursor.node();
        if child.kind() == "identifier" {
            *namespace_import = Some(source[child.byte_range()].to_string());
            return;
        }
        if !cursor.goto_next_sibling() {
            break;
        }
    }
}

/// Generate an import line for TS/JS/TSX.
fn generate_ts_import_line(
    module_path: &str,
    names: &[String],
    default_import: Option<&str>,
    namespace_import: Option<&str>,
    type_only: bool,
) -> String {
    let type_prefix = if type_only { "type " } else { "" };

    // Side-effect import
    if names.is_empty() && default_import.is_none() && namespace_import.is_none() {
        return format!("import '{module_path}';");
    }

    // Namespace import only
    if names.is_empty() && default_import.is_none() {
        if let Some(namespace) = namespace_import {
            return format!("import {type_prefix}* as {namespace} from '{module_path}';");
        }
    }

    // Default + namespace import
    if names.is_empty() {
        if let (Some(def), Some(namespace)) = (default_import, namespace_import) {
            return format!("import {type_prefix}{def}, * as {namespace} from '{module_path}';");
        }
    }

    // Default import only
    if names.is_empty() && namespace_import.is_none() {
        if let Some(def) = default_import {
            return format!("import {type_prefix}{def} from '{module_path}';");
        }
    }

    // Named imports only
    if default_import.is_none() && namespace_import.is_none() {
        let mut sorted_names = names.to_vec();
        sort_named_specifiers(&mut sorted_names);
        let names_str = sorted_names.join(", ");
        return format!("import {type_prefix}{{ {names_str} }} from '{module_path}';");
    }

    // Namespace + named imports
    if default_import.is_none() {
        if let Some(namespace) = namespace_import {
            let mut sorted_names = names.to_vec();
            sort_named_specifiers(&mut sorted_names);
            let names_str = sorted_names.join(", ");
            return format!(
                "import {type_prefix}{{ {names_str} }}, * as {namespace} from '{module_path}';"
            );
        }
    }

    // Default + named + namespace imports
    if let (Some(def), Some(namespace)) = (default_import, namespace_import) {
        let mut sorted_names = names.to_vec();
        sort_named_specifiers(&mut sorted_names);
        let names_str = sorted_names.join(", ");
        return format!(
            "import {type_prefix}{def}, {{ {names_str} }}, * as {namespace} from '{module_path}';"
        );
    }

    // Both default and named imports
    if let Some(def) = default_import {
        let mut sorted_names = names.to_vec();
        sort_named_specifiers(&mut sorted_names);
        let names_str = sorted_names.join(", ");
        return format!("import {type_prefix}{def}, {{ {names_str} }} from '{module_path}';");
    }

    // Shouldn't reach here, but handle gracefully
    format!("import '{module_path}';")
}

// ---------------------------------------------------------------------------
// Python implementation
// ---------------------------------------------------------------------------

/// Python 3.x standard library module names (top-level modules).
/// Used for import group classification. Covers the commonly-used modules;
/// unknown modules are assumed third-party.
const PYTHON_STDLIB: &[&str] = &[
    "__future__",
    "_thread",
    "abc",
    "aifc",
    "argparse",
    "array",
    "ast",
    "asynchat",
    "asyncio",
    "asyncore",
    "atexit",
    "audioop",
    "base64",
    "bdb",
    "binascii",
    "bisect",
    "builtins",
    "bz2",
    "calendar",
    "cgi",
    "cgitb",
    "chunk",
    "cmath",
    "cmd",
    "code",
    "codecs",
    "codeop",
    "collections",
    "colorsys",
    "compileall",
    "concurrent",
    "configparser",
    "contextlib",
    "contextvars",
    "copy",
    "copyreg",
    "cProfile",
    "crypt",
    "csv",
    "ctypes",
    "curses",
    "dataclasses",
    "datetime",
    "dbm",
    "decimal",
    "difflib",
    "dis",
    "distutils",
    "doctest",
    "email",
    "encodings",
    "enum",
    "errno",
    "faulthandler",
    "fcntl",
    "filecmp",
    "fileinput",
    "fnmatch",
    "fractions",
    "ftplib",
    "functools",
    "gc",
    "getopt",
    "getpass",
    "gettext",
    "glob",
    "grp",
    "gzip",
    "hashlib",
    "heapq",
    "hmac",
    "html",
    "http",
    "idlelib",
    "imaplib",
    "imghdr",
    "importlib",
    "inspect",
    "io",
    "ipaddress",
    "itertools",
    "json",
    "keyword",
    "lib2to3",
    "linecache",
    "locale",
    "logging",
    "lzma",
    "mailbox",
    "mailcap",
    "marshal",
    "math",
    "mimetypes",
    "mmap",
    "modulefinder",
    "multiprocessing",
    "netrc",
    "numbers",
    "operator",
    "optparse",
    "os",
    "pathlib",
    "pdb",
    "pickle",
    "pickletools",
    "pipes",
    "pkgutil",
    "platform",
    "plistlib",
    "poplib",
    "posixpath",
    "pprint",
    "profile",
    "pstats",
    "pty",
    "pwd",
    "py_compile",
    "pyclbr",
    "pydoc",
    "queue",
    "quopri",
    "random",
    "re",
    "readline",
    "reprlib",
    "resource",
    "rlcompleter",
    "runpy",
    "sched",
    "secrets",
    "select",
    "selectors",
    "shelve",
    "shlex",
    "shutil",
    "signal",
    "site",
    "smtplib",
    "sndhdr",
    "socket",
    "socketserver",
    "sqlite3",
    "ssl",
    "stat",
    "statistics",
    "string",
    "stringprep",
    "struct",
    "subprocess",
    "symtable",
    "sys",
    "sysconfig",
    "syslog",
    "tabnanny",
    "tarfile",
    "tempfile",
    "termios",
    "textwrap",
    "threading",
    "time",
    "timeit",
    "tkinter",
    "token",
    "tokenize",
    "tomllib",
    "trace",
    "traceback",
    "tracemalloc",
    "tty",
    "turtle",
    "types",
    "typing",
    "unicodedata",
    "unittest",
    "urllib",
    "uuid",
    "venv",
    "warnings",
    "wave",
    "weakref",
    "webbrowser",
    "wsgiref",
    "xml",
    "xmlrpc",
    "zipapp",
    "zipfile",
    "zipimport",
    "zlib",
];

/// Classify a Python import into a group.
pub fn classify_group_py(module_path: &str) -> ImportGroup {
    // Relative imports start with '.'
    if module_path.starts_with('.') {
        return ImportGroup::Internal;
    }
    // Check stdlib: use the top-level module name (before first '.')
    let top_module = module_path.split('.').next().unwrap_or(module_path);
    if PYTHON_STDLIB.contains(&top_module) {
        ImportGroup::Stdlib
    } else {
        ImportGroup::External
    }
}

/// Parse imports from a Python file.
fn parse_py_imports(source: &str, tree: &Tree) -> ImportBlock {
    let root = tree.root_node();
    let mut imports = Vec::new();

    let mut cursor = root.walk();
    if !cursor.goto_first_child() {
        return ImportBlock::empty();
    }

    loop {
        let node = cursor.node();
        match node.kind() {
            "import_statement" => {
                if let Some(imp) = parse_py_import_statement(source, &node) {
                    imports.push(imp);
                }
            }
            "import_from_statement" => {
                if let Some(imp) = parse_py_import_from_statement(source, &node) {
                    imports.push(imp);
                }
            }
            _ => {}
        }
        if !cursor.goto_next_sibling() {
            break;
        }
    }

    let byte_range = import_byte_range(&imports);

    ImportBlock {
        imports,
        byte_range,
    }
}

/// Parse `import X` or `import X.Y` Python statements.
fn parse_py_import_statement(source: &str, node: &Node) -> Option<ImportStatement> {
    let raw_text = source[node.byte_range()].to_string();
    let byte_range = node.byte_range();

    // Find the dotted_name child (the module name)
    let mut module_path = String::new();
    let mut c = node.walk();
    if c.goto_first_child() {
        loop {
            if c.node().kind() == "dotted_name" {
                module_path = source[c.node().byte_range()].to_string();
                break;
            }
            if !c.goto_next_sibling() {
                break;
            }
        }
    }
    if module_path.is_empty() {
        return None;
    }

    let group = classify_group_py(&module_path);

    Some(ImportStatement {
        module_path,
        names: Vec::new(),
        default_import: None,
        namespace_import: None,
        kind: ImportKind::Value,
        group,
        byte_range,
        raw_text,
        form: ImportForm::Python {
            from_import: false,
            named: Vec::new(),
        },
    })
}

/// Parse `from X import Y, Z` or `from . import Y` Python statements.
fn parse_py_import_from_statement(source: &str, node: &Node) -> Option<ImportStatement> {
    let raw_text = source[node.byte_range()].to_string();
    let byte_range = node.byte_range();

    let mut module_path = String::new();
    let mut names = Vec::new();

    let mut c = node.walk();
    if c.goto_first_child() {
        loop {
            let child = c.node();
            match child.kind() {
                "dotted_name" => {
                    // Could be the module name or an imported name
                    // The module name comes right after `from`, imported names come after `import`
                    // Use position: if we haven't set module_path yet and this comes
                    // before the `import` keyword, it's the module.
                    if module_path.is_empty()
                        && !has_seen_import_keyword(source, node, child.start_byte())
                    {
                        module_path = source[child.byte_range()].to_string();
                    } else {
                        // It's an imported name
                        names.push(source[child.byte_range()].to_string());
                    }
                }
                "relative_import" => {
                    // from . import X or from ..module import X
                    module_path = source[child.byte_range()].to_string();
                }
                _ => {}
            }
            if !c.goto_next_sibling() {
                break;
            }
        }
    }

    // module_path must be non-empty for a valid import
    if module_path.is_empty() {
        return None;
    }

    let group = classify_group_py(&module_path);

    Some(ImportStatement {
        module_path,
        names: names.clone(),
        default_import: None,
        namespace_import: None,
        kind: ImportKind::Value,
        group,
        byte_range,
        raw_text,
        form: ImportForm::Python {
            from_import: true,
            named: names,
        },
    })
}

/// Check if the `import` keyword appears before the given byte position in a from...import node.
fn has_seen_import_keyword(_source: &str, parent: &Node, before_byte: usize) -> bool {
    let mut c = parent.walk();
    if c.goto_first_child() {
        loop {
            let child = c.node();
            if child.kind() == "import" && child.start_byte() < before_byte {
                return true;
            }
            if child.start_byte() >= before_byte {
                return false;
            }
            if !c.goto_next_sibling() {
                break;
            }
        }
    }
    false
}

/// Generate a Python import line.
fn generate_py_import_line(
    module_path: &str,
    names: &[String],
    _default_import: Option<&str>,
) -> String {
    if names.is_empty() {
        // `import module`
        format!("import {module_path}")
    } else {
        // `from module import name1, name2`
        let mut sorted = names.to_vec();
        sorted.sort();
        let names_str = sorted.join(", ");
        format!("from {module_path} import {names_str}")
    }
}

// ---------------------------------------------------------------------------
// Rust implementation
// ---------------------------------------------------------------------------

/// Classify a Rust use path into a group.
pub fn classify_group_rs(module_path: &str) -> ImportGroup {
    // Extract the first path segment (before ::)
    let first_seg = module_path.split("::").next().unwrap_or(module_path);
    match first_seg {
        "std" | "core" | "alloc" => ImportGroup::Stdlib,
        "crate" | "self" | "super" => ImportGroup::Internal,
        _ => ImportGroup::External,
    }
}

/// Parse imports from a Rust file.
fn parse_rs_imports(source: &str, tree: &Tree) -> ImportBlock {
    let root = tree.root_node();
    let mut imports = Vec::new();

    let mut cursor = root.walk();
    if !cursor.goto_first_child() {
        return ImportBlock::empty();
    }

    loop {
        let node = cursor.node();
        if node.kind() == "use_declaration" {
            if let Some(imp) = parse_rs_use_declaration(source, &node) {
                imports.push(imp);
            }
        }
        if !cursor.goto_next_sibling() {
            break;
        }
    }

    let byte_range = import_byte_range(&imports);

    ImportBlock {
        imports,
        byte_range,
    }
}

/// Parse a single `use` declaration from Rust.
fn parse_rs_use_declaration(source: &str, node: &Node) -> Option<ImportStatement> {
    let raw_text = source[node.byte_range()].to_string();
    let byte_range = node.byte_range();

    // Check for `pub` visibility modifier
    let mut has_pub = false;
    let mut use_path = String::new();
    let mut names = Vec::new();

    let mut c = node.walk();
    if c.goto_first_child() {
        loop {
            let child = c.node();
            match child.kind() {
                "visibility_modifier" => {
                    has_pub = true;
                }
                "scoped_identifier" | "identifier" | "use_as_clause" => {
                    // Full path like `std::collections::HashMap` or just `serde`
                    use_path = source[child.byte_range()].to_string();
                }
                "scoped_use_list" => {
                    // e.g. `serde::{Deserialize, Serialize}`
                    use_path = source[child.byte_range()].to_string();
                    // Also extract the individual names from the use_list
                    extract_rs_use_list_names(source, &child, &mut names);
                }
                _ => {}
            }
            if !c.goto_next_sibling() {
                break;
            }
        }
    }

    if use_path.is_empty() {
        return None;
    }

    let group = classify_group_rs(&use_path);

    Some(ImportStatement {
        module_path: use_path,
        names: names.clone(),
        default_import: if has_pub {
            Some("pub".to_string())
        } else {
            None
        },
        namespace_import: None,
        kind: ImportKind::Value,
        group,
        byte_range,
        raw_text,
        form: ImportForm::RustUse {
            // Only bare `pub` is recognized by the current parser; richer
            // visibilities (`pub(crate)`, …) collapse to the same flag today and
            // will be parsed precisely when the Rust engine moves onto `form`.
            visibility: has_pub.then(|| "pub".to_string()),
            named: names,
        },
    })
}

/// Extract individual names from a Rust `scoped_use_list` node.
fn extract_rs_use_list_names(source: &str, node: &Node, names: &mut Vec<String>) {
    let mut c = node.walk();
    if c.goto_first_child() {
        loop {
            let child = c.node();
            if child.kind() == "use_list" {
                // Walk into the use_list to find identifiers
                let mut lc = child.walk();
                if lc.goto_first_child() {
                    loop {
                        let lchild = lc.node();
                        if lchild.kind() == "identifier" || lchild.kind() == "scoped_identifier" {
                            names.push(source[lchild.byte_range()].to_string());
                        }
                        if !lc.goto_next_sibling() {
                            break;
                        }
                    }
                }
            }
            if !c.goto_next_sibling() {
                break;
            }
        }
    }
}

/// Generate a Rust import line.
fn generate_rs_import_line(module_path: &str, names: &[String], _type_only: bool) -> String {
    if names.is_empty() {
        format!("use {module_path};")
    } else {
        let mut sorted_names = names.to_vec();
        sort_named_specifiers(&mut sorted_names);
        format!("use {module_path}::{{{}}};", sorted_names.join(", "))
    }
}

// ---------------------------------------------------------------------------
// Go implementation
// ---------------------------------------------------------------------------

/// Classify a Go import path into a group.
pub fn classify_group_go(module_path: &str) -> ImportGroup {
    // stdlib paths don't contain dots (e.g., "fmt", "os", "net/http")
    // external paths contain dots (e.g., "github.com/pkg/errors")
    if module_path.contains('.') {
        ImportGroup::External
    } else {
        ImportGroup::Stdlib
    }
}

/// Parse imports from a Go file.
fn parse_go_imports(source: &str, tree: &Tree) -> ImportBlock {
    let root = tree.root_node();
    let mut imports = Vec::new();

    let mut cursor = root.walk();
    if !cursor.goto_first_child() {
        return ImportBlock::empty();
    }

    loop {
        let node = cursor.node();
        if node.kind() == "import_declaration" {
            parse_go_import_declaration(source, &node, &mut imports);
        }
        if !cursor.goto_next_sibling() {
            break;
        }
    }

    let byte_range = import_byte_range(&imports);

    ImportBlock {
        imports,
        byte_range,
    }
}

/// Parse a single Go import_declaration (may contain one or multiple specs).
fn parse_go_import_declaration(source: &str, node: &Node, imports: &mut Vec<ImportStatement>) {
    let mut c = node.walk();
    if c.goto_first_child() {
        loop {
            let child = c.node();
            match child.kind() {
                "import_spec" => {
                    if let Some(imp) = parse_go_import_spec(source, &child) {
                        imports.push(imp);
                    }
                }
                "import_spec_list" => {
                    // Grouped imports: walk into the list
                    let mut lc = child.walk();
                    if lc.goto_first_child() {
                        loop {
                            if lc.node().kind() == "import_spec" {
                                if let Some(imp) = parse_go_import_spec(source, &lc.node()) {
                                    imports.push(imp);
                                }
                            }
                            if !lc.goto_next_sibling() {
                                break;
                            }
                        }
                    }
                }
                _ => {}
            }
            if !c.goto_next_sibling() {
                break;
            }
        }
    }
}

/// Parse a single Go import_spec node.
fn parse_go_import_spec(source: &str, node: &Node) -> Option<ImportStatement> {
    let raw_text = source[node.byte_range()].to_string();
    let byte_range = node.byte_range();

    let mut import_path = String::new();
    let mut alias = None;

    let mut c = node.walk();
    if c.goto_first_child() {
        loop {
            let child = c.node();
            match child.kind() {
                "interpreted_string_literal" => {
                    // Extract the path without quotes
                    let text = source[child.byte_range()].to_string();
                    import_path = text.trim_matches('"').to_string();
                }
                "identifier" | "blank_identifier" | "dot" => {
                    // This is an alias (e.g., `alias "path"` or `. "path"` or `_ "path"`)
                    alias = Some(source[child.byte_range()].to_string());
                }
                _ => {}
            }
            if !c.goto_next_sibling() {
                break;
            }
        }
    }

    if import_path.is_empty() {
        return None;
    }

    let group = classify_group_go(&import_path);

    Some(ImportStatement {
        module_path: import_path,
        names: Vec::new(),
        default_import: alias.clone(),
        namespace_import: None,
        kind: ImportKind::Value,
        group,
        byte_range,
        raw_text,
        form: ImportForm::Go { alias },
    })
}

/// Public API for Go import line generation (used by add_import handler).
pub fn generate_go_import_line_pub(
    module_path: &str,
    alias: Option<&str>,
    in_group: bool,
) -> String {
    generate_go_import_line(module_path, alias, in_group)
}

/// Generate a Go import line (public API for command handler).
///
/// `in_group` controls whether to generate a spec for insertion into an
/// existing grouped import (`\t"path"`) or a standalone import (`import "path"`).
fn generate_go_import_line(module_path: &str, alias: Option<&str>, in_group: bool) -> String {
    if in_group {
        // Spec for grouped import block
        match alias {
            Some(a) => format!("\t{a} \"{module_path}\""),
            None => format!("\t\"{module_path}\""),
        }
    } else {
        // Standalone import
        match alias {
            Some(a) => format!("import {a} \"{module_path}\""),
            None => format!("import \"{module_path}\""),
        }
    }
}

/// Check if a Go import block has a grouped import declaration.
/// Returns the byte range of the full import_declaration if found.
pub fn go_has_grouped_import(_source: &str, tree: &Tree) -> Option<Range<usize>> {
    let root = tree.root_node();
    let mut cursor = root.walk();
    if !cursor.goto_first_child() {
        return None;
    }

    loop {
        let node = cursor.node();
        if node.kind() == "import_declaration" && go_import_declaration_is_grouped(&node) {
            return Some(node.byte_range());
        }
        if !cursor.goto_next_sibling() {
            break;
        }
    }
    None
}

pub fn go_import_declarations_range(_source: &str, tree: &Tree) -> Option<Range<usize>> {
    let root = tree.root_node();
    let mut cursor = root.walk();
    let mut range: Option<Range<usize>> = None;
    if !cursor.goto_first_child() {
        return None;
    }

    loop {
        let node = cursor.node();
        if node.kind() == "import_declaration" {
            let node_range = node.byte_range();
            range = Some(match range {
                Some(existing) => {
                    existing.start.min(node_range.start)..existing.end.max(node_range.end)
                }
                None => node_range,
            });
        }
        if !cursor.goto_next_sibling() {
            break;
        }
    }

    range
}

pub fn go_offset_is_in_grouped_import(_source: &str, tree: &Tree, offset: usize) -> bool {
    let root = tree.root_node();
    let mut cursor = root.walk();
    if !cursor.goto_first_child() {
        return false;
    }

    loop {
        let node = cursor.node();
        if node.kind() == "import_declaration"
            && node.start_byte() < offset
            && offset < node.end_byte()
            && go_import_declaration_is_grouped(&node)
        {
            return true;
        }
        if !cursor.goto_next_sibling() {
            break;
        }
    }

    false
}

fn go_import_declaration_is_grouped(node: &Node) -> bool {
    let mut c = node.walk();
    if c.goto_first_child() {
        loop {
            if c.node().kind() == "import_spec_list" {
                return true;
            }
            if !c.goto_next_sibling() {
                break;
            }
        }
    }
    false
}

// ---------------------------------------------------------------------------
// Solidity implementation
// ---------------------------------------------------------------------------

/// Classify a Solidity import path: relative (`./`, `../`) is internal,
/// everything else (remappings, `@scope/...`, bare) is external. No stdlib.
pub fn classify_group_solidity(module_path: &str) -> ImportGroup {
    if module_path.starts_with('.') {
        ImportGroup::Internal
    } else {
        ImportGroup::External
    }
}

fn parse_solidity_imports(source: &str, tree: &Tree) -> ImportBlock {
    let root = tree.root_node();
    let mut imports = Vec::new();
    let mut cursor = root.walk();
    if cursor.goto_first_child() {
        loop {
            let node = cursor.node();
            if node.kind() == "import_directive" {
                if let Some(imp) = parse_solidity_import_directive(source, &node) {
                    imports.push(imp);
                }
            }
            if !cursor.goto_next_sibling() {
                break;
            }
        }
    }
    let byte_range = import_byte_range(&imports);
    ImportBlock {
        imports,
        byte_range,
    }
}

/// Parse one `import_directive`. The Solidity grammar emits a flat token
/// sequence (verified by grammar fixture test), so the four forms are
/// distinguished by the presence of `{` (named), `*` (namespace), a trailing
/// `as` (whole-file alias), or none (side-effect).
fn parse_solidity_import_directive(source: &str, node: &Node) -> Option<ImportStatement> {
    let raw_text = source[node.byte_range()].to_string();
    let byte_range = node.byte_range();

    let mut children: Vec<(String, String)> = Vec::new();
    let mut c = node.walk();
    if c.goto_first_child() {
        loop {
            let ch = c.node();
            children.push((ch.kind().to_string(), source[ch.byte_range()].to_string()));
            if !c.goto_next_sibling() {
                break;
            }
        }
    }

    // Every form carries exactly one string literal: the imported file path.
    let module_path = children
        .iter()
        .find(|(k, _)| k == "string")
        .map(|(_, t)| t.trim_matches('"').to_string())?;
    if module_path.is_empty() {
        return None;
    }

    let has_brace = children.iter().any(|(k, _)| k == "{");
    let has_star = children.iter().any(|(k, _)| k == "*");

    let mut named: Vec<String> = Vec::new();
    let mut namespace: Option<String> = None;
    let mut alias: Option<String> = None;

    if has_brace {
        named = parse_solidity_named_specifiers(&children);
    } else if has_star {
        namespace = solidity_identifier_after_as(&children);
    } else {
        // No `{`, no `*`: a trailing `as IDENT` is a whole-file alias;
        // otherwise a bare side-effect import.
        alias = solidity_identifier_after_as(&children);
    }

    let kind = if named.is_empty() && namespace.is_none() && alias.is_none() {
        ImportKind::SideEffect
    } else {
        ImportKind::Value
    };
    let group = classify_group_solidity(&module_path);

    Some(ImportStatement {
        module_path,
        names: named.clone(),
        default_import: None,
        // Namespace maps to the flat slot so existing readers (dedup) see it;
        // the whole-file alias has no flat slot and lives only in `form`.
        namespace_import: namespace.clone(),
        kind,
        group,
        byte_range,
        raw_text,
        form: ImportForm::Solidity {
            named,
            namespace,
            alias,
        },
    })
}

/// Return the `identifier` token immediately following the first `as`.
fn solidity_identifier_after_as(children: &[(String, String)]) -> Option<String> {
    let as_pos = children.iter().position(|(k, _)| k == "as")?;
    children[as_pos + 1..]
        .iter()
        .find(|(k, _)| k == "identifier")
        .map(|(_, t)| t.clone())
}

/// Collect named specifiers between `{` and `}` into verbatim strings,
/// combining `A as B` into `"A as B"` to match the ES specifier convention.
fn parse_solidity_named_specifiers(children: &[(String, String)]) -> Vec<String> {
    let mut names = Vec::new();
    let mut in_braces = false;
    let mut current: Option<String> = None;
    let mut expect_alias = false;
    for (k, t) in children {
        match k.as_str() {
            "{" => in_braces = true,
            "}" => {
                if let Some(n) = current.take() {
                    names.push(n);
                }
                in_braces = false;
            }
            _ if !in_braces => {}
            "identifier" => {
                if expect_alias {
                    if let Some(n) = current.take() {
                        names.push(format!("{n} as {t}"));
                    }
                    expect_alias = false;
                } else {
                    if let Some(n) = current.take() {
                        names.push(n);
                    }
                    current = Some(t.clone());
                }
            }
            "as" => expect_alias = true,
            "," => {
                if let Some(n) = current.take() {
                    names.push(n);
                }
                expect_alias = false;
            }
            _ => {}
        }
    }
    names
}

/// Generate a Solidity import line in the appropriate form.
fn generate_solidity_import_line(req: &ImportRequest) -> String {
    if !req.names.is_empty() {
        format!(
            "import {{ {} }} from \"{}\";",
            req.names.join(", "),
            req.module_path
        )
    } else if let Some(ns) = req.namespace {
        format!("import * as {} from \"{}\";", ns, req.module_path)
    } else if let Some(al) = req.alias {
        format!("import \"{}\" as {};", req.module_path, al)
    } else {
        format!("import \"{}\";", req.module_path)
    }
}

/// Skip past a newline character at the given position.
fn skip_newline(source: &str, pos: usize) -> usize {
    if pos < source.len() {
        let bytes = source.as_bytes();
        if bytes[pos] == b'\n' {
            return pos + 1;
        }
        if bytes[pos] == b'\r' {
            if pos + 1 < source.len() && bytes[pos + 1] == b'\n' {
                return pos + 2;
            }
            return pos + 1;
        }
    }
    pos
}

// ---------------------------------------------------------------------------
// Unit tests
// ---------------------------------------------------------------------------

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

    // --- ImportForm field-mapping contract (Stream M) ---
    //
    // These assert the additive `form` field faithfully mirrors the flat
    // fields each parser populates. They are the executable field-mapping
    // contract from the migration plan: when a reader is moved off a flat
    // field onto `form`, these guarantee no information was lost in the
    // de-overloading (Rust `pub`, Go alias) or restructuring.

    #[test]
    fn form_es_mirrors_flat_fields() {
        let (_, block) = parse_ts(
            "import Default, { a, b as c } from \"ext\";\nimport type { T } from \"./t\";\nimport \"./side\";\nimport * as ns from \"nspkg\";\n",
        );
        // import Default, { a, b as c } from "ext"
        match &block.imports[0].form {
            ImportForm::Es {
                default_import,
                namespace_import,
                named,
                type_only,
                side_effect,
            } => {
                assert_eq!(default_import.as_deref(), Some("Default"));
                assert_eq!(namespace_import, &None);
                assert_eq!(named, &block.imports[0].names);
                assert!(!type_only);
                assert!(!side_effect);
            }
            other => panic!("expected Es, got {other:?}"),
        }
        // import type { T } from "./t"
        match &block.imports[1].form {
            ImportForm::Es {
                type_only, named, ..
            } => {
                assert!(type_only);
                assert_eq!(named, &block.imports[1].names);
            }
            other => panic!("expected Es type-only, got {other:?}"),
        }
        // import "./side"
        match &block.imports[2].form {
            ImportForm::Es { side_effect, .. } => assert!(side_effect),
            other => panic!("expected Es side-effect, got {other:?}"),
        }
        // import * as ns from "nspkg"
        match &block.imports[3].form {
            ImportForm::Es {
                namespace_import, ..
            } => assert_eq!(namespace_import.as_deref(), Some("ns")),
            other => panic!("expected Es namespace, got {other:?}"),
        }
    }

    #[test]
    fn form_python_mirrors_flat_fields() {
        let (_, block) = parse_py("import os\nfrom sys import argv, path\n");
        match &block.imports[0].form {
            ImportForm::Python { from_import, named } => {
                assert!(!from_import, "`import os` is not a from-import");
                assert!(named.is_empty());
            }
            other => panic!("expected Python import, got {other:?}"),
        }
        match &block.imports[1].form {
            ImportForm::Python { from_import, named } => {
                assert!(from_import, "`from sys import ...` is a from-import");
                assert_eq!(named, &block.imports[1].names);
            }
            other => panic!("expected Python from-import, got {other:?}"),
        }
    }

    #[test]
    fn form_rust_de_overloads_pub_from_default_import() {
        let (_, block) = parse_rust("pub use crate::a::Exported;\nuse std::fmt::Debug;\n");
        // pub use -> visibility=Some("pub"); flat field still carries the "pub" hack.
        match &block.imports[0].form {
            ImportForm::RustUse { visibility, named } => {
                assert_eq!(visibility.as_deref(), Some("pub"));
                assert_eq!(named, &block.imports[0].names);
            }
            other => panic!("expected RustUse, got {other:?}"),
        }
        assert_eq!(
            block.imports[0].default_import.as_deref(),
            Some("pub"),
            "flat field unchanged during additive migration"
        );
        // plain use -> visibility=None
        match &block.imports[1].form {
            ImportForm::RustUse { visibility, .. } => assert_eq!(visibility, &None),
            other => panic!("expected RustUse, got {other:?}"),
        }
        assert_eq!(block.imports[1].default_import, None);
    }

    #[test]
    fn form_go_de_overloads_alias_from_default_import() {
        // The current Go parser only captures blank (`_`) / dot bindings as the
        // alias (regular package aliases like `al "path"` are a pre-existing
        // parser gap — not extracted into `default_import` today). The contract
        // locked here is that `form.alias` mirrors `default_import` exactly,
        // whatever the parser captures, so the de-overload is information-faithful.
        let (_, block) =
            parse_go("package main\n\nimport (\n\t_ \"github.com/x/y\"\n\t\"fmt\"\n)\n");
        let blank = block
            .imports
            .iter()
            .find(|i| i.module_path == "github.com/x/y")
            .expect("blank import parsed");
        match &blank.form {
            ImportForm::Go { alias } => assert_eq!(alias.as_deref(), Some("_")),
            other => panic!("expected Go blank-aliased, got {other:?}"),
        }
        assert_eq!(
            blank.default_import.as_deref(),
            Some("_"),
            "form.alias mirrors the flat default_import field exactly"
        );
        let plain = block
            .imports
            .iter()
            .find(|i| i.module_path == "fmt")
            .expect("plain import parsed");
        match &plain.form {
            ImportForm::Go { alias } => assert_eq!(alias, &None),
            other => panic!("expected Go plain, got {other:?}"),
        }
        assert_eq!(plain.default_import, None);
    }

    fn parse_ts(source: &str) -> (Tree, ImportBlock) {
        let grammar = grammar_for(LangId::TypeScript);
        let mut parser = Parser::new();
        parser.set_language(&grammar).unwrap();
        let tree = parser.parse(source, None).unwrap();
        let block = parse_imports(source, &tree, LangId::TypeScript);
        (tree, block)
    }

    fn parse_js(source: &str) -> (Tree, ImportBlock) {
        let grammar = grammar_for(LangId::JavaScript);
        let mut parser = Parser::new();
        parser.set_language(&grammar).unwrap();
        let tree = parser.parse(source, None).unwrap();
        let block = parse_imports(source, &tree, LangId::JavaScript);
        (tree, block)
    }

    fn parse_vue(source: &str) -> (Tree, ImportBlock) {
        let grammar = grammar_for(LangId::Vue);
        let mut parser = Parser::new();
        parser.set_language(&grammar).unwrap();
        let tree = parser.parse(source, None).unwrap();
        let block = parse_imports(source, &tree, LangId::Vue);
        (tree, block)
    }

    /// Locks the tree-sitter-vue node kinds the Vue engine depends on: the
    /// `<script>` body is exposed as a single `raw_text` node inside a
    /// `script_element`. If a grammar bump changes this, the engine breaks
    /// silently, so assert it here.
    #[test]
    fn vue_grammar_node_kinds_are_stable() {
        let src = "<template>\n  <div />\n</template>\n\n<script setup lang=\"ts\">\nimport { ref } from 'vue'\n</script>\n";
        let grammar = grammar_for(LangId::Vue);
        let mut parser = Parser::new();
        parser.set_language(&grammar).unwrap();
        let tree = parser.parse(src, None).unwrap();
        let root = tree.root_node();
        let mut cursor = root.walk();
        let script = root
            .named_children(&mut cursor)
            .find(|n| n.kind() == "script_element")
            .expect("expected a script_element node");
        let mut inner = script.walk();
        assert!(
            script
                .named_children(&mut inner)
                .any(|n| n.kind() == "raw_text"),
            "expected script body exposed as raw_text"
        );
    }

    #[test]
    fn vue_parses_script_imports_with_whole_file_offsets() {
        let src = "<template>\n  <div />\n</template>\n\n<script setup lang=\"ts\">\nimport { ref } from 'vue'\nimport Foo from './Foo.vue'\nconst x = ref(0)\n</script>\n";
        let (_tree, block) = parse_vue(src);
        assert_eq!(block.imports.len(), 2, "should find both script imports");
        // Byte ranges must be whole-file (inside the <script> block), not
        // script-relative — verify the raw slice round-trips.
        for imp in &block.imports {
            assert_eq!(&src[imp.byte_range.clone()], imp.raw_text);
            assert!(
                imp.byte_range.start > src.find("<script").unwrap(),
                "import offset must fall inside the script block"
            );
        }
        assert_eq!(block.imports[0].module_path, "vue");
        assert_eq!(block.imports[1].module_path, "./Foo.vue");
    }

    #[test]
    fn vue_without_script_block_has_no_imports() {
        let src = "<template>\n  <div />\n</template>\n\n<style>.x{}</style>\n";
        let (_tree, block) = parse_vue(src);
        assert!(block.imports.is_empty());
        assert!(block.byte_range.is_none());
    }

    // --- Basic parsing ---

    #[test]
    fn parse_ts_named_imports() {
        let source = "import { useState, useEffect } from 'react';\n";
        let (_, block) = parse_ts(source);
        assert_eq!(block.imports.len(), 1);
        let imp = &block.imports[0];
        assert_eq!(imp.module_path, "react");
        assert!(imp.names.contains(&"useState".to_string()));
        assert!(imp.names.contains(&"useEffect".to_string()));
        assert_eq!(imp.kind, ImportKind::Value);
        assert_eq!(imp.group, ImportGroup::External);
    }

    #[test]
    fn parse_ts_default_import() {
        let source = "import React from 'react';\n";
        let (_, block) = parse_ts(source);
        assert_eq!(block.imports.len(), 1);
        let imp = &block.imports[0];
        assert_eq!(imp.default_import.as_deref(), Some("React"));
        assert_eq!(imp.kind, ImportKind::Value);
    }

    #[test]
    fn parse_ts_side_effect_import() {
        let source = "import './styles.css';\n";
        let (_, block) = parse_ts(source);
        assert_eq!(block.imports.len(), 1);
        assert_eq!(block.imports[0].kind, ImportKind::SideEffect);
        assert_eq!(block.imports[0].module_path, "./styles.css");
    }

    #[test]
    fn parse_ts_relative_import() {
        let source = "import { helper } from './utils';\n";
        let (_, block) = parse_ts(source);
        assert_eq!(block.imports.len(), 1);
        assert_eq!(block.imports[0].group, ImportGroup::Internal);
    }

    #[test]
    fn parse_ts_multiple_groups() {
        let source = "\
import React from 'react';
import { useState } from 'react';
import { helper } from './utils';
import { Config } from '../config';
";
        let (_, block) = parse_ts(source);
        assert_eq!(block.imports.len(), 4);

        let external: Vec<_> = block
            .imports
            .iter()
            .filter(|i| i.group == ImportGroup::External)
            .collect();
        let relative: Vec<_> = block
            .imports
            .iter()
            .filter(|i| i.group == ImportGroup::Internal)
            .collect();
        assert_eq!(external.len(), 2);
        assert_eq!(relative.len(), 2);
    }

    #[test]
    fn parse_ts_namespace_import() {
        let source = "import * as path from 'path';\n";
        let (_, block) = parse_ts(source);
        assert_eq!(block.imports.len(), 1);
        let imp = &block.imports[0];
        assert_eq!(imp.namespace_import.as_deref(), Some("path"));
        assert_eq!(imp.kind, ImportKind::Value);
    }

    #[test]
    fn parse_js_imports() {
        let source = "import { readFile } from 'fs';\nimport { helper } from './helper';\n";
        let (_, block) = parse_js(source);
        assert_eq!(block.imports.len(), 2);
        assert_eq!(block.imports[0].group, ImportGroup::External);
        assert_eq!(block.imports[1].group, ImportGroup::Internal);
    }

    // --- Group classification ---

    #[test]
    fn classify_external() {
        assert_eq!(classify_group_ts("react"), ImportGroup::External);
        assert_eq!(classify_group_ts("@scope/pkg"), ImportGroup::External);
        assert_eq!(classify_group_ts("lodash/map"), ImportGroup::External);
    }

    #[test]
    fn classify_relative() {
        assert_eq!(classify_group_ts("./utils"), ImportGroup::Internal);
        assert_eq!(classify_group_ts("../config"), ImportGroup::Internal);
        assert_eq!(classify_group_ts("./"), ImportGroup::Internal);
    }

    // --- Dedup ---

    #[test]
    fn dedup_detects_same_named_import() {
        let source = "import { useState } from 'react';\n";
        let (_, block) = parse_ts(source);
        assert!(is_duplicate(
            &block,
            "react",
            &["useState".to_string()],
            None,
            false
        ));
    }

    #[test]
    fn dedup_misses_different_name() {
        let source = "import { useState } from 'react';\n";
        let (_, block) = parse_ts(source);
        assert!(!is_duplicate(
            &block,
            "react",
            &["useEffect".to_string()],
            None,
            false
        ));
    }

    #[test]
    fn dedup_detects_default_import() {
        let source = "import React from 'react';\n";
        let (_, block) = parse_ts(source);
        assert!(is_duplicate(&block, "react", &[], Some("React"), false));
    }

    #[test]
    fn dedup_side_effect() {
        let source = "import './styles.css';\n";
        let (_, block) = parse_ts(source);
        assert!(is_duplicate(&block, "./styles.css", &[], None, false));
    }

    #[test]
    fn dedup_namespace_import_distinct_from_side_effect_import() {
        let side_effect_source = "import 'fs';\n";
        let (_, side_effect_block) = parse_ts(side_effect_source);
        assert!(!is_duplicate_with_namespace(
            &side_effect_block,
            "fs",
            &[],
            None,
            Some("fs"),
            false
        ));

        let namespace_source = "import * as fs from 'fs';\n";
        let (_, namespace_block) = parse_ts(namespace_source);
        assert!(!is_duplicate(&namespace_block, "fs", &[], None, false));
        assert!(is_duplicate_with_namespace(
            &namespace_block,
            "fs",
            &[],
            None,
            Some("fs"),
            false
        ));
        assert!(!is_duplicate_with_namespace(
            &namespace_block,
            "fs",
            &[],
            None,
            Some("other"),
            false
        ));
    }

    #[test]
    fn dedup_type_vs_value() {
        let source = "import { FC } from 'react';\n";
        let (_, block) = parse_ts(source);
        // Type import should NOT match a value import of the same name
        assert!(!is_duplicate(
            &block,
            "react",
            &["FC".to_string()],
            None,
            true
        ));
    }

    // --- Generation ---

    #[test]
    fn generate_named_import() {
        let line = generate_import_line(
            LangId::TypeScript,
            "react",
            &["useState".to_string(), "useEffect".to_string()],
            None,
            false,
        );
        assert_eq!(line, "import { useEffect, useState } from 'react';");
    }

    #[test]
    fn generate_named_import_sorts_by_imported_name() {
        let line = generate_import_line(
            LangId::TypeScript,
            "x",
            &[
                "useState".to_string(),
                "type Foo".to_string(),
                "stdin as input".to_string(),
                "type Bar".to_string(),
            ],
            None,
            false,
        );
        assert_eq!(
            line,
            "import { type Bar, type Foo, stdin as input, useState } from 'x';"
        );
    }

    #[test]
    fn generate_default_import() {
        let line = generate_import_line(LangId::TypeScript, "react", &[], Some("React"), false);
        assert_eq!(line, "import React from 'react';");
    }

    #[test]
    fn generate_type_import() {
        let line =
            generate_import_line(LangId::TypeScript, "react", &["FC".to_string()], None, true);
        assert_eq!(line, "import type { FC } from 'react';");
    }

    #[test]
    fn generate_side_effect_import() {
        let line = generate_import_line(LangId::TypeScript, "./styles.css", &[], None, false);
        assert_eq!(line, "import './styles.css';");
    }

    #[test]
    fn generate_default_and_named() {
        let line = generate_import_line(
            LangId::TypeScript,
            "react",
            &["useState".to_string()],
            Some("React"),
            false,
        );
        assert_eq!(line, "import React, { useState } from 'react';");
    }

    #[test]
    fn parse_ts_type_import() {
        let source = "import type { FC } from 'react';\n";
        let (_, block) = parse_ts(source);
        assert_eq!(block.imports.len(), 1);
        let imp = &block.imports[0];
        assert_eq!(imp.kind, ImportKind::Type);
        assert!(imp.names.contains(&"FC".to_string()));
        assert_eq!(imp.group, ImportGroup::External);
    }

    // --- Insertion point ---

    #[test]
    fn insertion_empty_file() {
        let source = "";
        let (_, block) = parse_ts(source);
        let (offset, _, _) =
            find_insertion_point(source, &block, ImportGroup::External, "react", false);
        assert_eq!(offset, 0);
    }

    #[test]
    fn insertion_alphabetical_within_group() {
        let source = "\
import { a } from 'alpha';
import { c } from 'charlie';
";
        let (_, block) = parse_ts(source);
        let (offset, _, _) =
            find_insertion_point(source, &block, ImportGroup::External, "bravo", false);
        // Should insert before 'charlie' (which starts at line 2)
        let before_charlie = source.find("import { c }").unwrap();
        assert_eq!(offset, before_charlie);
    }

    // --- Python parsing ---

    fn parse_py(source: &str) -> (Tree, ImportBlock) {
        let grammar = grammar_for(LangId::Python);
        let mut parser = Parser::new();
        parser.set_language(&grammar).unwrap();
        let tree = parser.parse(source, None).unwrap();
        let block = parse_imports(source, &tree, LangId::Python);
        (tree, block)
    }

    #[test]
    fn parse_py_import_statement() {
        let source = "import os\nimport sys\n";
        let (_, block) = parse_py(source);
        assert_eq!(block.imports.len(), 2);
        assert_eq!(block.imports[0].module_path, "os");
        assert_eq!(block.imports[1].module_path, "sys");
        assert_eq!(block.imports[0].group, ImportGroup::Stdlib);
    }

    #[test]
    fn parse_py_from_import() {
        let source = "from collections import OrderedDict\nfrom typing import List, Optional\n";
        let (_, block) = parse_py(source);
        assert_eq!(block.imports.len(), 2);
        assert_eq!(block.imports[0].module_path, "collections");
        assert!(block.imports[0].names.contains(&"OrderedDict".to_string()));
        assert_eq!(block.imports[0].group, ImportGroup::Stdlib);
        assert_eq!(block.imports[1].module_path, "typing");
        assert!(block.imports[1].names.contains(&"List".to_string()));
        assert!(block.imports[1].names.contains(&"Optional".to_string()));
    }

    #[test]
    fn parse_py_relative_import() {
        let source = "from . import utils\nfrom ..config import Settings\n";
        let (_, block) = parse_py(source);
        assert_eq!(block.imports.len(), 2);
        assert_eq!(block.imports[0].module_path, ".");
        assert!(block.imports[0].names.contains(&"utils".to_string()));
        assert_eq!(block.imports[0].group, ImportGroup::Internal);
        assert_eq!(block.imports[1].module_path, "..config");
        assert_eq!(block.imports[1].group, ImportGroup::Internal);
    }

    #[test]
    fn classify_py_groups() {
        assert_eq!(classify_group_py("os"), ImportGroup::Stdlib);
        assert_eq!(classify_group_py("sys"), ImportGroup::Stdlib);
        assert_eq!(classify_group_py("json"), ImportGroup::Stdlib);
        assert_eq!(classify_group_py("collections"), ImportGroup::Stdlib);
        assert_eq!(classify_group_py("os.path"), ImportGroup::Stdlib);
        assert_eq!(classify_group_py("requests"), ImportGroup::External);
        assert_eq!(classify_group_py("flask"), ImportGroup::External);
        assert_eq!(classify_group_py("."), ImportGroup::Internal);
        assert_eq!(classify_group_py("..config"), ImportGroup::Internal);
        assert_eq!(classify_group_py(".utils"), ImportGroup::Internal);
    }

    #[test]
    fn parse_py_three_groups() {
        let source = "import os\nimport sys\n\nimport requests\n\nfrom . import utils\n";
        let (_, block) = parse_py(source);
        let stdlib: Vec<_> = block
            .imports
            .iter()
            .filter(|i| i.group == ImportGroup::Stdlib)
            .collect();
        let external: Vec<_> = block
            .imports
            .iter()
            .filter(|i| i.group == ImportGroup::External)
            .collect();
        let internal: Vec<_> = block
            .imports
            .iter()
            .filter(|i| i.group == ImportGroup::Internal)
            .collect();
        assert_eq!(stdlib.len(), 2);
        assert_eq!(external.len(), 1);
        assert_eq!(internal.len(), 1);
    }

    #[test]
    fn generate_py_import() {
        let line = generate_import_line(LangId::Python, "os", &[], None, false);
        assert_eq!(line, "import os");
    }

    #[test]
    fn generate_py_from_import() {
        let line = generate_import_line(
            LangId::Python,
            "collections",
            &["OrderedDict".to_string()],
            None,
            false,
        );
        assert_eq!(line, "from collections import OrderedDict");
    }

    #[test]
    fn generate_py_from_import_multiple() {
        let line = generate_import_line(
            LangId::Python,
            "typing",
            &["Optional".to_string(), "List".to_string()],
            None,
            false,
        );
        assert_eq!(line, "from typing import List, Optional");
    }

    // --- Rust parsing ---

    fn parse_rust(source: &str) -> (Tree, ImportBlock) {
        let grammar = grammar_for(LangId::Rust);
        let mut parser = Parser::new();
        parser.set_language(&grammar).unwrap();
        let tree = parser.parse(source, None).unwrap();
        let block = parse_imports(source, &tree, LangId::Rust);
        (tree, block)
    }

    #[test]
    fn parse_rs_use_std() {
        let source = "use std::collections::HashMap;\nuse std::io::Read;\n";
        let (_, block) = parse_rust(source);
        assert_eq!(block.imports.len(), 2);
        assert_eq!(block.imports[0].module_path, "std::collections::HashMap");
        assert_eq!(block.imports[0].group, ImportGroup::Stdlib);
        assert_eq!(block.imports[1].group, ImportGroup::Stdlib);
    }

    #[test]
    fn parse_rs_use_external() {
        let source = "use serde::{Deserialize, Serialize};\n";
        let (_, block) = parse_rust(source);
        assert_eq!(block.imports.len(), 1);
        assert_eq!(block.imports[0].group, ImportGroup::External);
        assert!(block.imports[0].names.contains(&"Deserialize".to_string()));
        assert!(block.imports[0].names.contains(&"Serialize".to_string()));
    }

    #[test]
    fn parse_rs_use_crate() {
        let source = "use crate::config::Settings;\nuse super::parent::Thing;\n";
        let (_, block) = parse_rust(source);
        assert_eq!(block.imports.len(), 2);
        assert_eq!(block.imports[0].group, ImportGroup::Internal);
        assert_eq!(block.imports[1].group, ImportGroup::Internal);
    }

    #[test]
    fn parse_rs_pub_use() {
        let source = "pub use super::parent::Thing;\n";
        let (_, block) = parse_rust(source);
        assert_eq!(block.imports.len(), 1);
        // `pub` is stored in default_import as a marker
        assert_eq!(block.imports[0].default_import.as_deref(), Some("pub"));
    }

    #[test]
    fn classify_rs_groups() {
        assert_eq!(
            classify_group_rs("std::collections::HashMap"),
            ImportGroup::Stdlib
        );
        assert_eq!(classify_group_rs("core::mem"), ImportGroup::Stdlib);
        assert_eq!(classify_group_rs("alloc::vec"), ImportGroup::Stdlib);
        assert_eq!(
            classify_group_rs("serde::Deserialize"),
            ImportGroup::External
        );
        assert_eq!(classify_group_rs("tokio::runtime"), ImportGroup::External);
        assert_eq!(classify_group_rs("crate::config"), ImportGroup::Internal);
        assert_eq!(classify_group_rs("self::utils"), ImportGroup::Internal);
        assert_eq!(classify_group_rs("super::parent"), ImportGroup::Internal);
    }

    #[test]
    fn generate_rs_use() {
        let line = generate_import_line(LangId::Rust, "std::fmt::Display", &[], None, false);
        assert_eq!(line, "use std::fmt::Display;");
    }

    // --- Go parsing ---

    fn parse_go(source: &str) -> (Tree, ImportBlock) {
        let grammar = grammar_for(LangId::Go);
        let mut parser = Parser::new();
        parser.set_language(&grammar).unwrap();
        let tree = parser.parse(source, None).unwrap();
        let block = parse_imports(source, &tree, LangId::Go);
        (tree, block)
    }

    #[test]
    fn parse_go_single_import() {
        let source = "package main\n\nimport \"fmt\"\n";
        let (_, block) = parse_go(source);
        assert_eq!(block.imports.len(), 1);
        assert_eq!(block.imports[0].module_path, "fmt");
        assert_eq!(block.imports[0].group, ImportGroup::Stdlib);
    }

    #[test]
    fn parse_go_grouped_import() {
        let source =
            "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/pkg/errors\"\n)\n";
        let (_, block) = parse_go(source);
        assert_eq!(block.imports.len(), 3);
        assert_eq!(block.imports[0].module_path, "fmt");
        assert_eq!(block.imports[0].group, ImportGroup::Stdlib);
        assert_eq!(block.imports[1].module_path, "os");
        assert_eq!(block.imports[1].group, ImportGroup::Stdlib);
        assert_eq!(block.imports[2].module_path, "github.com/pkg/errors");
        assert_eq!(block.imports[2].group, ImportGroup::External);
    }

    #[test]
    fn parse_go_mixed_imports() {
        // Single + grouped
        let source = "package main\n\nimport \"fmt\"\n\nimport (\n\t\"os\"\n\t\"github.com/pkg/errors\"\n)\n";
        let (_, block) = parse_go(source);
        assert_eq!(block.imports.len(), 3);
    }

    #[test]
    fn classify_go_groups() {
        assert_eq!(classify_group_go("fmt"), ImportGroup::Stdlib);
        assert_eq!(classify_group_go("os"), ImportGroup::Stdlib);
        assert_eq!(classify_group_go("net/http"), ImportGroup::Stdlib);
        assert_eq!(classify_group_go("encoding/json"), ImportGroup::Stdlib);
        assert_eq!(
            classify_group_go("github.com/pkg/errors"),
            ImportGroup::External
        );
        assert_eq!(
            classify_group_go("golang.org/x/tools"),
            ImportGroup::External
        );
    }

    #[test]
    fn generate_go_standalone() {
        let line = generate_go_import_line("fmt", None, false);
        assert_eq!(line, "import \"fmt\"");
    }

    #[test]
    fn generate_go_grouped_spec() {
        let line = generate_go_import_line("fmt", None, true);
        assert_eq!(line, "\t\"fmt\"");
    }

    #[test]
    fn generate_go_with_alias() {
        let line = generate_go_import_line("github.com/pkg/errors", Some("errs"), false);
        assert_eq!(line, "import errs \"github.com/pkg/errors\"");
    }

    // --- Solidity (Phase 1: first new language on the ImportSyntax registry) ---

    fn parse_solidity(source: &str) -> (Tree, ImportBlock) {
        let grammar = grammar_for(LangId::Solidity);
        let mut parser = Parser::new();
        parser.set_language(&grammar).unwrap();
        let tree = parser.parse(source, None).unwrap();
        let block = parse_imports(source, &tree, LangId::Solidity);
        (tree, block)
    }

    /// Grammar fixture (council #6): lock the tree-sitter-solidity node kinds the
    /// parser depends on. If the grammar updates and renames these, this test
    /// fails loudly before the parser silently mis-parses.
    #[test]
    fn solidity_grammar_node_kinds_are_stable() {
        let grammar = grammar_for(LangId::Solidity);
        let mut parser = Parser::new();
        parser.set_language(&grammar).unwrap();
        let src = "import { Foo, Bar as Baz } from \"./A.sol\";\nimport * as N from \"./B.sol\";\nimport \"./C.sol\" as C;\nimport \"./D.sol\";\n";
        let tree = parser.parse(src, None).unwrap();
        let mut kinds: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
        fn walk(node: tree_sitter::Node, kinds: &mut std::collections::BTreeSet<String>) {
            kinds.insert(node.kind().to_string());
            let mut c = node.walk();
            if c.goto_first_child() {
                loop {
                    walk(c.node(), kinds);
                    if !c.goto_next_sibling() {
                        break;
                    }
                }
            }
        }
        walk(tree.root_node(), &mut kinds);
        for required in [
            "import_directive",
            "string",
            "identifier",
            "as",
            "from",
            "*",
            "{",
            "}",
        ] {
            assert!(
                kinds.contains(required),
                "solidity grammar missing node kind {required:?}; present: {kinds:?}"
            );
        }
    }

    #[test]
    fn parse_solidity_all_four_forms() {
        let (_, block) = parse_solidity(
            "import \"./A.sol\";\nimport \"./B.sol\" as B;\nimport * as C from \"./C.sol\";\nimport { Foo, Bar as Baz } from \"./D.sol\";\n",
        );
        assert_eq!(block.imports.len(), 4);

        // side-effect
        assert_eq!(block.imports[0].module_path, "./A.sol");
        assert_eq!(block.imports[0].kind, ImportKind::SideEffect);
        assert_eq!(
            block.imports[0].form,
            ImportForm::Solidity {
                named: vec![],
                namespace: None,
                alias: None
            }
        );

        // whole-file alias
        assert_eq!(
            block.imports[1].form,
            ImportForm::Solidity {
                named: vec![],
                namespace: None,
                alias: Some("B".to_string())
            }
        );

        // namespace
        match &block.imports[2].form {
            ImportForm::Solidity { namespace, .. } => assert_eq!(namespace.as_deref(), Some("C")),
            other => panic!("expected Solidity namespace, got {other:?}"),
        }
        assert_eq!(block.imports[2].namespace_import.as_deref(), Some("C"));

        // named with alias (verbatim specifier convention)
        match &block.imports[3].form {
            ImportForm::Solidity { named, .. } => {
                assert_eq!(named, &vec!["Foo".to_string(), "Bar as Baz".to_string()]);
            }
            other => panic!("expected Solidity named, got {other:?}"),
        }
        assert_eq!(
            block.imports[3].names,
            vec!["Foo".to_string(), "Bar as Baz".to_string()]
        );
    }

    #[test]
    fn generate_solidity_all_forms() {
        // side-effect
        assert_eq!(
            generate_import(
                LangId::Solidity,
                &ImportRequest::legacy("./A.sol", &[], None, None, false)
            ),
            "import \"./A.sol\";"
        );
        // named
        let names = vec!["Foo".to_string(), "Bar as Baz".to_string()];
        assert_eq!(
            generate_import(
                LangId::Solidity,
                &ImportRequest::legacy("./D.sol", &names, None, None, false)
            ),
            "import { Foo, Bar as Baz } from \"./D.sol\";"
        );
        // namespace
        assert_eq!(
            generate_import(
                LangId::Solidity,
                &ImportRequest::legacy("./C.sol", &[], None, Some("C"), false)
            ),
            "import * as C from \"./C.sol\";"
        );
        // whole-file alias
        assert_eq!(
            generate_import(
                LangId::Solidity,
                &ImportRequest {
                    module_path: "./B.sol",
                    names: &[],
                    default_import: None,
                    namespace: None,
                    alias: Some("B"),
                    type_only: false,
                    modifiers: &[],
                    import_kind: None,
                }
            ),
            "import \"./B.sol\" as B;"
        );
    }

    #[test]
    fn solidity_round_trips_through_parse_generate() {
        // Every generated form must parse back to the same structured shape.
        for src in [
            "import \"./A.sol\";",
            "import \"./B.sol\" as B;",
            "import * as C from \"./C.sol\";",
            "import { Foo, Bar as Baz } from \"./D.sol\";",
        ] {
            let (_, block) = parse_solidity(src);
            assert_eq!(block.imports.len(), 1, "parse {src:?}");
            let imp = &block.imports[0];
            let (namespace, alias) = match &imp.form {
                ImportForm::Solidity {
                    namespace, alias, ..
                } => (namespace.as_deref(), alias.as_deref()),
                other => panic!("expected Solidity, got {other:?}"),
            };
            let regenerated = generate_import(
                LangId::Solidity,
                &ImportRequest {
                    module_path: &imp.module_path,
                    names: &imp.names,
                    default_import: None,
                    namespace,
                    alias,
                    type_only: false,
                    modifiers: &[],
                    import_kind: None,
                },
            );
            assert_eq!(regenerated, src, "round-trip mismatch for {src:?}");
        }
    }

    #[test]
    fn classify_group_solidity_relative_vs_external() {
        assert_eq!(classify_group_solidity("./A.sol"), ImportGroup::Internal);
        assert_eq!(
            classify_group_solidity("../lib/B.sol"),
            ImportGroup::Internal
        );
        assert_eq!(
            classify_group_solidity("@openzeppelin/contracts/token/ERC20/ERC20.sol"),
            ImportGroup::External
        );
    }
}