http-nu 0.15.0

The surprisingly performant, Nushell-scriptable, cross.stream-powered, Datastar-ready HTTP server that fits in your back pocket.
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
use std::path::PathBuf;
use std::process;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::process::{Child, ChildStdin};
use tokio::time::timeout;

/// Get path to a workspace member binary (uses deprecated function because
/// CARGO_BIN_EXE_* env vars only work for same-package binaries)
#[allow(deprecated)]
fn workspace_bin(name: &str) -> PathBuf {
    assert_cmd::cargo::cargo_bin(name)
}

struct TestServer {
    child: Child,
    address: String,
}

impl TestServer {
    async fn new(addr: &str, closure: &str, tls: bool) -> Self {
        Self::new_with_options(addr, closure, tls, &[], None, false).await
    }

    async fn new_with_plugins(
        addr: &str,
        closure: &str,
        tls: bool,
        plugins: &[std::path::PathBuf],
    ) -> Self {
        Self::new_with_options(addr, closure, tls, plugins, None, false).await
    }

    async fn new_with_store(addr: &str, closure: &str, store_path: &std::path::Path) -> Self {
        Self::new_with_options(addr, closure, false, &[], Some(store_path), false).await
    }

    async fn new_with_store_and_services(
        addr: &str,
        closure: &str,
        store_path: &std::path::Path,
    ) -> Self {
        Self::new_with_options(addr, closure, false, &[], Some(store_path), true).await
    }

    async fn new_with_options(
        addr: &str,
        closure: &str,
        tls: bool,
        plugins: &[std::path::PathBuf],
        store_path: Option<&std::path::Path>,
        services: bool,
    ) -> Self {
        let mut cmd = tokio::process::Command::new(assert_cmd::cargo::cargo_bin!("http-nu"));
        cmd.arg("--log-format").arg("jsonl");

        // Add plugin arguments first
        for plugin in plugins {
            cmd.arg("--plugin").arg(plugin);
        }

        // Add store path if provided
        if let Some(path) = store_path {
            cmd.arg("--store").arg(path);
            if services {
                cmd.arg("--services");
            }
        }

        cmd.arg(addr).arg("-c").arg(closure);

        if tls {
            cmd.arg("--tls").arg("tests/combined.pem");
        }

        let mut child = cmd
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .spawn()
            .expect("Failed to start http-nu server");

        let stdout = child.stdout.take().unwrap();
        let stderr = child.stderr.take().unwrap();

        let (addr_tx, addr_rx) = tokio::sync::oneshot::channel();

        // Spawn tasks to read output
        let mut addr_tx = Some(addr_tx);
        tokio::spawn(async move {
            let mut reader = BufReader::new(stdout).lines();
            while let Ok(Some(line)) = reader.next_line().await {
                eprintln!("[HTTP-NU STDOUT] {line}");
                if addr_tx.is_some() {
                    if let Ok(json) = serde_json::from_str::<serde_json::Value>(&line) {
                        if let Some(addr_str) = json.get("address").and_then(|a| a.as_str()) {
                            if let Some(tx) = addr_tx.take() {
                                let _ = tx.send(addr_str.trim().to_string());
                            }
                        }
                    }
                }
            }
        });

        tokio::spawn(async move {
            let mut reader = BufReader::new(stderr).lines();
            while let Ok(Some(line)) = reader.next_line().await {
                eprintln!("[HTTP-NU STDERR] {line}");
            }
        });

        let address = timeout(std::time::Duration::from_secs(5), addr_rx)
            .await
            .expect("Failed to get address from http-nu server")
            .expect("Channel closed before address received");

        Self { child, address }
    }

    async fn curl(&self, path: &str) -> process::Output {
        let mut cmd = tokio::process::Command::new("curl");
        if self.address.starts_with('/') {
            cmd.arg("--unix-socket").arg(&self.address);
            cmd.arg(format!("http://localhost{path}"));
        } else {
            cmd.arg(format!("{}{path}", self.address));
        }
        cmd.output().await.expect("Failed to execute curl")
    }

    async fn curl_tls(&self, path: &str) -> process::Output {
        // Extract port from address format "https://127.0.0.1:8080"
        let port = self.address.split(':').next_back().unwrap();
        let mut cmd = tokio::process::Command::new("curl");
        cmd.arg("--cacert")
            .arg("tests/cert.pem")
            .arg("--resolve")
            .arg(format!("localhost:{port}:127.0.0.1"))
            .arg(format!("https://localhost:{port}{path}"));

        cmd.output().await.expect("Failed to execute curl")
    }

    fn send_ctrl_c(&mut self) {
        #[cfg(unix)]
        {
            use nix::sys::signal::{kill, Signal};
            use nix::unistd::Pid;

            let pid = Pid::from_raw(self.child.id().expect("child id") as i32);
            kill(pid, Signal::SIGINT).expect("failed to send SIGINT");
        }
        #[cfg(not(unix))]
        {
            // On Windows, use forceful termination since console Ctrl+C handling
            // requires special setup that our server doesn't have
            let _ = self.child.start_kill();
        }
    }

    fn send_sigterm(&mut self) {
        #[cfg(unix)]
        {
            use nix::sys::signal::{kill, Signal};
            use nix::unistd::Pid;

            let pid = Pid::from_raw(self.child.id().expect("child id") as i32);
            kill(pid, Signal::SIGTERM).expect("failed to send SIGTERM");
        }
        #[cfg(not(unix))]
        {
            let _ = self.child.start_kill();
        }
    }

    async fn wait_for_exit(&mut self) -> std::process::ExitStatus {
        use tokio::time::{timeout, Duration};
        timeout(Duration::from_secs(5), self.child.wait())
            .await
            .expect("server did not exit in time")
            .expect("failed waiting for child")
    }

    fn has_exited(&mut self) -> bool {
        matches!(self.child.try_wait(), Ok(Some(_)))
    }
}

impl Drop for TestServer {
    fn drop(&mut self) {
        if !self.has_exited() {
            let _ = self.child.start_kill();
        }
    }
}

/// Test server with stdin support for dynamic script reloading
struct TestServerWithStdin {
    child: Child,
    address: String,
    stdin: Option<ChildStdin>,
}

impl TestServerWithStdin {
    /// Spawn the server process and return handles, but don't send any script yet.
    /// The server will wait for a valid script before emitting the "start" message.
    /// Note: This uses -w flag for watch mode (required for stdin to work).
    fn spawn(addr: &str, tls: bool) -> (Child, ChildStdin, tokio::sync::oneshot::Receiver<String>) {
        Self::spawn_with_watch(addr, tls)
    }

    /// Spawn the server with -w flag for watch mode
    fn spawn_with_watch(
        addr: &str,
        tls: bool,
    ) -> (Child, ChildStdin, tokio::sync::oneshot::Receiver<String>) {
        let mut cmd = tokio::process::Command::new(assert_cmd::cargo::cargo_bin!("http-nu"));
        cmd.arg("--log-format").arg("jsonl");
        cmd.arg(addr).arg("-").arg("-w");

        if tls {
            cmd.arg("--tls").arg("tests/combined.pem");
        }

        let mut child = cmd
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .spawn()
            .expect("Failed to start http-nu server");

        let stdin = child.stdin.take().unwrap();
        let stdout = child.stdout.take().unwrap();
        let stderr = child.stderr.take().unwrap();

        let (addr_tx, addr_rx) = tokio::sync::oneshot::channel();

        // Spawn tasks to read output
        let mut addr_tx = Some(addr_tx);
        tokio::spawn(async move {
            let mut reader = BufReader::new(stdout).lines();
            while let Ok(Some(line)) = reader.next_line().await {
                eprintln!("[HTTP-NU STDOUT] {line}");
                if addr_tx.is_some() {
                    if let Ok(json) = serde_json::from_str::<serde_json::Value>(&line) {
                        if let Some(addr_str) = json.get("address").and_then(|a| a.as_str()) {
                            if let Some(tx) = addr_tx.take() {
                                let _ = tx.send(addr_str.trim().to_string());
                            }
                        }
                    }
                }
            }
        });

        tokio::spawn(async move {
            let mut reader = BufReader::new(stderr).lines();
            while let Ok(Some(line)) = reader.next_line().await {
                eprintln!("[HTTP-NU STDERR] {line}");
            }
        });

        (child, stdin, addr_rx)
    }

    async fn write_script(&mut self, script: &str) {
        let stdin = self.stdin.as_mut().expect("stdin already closed");
        stdin
            .write_all(script.as_bytes())
            .await
            .expect("Failed to write script to stdin");
        stdin
            .write_all(b"\0")
            .await
            .expect("Failed to write null terminator to stdin");
        stdin.flush().await.expect("Failed to flush stdin");
    }

    async fn close_stdin(&mut self) {
        self.stdin.take();
    }

    async fn curl_get(&self) -> String {
        let mut cmd = tokio::process::Command::new("curl");
        cmd.arg("-s").arg(format!("{}/", self.address));
        let output = cmd.output().await.expect("Failed to execute curl");
        String::from_utf8_lossy(&output.stdout).trim().to_string()
    }
}

impl Drop for TestServerWithStdin {
    fn drop(&mut self) {
        let _ = self.child.start_kill();
    }
}

#[tokio::test]
async fn test_server_startup_and_shutdown() {
    let _server = TestServer::new("127.0.0.1:0", "{|req| $req.method}", false).await;
    tokio::time::sleep(std::time::Duration::from_millis(1000)).await;
}

#[cfg(unix)]
#[tokio::test]
async fn test_server_unix_socket() {
    let tmp = tempfile::tempdir().unwrap();
    let socket_path = tmp.path().join("test.sock");
    let socket_path_str = socket_path.to_str().unwrap();
    let server = TestServer::new(socket_path_str, "{|req| $req.method}", false).await;
    tokio::time::sleep(std::time::Duration::from_millis(1000)).await;

    let output = server.curl("").await;
    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert_eq!(stdout.trim(), "GET");
}

#[tokio::test]
async fn test_server_tcp_socket() {
    let server = TestServer::new("127.0.0.1:0", "{|req| $req.method}", false).await;
    tokio::time::sleep(std::time::Duration::from_millis(1000)).await;

    let output = server.curl("").await;
    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert_eq!(stdout.trim(), "GET");
}

#[tokio::test]
async fn test_server_tls_socket() {
    let server = TestServer::new("127.0.0.1:0", "{|req| $req.method}", true).await;
    tokio::time::sleep(std::time::Duration::from_millis(1000)).await;

    let output = server.curl_tls("").await;
    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert_eq!(stdout.trim(), "GET");
}

#[tokio::test]
async fn test_server_static_files() {
    let tmp = tempfile::tempdir().unwrap();
    let file_path = tmp.path().join("test.txt");
    std::fs::write(&file_path, "Hello from static file").unwrap();

    let closure = format!(
        "{{|req| .static '{}' $req.path }}",
        tmp.path().to_str().unwrap()
    );
    let server = TestServer::new("127.0.0.1:0", &closure, false).await;
    tokio::time::sleep(std::time::Duration::from_millis(1000)).await;

    let output = server.curl("/test.txt").await;
    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert_eq!(stdout.trim(), "Hello from static file");
}

#[tokio::test]
async fn test_server_static_files_fallback() {
    let tmp = tempfile::tempdir().unwrap();
    let index_path = tmp.path().join("index.html");
    std::fs::write(&index_path, "fallback page").unwrap();

    let closure = format!(
        "{{|req| .static '{}' $req.path --fallback 'index.html' }}",
        tmp.path().to_str().unwrap()
    );
    let server = TestServer::new("127.0.0.1:0", &closure, false).await;
    tokio::time::sleep(std::time::Duration::from_millis(1000)).await;

    let output = server.curl("/missing/route").await;
    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert_eq!(stdout.trim(), "fallback page");
}

#[tokio::test]
async fn test_server_reverse_proxy() {
    // Start a backend server that echoes the method, path, query, and a custom header.
    let backend = TestServer::new(
        "127.0.0.1:0",
        r#"{|req|
            let method = $req.method
            let path = $req.path
            let query = ($req.query | get foo | default 'none')
            let header = ($req.headers | get "x-custom-header" | default "not-found")
            $"Backend: ($method) ($path) ($query) ($header)"
        }"#,
        false,
    )
    .await;
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;

    // Start a proxy server that forwards to the backend with a custom header.
    let proxy_closure = format!(
        r#"{{|req| .reverse-proxy "{}" {{ headers: {{ "x-custom-header": "proxy-added" }} }} }}"#,
        backend.address
    );
    let proxy = TestServer::new("127.0.0.1:0", &proxy_closure, false).await;
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;

    // Test basic proxying with a query parameter.
    let output = proxy.curl("/test?foo=bar").await;
    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert_eq!(stdout.trim(), "Backend: GET /test bar proxy-added");
}

#[tokio::test]
async fn test_server_reverse_proxy_strip_prefix() {
    // Start a backend server that returns the request path.
    let backend = TestServer::new("127.0.0.1:0", r#"{|req| $"Path: ($req.path)"}"#, false).await;
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;

    // Start a proxy server with prefix stripping.
    let proxy_closure = format!(
        r#"{{|req| .reverse-proxy "{}" {{ strip_prefix: "/api" }} }}"#,
        backend.address
    );
    let proxy = TestServer::new("127.0.0.1:0", &proxy_closure, false).await;
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;

    // Test that the /api prefix is stripped from the request path.
    let output = proxy.curl("/api/users").await;
    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert_eq!(stdout.trim(), "Path: /users");
}

#[tokio::test]
async fn test_server_reverse_proxy_strip_prefix_ssrf() {
    // Start a backend server that returns the request path.
    let backend = TestServer::new("127.0.0.1:0", r#"{|req| $"Path: ($req.path)"}"#, false).await;
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;

    // Start a proxy server with prefix stripping.
    let proxy_closure = format!(
        r#"{{|req| .reverse-proxy "{}" {{ strip_prefix: "/api" }} }}"#,
        backend.address
    );
    let proxy = TestServer::new("127.0.0.1:0", &proxy_closure, false).await;
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;

    // A path like /api@evil.com/ after stripping "/api" becomes "@evil.com/".
    // Without sanitization, this produces "http://backend@evil.com/" which
    // sends the request to evil.com instead of the backend.
    let output = proxy.curl("/api@evil.com/").await;
    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert_eq!(stdout.trim(), "Path: /@evil.com/");
}

#[tokio::test]
async fn test_server_reverse_proxy_body_handling() {
    // Start a backend server that echoes the request body.
    let backend = TestServer::new("127.0.0.1:0", r#"{|req| $in}"#, false).await;
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;

    // Start a proxy server that forwards the original request body.
    let proxy_closure = format!(r#"{{|req| .reverse-proxy "{}" }}"#, backend.address);
    let proxy_forward = TestServer::new("127.0.0.1:0", &proxy_closure, false).await;
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;

    // Test that the original request body is forwarded.
    let mut cmd = tokio::process::Command::new("curl");
    cmd.arg("-s")
        .arg("-d")
        .arg("forwarded")
        .arg(&proxy_forward.address);
    let output = cmd.output().await.expect("Failed to execute curl");
    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert_eq!(stdout.trim(), "forwarded");

    // Start a proxy server that overrides the request body.
    let proxy_closure = format!(
        r#"{{|req| "override" | .reverse-proxy "{}" }}"#,
        backend.address
    );
    let proxy_override = TestServer::new("127.0.0.1:0", &proxy_closure, false).await;
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;

    // Test that the request body is overridden.
    let mut cmd = tokio::process::Command::new("curl");
    cmd.arg("-s")
        .arg("-d")
        .arg("original")
        .arg(&proxy_override.address);
    let output = cmd.output().await.expect("Failed to execute curl");
    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert_eq!(stdout.trim(), "override");
}

#[tokio::test]
async fn test_server_reverse_proxy_host_header() {
    // Start a backend server that echoes the Host header.
    let backend =
        TestServer::new("127.0.0.1:0", r#"{|req| $req.headers | get "host"}"#, false).await;
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;

    // Start a proxy server.
    let proxy_closure = format!(r#"{{|req| .reverse-proxy "{}" }}"#, backend.address);
    let proxy = TestServer::new("127.0.0.1:0", &proxy_closure, false).await;
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;

    // Test that the Host header is forwarded correctly.
    let mut cmd = tokio::process::Command::new("curl");
    cmd.arg("-s")
        .arg("-H")
        .arg("Host: example.com")
        .arg(&proxy.address);
    let output = cmd.output().await.expect("Failed to execute curl");
    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert_eq!(stdout.trim(), "example.com");
}

#[tokio::test]
async fn test_reverse_proxy_streaming() {
    // Start a backend server that streams data with delays
    let backend = TestServer::new(
        "127.0.0.1:0",
        r#"{|req|
            1..3 | each {|i|
                sleep 100ms
                $"chunk-($i)\n"
            }
        }"#,
        false,
    )
    .await;
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;

    // Start a proxy server
    let proxy_closure = format!(r#"{{|req| .reverse-proxy "{}" }}"#, backend.address);
    let proxy = TestServer::new("127.0.0.1:0", &proxy_closure, false).await;
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;

    // First test: verify backend server streams properly on its own
    println!("Testing backend directly...");
    let backend_start = std::time::Instant::now();
    let mut backend_child = tokio::process::Command::new("curl")
        .arg("-s")
        .arg("--raw")
        .arg("-N") // --no-buffer
        .arg(&backend.address)
        .stdout(std::process::Stdio::piped())
        .spawn()
        .expect("Failed to start curl for backend");

    let backend_stdout = backend_child.stdout.take().unwrap();
    use tokio::io::AsyncReadExt;
    let mut backend_reader = backend_stdout;
    let mut backend_first_byte = [0u8; 1];

    backend_reader
        .read_exact(&mut backend_first_byte)
        .await
        .unwrap();
    let backend_first_byte_time = backend_start.elapsed();

    let mut backend_remaining = Vec::new();
    backend_reader
        .read_to_end(&mut backend_remaining)
        .await
        .unwrap();
    let backend_total_time = backend_start.elapsed();

    backend_child.wait().await.unwrap();

    println!(
        "Backend - First byte: {:?}, Total: {:?}, Diff: {:?}",
        backend_first_byte_time,
        backend_total_time,
        backend_total_time.saturating_sub(backend_first_byte_time)
    );

    // Let's see what data we actually got
    let all_backend_data = [&backend_first_byte[..], &backend_remaining[..]].concat();
    println!(
        "Backend data: {:?}",
        String::from_utf8_lossy(&all_backend_data)
    );

    // Test to prove reverse proxy streams correctly
    // We'll measure when first byte arrives vs when request completes
    let start = std::time::Instant::now();
    let mut child = tokio::process::Command::new("curl")
        .arg("-s")
        .arg("--raw") // Don't parse chunked encoding
        .arg("-N") // --no-buffer
        .arg(&proxy.address)
        .stdout(std::process::Stdio::piped())
        .spawn()
        .expect("Failed to start curl");

    // Read output as it arrives
    let stdout = child.stdout.take().unwrap();
    let mut reader = stdout;
    let mut first_byte = [0u8; 1];

    // Measure when first byte arrives
    reader.read_exact(&mut first_byte).await.unwrap();
    let first_byte_time = start.elapsed();

    // Read remaining output
    let mut remaining = Vec::new();
    reader.read_to_end(&mut remaining).await.unwrap();
    let total_time = start.elapsed();

    child.wait().await.unwrap();

    println!("First byte at: {first_byte_time:?}, Total time: {total_time:?}");

    // If proxy were streaming: first byte ~100ms, total ~300ms
    let time_difference = total_time.saturating_sub(first_byte_time);

    // Total time should be at least the backend processing time
    assert!(total_time >= std::time::Duration::from_millis(280));

    // For true streaming, there should be at least 150ms between first byte and completion
    assert!(
        time_difference >= std::time::Duration::from_millis(150),
        "Expected at least 150ms between first byte and completion for streaming. Got: {time_difference:?}"
    );
}

#[tokio::test]
async fn test_server_reverse_proxy_custom_query() {
    // Start a backend server that echoes the query parameters it receives.
    let backend = TestServer::new("127.0.0.1:0", r#"{|req| $req.query | to json}"#, false).await;
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;

    // Start a proxy server that modifies query parameters.
    let proxy_closure = format!(
        r#"{{|req| .reverse-proxy "{}" {{ query: ($req.query | upsert "context-id" "smidgeons" | reject "debug") }} }}"#,
        backend.address
    );
    let proxy = TestServer::new("127.0.0.1:0", &proxy_closure, false).await;
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;

    // Test the query parameter modification.
    let mut cmd = tokio::process::Command::new("curl");
    cmd.arg("-s")
        .arg(format!("{}/test?page=1&debug=true&limit=10", proxy.address));

    let output = cmd.output().await.unwrap();
    assert!(output.status.success());

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();

    // Verify the query was modified: context-id added, debug removed, others preserved
    assert_eq!(json["context-id"], "smidgeons");
    assert_eq!(json["page"], "1");
    assert_eq!(json["limit"], "10");
    assert!(json.get("debug").is_none()); // debug should be removed
}

#[cfg(unix)]
#[tokio::test]
async fn test_server_tcp_graceful_shutdown() {
    let mut server = TestServer::new("127.0.0.1:0", "{|req| $req.method}", false).await;
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;
    server.send_ctrl_c();
    let status = server.wait_for_exit().await;
    assert!(status.success());
}

#[cfg(unix)]
#[tokio::test]
async fn test_server_tls_graceful_shutdown() {
    let mut server = TestServer::new("127.0.0.1:0", "{|req| $req.method}", true).await;
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;
    server.send_ctrl_c();
    let status = server.wait_for_exit().await;
    assert!(status.success());
}

#[cfg(unix)]
#[tokio::test]
async fn test_server_unix_graceful_shutdown() {
    let tmp = tempfile::tempdir().unwrap();
    let socket_path = tmp.path().join("test_sigint.sock");
    let socket_path_str = socket_path.to_str().unwrap();
    let mut server = TestServer::new(socket_path_str, "{|req| $req.method}", false).await;
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;
    server.send_ctrl_c();
    let status = server.wait_for_exit().await;
    assert!(status.success());
}

/// Tests that inflight requests complete during graceful shutdown.
/// Uses SIGTERM (not SIGINT) to avoid killing nushell jobs immediately.
#[cfg(unix)]
#[tokio::test]
async fn test_graceful_shutdown_waits_for_inflight_requests() {
    // Server with a 500ms delay in the response
    let mut server =
        TestServer::new("127.0.0.1:0", r#"{|req| sleep 500ms; "completed"}"#, false).await;

    // Start a request (will take 500ms to complete)
    // Use --retry and --retry-connrefused to handle slow server startup on CI
    let url = format!("{}/", server.address);
    let request_handle = tokio::spawn(async move {
        tokio::process::Command::new("curl")
            .arg("-s")
            .arg("--retry")
            .arg("3")
            .arg("--retry-delay")
            .arg("1")
            .arg("--retry-connrefused")
            .arg(&url)
            .output()
            .await
            .expect("curl failed")
    });

    // Give the request time to connect and start processing
    // Increased for CI environments (especially macOS) where timing can vary
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;

    // Send SIGTERM to trigger graceful shutdown (doesn't kill nushell jobs like SIGINT)
    server.send_sigterm();

    // The request should complete successfully despite shutdown being triggered
    let output = request_handle.await.expect("request task panicked");
    assert!(output.status.success(), "curl failed: {output:?}");
    let body = String::from_utf8_lossy(&output.stdout);
    assert_eq!(body, "completed");

    // Server should exit cleanly
    let status = server.wait_for_exit().await;
    assert!(status.success());
}

/// Tests that the server supports HTTP/1.1 connections
#[tokio::test]
async fn test_http1_support() {
    let mut server = TestServer::new("127.0.0.1:0", r#"{|req| $req.proto}"#, false).await;

    let output = tokio::process::Command::new("curl")
        .arg("-s")
        .arg("--http1.1")
        .arg(format!("{}/", server.address))
        .output()
        .await
        .expect("curl failed");

    assert!(output.status.success(), "curl failed: {output:?}");
    let body = String::from_utf8_lossy(&output.stdout);
    assert_eq!(body, "HTTP/1.1");

    server.send_sigterm();
    let status = server.wait_for_exit().await;
    assert!(status.success());
}

/// Tests that the server supports HTTP/2 connections (h2c - cleartext)
#[tokio::test]
async fn test_http2_support() {
    let mut server = TestServer::new("127.0.0.1:0", r#"{|req| $req.proto}"#, false).await;

    // Use --http2-prior-knowledge for h2c (HTTP/2 without TLS)
    let output = tokio::process::Command::new("curl")
        .arg("-s")
        .arg("--http2-prior-knowledge")
        .arg(format!("{}/", server.address))
        .output()
        .await
        .expect("curl failed");

    assert!(output.status.success(), "curl failed: {output:?}");
    let body = String::from_utf8_lossy(&output.stdout);
    assert_eq!(body, "HTTP/2.0");

    server.send_sigterm();
    let status = server.wait_for_exit().await;
    assert!(status.success());
}

/// Tests that HTTP/2 works over TLS (h2 via ALPN)
#[tokio::test]
async fn test_http2_tls_support() {
    let mut server = TestServer::new("127.0.0.1:0", r#"{|req| $req.proto}"#, true).await;

    // Extract port from address format "https://127.0.0.1:8080"
    let port = server.address.split(':').next_back().unwrap();

    // Use --http2 to prefer HTTP/2 via ALPN negotiation
    let output = tokio::process::Command::new("curl")
        .arg("-s")
        .arg("--http2")
        .arg("--cacert")
        .arg("tests/cert.pem")
        .arg("--resolve")
        .arg(format!("localhost:{port}:127.0.0.1"))
        .arg(format!("https://localhost:{port}/"))
        .output()
        .await
        .expect("curl failed");

    assert!(output.status.success(), "curl failed: {output:?}");
    let body = String::from_utf8_lossy(&output.stdout);
    assert_eq!(body, "HTTP/2.0");

    server.send_sigterm();
    let status = server.wait_for_exit().await;
    assert!(status.success());
}

#[tokio::test]
async fn test_parse_error_ansi_formatting() {
    let output = tokio::process::Command::new(assert_cmd::cargo::cargo_bin!("http-nu"))
        .arg("127.0.0.1:0")
        .arg("-c")
        .arg("{|req| use nonexistent oauth}")
        .output()
        .await
        .expect("Failed to execute http-nu");

    assert!(!output.status.success());

    let stderr = String::from_utf8_lossy(&output.stderr);

    // Should NOT contain escaped ANSI sequences
    assert!(
        !stderr.contains(r"\u{1b}"),
        "stderr contains escaped ANSI codes: {stderr}"
    );

    // Should contain the error text
    assert!(
        stderr.contains("Parse error") || stderr.contains("ExportNotFound"),
        "stderr missing expected error text: {stderr}"
    );
}

#[tokio::test]
async fn test_sse_brotli_compression_streams_immediately() {
    // Test that SSE responses with brotli compression stream events immediately,
    // not buffered until the stream ends.
    let server = TestServer::new(
        "127.0.0.1:0",
        r#"{|req|
            1..4 | each {|i|
                sleep 200ms
                {data: $"event-($i)"}
            } | to sse
        }"#,
        false,
    )
    .await;
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;

    // Start curl with brotli compression, reading raw compressed bytes
    let start = std::time::Instant::now();
    let mut child = tokio::process::Command::new("curl")
        .arg("-s")
        .arg("-N") // --no-buffer, stream data as it arrives
        .arg("-H")
        .arg("Accept-Encoding: br")
        .arg(&server.address)
        .stdout(std::process::Stdio::piped())
        .spawn()
        .expect("Failed to start curl");

    let stdout = child.stdout.take().unwrap();
    use tokio::io::AsyncReadExt;
    let mut reader = stdout;

    // Read first chunk - should arrive after ~200ms (first event), not ~800ms (all events)
    let mut first_chunk = vec![0u8; 64];
    let n = reader.read(&mut first_chunk).await.unwrap();
    let first_chunk_time = start.elapsed();

    assert!(n > 0, "Expected to receive data");

    // First chunk should arrive well before all events would complete (~800ms)
    // Give some margin for startup overhead, but it should be < 500ms
    assert!(
        first_chunk_time < std::time::Duration::from_millis(500),
        "First SSE chunk took {first_chunk_time:?}, expected < 500ms. SSE compression may be buffering instead of streaming.",
    );

    // Wait for the rest and verify total time is ~600ms (3 more events * 200ms)
    let mut remaining = Vec::new();
    reader.read_to_end(&mut remaining).await.unwrap();
    let total_time = start.elapsed();

    child.wait().await.unwrap();

    // Total time should be ~800ms (4 events * 200ms delay)
    assert!(
        total_time >= std::time::Duration::from_millis(700),
        "Total time {total_time:?} too short, expected ~800ms for streaming",
    );

    // Decompress and verify we got all events
    let all_compressed: Vec<u8> = first_chunk[..n]
        .iter()
        .chain(remaining.iter())
        .copied()
        .collect();
    let mut decompressed = Vec::new();
    brotli::BrotliDecompress(&mut &all_compressed[..], &mut decompressed)
        .expect("Failed to decompress brotli SSE data");

    let text = String::from_utf8(decompressed).expect("Invalid UTF-8");
    assert!(text.contains("data: event-1"), "Missing event-1");
    assert!(text.contains("data: event-2"), "Missing event-2");
    assert!(text.contains("data: event-3"), "Missing event-3");

    println!(
        "SSE brotli streaming verified: first chunk at {first_chunk_time:?}, total {total_time:?}"
    );
}

#[tokio::test]
async fn test_to_sse_command() {
    // Test that `to sse` properly formats records with id, event, data, retry fields
    // and auto-sets the correct headers
    let server = TestServer::new(
        "127.0.0.1:0",
        r#"{|req|
            [
                {id: "1", event: "greeting", data: "hello"}
                {id: "2", event: "update", data: "world", retry: 5000}
                {data: {count: 42}}
            ] | to sse
        }"#,
        false,
    )
    .await;

    // Use curl with -i to get headers
    let output = std::process::Command::new("curl")
        .arg("-s")
        .arg("-i")
        .arg(&server.address)
        .output()
        .expect("curl failed");

    assert!(output.status.success());
    let response = String::from_utf8_lossy(&output.stdout);

    // Check headers
    assert!(
        response.contains("content-type: text/event-stream"),
        "Missing content-type header"
    );
    assert!(
        response.contains("cache-control: no-cache"),
        "Missing cache-control header"
    );
    assert!(
        response.contains("connection: keep-alive"),
        "Missing connection header"
    );

    // Check SSE event formatting
    assert!(response.contains("id: 1"), "Missing id: 1");
    assert!(
        response.contains("event: greeting"),
        "Missing event: greeting"
    );
    assert!(response.contains("data: hello"), "Missing data: hello");

    assert!(response.contains("id: 2"), "Missing id: 2");
    assert!(response.contains("event: update"), "Missing event: update");
    assert!(response.contains("data: world"), "Missing data: world");
    assert!(response.contains("retry: 5000"), "Missing retry: 5000");

    // Check JSON serialization of record data
    assert!(
        response.contains(r#"data: {"count":42}"#),
        "Missing JSON data"
    );
}

#[tokio::test]
async fn test_to_sse_ignores_null_fields() {
    // Test that `to sse` ignores null values for optional fields
    let server = TestServer::new(
        "127.0.0.1:0",
        r#"{|req|
            [
                {event: "test", data: "hello", id: null, retry: null}
                {event: "with-id", data: "world", id: "123", retry: null}
                {event: "with-retry", data: "foo", id: null, retry: 5000}
            ] | to sse
        }"#,
        false,
    )
    .await;

    let output = std::process::Command::new("curl")
        .arg("-s")
        .arg(&server.address)
        .output()
        .expect("curl failed");

    assert!(output.status.success());
    let response = String::from_utf8_lossy(&output.stdout);

    // First event: no id or retry lines
    assert!(response.contains("event: test"), "Missing event: test");
    assert!(response.contains("data: hello"), "Missing data: hello");

    // Second event: has id, no retry
    assert!(response.contains("id: 123"), "Missing id: 123");
    assert!(
        response.contains("event: with-id"),
        "Missing event: with-id"
    );

    // Third event: has retry, no id
    assert!(response.contains("retry: 5000"), "Missing retry: 5000");
    assert!(
        response.contains("event: with-retry"),
        "Missing event: with-retry"
    );

    // Should not contain empty id/retry lines or "null"
    assert!(!response.contains("id: \n"), "Should not contain empty id");
    assert!(
        !response.contains("retry: \n"),
        "Should not contain empty retry"
    );
    assert!(
        !response.contains("id: null"),
        "Should not contain id: null"
    );
    assert!(
        !response.contains("retry: null"),
        "Should not contain retry: null"
    );
}

#[tokio::test]
async fn test_to_sse_data_list() {
    // Test that `to sse` handles data as a list of items
    let server = TestServer::new(
        "127.0.0.1:0",
        r#"{|req|
            [
                {event: "test", data: ["line1", "line2", "line3"]}
                {event: "embedded", data: ["first", "has\nnewline", "last"]}
                {event: "mixed", data: ["string", {num: 42}, "another"]}
            ] | to sse
        }"#,
        false,
    )
    .await;

    let output = std::process::Command::new("curl")
        .arg("-s")
        .arg(&server.address)
        .output()
        .expect("curl failed");

    assert!(output.status.success());
    let response = String::from_utf8_lossy(&output.stdout);

    // List items become separate data lines
    assert!(response.contains("data: line1"), "Missing data: line1");
    assert!(response.contains("data: line2"), "Missing data: line2");
    assert!(response.contains("data: line3"), "Missing data: line3");

    // Embedded newlines get split into separate data lines
    assert!(response.contains("data: first"), "Missing data: first");
    assert!(response.contains("data: has"), "Missing data: has");
    assert!(response.contains("data: newline"), "Missing data: newline");
    assert!(response.contains("data: last"), "Missing data: last");

    // Non-string items get JSON serialized
    assert!(response.contains("data: string"), "Missing data: string");
    assert!(
        response.contains(r#"data: {"num":42}"#),
        "Missing JSON data in list"
    );
    assert!(response.contains("data: another"), "Missing data: another");
}

/// Tests that missing Host header returns 500 error
#[tokio::test]
async fn test_server_missing_host_header() {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::TcpStream;

    let mut server = TestServer::new(
        "127.0.0.1:0",
        "{|req| let host = $req.headers.host; $\"Host: ($host)\" }",
        false,
    )
    .await;

    // Use a raw TCP connection so the test doesn't depend on `nc`
    // Strip the http:// prefix from address for raw TCP connection
    let addr = server.address.strip_prefix("http://").unwrap();
    let mut stream = TcpStream::connect(addr).await.expect("connect to server");
    stream
        .write_all(b"GET / HTTP/1.0\r\n\r\n")
        .await
        .expect("send request");
    let mut buf = Vec::new();
    stream.read_to_end(&mut buf).await.expect("read response");
    let text = String::from_utf8_lossy(&buf);
    assert!(text.contains("500"), "expected 500 status, got: {text}");

    server.send_sigterm();
    let status = server.wait_for_exit().await;
    assert!(status.success());
}

/// Tests basic router exact path matching
#[tokio::test]
async fn test_router_exact_path() {
    let server = TestServer::new(
        "127.0.0.1:0",
        r#"{|req|
            use http-nu/router *
            dispatch $req [
                (route {path: "/health"} {|req ctx| "OK"})
                (route {path: "/status"} {|req ctx| "RUNNING"})
                (route true {|req ctx| "NOT FOUND"})
            ]
        }"#,
        false,
    )
    .await;

    let output = server.curl("/health").await;
    assert!(output.status.success());
    assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "OK");

    let output = server.curl("/status").await;
    assert!(output.status.success());
    assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "RUNNING");

    let output = server.curl("/unknown").await;
    assert!(output.status.success());
    assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "NOT FOUND");
}

/// Tests router path parameter extraction
#[tokio::test]
async fn test_router_path_parameters() {
    let server = TestServer::new(
        "127.0.0.1:0",
        r#"{|req|
            use http-nu/router *
            dispatch $req [
                (route {path-matches: "/users/:id"} {|req ctx| $"User: ($ctx.id)"})
                (route {path-matches: "/posts/:userId/:postId"} {|req ctx| $"Post ($ctx.postId) by user ($ctx.userId)"})
                (route true {|req ctx| "NOT FOUND"})
            ]
        }"#,
        false,
    )
    .await;

    let output = server.curl("/users/alice").await;
    assert!(output.status.success());
    assert_eq!(
        String::from_utf8_lossy(&output.stdout).trim(),
        "User: alice"
    );

    let output = server.curl("/posts/bob/123").await;
    assert!(output.status.success());
    assert_eq!(
        String::from_utf8_lossy(&output.stdout).trim(),
        "Post 123 by user bob"
    );
}

/// Tests router method matching
#[tokio::test]
async fn test_router_method_matching() {
    let server = TestServer::new(
        "127.0.0.1:0",
        r#"{|req|
            use http-nu/router *
            dispatch $req [
                (route {method: "GET", path: "/items"} {|req ctx| "LIST"})
                (route {method: "POST", path: "/items"} {|req ctx| "CREATE"})
                (route true {|req ctx| "NOT FOUND"})
            ]
        }"#,
        false,
    )
    .await;

    let output = server.curl("/items").await;
    assert!(output.status.success());
    assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "LIST");

    let output = tokio::process::Command::new("curl")
        .arg("-X")
        .arg("POST")
        .arg(format!("{}/items", server.address))
        .output()
        .await
        .expect("curl failed");
    assert!(output.status.success());
    assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "CREATE");
}

/// Tests router header matching
#[tokio::test]
async fn test_router_header_matching() {
    let server = TestServer::new(
        "127.0.0.1:0",
        r#"{|req|
            use http-nu/router *
            dispatch $req [
                (route {has-header: {accept: "application/json"}} {|req ctx| "JSON"})
                (route true {|req ctx| "OTHER"})
            ]
        }"#,
        false,
    )
    .await;

    let output = tokio::process::Command::new("curl")
        .arg("-H")
        .arg("Accept: application/json")
        .arg(format!("{}/", server.address))
        .output()
        .await
        .expect("curl failed");
    assert!(output.status.success());
    assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "JSON");

    let output = tokio::process::Command::new("curl")
        .arg("-H")
        .arg("Accept: text/html")
        .arg(format!("{}/", server.address))
        .output()
        .await
        .expect("curl failed");
    assert!(output.status.success());
    assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "OTHER");
}

/// Tests router combined conditions (method + path + headers)
#[tokio::test]
async fn test_router_combined_conditions() {
    let server = TestServer::new(
        "127.0.0.1:0",
        r#"{|req|
            use http-nu/router *
            dispatch $req [
                (route {
                    method: "POST"
                    path-matches: "/api/:version/data"
                    has-header: {accept: "application/json"}
                } {|req ctx| $"API ($ctx.version) JSON"})
                (route true {|req ctx| "FALLBACK"})
            ]
        }"#,
        false,
    )
    .await;

    let output = tokio::process::Command::new("curl")
        .arg("-X")
        .arg("POST")
        .arg("-H")
        .arg("Accept: application/json")
        .arg(format!("{}/api/v1/data", server.address))
        .output()
        .await
        .expect("curl failed");
    assert!(output.status.success());
    assert_eq!(
        String::from_utf8_lossy(&output.stdout).trim(),
        "API v1 JSON"
    );

    // Wrong method
    let output = tokio::process::Command::new("curl")
        .arg("-H")
        .arg("Accept: application/json")
        .arg(format!("{}/api/v1/data", server.address))
        .output()
        .await
        .expect("curl failed");
    assert!(output.status.success());
    assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "FALLBACK");
}

/// Tests router 501 response when no routes match
#[tokio::test]
async fn test_router_no_match_501() {
    let server = TestServer::new(
        "127.0.0.1:0",
        r#"{|req|
            use http-nu/router *
            dispatch $req [
                (route {method: "POST", path: "/users"} {|req ctx| "CREATED"})
            ]
        }"#,
        false,
    )
    .await;

    let output = tokio::process::Command::new("curl")
        .arg("-i")
        .arg(format!("{}/unknown", server.address))
        .output()
        .await
        .expect("curl failed");
    assert!(output.status.success());
    let response = String::from_utf8_lossy(&output.stdout);
    assert!(response.contains("501 Not Implemented"));
    assert!(response.contains("No route configured"));
}

/// Tests that plugins can be loaded and their commands used
#[tokio::test]
async fn test_plugin_loading() {
    let plugin_path = workspace_bin("nu_plugin_test");
    let server = TestServer::new_with_plugins(
        "127.0.0.1:0",
        "{|req| test-plugin-cmd}",
        false,
        &[plugin_path],
    )
    .await;

    let output = server.curl("/").await;
    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert_eq!(stdout.trim(), "PLUGIN_WORKS");
}

/// Tests that plugin process is shared across requests (not spawned per-request).
/// The test plugin has a 100ms startup delay. If plugins were spawned per-request,
/// 10 requests would take at least 1000ms. With shared plugins, it should complete
/// well under 200ms total.
#[tokio::test]
async fn test_plugin_process_shared_across_requests() {
    let plugin_path = workspace_bin("nu_plugin_test");
    let server = TestServer::new_with_plugins(
        "127.0.0.1:0",
        "{|req| test-plugin-cmd}",
        false,
        &[plugin_path],
    )
    .await;

    let start = std::time::Instant::now();

    for _ in 0..10 {
        let output = server.curl("/").await;
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert_eq!(stdout.trim(), "PLUGIN_WORKS");
    }

    let elapsed = start.elapsed();
    assert!(
        elapsed < std::time::Duration::from_millis(400),
        "10 requests took {elapsed:?}, expected < 400ms (plugin should be shared, not spawned per-request)"
    );
}

// ============================================================================
// Watch mode tests (-w/--watch)
// ============================================================================

/// Tests that -w/--watch flag is incompatible with -c/--commands flag
#[tokio::test]
async fn test_watch_flag_incompatible_with_commands() {
    let output = tokio::process::Command::new(assert_cmd::cargo::cargo_bin!("http-nu"))
        .arg("127.0.0.1:0")
        .arg("-c")
        .arg("{|req| 'hello'}")
        .arg("-w")
        .output()
        .await
        .expect("Failed to execute http-nu");

    assert!(!output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("cannot be used with") || stderr.contains("conflict"),
        "Expected error about -w and -c being incompatible, got: {stderr}"
    );
}

/// Tests that file watch mode reloads script when file changes
#[tokio::test]
async fn test_watch_file_reload_on_change() {
    let tmp = tempfile::tempdir().unwrap();
    let script_path = tmp.path().join("handler.nu");

    // Write initial script
    std::fs::write(&script_path, r#"{|req| "version1"}"#).unwrap();

    // Start server with --watch
    let mut cmd = tokio::process::Command::new(assert_cmd::cargo::cargo_bin!("http-nu"));
    cmd.arg("--log-format")
        .arg("jsonl")
        .arg("127.0.0.1:0")
        .arg(&script_path)
        .arg("-w");

    let mut child = cmd
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .expect("Failed to start http-nu server");

    let stdout = child.stdout.take().unwrap();
    let stderr = child.stderr.take().unwrap();

    let (addr_tx, addr_rx) = tokio::sync::oneshot::channel();

    let mut addr_tx = Some(addr_tx);
    tokio::spawn(async move {
        let mut reader = BufReader::new(stdout).lines();
        while let Ok(Some(line)) = reader.next_line().await {
            eprintln!("[HTTP-NU STDOUT] {line}");
            if addr_tx.is_some() {
                if let Ok(json) = serde_json::from_str::<serde_json::Value>(&line) {
                    if let Some(addr_str) = json.get("address").and_then(|a| a.as_str()) {
                        if let Some(tx) = addr_tx.take() {
                            let _ = tx.send(addr_str.trim().to_string());
                        }
                    }
                }
            }
        }
    });

    tokio::spawn(async move {
        let mut reader = BufReader::new(stderr).lines();
        while let Ok(Some(line)) = reader.next_line().await {
            eprintln!("[HTTP-NU STDERR] {line}");
        }
    });

    let address = timeout(std::time::Duration::from_secs(5), addr_rx)
        .await
        .expect("Failed to get address")
        .expect("Channel closed");

    // Verify initial response
    let output = tokio::process::Command::new("curl")
        .arg("-s")
        .arg(format!("{address}/"))
        .output()
        .await
        .expect("curl failed");
    assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "version1");

    // Trigger a spurious event, then write the actual change.
    // This tests trailing-edge debounce: the reload should wait for events to
    // settle and read the final content, not the content at the first event.
    let dummy_path = tmp.path().join("trigger.txt");
    std::fs::write(&dummy_path, "trigger").unwrap();
    tokio::time::sleep(std::time::Duration::from_millis(10)).await;
    std::fs::write(&script_path, r#"{|req| "version2"}"#).unwrap();

    // Wait for debounced reload to complete
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;

    // Verify updated response
    let output = tokio::process::Command::new("curl")
        .arg("-s")
        .arg(format!("{address}/"))
        .output()
        .await
        .expect("curl failed");
    assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "version2");

    let _ = child.kill().await;
}

/// Tests that file watch mode reloads when a file in the script's directory changes
#[tokio::test]
async fn test_watch_directory_change_triggers_reload() {
    let tmp = tempfile::tempdir().unwrap();
    let script_path = tmp.path().join("handler.nu");
    let include_path = tmp.path().join("helpers.nu");

    // Write initial files
    std::fs::write(&include_path, r#"def get-version [] { "v1" }"#).unwrap();
    std::fs::write(
        &script_path,
        format!(
            r#"source "{}"
{{|req| get-version}}"#,
            include_path.display()
        ),
    )
    .unwrap();

    // Start server with --watch
    let mut cmd = tokio::process::Command::new(assert_cmd::cargo::cargo_bin!("http-nu"));
    cmd.arg("--log-format")
        .arg("jsonl")
        .arg("127.0.0.1:0")
        .arg(&script_path)
        .arg("-w");

    let mut child = cmd
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .expect("Failed to start http-nu server");

    let stdout = child.stdout.take().unwrap();
    let stderr = child.stderr.take().unwrap();

    let (addr_tx, addr_rx) = tokio::sync::oneshot::channel();

    let mut addr_tx = Some(addr_tx);
    tokio::spawn(async move {
        let mut reader = BufReader::new(stdout).lines();
        while let Ok(Some(line)) = reader.next_line().await {
            eprintln!("[HTTP-NU STDOUT] {line}");
            if addr_tx.is_some() {
                if let Ok(json) = serde_json::from_str::<serde_json::Value>(&line) {
                    if let Some(addr_str) = json.get("address").and_then(|a| a.as_str()) {
                        if let Some(tx) = addr_tx.take() {
                            let _ = tx.send(addr_str.trim().to_string());
                        }
                    }
                }
            }
        }
    });

    tokio::spawn(async move {
        let mut reader = BufReader::new(stderr).lines();
        while let Ok(Some(line)) = reader.next_line().await {
            eprintln!("[HTTP-NU STDERR] {line}");
        }
    });

    let address = timeout(std::time::Duration::from_secs(5), addr_rx)
        .await
        .expect("Failed to get address")
        .expect("Channel closed");

    // Verify initial response
    let output = tokio::process::Command::new("curl")
        .arg("-s")
        .arg(format!("{address}/"))
        .output()
        .await
        .expect("curl failed");
    assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "v1");

    // Modify the included file (not the main script)
    std::fs::write(&include_path, r#"def get-version [] { "v2" }"#).unwrap();

    // Wait for file watcher to detect change and reload
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;

    // Verify updated response
    let output = tokio::process::Command::new("curl")
        .arg("-s")
        .arg(format!("{address}/"))
        .output()
        .await
        .expect("curl failed");
    assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "v2");

    let _ = child.kill().await;
}

/// Tests that stdin mode works without -w (one-shot read)
#[tokio::test]
async fn test_stdin_one_shot() {
    let mut cmd = tokio::process::Command::new(assert_cmd::cargo::cargo_bin!("http-nu"));
    cmd.arg("--log-format")
        .arg("jsonl")
        .arg("127.0.0.1:0")
        .arg("-");

    let mut child = cmd
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .expect("Failed to start http-nu");

    // Write script to stdin and close it
    let mut stdin = child.stdin.take().unwrap();
    stdin.write_all(br#"{|req| "one-shot"}"#).await.unwrap();
    drop(stdin); // Close stdin to signal EOF

    let stdout = child.stdout.take().unwrap();
    let (addr_tx, addr_rx) = tokio::sync::oneshot::channel();

    let mut addr_tx = Some(addr_tx);
    tokio::spawn(async move {
        let mut reader = BufReader::new(stdout).lines();
        while let Ok(Some(line)) = reader.next_line().await {
            if addr_tx.is_some() {
                if let Ok(json) = serde_json::from_str::<serde_json::Value>(&line) {
                    if let Some(addr_str) = json.get("address").and_then(|a| a.as_str()) {
                        if let Some(tx) = addr_tx.take() {
                            let _ = tx.send(addr_str.trim().to_string());
                        }
                    }
                }
            }
        }
    });

    let address = timeout(std::time::Duration::from_secs(5), addr_rx)
        .await
        .expect("Server didn't start")
        .expect("Channel closed");

    // Verify response
    let output = tokio::process::Command::new("curl")
        .arg("-s")
        .arg(format!("{address}/"))
        .output()
        .await
        .expect("curl failed");
    assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "one-shot");

    let _ = child.kill().await;
}

/// Tests dynamic script reload via stdin (null-terminated protocol)
#[tokio::test]
async fn test_watch_stdin_dynamic_reload() {
    // Spawn server process - it will wait for a valid script
    let (child, mut stdin, addr_rx) = TestServerWithStdin::spawn("127.0.0.1:0", false);

    // Helper to write a script to stdin
    async fn write_script(stdin: &mut ChildStdin, script: &str) {
        stdin.write_all(script.as_bytes()).await.unwrap();
        stdin.write_all(b"\0").await.unwrap();
        stdin.flush().await.unwrap();
        // Give tokio a chance to actually send the data to the child process
        tokio::task::yield_now().await;
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
    }

    // 1. Send bad script (actual parse error) - server should reject it and keep waiting
    write_script(&mut stdin, "{|req| { unclosed").await;
    tokio::time::sleep(std::time::Duration::from_millis(200)).await;

    // 2. Send good script "1" - server should start
    write_script(&mut stdin, r#"{|req| "1"}"#).await;

    // Wait for server to start
    let address = timeout(std::time::Duration::from_secs(5), addr_rx)
        .await
        .expect("Server didn't start")
        .expect("Channel closed");

    let mut server = TestServerWithStdin {
        child,
        address,
        stdin: Some(stdin),
    };

    // 3. Curl should return "1"
    assert_eq!(server.curl_get().await, "1");

    // 4. Send bad script (different parse error) - server should reject and keep "1"
    server.write_script("{|req| ] unbalanced").await;
    tokio::time::sleep(std::time::Duration::from_millis(100)).await;

    // 5. Curl should still return "1"
    assert_eq!(server.curl_get().await, "1");

    // 6. Send good script "2"
    server.write_script(r#"{|req| "2"}"#).await;
    tokio::time::sleep(std::time::Duration::from_millis(100)).await;

    // 7. Curl should return "2"
    assert_eq!(server.curl_get().await, "2");

    // 8. Send script "3" without null terminator, then close stdin
    // The script should be processed when stdin closes (EOF acts as terminator)
    {
        let stdin = server.stdin.as_mut().unwrap();
        stdin.write_all(br#"{|req| "3"}"#).await.unwrap();
        stdin.flush().await.unwrap();
        tokio::task::yield_now().await;
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
    }
    server.close_stdin().await;
    tokio::time::sleep(std::time::Duration::from_millis(100)).await;

    // 9. Curl should return "3" (script was processed on stdin close)
    assert_eq!(server.curl_get().await, "3");
}

// ============================================================================
// Store integration tests (cross.stream)
// ============================================================================

/// Tests that .cat -f streams frames appended via .append
#[cfg(feature = "cross-stream")]
#[tokio::test]
async fn test_store_cat_follow_receives_appended_frames() {
    use tokio::io::{AsyncBufReadExt, BufReader};

    let tmp = tempfile::tempdir().unwrap();
    let store_path = tmp.path().join("store");

    // Server with two endpoints:
    // GET /stream - streams frames from topic "ping" as JSONL
    // POST /append - appends a frame to topic "ping"
    let server = TestServer::new_with_store(
        "127.0.0.1:0",
        r#"{|req|
            if $req.method == "GET" and $req.path == "/stream" {
                .cat -f -n -T ping | each {|frame| $frame | to json -r | $"($in)\n" }
            } else if $req.method == "POST" and $req.path == "/append" {
                $in | .append ping --meta {source: "test"}
                "ok"
            } else {
                "not found" | metadata set { merge {'http.response': {status: 404}}}
            }
        }"#,
        &store_path,
    )
    .await;

    // Start long-poll connection to /stream
    let stream_url = format!("{}/stream", server.address);
    let mut stream_child = tokio::process::Command::new("curl")
        .arg("-s")
        .arg("-N") // no buffering
        .arg(&stream_url)
        .stdout(std::process::Stdio::piped())
        .spawn()
        .expect("Failed to start curl for stream");

    let stream_stdout = stream_child.stdout.take().unwrap();
    let mut stream_reader = BufReader::new(stream_stdout).lines();

    // Give the stream connection time to establish
    tokio::time::sleep(std::time::Duration::from_millis(200)).await;

    // Append a frame via POST /append
    let append_output = tokio::process::Command::new("curl")
        .arg("-s")
        .arg("-X")
        .arg("POST")
        .arg("-d")
        .arg("hello world")
        .arg(format!("{}/append", server.address))
        .output()
        .await
        .expect("Failed to execute append curl");

    assert!(append_output.status.success());
    assert_eq!(String::from_utf8_lossy(&append_output.stdout).trim(), "ok");

    // Read the streamed frame from the long-poll connection
    let frame_line = timeout(std::time::Duration::from_secs(5), stream_reader.next_line())
        .await
        .expect("Timed out waiting for streamed frame")
        .expect("Failed to read line")
        .expect("Stream ended unexpectedly");

    // Parse the JSONL and verify it's our frame
    let frame: serde_json::Value =
        serde_json::from_str(&frame_line).expect("Failed to parse frame JSON");

    assert_eq!(frame["topic"], "ping", "Frame should have topic 'ping'");
    assert_eq!(
        frame["meta"]["source"], "test",
        "Frame should have meta.source 'test'"
    );
    assert!(frame["hash"].is_string(), "Frame should have a hash");

    // Clean up
    let _ = stream_child.kill().await;
}

/// Tests that --services enables xs handlers
#[cfg(feature = "cross-stream")]
#[tokio::test]
async fn test_services_flag_enables_handlers() {
    use tokio::io::{AsyncBufReadExt, BufReader};

    let tmp = tempfile::tempdir().unwrap();
    let store_path = tmp.path().join("store");

    // Start server with --store and --services
    let server =
        TestServer::new_with_store_and_services("127.0.0.1:0", r#"{|req| "ok"}"#, &store_path)
            .await;

    // Give services time to start
    tokio::time::sleep(std::time::Duration::from_millis(200)).await;

    let sock_path = store_path.join("sock");

    // Wait for the socket to be created
    let sock_ready = timeout(std::time::Duration::from_secs(5), async {
        loop {
            if sock_path.exists() {
                return;
            }
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        }
    })
    .await;
    assert!(
        sock_ready.is_ok(),
        "Socket was not created at {sock_path:?}"
    );

    // Start a streaming reader via the xs API socket
    let mut stream_child = tokio::process::Command::new("curl")
        .arg("-s")
        .arg("-N") // no buffering
        .arg("--unix-socket")
        .arg(&sock_path)
        .arg("http://localhost/?follow=true")
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .expect("Failed to start curl for stream");

    let stream_stdout = stream_child.stdout.take().unwrap();
    let mut stream_reader = BufReader::new(stream_stdout).lines();

    // Give the stream connection time to establish
    tokio::time::sleep(std::time::Duration::from_millis(100)).await;

    // Register a simple echo handler via the xs API socket
    let handler_script = r#"{run: {|frame, state| $frame.topic | .append echo.out}}"#;
    let register_output = tokio::process::Command::new("curl")
        .arg("-s")
        .arg("-X")
        .arg("POST")
        .arg("--unix-socket")
        .arg(&sock_path)
        .arg("-d")
        .arg(handler_script)
        .arg("http://localhost/append/echo.register")
        .output()
        .await
        .expect("Failed to register handler");

    assert!(
        register_output.status.success(),
        "Handler registration failed: {}",
        String::from_utf8_lossy(&register_output.stderr)
    );

    // Wait for handler to become active by reading streamed frames
    let active_frame = timeout(std::time::Duration::from_secs(5), async {
        loop {
            let line = stream_reader
                .next_line()
                .await
                .expect("Failed to read line")
                .expect("Stream ended unexpectedly");
            eprintln!("[TEST] Received frame: {line}");
            let frame: serde_json::Value = serde_json::from_str(&line).unwrap();
            let topic = frame["topic"].as_str().unwrap();
            if topic == "echo.active" || topic == "echo.unregistered" {
                return frame;
            }
        }
    })
    .await
    .expect("Handler did not become active or fail");

    assert_eq!(
        active_frame["topic"], "echo.active",
        "Handler failed to activate"
    );

    // Trigger the handler via the xs API socket
    let trigger_output = tokio::process::Command::new("curl")
        .arg("-s")
        .arg("-X")
        .arg("POST")
        .arg("--unix-socket")
        .arg(&sock_path)
        .arg("http://localhost/append/test.trigger")
        .output()
        .await
        .expect("Failed to trigger handler");

    assert!(
        trigger_output.status.success(),
        "Trigger failed: {}",
        String::from_utf8_lossy(&trigger_output.stderr)
    );

    // Wait for the handler output
    let output_frame = timeout(std::time::Duration::from_secs(5), async {
        loop {
            let line = stream_reader.next_line().await.unwrap().unwrap();
            let frame: serde_json::Value = serde_json::from_str(&line).unwrap();
            if frame["topic"] == "echo.out" {
                return frame;
            }
        }
    })
    .await
    .expect("Handler did not produce output");

    assert_eq!(output_frame["topic"], "echo.out");

    // Verify the handler echoed the trigger topic by fetching CAS content
    let hash = output_frame["hash"].as_str().unwrap();
    let cas_output = tokio::process::Command::new("curl")
        .arg("-s")
        .arg("--unix-socket")
        .arg(&sock_path)
        .arg(format!("http://localhost/cas/{hash}"))
        .output()
        .await
        .expect("Failed to fetch CAS content");

    assert_eq!(String::from_utf8_lossy(&cas_output.stdout), "test.trigger");

    // Clean up
    let _ = stream_child.kill().await;
    drop(server);
}

#[tokio::test]
async fn test_record_json_content_type() {
    let server = TestServer::new("127.0.0.1:0", "{|req| {foo: 1, bar: 'hello'}}", false).await;
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;

    let output = std::process::Command::new("curl")
        .arg("-s")
        .arg("-i")
        .arg(&server.address)
        .output()
        .expect("curl failed");

    assert!(output.status.success());
    let response = String::from_utf8_lossy(&output.stdout);

    assert!(
        response.contains("content-type: application/json"),
        "Expected application/json content-type, got: {response}"
    );
    assert!(
        response.contains(r#""foo":1"#) || response.contains(r#""foo": 1"#),
        "Expected JSON body with foo:1"
    );
}

#[tokio::test]
async fn test_list_of_records_json_content_type() {
    // Lists serialize as JSON arrays (streams serialize as JSONL)
    let server = TestServer::new("127.0.0.1:0", "{|req| [{a: 1}, {b: 2}, {c: 3}]}", false).await;
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;

    let output = std::process::Command::new("curl")
        .arg("-s")
        .arg("-i")
        .arg(&server.address)
        .output()
        .expect("curl failed");

    assert!(output.status.success());
    let response = String::from_utf8_lossy(&output.stdout);

    assert!(
        response.contains("content-type: application/json"),
        "Expected application/json content-type, got: {response}"
    );

    // Check JSON array format
    assert!(
        response.contains(r#"[{"a":1},{"b":2},{"c":3}]"#),
        "Expected JSON array, got: {response}"
    );
}

#[tokio::test]
async fn test_html_record_not_jsonl() {
    // Records with __html should get text/html, not JSON
    let server = TestServer::new(
        "127.0.0.1:0",
        r#"{|req| {__html: "<h1>Hello</h1>"}}"#,
        false,
    )
    .await;
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;

    let output = std::process::Command::new("curl")
        .arg("-s")
        .arg("-i")
        .arg(&server.address)
        .output()
        .expect("curl failed");

    assert!(output.status.success());
    let response = String::from_utf8_lossy(&output.stdout);

    assert!(
        response.contains("content-type: text/html"),
        "Expected text/html content-type for __html record, got: {response}"
    );
    assert!(response.contains("<h1>Hello</h1>"), "Expected HTML body");
}

#[tokio::test]
async fn test_binary_octet_stream_content_type() {
    let server = TestServer::new("127.0.0.1:0", "{|req| 0x[deadbeef]}", false).await;
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;

    let output = std::process::Command::new("curl")
        .arg("-s")
        .arg("-i")
        .arg(&server.address)
        .output()
        .expect("curl failed");

    assert!(output.status.success());
    let response = String::from_utf8_lossy(&output.stdout);

    assert!(
        response.contains("content-type: application/octet-stream"),
        "Expected application/octet-stream content-type for binary, got: {response}"
    );
}

#[tokio::test]
async fn test_sse_cancelled_on_hot_reload() {
    use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};

    // Spawn server with an SSE endpoint that streams indefinitely
    let (mut child, mut stdin, addr_rx) = TestServerWithStdin::spawn("127.0.0.1:0", false);

    // Send initial SSE script - stream many events slowly
    let sse_script = r#"{|req|
        1..100 | each {|i|
            sleep 100ms
            {data: $"event-($i)"}
        } | to sse
    }"#;
    stdin.write_all(sse_script.as_bytes()).await.unwrap();
    stdin.write_all(b"\0").await.unwrap();
    stdin.flush().await.unwrap();

    // Wait for server to start
    let address = tokio::time::timeout(std::time::Duration::from_secs(5), addr_rx)
        .await
        .expect("Server didn't start")
        .expect("Channel closed");

    tokio::time::sleep(std::time::Duration::from_millis(200)).await;

    // Start curl to SSE endpoint
    let mut sse_child = tokio::process::Command::new("curl")
        .arg("-sN")
        .arg(&address)
        .stdout(std::process::Stdio::piped())
        .spawn()
        .expect("Failed to start curl");

    let stdout = sse_child.stdout.take().expect("Failed to get stdout");
    let mut reader = BufReader::new(stdout).lines();

    // Read a few events to confirm SSE is working
    let mut events_received = 0;
    for _ in 0..3 {
        if let Ok(Ok(Some(line))) =
            tokio::time::timeout(std::time::Duration::from_secs(2), reader.next_line()).await
        {
            if line.starts_with("data:") {
                events_received += 1;
            }
        }
    }
    assert!(
        events_received >= 1,
        "Should have received at least one SSE event before reload"
    );

    // Trigger hot reload with a different script
    let new_script = r#"{|req| "reloaded"}"#;
    stdin.write_all(new_script.as_bytes()).await.unwrap();
    stdin.write_all(b"\0").await.unwrap();
    stdin.flush().await.unwrap();

    // Wait for reload to process
    tokio::time::sleep(std::time::Duration::from_millis(200)).await;

    // After reload, the SSE stream should be cancelled.
    // With HTTP keep-alive, curl won't exit on its own, but no more events should arrive.
    // Try to read another event - it should timeout (stream cancelled) or return None.
    let more_events =
        tokio::time::timeout(std::time::Duration::from_millis(500), reader.next_line()).await;

    // Either timeout (stream stalled) or None (stream ended) is acceptable
    let stream_stopped = match more_events {
        Err(_) => true,                                   // Timeout - no more data
        Ok(Ok(None)) => true,                             // Stream ended
        Ok(Ok(Some(line))) => !line.starts_with("data:"), // Got something but not an event
        Ok(Err(_)) => true,                               // Read error
    };
    assert!(stream_stopped, "SSE stream should stop after reload");

    // Kill the curl process since it won't exit with keep-alive
    sse_child.kill().await.ok();

    // Verify the new handler works
    let output = std::process::Command::new("curl")
        .arg("-s")
        .arg(&address)
        .output()
        .expect("curl failed");

    assert_eq!(
        String::from_utf8_lossy(&output.stdout).trim(),
        "reloaded",
        "New handler should be active after reload"
    );

    // Cleanup - kill the server
    child.kill().await.ok();
}

#[tokio::test]
async fn test_sse_cancelled_on_hot_reload_with_brotli() {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    // Spawn server with an SSE endpoint that streams indefinitely
    let (mut child, mut stdin, addr_rx) = TestServerWithStdin::spawn("127.0.0.1:0", false);

    // Send initial SSE script
    let sse_script = r#"{|req|
        1..100 | each {|i|
            sleep 100ms
            {data: $"event-($i)"}
        } | to sse
    }"#;
    stdin.write_all(sse_script.as_bytes()).await.unwrap();
    stdin.write_all(b"\0").await.unwrap();
    stdin.flush().await.unwrap();

    let address = tokio::time::timeout(std::time::Duration::from_secs(5), addr_rx)
        .await
        .expect("Server didn't start")
        .expect("Channel closed");

    tokio::time::sleep(std::time::Duration::from_millis(200)).await;

    // Start curl with brotli compression
    let mut sse_child = tokio::process::Command::new("curl")
        .arg("-sN")
        .arg("-H")
        .arg("Accept-Encoding: br")
        .arg(&address)
        .stdout(std::process::Stdio::piped())
        .spawn()
        .expect("Failed to start curl");

    let stdout = sse_child.stdout.take().expect("Failed to get stdout");
    let mut reader = stdout;

    // Read some data to confirm SSE is streaming
    let mut buf = vec![0u8; 256];
    let n = tokio::time::timeout(std::time::Duration::from_secs(2), reader.read(&mut buf))
        .await
        .expect("Timeout reading initial SSE data")
        .expect("Read error");
    assert!(n > 0, "Should have received SSE data");

    // Trigger hot reload
    let new_script = r#"{|req| "reloaded"}"#;
    stdin.write_all(new_script.as_bytes()).await.unwrap();
    stdin.write_all(b"\0").await.unwrap();
    stdin.flush().await.unwrap();

    tokio::time::sleep(std::time::Duration::from_millis(200)).await;

    // After reload, the compressed SSE stream should end.
    // Drain remaining data (brotli FINISH frame) and check for EOF.
    let stream_ended = tokio::time::timeout(std::time::Duration::from_secs(2), async {
        loop {
            match reader.read(&mut buf).await {
                Ok(0) => return true,  // EOF - stream ended
                Ok(_) => continue,     // Drain remaining data (e.g. brotli FINISH frame)
                Err(_) => return true, // Read error
            }
        }
    })
    .await;

    assert!(
        matches!(stream_ended, Ok(true)),
        "Compressed SSE stream should stop after reload"
    );

    sse_child.kill().await.ok();

    // Verify the new handler works
    let output = std::process::Command::new("curl")
        .arg("-s")
        .arg(&address)
        .output()
        .expect("curl failed");

    assert_eq!(
        String::from_utf8_lossy(&output.stdout).trim(),
        "reloaded",
        "New handler should be active after reload"
    );

    child.kill().await.ok();
}

/// Tests that --topic with -w loads a handler from the store, serves a placeholder
/// when the topic is empty, reloads when the topic is appended, and reloads again
/// when the topic is updated.
#[cfg(feature = "cross-stream")]
#[tokio::test]
async fn test_watch_topic_reload_on_append() {
    let tmp = tempfile::tempdir().unwrap();
    let store_path = tmp.path().join("store");

    // Start server with --store, --topic, and -w (no script file)
    let mut cmd = tokio::process::Command::new(assert_cmd::cargo::cargo_bin!("http-nu"));
    cmd.arg("--log-format")
        .arg("jsonl")
        .arg("--store")
        .arg(&store_path)
        .arg("--topic")
        .arg("serve.nu")
        .arg("-w")
        .arg("127.0.0.1:0");

    let mut child = cmd
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .expect("Failed to start http-nu server");

    let stdout = child.stdout.take().unwrap();
    let stderr = child.stderr.take().unwrap();

    let (addr_tx, addr_rx) = tokio::sync::oneshot::channel();

    let mut addr_tx = Some(addr_tx);
    tokio::spawn(async move {
        let mut reader = BufReader::new(stdout).lines();
        while let Ok(Some(line)) = reader.next_line().await {
            eprintln!("[HTTP-NU STDOUT] {line}");
            if addr_tx.is_some() {
                if let Ok(json) = serde_json::from_str::<serde_json::Value>(&line) {
                    if let Some(addr_str) = json.get("address").and_then(|a| a.as_str()) {
                        if let Some(tx) = addr_tx.take() {
                            let _ = tx.send(addr_str.trim().to_string());
                        }
                    }
                }
            }
        }
    });

    tokio::spawn(async move {
        let mut reader = BufReader::new(stderr).lines();
        while let Ok(Some(line)) = reader.next_line().await {
            eprintln!("[HTTP-NU STDERR] {line}");
        }
    });

    let address = timeout(std::time::Duration::from_secs(5), addr_rx)
        .await
        .expect("Failed to get address")
        .expect("Channel closed");

    // Verify placeholder response (503) when topic is empty
    let output = tokio::process::Command::new("curl")
        .arg("-s")
        .arg("-o")
        .arg("/dev/null")
        .arg("-w")
        .arg("%{http_code}")
        .arg(format!("{address}/"))
        .output()
        .await
        .expect("curl failed");
    assert_eq!(
        String::from_utf8_lossy(&output.stdout).trim(),
        "503",
        "Empty topic should serve placeholder with 503"
    );

    // Append a handler closure via the xs API socket
    let sock_path = store_path.join("sock");
    let output = tokio::process::Command::new("curl")
        .arg("-s")
        .arg("--unix-socket")
        .arg(&sock_path)
        .arg("-X")
        .arg("POST")
        .arg("-d")
        .arg(r#"{|req| "version1"}"#)
        .arg("http://localhost/append/serve.nu")
        .output()
        .await
        .expect("curl append failed");
    assert!(
        output.status.success(),
        "append should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // Wait for reload
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;

    // Verify updated response
    let output = tokio::process::Command::new("curl")
        .arg("-s")
        .arg(format!("{address}/"))
        .output()
        .await
        .expect("curl failed");
    assert_eq!(
        String::from_utf8_lossy(&output.stdout).trim(),
        "version1",
        "Should serve handler from topic"
    );

    // Update the topic with a new closure
    let output = tokio::process::Command::new("curl")
        .arg("-s")
        .arg("--unix-socket")
        .arg(&sock_path)
        .arg("-X")
        .arg("POST")
        .arg("-d")
        .arg(r#"{|req| "version2"}"#)
        .arg("http://localhost/append/serve.nu")
        .output()
        .await
        .expect("curl append failed");
    assert!(output.status.success(), "second append should succeed");

    // Wait for reload
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;

    // Verify re-reloaded response
    let output = tokio::process::Command::new("curl")
        .arg("-s")
        .arg(format!("{address}/"))
        .output()
        .await
        .expect("curl failed");
    assert_eq!(
        String::from_utf8_lossy(&output.stdout).trim(),
        "version2",
        "Should serve updated handler after topic update"
    );

    let _ = child.kill().await;
}

/// Tests that --topic hot reload picks up VFS module changes from the stream.
///
/// Registers a module, serves a topic that uses it, then updates the module
/// and re-appends the topic. After hot reload the endpoint should reflect the
/// updated module.
#[cfg(feature = "cross-stream")]
#[tokio::test]
async fn test_watch_topic_reload_picks_up_module_changes() {
    let tmp = tempfile::tempdir().unwrap();
    let store_path = tmp.path().join("store");

    // Start server with --store, --topic, and -w
    let mut cmd = tokio::process::Command::new(assert_cmd::cargo::cargo_bin!("http-nu"));
    cmd.arg("--log-format")
        .arg("jsonl")
        .arg("--store")
        .arg(&store_path)
        .arg("--topic")
        .arg("serve.nu")
        .arg("-w")
        .arg("127.0.0.1:0");

    let mut child = cmd
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .expect("Failed to start http-nu server");

    let stdout = child.stdout.take().unwrap();
    let stderr = child.stderr.take().unwrap();

    let (addr_tx, addr_rx) = tokio::sync::oneshot::channel();

    let mut addr_tx = Some(addr_tx);
    tokio::spawn(async move {
        let mut reader = BufReader::new(stdout).lines();
        while let Ok(Some(line)) = reader.next_line().await {
            eprintln!("[HTTP-NU STDOUT] {line}");
            if addr_tx.is_some() {
                if let Ok(json) = serde_json::from_str::<serde_json::Value>(&line) {
                    if let Some(addr_str) = json.get("address").and_then(|a| a.as_str()) {
                        if let Some(tx) = addr_tx.take() {
                            let _ = tx.send(addr_str.trim().to_string());
                        }
                    }
                }
            }
        }
    });

    tokio::spawn(async move {
        let mut reader = BufReader::new(stderr).lines();
        while let Ok(Some(line)) = reader.next_line().await {
            eprintln!("[HTTP-NU STDERR] {line}");
        }
    });

    let address = timeout(std::time::Duration::from_secs(5), addr_rx)
        .await
        .expect("Failed to get address")
        .expect("Channel closed");

    let sock_path = store_path.join("sock");

    // Append a VFS module `greeter.nu` that returns "foo"
    let output = tokio::process::Command::new("curl")
        .arg("-s")
        .arg("--unix-socket")
        .arg(&sock_path)
        .arg("-X")
        .arg("POST")
        .arg("-d")
        .arg(r#"export def hello [] { "foo" }"#)
        .arg("http://localhost/append/greeter.nu")
        .output()
        .await
        .expect("curl append module failed");
    assert!(output.status.success(), "append module should succeed");

    // Append serve topic that uses the module
    let output = tokio::process::Command::new("curl")
        .arg("-s")
        .arg("--unix-socket")
        .arg(&sock_path)
        .arg("-X")
        .arg("POST")
        .arg("-d")
        .arg("{|req| use greeter; greeter hello}")
        .arg("http://localhost/append/serve.nu")
        .output()
        .await
        .expect("curl append topic failed");
    assert!(output.status.success(), "append topic should succeed");

    // Wait for reload
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;

    // Verify endpoint returns "foo"
    let output = tokio::process::Command::new("curl")
        .arg("-s")
        .arg(format!("{address}/"))
        .output()
        .await
        .expect("curl failed");
    assert_eq!(
        String::from_utf8_lossy(&output.stdout).trim(),
        "foo",
        "Should return foo from greeter module"
    );

    // Append updated module that returns "bar"
    let output = tokio::process::Command::new("curl")
        .arg("-s")
        .arg("--unix-socket")
        .arg(&sock_path)
        .arg("-X")
        .arg("POST")
        .arg("-d")
        .arg(r#"export def hello [] { "bar" }"#)
        .arg("http://localhost/append/greeter.nu")
        .output()
        .await
        .expect("curl append updated module failed");
    assert!(
        output.status.success(),
        "append updated module should succeed"
    );

    // Append new serve topic to trigger hot reload
    let output = tokio::process::Command::new("curl")
        .arg("-s")
        .arg("--unix-socket")
        .arg(&sock_path)
        .arg("-X")
        .arg("POST")
        .arg("-d")
        .arg("{|req| use greeter; greeter hello}")
        .arg("http://localhost/append/serve.nu")
        .output()
        .await
        .expect("curl append updated topic failed");
    assert!(
        output.status.success(),
        "append updated topic should succeed"
    );

    // Wait for reload
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;

    // Verify endpoint returns "bar" (picks up updated module)
    let output = tokio::process::Command::new("curl")
        .arg("-s")
        .arg(format!("{address}/"))
        .output()
        .await
        .expect("curl failed");
    assert_eq!(
        String::from_utf8_lossy(&output.stdout).trim(),
        "bar",
        "Should return bar from updated greeter module after hot reload"
    );

    let _ = child.kill().await;
}

/// Tests that .mj --topic resolves templates from store topics, including
/// {% include %} and {% extends %} references to other topics.
#[cfg(feature = "cross-stream")]
#[tokio::test]
async fn test_mj_topic_resolves_templates_from_store() {
    let tmp = tempfile::tempdir().unwrap();
    let store_path = tmp.path().join("store");

    // The handler uses --topic to load the main template from the store.
    // The "page" topic will {% include "header" %} and {% extends "layout" %}.
    let server = TestServer::new_with_store(
        "127.0.0.1:0",
        r#"{|req|
            if $req.path == "/include" {
                {name: "world"} | .mj --topic page.include
            } else if $req.path == "/extends" {
                {title: "Home"} | .mj --topic page.extends
            } else {
                "not found"
            }
        }"#,
        &store_path,
    )
    .await;

    // Wait for store API socket
    let sock_path = store_path.join("sock");
    for _ in 0..20 {
        if sock_path.exists() {
            break;
        }
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
    }

    // Append supporting templates to store
    let append = |topic: &str, content: &str| {
        let sock = sock_path.clone();
        let topic = topic.to_string();
        let content = content.to_string();
        async move {
            let output = tokio::process::Command::new("curl")
                .arg("-s")
                .arg("--unix-socket")
                .arg(&sock)
                .arg("-X")
                .arg("POST")
                .arg("-d")
                .arg(&content)
                .arg(format!("http://localhost/append/{topic}"))
                .output()
                .await
                .expect("curl append failed");
            assert!(
                output.status.success(),
                "append {topic} should succeed: {}",
                String::from_utf8_lossy(&output.stderr)
            );
        }
    };

    append("header", "<h1>Header</h1>\n").await;
    append("layout", "LAYOUT[{% block body %}{% endblock %}]LAYOUT").await;
    append(
        "page.include",
        r#"{% include "header" %}Hello, {{ name }}!"#,
    )
    .await;
    append(
        "page.extends",
        r#"{% extends "layout" %}{% block body %}page content{% endblock %}"#,
    )
    .await;

    tokio::time::sleep(std::time::Duration::from_millis(200)).await;

    // Test {% include %} resolves from store
    let output = server.curl("/include").await;
    let body = String::from_utf8_lossy(&output.stdout);
    assert!(
        body.contains("<h1>Header</h1>"),
        "should include header from store, got: {body}"
    );
    assert!(
        body.contains("Hello, world!"),
        "should render template content, got: {body}"
    );

    // Test {% extends %} resolves from store
    let output = server.curl("/extends").await;
    let body = String::from_utf8_lossy(&output.stdout);
    assert!(
        body.contains("LAYOUT[page content]LAYOUT"),
        "should extend layout from store, got: {body}"
    );
}

/// Tests that .mj compile --topic + .mj render works end-to-end.
#[cfg(feature = "cross-stream")]
#[tokio::test]
async fn test_mj_compile_topic_and_render() {
    let tmp = tempfile::tempdir().unwrap();
    let store_path = tmp.path().join("store");

    let server = TestServer::new_with_store(
        "127.0.0.1:0",
        r#"{|req|
            let t = .mj compile --topic page
            {name: "world"} | .mj render $t
        }"#,
        &store_path,
    )
    .await;

    let sock_path = store_path.join("sock");
    for _ in 0..20 {
        if sock_path.exists() {
            break;
        }
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
    }

    // Append template to store
    let output = tokio::process::Command::new("curl")
        .arg("-s")
        .arg("--unix-socket")
        .arg(&sock_path)
        .arg("-X")
        .arg("POST")
        .arg("-d")
        .arg("Hello, {{ name }}!")
        .arg("http://localhost/append/page")
        .output()
        .await
        .expect("curl append failed");
    assert!(output.status.success());

    tokio::time::sleep(std::time::Duration::from_millis(200)).await;

    let output = server.curl("/").await;
    let body = String::from_utf8_lossy(&output.stdout);
    assert_eq!(body.trim(), "Hello, world!");
}

/// Tests that .mj --topic with a missing topic returns an error, not a crash.
#[cfg(feature = "cross-stream")]
#[tokio::test]
async fn test_mj_topic_missing_returns_error() {
    let tmp = tempfile::tempdir().unwrap();
    let store_path = tmp.path().join("store");

    let server = TestServer::new_with_store(
        "127.0.0.1:0",
        r#"{|req|
            {} | .mj --topic nonexistent
        }"#,
        &store_path,
    )
    .await;

    // Wait for store API socket
    let sock_path = store_path.join("sock");
    for _ in 0..20 {
        if sock_path.exists() {
            break;
        }
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
    }

    let output = server.curl("/").await;
    let body = String::from_utf8_lossy(&output.stdout);
    // Server should return 500 with error, not crash
    assert!(
        body.contains("Topic not found") || body.contains("error"),
        "should report topic not found, got: {body}"
    );
}

/// When the initial script fails (e.g. .mj compile with a missing file) in watch mode,
/// the server should still respond to Ctrl+C (SIGINT) and exit.
#[tokio::test]
async fn test_watch_script_error_ctrl_c_exits() {
    let tmp = tempfile::tempdir().unwrap();
    let script_path = tmp.path().join("handler.nu");

    // Script that fails: .mj compile references a nonexistent file
    std::fs::write(
        &script_path,
        r#"let page = .mj compile "nonexistent/template.html"
{|req| "hello"}"#,
    )
    .unwrap();

    let mut child = tokio::process::Command::new(assert_cmd::cargo::cargo_bin!("http-nu"))
        .arg("--log-format")
        .arg("jsonl")
        .arg("127.0.0.1:0")
        .arg(&script_path)
        .arg("-w")
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .expect("Failed to start http-nu server");

    let stdout = child.stdout.take().unwrap();
    let stderr = child.stderr.take().unwrap();

    // Wait for the error to appear on stdout (jsonl log format)
    let (err_tx, err_rx) = tokio::sync::oneshot::channel();
    let mut err_tx = Some(err_tx);
    tokio::spawn(async move {
        let mut reader = BufReader::new(stdout).lines();
        while let Ok(Some(line)) = reader.next_line().await {
            eprintln!("[HTTP-NU STDOUT] {line}");
            if err_tx.is_some() && line.contains("Failed to read template file") {
                if let Some(tx) = err_tx.take() {
                    let _ = tx.send(());
                }
            }
        }
    });

    tokio::spawn(async move {
        let mut reader = BufReader::new(stderr).lines();
        while let Ok(Some(line)) = reader.next_line().await {
            eprintln!("[HTTP-NU STDERR] {line}");
        }
    });

    // Wait for the error message (the script should fail quickly)
    timeout(std::time::Duration::from_secs(5), err_rx)
        .await
        .expect("Timed out waiting for script error")
        .expect("Channel closed");

    // Send SIGINT
    #[cfg(unix)]
    {
        use nix::sys::signal::{kill, Signal};
        use nix::unistd::Pid;
        let pid = Pid::from_raw(child.id().expect("child id") as i32);
        kill(pid, Signal::SIGINT).expect("failed to send SIGINT");
    }
    #[cfg(not(unix))]
    {
        let _ = child.start_kill();
    }

    // The server should exit within a reasonable time
    let status = timeout(std::time::Duration::from_secs(3), child.wait())
        .await
        .expect(
            "server did not exit after SIGINT - Ctrl+C is broken when script fails in watch mode",
        )
        .expect("failed waiting for child");

    // We don't care about the exact exit code, just that it exited
    eprintln!("Server exited with status: {status}");
}