agent-file-tools 0.35.2

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
//! Integration tests for the add_import command through the binary protocol.

use super::helpers::{fixture_path, AftProcess};
use aft::imports::{generate_import_line_with_namespace, parse_file_imports};
use aft::parser::LangId;
use std::fs;

/// Helper: copy a fixture to a uniquely-named temp file for mutation testing.
fn temp_copy(fixture_name: &str) -> (tempfile::TempDir, std::path::PathBuf) {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);

    let src = fixture_path(fixture_name);
    let dir = tempfile::tempdir().unwrap();

    let n = COUNTER.fetch_add(1, Ordering::SeqCst);
    let (stem, ext) = fixture_name.rsplit_once('.').unwrap_or((fixture_name, ""));
    let unique = if ext.is_empty() {
        format!("{}_{}", stem, n)
    } else {
        format!("{}_{}.{}", stem, n, ext)
    };
    let dest = dir.path().join(unique);
    fs::copy(&src, &dest).unwrap();
    (dir, dest)
}

/// Helper: send an add_import request and return the response.
fn send_add_import(
    aft: &mut AftProcess,
    id: &str,
    file: &str,
    module: &str,
    names: Option<&[&str]>,
    default_import: Option<&str>,
    type_only: bool,
) -> serde_json::Value {
    let mut params = serde_json::json!({
        "id": id,
        "command": "add_import",
        "file": file,
        "module": module,
    });

    if let Some(names) = names {
        params["names"] = serde_json::json!(names);
    }
    if let Some(def) = default_import {
        params["default_import"] = serde_json::json!(def);
    }
    if type_only {
        params["type_only"] = serde_json::json!(true);
    }

    aft.send(&serde_json::to_string(&params).unwrap())
}

// --- TS tests ---

#[test]
fn add_import_ts_external_group() {
    let mut aft = AftProcess::spawn();
    let (_dir, file) = temp_copy("imports_ts.ts");
    let file_str = file.display().to_string();

    let resp = send_add_import(
        &mut aft,
        "imp-1",
        &file_str,
        "lodash",
        Some(&["debounce"]),
        None,
        false,
    );

    assert_eq!(
        resp["success"], true,
        "add_import should succeed: {:?}",
        resp
    );
    assert_eq!(resp["added"], true);
    assert_eq!(resp["group"], "external");

    // Verify the import was added to the file
    let content = fs::read_to_string(&file).unwrap();
    assert!(
        content.contains("import { debounce } from 'lodash';"),
        "should contain the new import. content:\n{}",
        content
    );

    // Verify it's in the external group (before relative imports)
    let lodash_pos = content.find("import { debounce } from 'lodash'").unwrap();
    let relative_pos = content.find("import { helper } from './utils'").unwrap();
    assert!(
        lodash_pos < relative_pos,
        "lodash import should be before relative imports"
    );

    // Syntax should be valid
    assert_eq!(
        resp["syntax_valid"], true,
        "syntax should be valid after add, resp: {:?}",
        resp
    );

    // Cleanup
    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn add_import_ts_relative_group() {
    let mut aft = AftProcess::spawn();
    let (_dir, file) = temp_copy("imports_ts.ts");
    let file_str = file.display().to_string();

    let resp = send_add_import(
        &mut aft,
        "imp-2",
        &file_str,
        "./components",
        Some(&["Button"]),
        None,
        false,
    );

    assert_eq!(
        resp["success"], true,
        "add_import should succeed: {:?}",
        resp
    );
    assert_eq!(resp["added"], true);
    assert_eq!(resp["group"], "internal");

    let content = fs::read_to_string(&file).unwrap();
    assert!(
        content.contains("import { Button } from './components';"),
        "should contain the new relative import. content:\n{}",
        content
    );

    // Verify it's in the relative group (after external imports)
    let button_pos = content
        .find("import { Button } from './components'")
        .unwrap();
    let react_pos = content.find("import React from 'react'").unwrap();
    assert!(
        button_pos > react_pos,
        "relative import should be after external imports"
    );

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn add_import_ts_allows_parent_relative_module() {
    let mut aft = AftProcess::spawn();
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("parent_relative.ts");
    fs::write(&file, "export const x = 1;\n").unwrap();

    let resp = send_add_import(
        &mut aft,
        "imp-parent-relative",
        &file.display().to_string(),
        "../config",
        Some(&["Config"]),
        None,
        false,
    );

    assert_eq!(
        resp["success"], true,
        "relative add should succeed: {resp:?}"
    );
    let content = fs::read_to_string(&file).unwrap();
    assert!(
        content.contains("import { Config } from '../config';"),
        "single-parent ES relative imports must remain allowed:\n{content}"
    );

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn add_import_c_allows_parent_relative_include() {
    let mut aft = AftProcess::spawn();
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("relative_include.c");
    fs::write(&file, "int main(void) { return 0; }\n").unwrap();

    let resp = send_add_import(
        &mut aft,
        "imp-c-parent-relative",
        &file.display().to_string(),
        "\"../foo.h\"",
        None,
        None,
        false,
    );

    assert_eq!(
        resp["success"], true,
        "parent-relative C include should succeed: {resp:?}"
    );
    let content = fs::read_to_string(&file).unwrap();
    assert!(
        content.contains("#include \"../foo.h\""),
        "C include should preserve the parent-relative local path:\n{content}"
    );

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn add_import_solidity_allows_parent_relative_import() {
    let mut aft = AftProcess::spawn();
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("RelativeImport.sol");
    fs::write(
        &file,
        "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ncontract C {}\n",
    )
    .unwrap();

    let resp = send_add_import(
        &mut aft,
        "imp-sol-parent-relative",
        &file.display().to_string(),
        "../lib/X.sol",
        None,
        None,
        false,
    );

    assert_eq!(
        resp["success"], true,
        "parent-relative Solidity import should succeed: {resp:?}"
    );
    let content = fs::read_to_string(&file).unwrap();
    assert!(
        content.contains("import \"../lib/X.sol\";"),
        "Solidity import should preserve the parent-relative path:\n{content}"
    );

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn add_import_c_rejects_absolute_modules() {
    let mut aft = AftProcess::spawn();
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("unsafe_include.c");
    let original = "int main(void) { return 0; }\n";
    fs::write(&file, original).unwrap();
    let file_str = file.display().to_string();

    for (id, module) in [
        ("imp-c-posix-absolute", "/etc/passwd"),
        ("imp-c-drive-absolute", "C:\\evil"),
        ("imp-c-unc-absolute", "\\\\srv\\x"),
    ] {
        let resp = send_add_import(&mut aft, id, &file_str, module, None, None, false);
        assert_eq!(
            resp["success"], false,
            "absolute module {module:?} should be rejected: {resp:?}"
        );
        assert_eq!(resp["code"], "invalid_request");
        assert_eq!(
            fs::read_to_string(&file).unwrap(),
            original,
            "rejected module {module:?} must not mutate the file"
        );
    }

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn add_import_java_and_php_reject_filesystem_modules() {
    let mut aft = AftProcess::spawn();
    let dir = tempfile::tempdir().unwrap();

    let java_file = dir.path().join("Unsafe.java");
    let java_original = "package demo;\n\nclass Unsafe {}\n";
    fs::write(&java_file, java_original).unwrap();
    let java_file_str = java_file.display().to_string();

    for (id, module) in [
        ("imp-java-parent", "../evil"),
        ("imp-java-slash", "/evil"),
        ("imp-java-drive", "C:\\evil"),
    ] {
        let resp = send_add_import(&mut aft, id, &java_file_str, module, None, None, false);
        assert_eq!(
            resp["success"], false,
            "Java filesystem module {module:?} should be rejected: {resp:?}"
        );
        assert_eq!(resp["code"], "invalid_request");
        assert_eq!(fs::read_to_string(&java_file).unwrap(), java_original);
    }

    let php_file = dir.path().join("unsafe.php");
    let php_original = "<?php\n\nnamespace Demo;\n\nclass C {}\n";
    fs::write(&php_file, php_original).unwrap();
    let php_file_str = php_file.display().to_string();

    for (id, module) in [
        ("imp-php-parent", "..\\Evil"),
        ("imp-php-slash", "/tmp/Evil"),
        ("imp-php-drive", "C:\\evil"),
    ] {
        let resp = send_add_import(&mut aft, id, &php_file_str, module, None, None, false);
        assert_eq!(
            resp["success"], false,
            "PHP filesystem module {module:?} should be rejected: {resp:?}"
        );
        assert_eq!(resp["code"], "invalid_request");
        assert_eq!(fs::read_to_string(&php_file).unwrap(), php_original);
    }

    fs::remove_file(&java_file).ok();
    fs::remove_file(&php_file).ok();
    aft.shutdown();
}

#[test]
fn add_import_ts_dedup() {
    let mut aft = AftProcess::spawn();
    let (_dir, file) = temp_copy("imports_ts.ts");
    let file_str = file.display().to_string();

    // Try to add useState which already exists in the fixture
    let resp = send_add_import(
        &mut aft,
        "imp-3",
        &file_str,
        "react",
        Some(&["useState"]),
        None,
        false,
    );

    assert_eq!(resp["success"], true);
    assert_eq!(resp["added"], false, "should not add duplicate");
    assert_eq!(resp["already_present"], true);

    // File should not have been modified
    let original = fs::read_to_string(fixture_path("imports_ts.ts")).unwrap();
    let current = fs::read_to_string(&file).unwrap();
    assert_eq!(
        original, current,
        "file should not have been modified for duplicate"
    );

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn add_import_ts_alphabetizes() {
    let mut aft = AftProcess::spawn();
    let (_dir, file) = temp_copy("imports_ts.ts");
    let file_str = file.display().to_string();

    // Add 'axios' which should sort before 'react' and after nothing (first external)
    let resp = send_add_import(
        &mut aft,
        "imp-4",
        &file_str,
        "axios",
        None,
        Some("axios"),
        false,
    );

    assert_eq!(resp["success"], true);
    assert_eq!(resp["added"], true);

    let content = fs::read_to_string(&file).unwrap();
    let axios_pos = content.find("import axios from 'axios'").unwrap();
    let react_pos = content.find("import React from 'react'").unwrap();
    assert!(
        axios_pos < react_pos,
        "axios should sort before react alphabetically. content:\n{}",
        content
    );

    fs::remove_file(&file).ok();
    aft.shutdown();
}

// --- JS tests ---

#[test]
fn add_import_js_works() {
    let mut aft = AftProcess::spawn();
    let (_dir, file) = temp_copy("imports_js.js");
    let file_str = file.display().to_string();

    let resp = send_add_import(
        &mut aft,
        "imp-5",
        &file_str,
        "cors",
        None,
        Some("cors"),
        false,
    );

    assert_eq!(
        resp["success"], true,
        "add_import on JS should succeed: {:?}",
        resp
    );
    assert_eq!(resp["added"], true);
    assert_eq!(resp["group"], "external");

    let content = fs::read_to_string(&file).unwrap();
    assert!(
        content.contains("import cors from 'cors';"),
        "should contain the new JS import. content:\n{}",
        content
    );

    fs::remove_file(&file).ok();
    aft.shutdown();
}

// --- Edge cases ---

#[test]
fn add_import_empty_file() {
    use std::sync::atomic::{AtomicU64, Ordering};
    static EMPTY_COUNTER: AtomicU64 = AtomicU64::new(0);

    let mut aft = AftProcess::spawn();
    let dir = tempfile::tempdir().unwrap();
    let n = EMPTY_COUNTER.fetch_add(1, Ordering::SeqCst);
    let file = dir.path().join(format!("empty_{}.ts", n));
    fs::write(&file, "").unwrap();
    let file_str = file.display().to_string();

    let resp = send_add_import(
        &mut aft,
        "imp-6",
        &file_str,
        "react",
        Some(&["useState"]),
        None,
        false,
    );

    assert_eq!(
        resp["success"], true,
        "add_import on empty file should succeed: {:?}",
        resp
    );
    assert_eq!(resp["added"], true);

    let content = fs::read_to_string(&file).unwrap();
    assert!(
        content.contains("import { useState } from 'react';"),
        "should contain the import at top. content:\n{}",
        content
    );

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn add_import_missing_file_returns_error() {
    let mut aft = AftProcess::spawn();

    let resp = send_add_import(
        &mut aft,
        "imp-7",
        "/tmp/nonexistent_aft_test.ts",
        "react",
        Some(&["useState"]),
        None,
        false,
    );

    assert_eq!(resp["success"], false, "should fail for missing file");
    assert_eq!(resp["code"], "file_not_found");

    aft.shutdown();
}

#[test]
fn add_import_unsupported_language_returns_error() {
    use std::sync::atomic::{AtomicU64, Ordering};
    static UNSUP_COUNTER: AtomicU64 = AtomicU64::new(0);

    let mut aft = AftProcess::spawn();
    let dir = tempfile::tempdir().unwrap();
    let n = UNSUP_COUNTER.fetch_add(1, Ordering::SeqCst);
    let file = dir.path().join(format!("test_{}.txt", n));
    fs::write(&file, "hello world").unwrap();
    let file_str = file.display().to_string();

    let resp = send_add_import(
        &mut aft,
        "imp-8",
        &file_str,
        "react",
        Some(&["useState"]),
        None,
        false,
    );

    assert_eq!(
        resp["success"], false,
        "should fail for unsupported language"
    );
    assert_eq!(
        resp["code"], "unsupported_language",
        "unsupported file type uses the actionable standardized code, not invalid_request"
    );

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn add_import_missing_params_returns_error() {
    let mut aft = AftProcess::spawn();

    // Missing 'module' param
    let resp = aft.send(r#"{"id":"imp-9","command":"add_import","file":"/tmp/test.ts"}"#);

    assert_eq!(resp["success"], false);
    assert_eq!(resp["code"], "invalid_request");
    assert!(
        resp["message"].as_str().unwrap().contains("module"),
        "error should mention missing 'module' param"
    );

    aft.shutdown();
}

// --- Python tests ---

#[test]
fn add_import_py_stdlib_group() {
    let mut aft = AftProcess::spawn();
    let (_dir, file) = temp_copy("imports_py.py");
    let file_str = file.display().to_string();

    let resp = send_add_import(
        &mut aft,
        "py-1",
        &file_str,
        "pathlib",
        Some(&["Path"]),
        None,
        false,
    );

    assert_eq!(
        resp["success"], true,
        "add_import py stdlib should succeed: {:?}",
        resp
    );
    assert_eq!(resp["added"], true);
    assert_eq!(resp["group"], "stdlib");

    let content = fs::read_to_string(&file).unwrap();
    assert!(
        content.contains("from pathlib import Path"),
        "should contain the new stdlib import. content:\n{}",
        content
    );

    // Verify it's in the stdlib group (before third-party imports)
    let pathlib_pos = content.find("from pathlib import Path").unwrap();
    let requests_pos = content.find("import requests").unwrap();
    assert!(
        pathlib_pos < requests_pos,
        "stdlib import should be before third-party imports"
    );

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn add_import_py_third_party_group() {
    let mut aft = AftProcess::spawn();
    let (_dir, file) = temp_copy("imports_py.py");
    let file_str = file.display().to_string();

    let resp = send_add_import(&mut aft, "py-2", &file_str, "click", None, None, false);

    assert_eq!(
        resp["success"], true,
        "add_import py third-party should succeed: {:?}",
        resp
    );
    assert_eq!(resp["added"], true);
    assert_eq!(resp["group"], "external");

    let content = fs::read_to_string(&file).unwrap();
    assert!(
        content.contains("import click"),
        "should contain the new third-party import. content:\n{}",
        content
    );

    // Verify it's in the external group (after stdlib, before local)
    let click_pos = content.find("import click").unwrap();
    let os_pos = content.find("import os").unwrap();
    let utils_pos = content.find("from . import utils").unwrap();
    assert!(
        click_pos > os_pos,
        "third-party import should be after stdlib"
    );
    assert!(
        click_pos < utils_pos,
        "third-party import should be before local"
    );

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn add_import_py_local_group() {
    let mut aft = AftProcess::spawn();
    let (_dir, file) = temp_copy("imports_py.py");
    let file_str = file.display().to_string();

    let resp = send_add_import(
        &mut aft,
        "py-3",
        &file_str,
        ".models",
        Some(&["User"]),
        None,
        false,
    );

    assert_eq!(
        resp["success"], true,
        "add_import py local should succeed: {:?}",
        resp
    );
    assert_eq!(resp["added"], true);
    assert_eq!(resp["group"], "internal");

    let content = fs::read_to_string(&file).unwrap();
    assert!(
        content.contains("from .models import User"),
        "should contain the new local import. content:\n{}",
        content
    );

    // Verify it's in the internal group (after third-party)
    let models_pos = content.find("from .models import User").unwrap();
    let requests_pos = content.find("import requests").unwrap();
    assert!(
        models_pos > requests_pos,
        "local import should be after third-party"
    );

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn add_import_py_dedup() {
    let mut aft = AftProcess::spawn();
    let (_dir, file) = temp_copy("imports_py.py");
    let file_str = file.display().to_string();

    // Try to add 'os' which already exists
    let resp = send_add_import(&mut aft, "py-4", &file_str, "os", None, None, false);

    assert_eq!(resp["success"], true);
    assert_eq!(resp["added"], false, "should not add duplicate");
    assert_eq!(resp["already_present"], true);

    fs::remove_file(&file).ok();
    aft.shutdown();
}

// --- Rust tests ---

#[test]
fn add_import_rs_std_group() {
    let mut aft = AftProcess::spawn();
    let (_dir, file) = temp_copy("imports_rs.rs");
    let file_str = file.display().to_string();

    let resp = send_add_import(
        &mut aft,
        "rs-1",
        &file_str,
        "std::fmt::Display",
        None,
        None,
        false,
    );

    assert_eq!(
        resp["success"], true,
        "add_import rs std should succeed: {:?}",
        resp
    );
    assert_eq!(resp["added"], true);
    assert_eq!(resp["group"], "stdlib");

    let content = fs::read_to_string(&file).unwrap();
    assert!(
        content.contains("use std::fmt::Display;"),
        "should contain the new std import. content:\n{}",
        content
    );

    // Verify it's in the stdlib group (before external imports)
    let fmt_pos = content.find("use std::fmt::Display;").unwrap();
    let serde_pos = content.find("use serde").unwrap();
    assert!(
        fmt_pos < serde_pos,
        "std import should be before external imports"
    );

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn add_import_rs_external_group() {
    let mut aft = AftProcess::spawn();
    let (_dir, file) = temp_copy("imports_rs.rs");
    let file_str = file.display().to_string();

    let resp = send_add_import(
        &mut aft,
        "rs-2",
        &file_str,
        "anyhow::Result",
        None,
        None,
        false,
    );

    assert_eq!(
        resp["success"], true,
        "add_import rs external should succeed: {:?}",
        resp
    );
    assert_eq!(resp["added"], true);
    assert_eq!(resp["group"], "external");

    let content = fs::read_to_string(&file).unwrap();
    assert!(
        content.contains("use anyhow::Result;"),
        "should contain the new external import. content:\n{}",
        content
    );

    // Should be in external group (after std, before crate)
    let anyhow_pos = content.find("use anyhow::Result;").unwrap();
    let std_pos = content.find("use std::").unwrap();
    let crate_pos = content.find("use crate::").unwrap();
    assert!(anyhow_pos > std_pos, "external import should be after std");
    assert!(
        anyhow_pos < crate_pos,
        "external import should be before crate"
    );

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn add_import_rs_dedup() {
    let mut aft = AftProcess::spawn();
    let (_dir, file) = temp_copy("imports_rs.rs");
    let file_str = file.display().to_string();

    // Try to add std::collections::HashMap which already exists
    let resp = send_add_import(
        &mut aft,
        "rs-3",
        &file_str,
        "std::collections::HashMap",
        None,
        None,
        false,
    );

    assert_eq!(resp["success"], true);
    assert_eq!(resp["added"], false, "should not add duplicate");
    assert_eq!(resp["already_present"], true);

    fs::remove_file(&file).ok();
    aft.shutdown();
}

// --- Go tests ---

#[test]
fn add_import_go_stdlib_group() {
    let mut aft = AftProcess::spawn();
    let (_dir, file) = temp_copy("imports_go.go");
    let file_str = file.display().to_string();

    let resp = send_add_import(&mut aft, "go-1", &file_str, "net/http", None, None, false);

    assert_eq!(
        resp["success"], true,
        "add_import go stdlib should succeed: {:?}",
        resp
    );
    assert_eq!(resp["added"], true);
    assert_eq!(resp["group"], "stdlib");

    let content = fs::read_to_string(&file).unwrap();
    assert!(
        content.contains("\"net/http\""),
        "should contain the new stdlib import. content:\n{}",
        content
    );

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn add_import_go_external_group() {
    let mut aft = AftProcess::spawn();
    let (_dir, file) = temp_copy("imports_go.go");
    let file_str = file.display().to_string();

    let resp = send_add_import(
        &mut aft,
        "go-2",
        &file_str,
        "golang.org/x/tools",
        None,
        None,
        false,
    );

    assert_eq!(
        resp["success"], true,
        "add_import go external should succeed: {:?}",
        resp
    );
    assert_eq!(resp["added"], true);
    assert_eq!(resp["group"], "external");

    let content = fs::read_to_string(&file).unwrap();
    assert!(
        content.contains("\"golang.org/x/tools\""),
        "should contain the new external import. content:\n{}",
        content
    );

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn add_import_go_dedup() {
    let mut aft = AftProcess::spawn();
    let (_dir, file) = temp_copy("imports_go.go");
    let file_str = file.display().to_string();

    // Try to add "fmt" which already exists
    let resp = send_add_import(&mut aft, "go-3", &file_str, "fmt", None, None, false);

    assert_eq!(resp["success"], true);
    assert_eq!(resp["added"], false, "should not add duplicate");
    assert_eq!(resp["already_present"], true);

    fs::remove_file(&file).ok();
    aft.shutdown();
}

// ===========================================================================
// remove_import tests
// ===========================================================================

/// Helper: send a remove_import request and return the response.
fn send_remove_import(
    aft: &mut AftProcess,
    id: &str,
    file: &str,
    module: &str,
    name: Option<&str>,
) -> serde_json::Value {
    let mut params = serde_json::json!({
        "id": id,
        "command": "remove_import",
        "file": file,
        "module": module,
    });

    if let Some(n) = name {
        params["name"] = serde_json::json!(n);
    }

    aft.send(&serde_json::to_string(&params).unwrap())
}

/// Helper: send an organize_imports request and return the response.
fn send_organize_imports(aft: &mut AftProcess, id: &str, file: &str) -> serde_json::Value {
    let params = serde_json::json!({
        "id": id,
        "command": "organize_imports",
        "file": file,
    });

    aft.send(&serde_json::to_string(&params).unwrap())
}

#[test]
fn remove_import_entire_statement_ts() {
    let mut aft = AftProcess::spawn();
    let (_dir, file) = temp_copy("imports_ts.ts");
    let file_str = file.display().to_string();

    // Remove the 'zod' import entirely
    let resp = send_remove_import(&mut aft, "rm-1", &file_str, "zod", None);

    assert_eq!(
        resp["success"], true,
        "remove_import should succeed: {:?}",
        resp
    );
    assert_eq!(resp["removed"], true);
    assert_eq!(resp["module"], "zod");

    let content = fs::read_to_string(&file).unwrap();
    assert!(
        !content.contains("from 'zod'"),
        "zod import should be removed. content:\n{}",
        content
    );
    // Other imports should remain
    assert!(
        content.contains("from 'react'"),
        "react imports should remain"
    );

    assert_eq!(resp["syntax_valid"], true);

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn remove_import_specific_name_from_multi_ts() {
    let mut aft = AftProcess::spawn();
    let (_dir, file) = temp_copy("imports_ts.ts");
    let file_str = file.display().to_string();

    // Remove 'useState' from `import { useState, useEffect } from 'react';`
    let resp = send_remove_import(&mut aft, "rm-2", &file_str, "react", Some("useState"));

    assert_eq!(
        resp["success"], true,
        "remove_import should succeed: {:?}",
        resp
    );
    assert_eq!(resp["removed"], true);
    assert_eq!(resp["name"], "useState");

    let content = fs::read_to_string(&file).unwrap();
    // Should still have useEffect from react
    assert!(
        content.contains("useEffect") && content.contains("react"),
        "useEffect import from react should remain. content:\n{}",
        content
    );
    // useState should not appear in that specific import anymore
    assert!(
        !content.contains("import { useState, useEffect }"),
        "the original multi-name import should be modified. content:\n{}",
        content
    );

    assert_eq!(resp["syntax_valid"], true);

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn remove_import_missing_module_reports_not_removed() {
    let mut aft = AftProcess::spawn();
    let (_dir, file) = temp_copy("imports_ts.ts");
    let file_str = file.display().to_string();

    let resp = send_remove_import(&mut aft, "rm-3", &file_str, "nonexistent-module", None);

    assert_eq!(resp["success"], true, "request should complete: {resp:?}");
    assert_eq!(resp["removed"], false, "nothing should be removed");
    assert_eq!(resp["reason"], "module_not_found");
    assert_eq!(resp["no_op"], true, "no-match removes must report no_op");

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn remove_import_missing_name_reports_no_op() {
    let mut aft = AftProcess::spawn();
    let (_dir, file) = temp_copy("imports_ts.ts");
    let file_str = file.display().to_string();

    let resp = send_remove_import(
        &mut aft,
        "rm-missing-name",
        &file_str,
        "react",
        Some("useMemo"),
    );

    assert_eq!(resp["success"], true, "request should complete: {resp:?}");
    assert_eq!(resp["removed"], false, "nothing should be removed");
    assert_eq!(resp["reason"], "name_not_found");
    assert_eq!(resp["name"], "useMemo");
    assert_eq!(resp["no_op"], true, "name misses must report no_op");

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn remove_import_preserves_default_when_named_removed() {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);

    let mut aft = AftProcess::spawn();
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join(format!(
        "remove_default_named_{}.ts",
        COUNTER.fetch_add(1, Ordering::SeqCst)
    ));
    fs::write(
        &file,
        "import React, { useState } from 'react';\n\nexport const App = React.Fragment;\n",
    )
    .unwrap();

    let resp = send_remove_import(
        &mut aft,
        "rm-preserve-default",
        &file.display().to_string(),
        "react",
        Some("useState"),
    );
    assert_eq!(resp["success"], true, "remove should succeed: {resp:?}");
    let content = fs::read_to_string(&file).unwrap();
    assert!(
        content.contains("import React from 'react';"),
        "default import should remain:\n{content}"
    );
    assert!(
        !content.contains("useState"),
        "named import should be removed"
    );

    fs::remove_file(&file).ok();
    aft.shutdown();
}

// ===========================================================================
// organize_imports tests
// ===========================================================================

#[test]
fn organize_imports_without_imports_reports_no_op() {
    let mut aft = AftProcess::spawn();
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("no_imports.ts");
    let original = "export const x = 1;\n";
    fs::write(&file, original).unwrap();

    let resp = send_organize_imports(&mut aft, "org-no-imports", &file.display().to_string());

    assert_eq!(resp["success"], true, "organize should succeed: {resp:?}");
    assert_eq!(resp["groups"].as_array().unwrap().len(), 0);
    assert_eq!(resp["removed_duplicates"], 0);
    assert_eq!(resp["no_op"], true, "no-import organize must report no_op");
    assert_eq!(fs::read_to_string(&file).unwrap(), original);

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn organize_imports_rejects_multi_namespace_php_without_mutating() {
    let mut aft = AftProcess::spawn();
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("multi_namespace.php");
    let original = r#"<?php

namespace Foo {
use Zed\Last;

class X {}
}

namespace Bar {
use App\Alpha;

class Y {}
}
"#;
    fs::write(&file, original).unwrap();

    let resp = send_organize_imports(&mut aft, "org-multi-php", &file.display().to_string());

    assert_eq!(
        resp["success"], false,
        "multi-namespace PHP organize should be refused: {resp:?}"
    );
    assert_eq!(resp["code"], "multi_region_imports");
    assert!(
        resp["message"]
            .as_str()
            .unwrap_or_default()
            .contains("span multiple code regions"),
        "error should explain the multi-region refusal: {resp:?}"
    );
    assert_eq!(
        fs::read_to_string(&file).unwrap(),
        original,
        "refused organize must leave the PHP file byte-for-byte unchanged"
    );

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn organize_imports_ts_regroups_and_sorts() {
    use std::sync::atomic::{AtomicU64, Ordering};
    static ORG_COUNTER: AtomicU64 = AtomicU64::new(0);

    let mut aft = AftProcess::spawn();
    let dir = tempfile::tempdir().unwrap();
    let n = ORG_COUNTER.fetch_add(1, Ordering::SeqCst);
    let file = dir.path().join(format!("organize_ts_{}.ts", n));

    // Write a scrambled import file
    fs::write(
        &file,
        "\
import { helper } from './utils';
import { z } from 'zod';
import React from 'react';
import { Config } from '../config';
import { useState } from 'react';

export function App() {}
",
    )
    .unwrap();

    let file_str = file.display().to_string();
    let resp = send_organize_imports(&mut aft, "org-1", &file_str);

    assert_eq!(
        resp["success"], true,
        "organize_imports should succeed: {:?}",
        resp
    );

    let content = fs::read_to_string(&file).unwrap();

    // External imports should come before internal
    let react_pos = content.find("react").unwrap();
    let utils_pos = content.find("./utils").unwrap();
    assert!(
        react_pos < utils_pos,
        "external imports should come before internal. content:\n{}",
        content
    );

    // Within external group, should be alphabetical: react before zod
    let zod_pos = content.find("zod").unwrap();
    assert!(
        react_pos < zod_pos,
        "react should come before zod (alphabetical). content:\n{}",
        content
    );

    assert_eq!(resp["syntax_valid"], true);

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn organize_imports_preserves_side_effect_order() {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);

    let mut aft = AftProcess::spawn();
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join(format!(
        "organize_side_effects_{}.ts",
        COUNTER.fetch_add(1, Ordering::SeqCst)
    ));
    // All imports below are in the EXTERNAL group, so within-group ordering applies:
    //   side-effects (preserve relative source order) before value/type (alphabetical).
    fs::write(
        &file,
        "import 'polyfill-b';\nimport z from 'zod';\nimport 'polyfill-a';\nimport React from 'react';\n\nexport const x = 1;\n",
    )
    .unwrap();

    let resp = send_organize_imports(&mut aft, "org-side-effects", &file.display().to_string());
    assert_eq!(resp["success"], true, "organize should succeed: {resp:?}");
    let content = fs::read_to_string(&file).unwrap();
    let polyfill_b_pos = content.find("import 'polyfill-b';").unwrap();
    let polyfill_a_pos = content.find("import 'polyfill-a';").unwrap();
    let react_pos = content.find("import React from 'react';").unwrap();
    let zod_pos = content.find("import z from 'zod';").unwrap();
    assert!(
        polyfill_b_pos < polyfill_a_pos,
        "side-effect imports keep original relative order (b before a):\n{content}"
    );
    assert!(
        zod_pos < polyfill_a_pos,
        "value imports before a side-effect barrier must not cross it:\n{content}"
    );
    assert!(
        polyfill_a_pos < react_pos,
        "side-effects keep their source position relative to following value imports:\n{content}"
    );

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn organize_imports_preserves_inter_import_comments() {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);

    let mut aft = AftProcess::spawn();
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join(format!(
        "organize_comment_gap_{}.ts",
        COUNTER.fetch_add(1, Ordering::SeqCst)
    ));
    let original =
        "import A from 'a';\n// keep me\nimport B from 'b';\n\nexport const x = A || B;\n";
    fs::write(&file, original).unwrap();

    let resp = send_organize_imports(&mut aft, "org-comment-gap", &file.display().to_string());
    assert_eq!(resp["success"], true, "organize should succeed: {resp:?}");
    let content = fs::read_to_string(&file).unwrap();
    assert_eq!(content, original, "comment gap must be preserved");

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn add_remove_import_refuse_csharp_and_php_multi_region_imports() {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);

    let mut aft = AftProcess::spawn();
    let dir = tempfile::tempdir().unwrap();
    let n = COUNTER.fetch_add(1, Ordering::SeqCst);

    let cs_file = dir.path().join(format!("multi_region_{n}.cs"));
    fs::write(
        &cs_file,
        "namespace A {\nusing Common;\nclass A {}\n}\nnamespace B {\nusing Common;\nclass B {}\n}\n",
    )
    .unwrap();
    let cs_file_str = cs_file.display().to_string();
    let add_cs = send_add_import(
        &mut aft,
        "cs-multi-add",
        &cs_file_str,
        "System",
        None,
        None,
        false,
    );
    assert_eq!(add_cs["success"], false, "C# add should refuse: {add_cs:?}");
    assert_eq!(add_cs["code"], "multi_region_imports");
    let remove_cs = send_remove_import(&mut aft, "cs-multi-remove", &cs_file_str, "Common", None);
    assert_eq!(
        remove_cs["success"], false,
        "C# remove should refuse: {remove_cs:?}"
    );
    assert_eq!(remove_cs["code"], "multi_region_imports");

    let php_file = dir.path().join(format!("multi_region_{n}.php"));
    fs::write(
        &php_file,
        "<?php\nnamespace A {\nuse Common\\Thing;\nclass A {}\n}\nnamespace B {\nuse Common\\Thing;\nclass B {}\n}\n",
    )
    .unwrap();
    let php_file_str = php_file.display().to_string();
    let add_php = send_add_import(
        &mut aft,
        "php-multi-add",
        &php_file_str,
        "Other\\Thing",
        None,
        None,
        false,
    );
    assert_eq!(
        add_php["success"], false,
        "PHP add should refuse: {add_php:?}"
    );
    assert_eq!(add_php["code"], "multi_region_imports");
    let remove_php = send_remove_import(
        &mut aft,
        "php-multi-remove",
        &php_file_str,
        "Common\\Thing",
        None,
    );
    assert_eq!(
        remove_php["success"], false,
        "PHP remove should refuse: {remove_php:?}"
    );
    assert_eq!(remove_php["code"], "multi_region_imports");

    fs::remove_file(&cs_file).ok();
    fs::remove_file(&php_file).ok();
    aft.shutdown();
}

#[test]
fn php_grouped_use_refuses_memberwise_add_and_remove() {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);

    let mut aft = AftProcess::spawn();
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join(format!(
        "php_grouped_use_{}.php",
        COUNTER.fetch_add(1, Ordering::SeqCst)
    ));
    let original = "<?php\nuse App\\{Foo, Bar as Baz};\n\nclass C {}\n";
    fs::write(&file, original).unwrap();
    let file_str = file.display().to_string();

    let add_resp = send_add_import(
        &mut aft,
        "php-group-add",
        &file_str,
        "App\\Foo",
        None,
        None,
        false,
    );
    assert_eq!(
        add_resp["success"], false,
        "add should refuse: {add_resp:?}"
    );
    assert_eq!(add_resp["code"], "unsupported_grouped_import");

    let remove_resp = send_remove_import(&mut aft, "php-group-remove", &file_str, "App\\Foo", None);
    assert_eq!(
        remove_resp["success"], false,
        "remove should refuse: {remove_resp:?}"
    );
    assert_eq!(remove_resp["code"], "unsupported_grouped_import");
    assert_eq!(fs::read_to_string(&file).unwrap(), original);

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn organize_imports_go_grouped_block_refuses_internal_comments() {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);

    let mut aft = AftProcess::spawn();
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join(format!(
        "organize_go_grouped_comments_{}.go",
        COUNTER.fetch_add(1, Ordering::SeqCst)
    ));
    let original = "package main\n\nimport (\n\t\"fmt\"\n\t// keep me with this block\n\t\"os\"\n)\n\nfunc main() {}\n";
    fs::write(&file, original).unwrap();

    let resp = send_organize_imports(
        &mut aft,
        "org-go-grouped-comments",
        &file.display().to_string(),
    );
    assert_eq!(
        resp["success"], false,
        "commented Go grouped imports should be refused: {resp:?}"
    );
    assert_eq!(resp["code"], "unsupported_import_comments");
    assert_eq!(
        fs::read_to_string(&file).unwrap(),
        original,
        "refused organize must leave the Go file byte-for-byte unchanged"
    );

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn organize_imports_go_grouped_block_parses() {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);

    let mut aft = AftProcess::spawn();
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join(format!(
        "organize_go_grouped_{}.go",
        COUNTER.fetch_add(1, Ordering::SeqCst)
    ));
    fs::write(
        &file,
        "package main\n\nimport (\n\t\"os\"\n\t\"fmt\"\n)\n\nfunc main() {}\n",
    )
    .unwrap();

    let resp = send_organize_imports(&mut aft, "org-go-grouped", &file.display().to_string());
    assert_eq!(resp["success"], true, "organize should succeed: {resp:?}");
    let content = fs::read_to_string(&file).unwrap();
    assert!(
        content.contains("import (\n\t\"fmt\"\n\t\"os\"\n)"),
        "grouped block should be regenerated and sorted:\n{content}"
    );
    let mut parser = tree_sitter::Parser::new();
    let language: tree_sitter::Language = tree_sitter_go::LANGUAGE.into();
    parser.set_language(&language).expect("set go grammar");
    let tree = parser.parse(&content, None).expect("parse go");
    assert!(
        !tree.root_node().has_error(),
        "Go output should parse:\n{content}"
    );

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn organize_imports_ts_deduplicates() {
    use std::sync::atomic::{AtomicU64, Ordering};
    static DEDUP_COUNTER: AtomicU64 = AtomicU64::new(0);

    let mut aft = AftProcess::spawn();
    let dir = tempfile::tempdir().unwrap();
    let n = DEDUP_COUNTER.fetch_add(1, Ordering::SeqCst);
    let file = dir.path().join(format!("organize_dedup_{}.ts", n));

    // Write a file with duplicate imports
    fs::write(
        &file,
        "\
import { z } from 'zod';
import { z } from 'zod';
import React from 'react';
import React from 'react';

export function App() {}
",
    )
    .unwrap();

    let file_str = file.display().to_string();
    let resp = send_organize_imports(&mut aft, "org-2", &file_str);

    assert_eq!(
        resp["success"], true,
        "organize_imports should succeed: {:?}",
        resp
    );
    assert!(
        resp["removed_duplicates"].as_u64().unwrap() >= 2,
        "should remove at least 2 duplicates: {:?}",
        resp
    );

    let content = fs::read_to_string(&file).unwrap();
    // Count occurrences of 'zod' — should appear exactly once
    let zod_count = content.matches("'zod'").count();
    assert_eq!(
        zod_count, 1,
        "should have exactly one zod import. content:\n{}",
        content
    );

    let react_count = content.matches("from 'react'").count();
    assert_eq!(
        react_count, 1,
        "should have exactly one react import. content:\n{}",
        content
    );

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn organize_imports_py_isort_grouping() {
    use std::sync::atomic::{AtomicU64, Ordering};
    static PY_ORG_COUNTER: AtomicU64 = AtomicU64::new(0);

    let mut aft = AftProcess::spawn();
    let dir = tempfile::tempdir().unwrap();
    let n = PY_ORG_COUNTER.fetch_add(1, Ordering::SeqCst);
    let file = dir.path().join(format!("organize_py_{}.py", n));

    // Write a scrambled Python import file (wrong order: local, external, stdlib)
    fs::write(
        &file,
        "\
from . import utils
import requests
import os
import sys
from ..config import Settings

def main():
    pass
",
    )
    .unwrap();

    let file_str = file.display().to_string();
    let resp = send_organize_imports(&mut aft, "org-3", &file_str);

    assert_eq!(
        resp["success"], true,
        "organize_imports should succeed: {:?}",
        resp
    );

    // Check groups: should be stdlib, external, internal
    let groups = resp["groups"].as_array().unwrap();
    assert!(
        groups.len() >= 2,
        "should have at least 2 groups: {:?}",
        groups
    );
    assert_eq!(groups[0]["name"], "stdlib", "first group should be stdlib");

    let content = fs::read_to_string(&file).unwrap();

    // Stdlib (os, sys) should come before external (requests)
    let os_pos = content.find("import os").unwrap();
    let requests_pos = content.find("import requests").unwrap();
    assert!(
        os_pos < requests_pos,
        "stdlib should come before external. content:\n{}",
        content
    );

    // External should come before internal
    let utils_pos = content.find("utils").unwrap();
    assert!(
        requests_pos < utils_pos,
        "external should come before internal. content:\n{}",
        content
    );

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn organize_imports_rs_merges_common_prefix() {
    use std::sync::atomic::{AtomicU64, Ordering};
    static RS_ORG_COUNTER: AtomicU64 = AtomicU64::new(0);

    let mut aft = AftProcess::spawn();
    let dir = tempfile::tempdir().unwrap();
    let n = RS_ORG_COUNTER.fetch_add(1, Ordering::SeqCst);
    let file = dir.path().join(format!("organize_rs_{}.rs", n));

    // Write Rust file with separate use declarations that share a common prefix
    fs::write(
        &file,
        "\
use std::path::PathBuf;
use std::path::Path;
use std::collections::HashMap;
use serde::Deserialize;
use serde::Serialize;
use crate::config::Settings;

fn main() {}
",
    )
    .unwrap();

    let file_str = file.display().to_string();
    let resp = send_organize_imports(&mut aft, "org-4", &file_str);

    assert_eq!(
        resp["success"], true,
        "organize_imports should succeed: {:?}",
        resp
    );

    let content = fs::read_to_string(&file).unwrap();

    // std::path::Path and std::path::PathBuf should be merged
    assert!(
        content.contains("use std::path::{Path, PathBuf};"),
        "should merge std::path imports into a use tree. content:\n{}",
        content
    );

    // serde::Deserialize and serde::Serialize should be merged
    assert!(
        content.contains("use serde::{Deserialize, Serialize};"),
        "should merge serde imports into a use tree. content:\n{}",
        content
    );

    // Groups should be in order: stdlib, external, internal
    let std_pos = content.find("use std::").unwrap();
    let serde_pos = content.find("use serde::").unwrap();
    let crate_pos = content.find("use crate::").unwrap();
    assert!(std_pos < serde_pos, "stdlib before external");
    assert!(serde_pos < crate_pos, "external before internal");

    assert_eq!(resp["syntax_valid"], true);

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn organize_imports_rs_preserves_nested_use_tree() {
    // Regression: a nested use tree like
    //   use std::collections::{hash_map::{Entry, HashMap}, BTreeMap};
    // was split on raw commas, corrupting the nested subtree into
    //   `hash_map::{Entry` / `HashMap}` / `BTreeMap`, which regrouped into
    //   `use std::collections::{BTreeMap, HashMap}, hash_map::{Entry};`
    // — invalid Rust. Brace-aware splitting must keep the subtree intact.
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);

    let mut aft = AftProcess::spawn();
    let dir = tempfile::tempdir().unwrap();
    let n = COUNTER.fetch_add(1, Ordering::SeqCst);
    let file = dir.path().join(format!("organize_rs_nested_{}.rs", n));

    fs::write(
        &file,
        "\
use std::collections::{hash_map::{Entry, HashMap}, BTreeMap};
use std::fmt;

fn main() {}
",
    )
    .unwrap();

    let file_str = file.display().to_string();
    let resp = send_organize_imports(&mut aft, "org-rs-nested", &file_str);

    assert_eq!(
        resp["success"], true,
        "organize_imports should succeed: {resp:?}"
    );
    assert_eq!(
        resp["syntax_valid"], true,
        "organized Rust must stay syntactically valid: {resp:?}"
    );

    let content = fs::read_to_string(&file).unwrap();

    // The nested subtree must survive as one item, not be exploded into
    // sibling top-level entries.
    assert!(
        content.contains("hash_map::{Entry, HashMap}"),
        "nested subtree must be preserved intact. content:\n{content}"
    );
    // The corruption signature must NOT appear: a brace tree followed by a
    // comma and another path at the same level inside one use statement.
    assert!(
        !content.contains("}, hash_map::{Entry};")
            && !content.contains("{BTreeMap, HashMap}, hash_map"),
        "must not produce invalid comma-joined brace trees. content:\n{content}"
    );

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn organize_imports_rs_preserves_pub_use_and_private_use_pair() {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);

    let mut aft = AftProcess::spawn();
    let dir = tempfile::tempdir().unwrap();
    let n = COUNTER.fetch_add(1, Ordering::SeqCst);
    let file = dir.path().join(format!("organize_rs_pub_private_{}.rs", n));

    fs::write(
        &file,
        "\
pub use serde;
use serde;

fn main() {}
",
    )
    .unwrap();

    let file_str = file.display().to_string();
    let resp = send_organize_imports(&mut aft, "org-rs-pub-private", &file_str);

    assert_eq!(
        resp["success"], true,
        "organize_imports should succeed: {:?}",
        resp
    );

    let content = fs::read_to_string(&file).unwrap();
    assert!(content.contains("pub use serde;"), "content:\n{content}");
    assert!(content.contains("use serde;"), "content:\n{content}");

    fs::remove_file(&file).ok();
    aft.shutdown();
}

// ---------------------------------------------------------------------------
// Regression: TS/JS named-import aliases and per-name type modifiers must
// survive `organize_imports` round-trips. Reported in dogfooding session
// `ses_23180bd14ffeTODg3ZRGsHKA55`: organize silently rewrote
// `import { stdin as input, stdout as output } from 'node:process'` to
// `import { stdin, stdout }`, breaking every reference to `input`/`output`
// in the file. Returned `success: true, syntax_valid: true` — silent
// semantic corruption. Fixed by storing TS/JS specifiers verbatim
// (alias and per-name `type` prefix included) so the regenerator can
// emit them unchanged.
// ---------------------------------------------------------------------------

#[test]
fn organize_imports_ts_preserves_named_aliases() {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);

    let mut aft = AftProcess::spawn();
    let dir = tempfile::tempdir().unwrap();
    let n = COUNTER.fetch_add(1, Ordering::SeqCst);
    let file = dir.path().join(format!("alias_ts_{}.ts", n));

    fs::write(
        &file,
        "import { stdin as input, stdout as output } from 'node:process'\n\
         \n\
         const rl = createInterface({ input, output })\n",
    )
    .unwrap();

    let file_str = file.display().to_string();
    let resp = send_organize_imports(&mut aft, "alias-ts", &file_str);
    assert_eq!(resp["success"], true, "organize succeeded: {:?}", resp);

    let content = fs::read_to_string(&file).unwrap();
    assert!(
        content.contains("stdin as input"),
        "alias `stdin as input` must survive organize. got:\n{content}"
    );
    assert!(
        content.contains("stdout as output"),
        "alias `stdout as output` must survive organize. got:\n{content}"
    );

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn organize_imports_ts_preserves_per_name_type_prefix() {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);

    let mut aft = AftProcess::spawn();
    let dir = tempfile::tempdir().unwrap();
    let n = COUNTER.fetch_add(1, Ordering::SeqCst);
    let file = dir.path().join(format!("typeprefix_ts_{}.ts", n));

    fs::write(
        &file,
        "import { type Foo, Bar, baz as qux } from './a'\n\
         \n\
         export type X = Foo\n\
         export const y: typeof Bar = baz\n\
         qux()\n",
    )
    .unwrap();

    let file_str = file.display().to_string();
    let resp = send_organize_imports(&mut aft, "typeprefix-ts", &file_str);
    assert_eq!(resp["success"], true, "organize succeeded: {:?}", resp);

    let content = fs::read_to_string(&file).unwrap();
    // Per-specifier `type` prefix is preserved (not promoted to `import type`
    // and not silently dropped).
    assert!(
        content.contains("type Foo"),
        "per-name `type Foo` modifier must survive. got:\n{content}"
    );
    assert!(
        content.contains("Bar"),
        "non-type `Bar` import must survive. got:\n{content}"
    );
    assert!(
        content.contains("baz as qux"),
        "alias `baz as qux` must survive alongside type modifiers. got:\n{content}"
    );

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn organize_imports_ts_aliased_and_bare_are_not_duplicates() {
    // `{ Foo }` and `{ Foo as Bar }` introduce different local bindings, so
    // dedup must not collapse them into one. This guards against an aliased
    // import being silently dropped during organize.
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);

    let mut aft = AftProcess::spawn();
    let dir = tempfile::tempdir().unwrap();
    let n = COUNTER.fetch_add(1, Ordering::SeqCst);
    let file = dir.path().join(format!("alias_dedup_ts_{}.ts", n));

    fs::write(
        &file,
        "import { Foo } from './a'\n\
         import { Foo as Bar } from './a'\n\
         \n\
         export const x = Foo\n\
         export const y = Bar\n",
    )
    .unwrap();

    let file_str = file.display().to_string();
    let resp = send_organize_imports(&mut aft, "alias-dedup-ts", &file_str);
    assert_eq!(resp["success"], true, "organize succeeded: {:?}", resp);

    let content = fs::read_to_string(&file).unwrap();
    assert!(
        content.contains("Foo as Bar"),
        "aliased import `Foo as Bar` must not be dedup'd away by bare `Foo`. got:\n{content}"
    );
    // Bare `Foo` must also still be reachable (could be merged into the
    // same import statement or kept separate — both are correct).
    assert!(
        content.matches("Foo").count() >= 2,
        "bare `Foo` and `Foo as Bar` must both survive. got:\n{content}"
    );

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn organize_imports_ts_preserves_namespace_and_side_effect_imports() {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);

    let mut aft = AftProcess::spawn();
    let dir = tempfile::tempdir().unwrap();
    let n = COUNTER.fetch_add(1, Ordering::SeqCst);
    let file = dir
        .path()
        .join(format!("namespace_side_effect_ts_{}.ts", n));

    fs::write(
        &file,
        "import 'fs'\n\
         import * as fs from 'fs'\n\
         \n\
         export const exists = fs.existsSync\n",
    )
    .unwrap();

    let file_str = file.display().to_string();
    let resp = send_organize_imports(&mut aft, "namespace-side-effect-ts", &file_str);
    assert_eq!(resp["success"], true, "organize succeeded: {:?}", resp);

    let content = fs::read_to_string(&file).unwrap();
    assert!(
        content.contains("import 'fs';"),
        "side-effect import must survive alongside namespace import. got:\n{content}"
    );
    assert!(
        content.contains("import * as fs from 'fs';"),
        "namespace import must not be dedup'd as a side-effect import. got:\n{content}"
    );

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn organize_imports_ts_preserves_side_effect_and_namespace_imports_reverse_order() {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);

    let mut aft = AftProcess::spawn();
    let dir = tempfile::tempdir().unwrap();
    let n = COUNTER.fetch_add(1, Ordering::SeqCst);
    let file = dir
        .path()
        .join(format!("side_effect_namespace_ts_{}.ts", n));

    fs::write(
        &file,
        "import * as fs from 'fs'\n\
         import 'fs'\n\
         \n\
         export const exists = fs.existsSync\n",
    )
    .unwrap();

    let file_str = file.display().to_string();
    let resp = send_organize_imports(&mut aft, "side-effect-namespace-ts", &file_str);
    assert_eq!(resp["success"], true, "organize succeeded: {:?}", resp);

    let content = fs::read_to_string(&file).unwrap();
    assert!(
        content.contains("import 'fs';"),
        "side-effect import must survive when namespace import appears first. got:\n{content}"
    );
    assert!(
        content.contains("import * as fs from 'fs';"),
        "namespace import must survive when side-effect import appears second. got:\n{content}"
    );

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn organize_imports_ts_dedupes_identical_namespace_imports() {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);

    let mut aft = AftProcess::spawn();
    let dir = tempfile::tempdir().unwrap();
    let n = COUNTER.fetch_add(1, Ordering::SeqCst);
    let file = dir.path().join(format!("namespace_dedup_ts_{}.ts", n));

    fs::write(
        &file,
        "import * as fs from 'fs'\n\
         import * as fs from 'fs'\n\
         \n\
         export const exists = fs.existsSync\n",
    )
    .unwrap();

    let file_str = file.display().to_string();
    let resp = send_organize_imports(&mut aft, "namespace-dedup-ts", &file_str);
    assert_eq!(resp["success"], true, "organize succeeded: {:?}", resp);

    let content = fs::read_to_string(&file).unwrap();
    assert_eq!(
        content.matches("import * as fs from 'fs';").count(),
        1,
        "identical namespace imports should dedupe. got:\n{content}"
    );

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn organize_imports_ts_keeps_distinct_namespace_aliases() {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);

    let mut aft = AftProcess::spawn();
    let dir = tempfile::tempdir().unwrap();
    let n = COUNTER.fetch_add(1, Ordering::SeqCst);
    let file = dir.path().join(format!("namespace_aliases_ts_{}.ts", n));

    fs::write(
        &file,
        "import * as foo from 'fs'\n\
         import * as bar from 'fs'\n\
         \n\
         export const a = foo.existsSync\n\
         export const b = bar.readFileSync\n",
    )
    .unwrap();

    let file_str = file.display().to_string();
    let resp = send_organize_imports(&mut aft, "namespace-aliases-ts", &file_str);
    assert_eq!(resp["success"], true, "organize succeeded: {:?}", resp);

    let content = fs::read_to_string(&file).unwrap();
    assert!(
        content.contains("import * as foo from 'fs';"),
        "namespace alias `foo` must survive. got:\n{content}"
    );
    assert!(
        content.contains("import * as bar from 'fs';"),
        "namespace alias `bar` must survive. got:\n{content}"
    );

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn organize_imports_ts_sorts_named_specifiers_by_imported_name() {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);

    let mut aft = AftProcess::spawn();
    let dir = tempfile::tempdir().unwrap();
    let n = COUNTER.fetch_add(1, Ordering::SeqCst);
    let file = dir.path().join(format!("specifier_sort_ts_{}.ts", n));

    fs::write(
        &file,
        "import { useState, type Foo, stdin as input, type Bar } from 'x'\n\
         \n\
         export const value = [input, useState]\n",
    )
    .unwrap();

    let file_str = file.display().to_string();
    let resp = send_organize_imports(&mut aft, "specifier-sort-ts", &file_str);
    assert_eq!(resp["success"], true, "organize succeeded: {:?}", resp);

    let content = fs::read_to_string(&file).unwrap();
    assert!(
        content.contains("import { type Bar, type Foo, stdin as input, useState } from 'x';"),
        "named specifiers should sort by imported name, ignoring `type` and aliases. got:\n{content}"
    );

    fs::remove_file(&file).ok();
    aft.shutdown();
}

#[test]
fn generate_ts_namespace_import_line_round_trips_namespace_only() {
    let tmp = tempfile::tempdir().expect("create temp dir");
    let file = tmp.path().join("namespace.ts");
    fs::write(&file, "import * as ns from './mod';\n").expect("write import file");
    let (_, _, block) = parse_file_imports(&file, LangId::TypeScript).expect("parse imports");
    let import = block.imports.first().expect("parsed import");

    let line = generate_import_line_with_namespace(
        LangId::TypeScript,
        &import.module_path,
        &import.names,
        import.default_import.as_deref(),
        import.namespace_import.as_deref(),
        false,
    );

    assert_eq!(line, "import * as ns from './mod';");
}

#[test]
fn generate_ts_namespace_import_line_round_trips_default_and_namespace() {
    let tmp = tempfile::tempdir().expect("create temp dir");
    let file = tmp.path().join("default_namespace.ts");
    fs::write(&file, "import Foo, * as ns from './mod';\n").expect("write import file");
    let (_, _, block) = parse_file_imports(&file, LangId::TypeScript).expect("parse imports");
    let import = block.imports.first().expect("parsed import");

    let line = generate_import_line_with_namespace(
        LangId::TypeScript,
        &import.module_path,
        &import.names,
        import.default_import.as_deref(),
        import.namespace_import.as_deref(),
        false,
    );

    assert_eq!(line, "import Foo, * as ns from './mod';");
}

// --- Merge into existing same-module import ---

/// When the target module already has a named-import statement of the same
/// kind, `add_import` should merge new `names` into that existing statement
/// instead of inserting a duplicate `import { ... } from "lib"` line.
///
/// Regression for the Pi-reported bug where adding `{ baz }` to a file with
/// `import { foo } from "lib"` produced two separate `import { ... } from "lib"`
/// statements that the linter then complained about.
#[test]
fn add_import_merges_into_existing_same_module_named_import() {
    let mut aft = AftProcess::spawn();

    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("merge.ts");
    fs::write(
        &file,
        "import { foo } from \"lib\";\n\nexport function use() {\n  return foo();\n}\n",
    )
    .unwrap();

    // Configure aft against the temp dir as project root.
    aft.send(&format!(
        r#"{{"id":"cfg","command":"configure","harness":"opencode","project_root":{}}}"#,
        crate::helpers::json_string(&dir.path().display())
    ));

    let resp = send_add_import(
        &mut aft,
        "merge1",
        file.to_str().unwrap(),
        "lib",
        Some(&["baz"]),
        None,
        false,
    );

    assert_eq!(
        resp["success"], true,
        "merge add should succeed: {:?}",
        resp
    );
    assert_eq!(resp["added"], true, "should report added=true: {:?}", resp);

    let content = fs::read_to_string(&file).unwrap();

    // Single merged statement (no duplicate `from "lib"` line)
    let from_lib_count =
        content.matches("from \"lib\"").count() + content.matches("from 'lib'").count();
    assert_eq!(
        from_lib_count, 1,
        "should have exactly one statement importing from 'lib':\n{}",
        content
    );

    // Both names present
    assert!(
        content.contains("baz") && content.contains("foo"),
        "merged statement should contain both names:\n{}",
        content
    );

    aft.shutdown();
}