esi 0.7.0

A streaming parser and executor for Edge Side Includes
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
use esi::{Configuration, Processor};
use fastly::{Error, Request};
use log::debug;
use std::sync::Once;

static INIT: Once = Once::new();

pub fn init_logs() {
    INIT.call_once(|| {
        // Read RUST_LOG if set; otherwise default to quiet globally, debug for *this* crate.
        let default = format!("warn,{}=debug", env!("CARGO_CRATE_NAME"));
        env_logger::Builder::from_env(env_logger::Env::default().filter_or("RUST_LOG", &default))
            .is_test(true) // shows logs without --nocapture
            .init();

        log::debug!("debug is enabled)");
    });
}

// Helper function to create a processor and process an ESI document
fn process_esi_document(input: &str, req: Request) -> Result<String, Error> {
    debug!("Processing ESI document: {input:?}");

    // Create a BufRead from the input string
    let reader = std::io::BufReader::new(std::io::Cursor::new(input.as_bytes()));

    // Create a writer with a Vec buffer to capture the output
    let mut output = Vec::new();

    // Create the processor and process the document
    let mut processor = Processor::new(Some(req), Configuration::default());
    processor.process_stream(reader, &mut output, None, None)?;

    // Convert the output to a string
    let result = String::from_utf8(output)
        .map_err(|e| Error::msg(format!("Invalid UTF-8 in processed output: {e}")))?;

    debug!("Processed result: {result:?}");
    Ok(result)
}

#[test]
fn test_response_overrides_applied() {
    init_logs();

    // Test $set_response_code
    let body_override = r#"<esi:vars>$set_response_code(404, 'oops')</esi:vars>"#;
    let reader = std::io::BufReader::new(std::io::Cursor::new(body_override.as_bytes()));
    let mut output = Vec::new();
    let mut processor = Processor::new(
        Some(Request::get("http://example.com")),
        Configuration::default(),
    );

    processor
        .process_stream(reader, &mut output, None, None)
        .expect("Processing should succeed");

    // Check the response status was set
    assert_eq!(processor.context().response_status(), Some(404));
    // Check the body override was set
    assert_eq!(
        processor
            .context()
            .response_body_override()
            .map(|b| String::from_utf8_lossy(b).to_string()),
        Some("oops".to_string())
    );

    // Test $set_redirect
    let redirect_doc = r#"<esi:vars>$set_redirect('http://example.com/next')</esi:vars>"#;
    let redirect_reader = std::io::BufReader::new(std::io::Cursor::new(redirect_doc.as_bytes()));
    let mut redirect_output = Vec::new();
    let mut redirect_processor = Processor::new(
        Some(Request::get("http://example.com")),
        Configuration::default(),
    );

    redirect_processor
        .process_stream(redirect_reader, &mut redirect_output, None, None)
        .expect("Processing should succeed");

    // Check redirect status was set
    assert_eq!(redirect_processor.context().response_status(), Some(302));
    // Check Location header was set
    let headers = redirect_processor.context().response_headers();
    let location = headers.iter().find(|(name, _)| name == "Location");
    assert_eq!(
        location.map(|(_, v)| v.as_str()),
        Some("http://example.com/next")
    );
    // Check body override was cleared (redirect should not have body)
    assert!(redirect_processor
        .context()
        .response_body_override()
        .is_none());
}

// Bareword in subfield position with QUERY_STRING
#[test]
fn test_bareword_subfield_query_string() {
    // init logs
    init_logs();
    let input = r#"
        <esi:vars>
            $(QUERY_STRING{param})
        </esi:vars>
    "#;
    let req = Request::get("http://example.com?param=value");
    let result = process_esi_document(input, req).expect("Processing should succeed");
    assert_eq!(
        result.trim(),
        "value",
        "Bareword subfield should resolve to 'value'"
    );
}

// Bareword in function argument: interpolation errors are intentionally swallowed
#[test]
fn test_bareword_function_argument_is_swallowed() {
    let input = r#"
        <esi:vars>
            $lower(bareword)
        </esi:vars>
    "#;

    let req = Request::get("http://example.com");
    let result = process_esi_document(input, req)
        .expect("ESI processing should succeed; interpolation errors are intentionally swallowed");

    // After swallowing the parse error, nothing should be emitted by <esi:vars>.
    assert!(
        result.trim().is_empty(),
        "Expected empty output when a bareword is used as a function argument during interpolation, got: {:?}",
        result
    );
}

// Mixed subfield types (bareword and expression) with QUERY_STRING
#[test]
fn test_mixed_subfield_types() {
    init_logs();
    let input = r#"
        <esi:assign name="keyVar" value="'param'" />
        <esi:vars>
            $(QUERY_STRING{param})
            $(QUERY_STRING{$(keyVar)})
        </esi:vars>
    "#;
    let req = Request::get("http://example.com?param=value");
    let result = process_esi_document(input, req).expect("Processing should succeed");
    assert_eq!(
        result.trim(),
        "value\n            value",
        "Bareword and expression subfields should both resolve to 'value'"
    );
}

// Compatibility with ESI choose/when
#[test]
fn test_esi_choose_compatibility_equal() {
    let input = r#"
        <esi:choose>
            <esi:when test="$(QUERY_STRING{param}) == 'value'">
                Match
            </esi:when>
            <esi:otherwise>
                Fallback
            </esi:otherwise>
        </esi:choose>
    "#;
    let req = Request::get("http://example.com?param=value");
    let result = process_esi_document(input, req).expect("Processing should succeed");
    assert_eq!(
        result.trim(),
        "Match",
        "ESI choose/when should work with bareword subfield"
    );
}

// Compatibility with ESI choose/when with not equal
#[test]
fn test_esi_choose_compatibility_not_equal() {
    let input = r#"
        <esi:choose>
            <esi:when test="$(QUERY_STRING{param}) != 'wrongvalue'">
                Match
            </esi:when>
            <esi:otherwise>
                Fallback
            </esi:otherwise>
        </esi:choose>
    "#;
    let req = Request::get("http://example.com?param=value");
    let result = process_esi_document(input, req).expect("Processing should succeed");
    assert_eq!(
        result.trim(),
        "Match",
        "ESI choose/when should work with bareword subfield"
    );
}
// Test for nested variable expansion - INVALID ESI SYNTAX
// The construct $($(outer){param}) is NOT valid Akamai ESI syntax.
// Akamai's ESI does not support nested variable expansion like this.
#[test]
fn test_nested_subfields_is_invalid() {
    let input = r#"
        <esi:assign name="outer" value="'QUERY_STRING'" />
        <esi:vars>
            $($(outer){param})
        </esi:vars>
    "#;
    let req = Request::get("http://example.com?param=value");
    let result = process_esi_document(input, req);
    assert!(
        result.is_err(),
        "Nested variable expansion $($(var){{key}}) is not valid ESI syntax and should fail"
    );
}

#[test]
fn process_include_with_query_string_interpolation() -> Result<(), Error> {
    use esi::{Configuration, Processor};
    use fastly::{Request, Response};
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::Arc;

    // Create the ESI document with the include tag
    let esi_document = r#"<esi:include 
      src="/v1/product?apiKey=$(QUERY_STRING{apiKey})" />"#;

    // Create a request with the apiKey query parameter
    let req = Some(Request::get("http://example.com?apiKey=value"));

    // Create a response with the ESI document
    let mut resp = Response::from_body(esi_document);

    // Create a processor with default config
    let processor = Processor::new(req, Configuration::default());

    // Track if the fragment request was made with the correct URL
    let correct_fragment_request_made = Arc::new(AtomicBool::new(false));
    let correct_fragment_request_made_clone = Arc::clone(&correct_fragment_request_made);

    // Process the response
    processor
        .process_response(
            &mut resp,
            None,
            Some(&move |fragment_req: Request, _maxwait: Option<u32>| {
                // Check that the fragment request URL contains the interpolated apiKey
                let url = fragment_req.get_url();
                let url_str = url.to_string();
                let contains_api_key = url_str.contains("apiKey=value");

                // Store the result in our atomic boolean
                correct_fragment_request_made_clone.store(contains_api_key, Ordering::SeqCst);

                // Return a mock response for the fragment request
                Ok(esi::PendingFragmentContent::CompletedRequest(Box::new(
                    Response::from_body("fragment content"),
                )))
            }),
            None,
        )
        .unwrap();

    assert!(
        correct_fragment_request_made.load(Ordering::SeqCst),
        "Fragment request should contain the interpolated apiKey value"
    );
    Ok(())
}

#[test]
fn test_simple_negation() {
    let input = r#"
        <esi:choose>
            <esi:when test="!$(QUERY_STRING{empty})">
                Empty parameter was negated
            </esi:when>
            <esi:otherwise>
                Fallback
            </esi:otherwise>
        </esi:choose>
    "#;
    let req = Request::get("http://example.com?nonempty=value");
    let result = process_esi_document(input, req).expect("Processing should succeed");
    assert_eq!(
        result.trim(),
        "Empty parameter was negated",
        "Negation of null/empty value should evaluate to true"
    );
}

#[test]
fn test_negation_with_value() {
    let input = r#"
        <esi:choose>
            <esi:when test="!$(QUERY_STRING{param})">
                Parameter was negated
            </esi:when>
            <esi:otherwise>
                Parameter exists
            </esi:otherwise>
        </esi:choose>
    "#;
    let req = Request::get("http://example.com?param=value");
    let result = process_esi_document(input, req).expect("Processing should succeed");
    assert_eq!(
        result.trim(),
        "Parameter exists",
        "Negation of non-empty value should evaluate to false"
    );
}

#[test]
fn test_negation_of_comparison() {
    let input = r#"
        <esi:choose>
            <esi:when test="!($(QUERY_STRING{param}) == 'wrong')">
                Comparison was negated
            </esi:when>
            <esi:otherwise>
                Fallback
            </esi:otherwise>
        </esi:choose>
    "#;
    let req = Request::get("http://example.com?param=value");
    let result = process_esi_document(input, req).expect("Processing should succeed");
    assert_eq!(
        result.trim(),
        "Comparison was negated",
        "Negation of false comparison should evaluate to true"
    );
}

#[test]
fn test_double_negation() {
    let input = r#"
        <esi:choose>
            <esi:when test="!!$(QUERY_STRING{param})">
                Double negation works
            </esi:when>
            <esi:otherwise>
                Fallback
            </esi:otherwise>
        </esi:choose>
    "#;
    let req = Request::get("http://example.com?param=value");
    let result = process_esi_document(input, req).expect("Processing should succeed");
    assert_eq!(
        result.trim(),
        "Double negation works",
        "Double negation should restore original boolean value"
    );
}

#[test]
fn test_negation_with_not_equals() {
    let input = r#"
        <esi:choose>
            <esi:when test="!($(QUERY_STRING{param}) != 'value')">
                Negation of not-equals works
            </esi:when>
            <esi:otherwise>
                Fallback
            </esi:otherwise>
        </esi:choose>
    "#;
    let req = Request::get("http://example.com?param=value");
    let result = process_esi_document(input, req).expect("Processing should succeed");
    assert_eq!(
        result.trim(),
        "Negation of not-equals works",
        "Negation of not-equals should work correctly"
    );
}

#[test]
fn test_negation_in_vars() {
    let input = r#"
        <esi:vars>
            <esi:assign name="result" value="!$(QUERY_STRING{empty})" />
            $(result)
        </esi:vars>
    "#;
    let req = Request::get("http://example.com?nonempty=value");
    let result = process_esi_document(input, req).expect("Processing should succeed");
    assert_eq!(
        result.trim(),
        "true",
        "Negation in variable assignment should work"
    );
}

#[test]
fn test_exists_in_when() {
    let input = r#"
        <esi:assign name="foo" value="'bar'" />
        <esi:choose>
            <esi:when test="$exists($(foo))">
                present
            </esi:when>
            <esi:when test="$is_empty($(foo))">
                empty
            </esi:when>
            <esi:otherwise>
                missing
            </esi:otherwise>
        </esi:choose>
    "#;

    let req = Request::get("http://example.com");
    let result = process_esi_document(input, req).expect("Processing should succeed");
    assert_eq!(result.trim(), "present");
}

#[test]
fn test_is_empty_in_when() {
    let input = r#"
        <esi:assign name="foo" value="" />
        <esi:choose>
            <esi:when test="$exists($(foo))">
                present
            </esi:when>
            <esi:when test="$is_empty($(foo))">
                empty
            </esi:when>
            <esi:otherwise>
                missing
            </esi:otherwise>
        </esi:choose>
    "#;

    let req = Request::get("http://example.com");
    let result = process_esi_document(input, req).expect("Processing should succeed");
    assert_eq!(result.trim(), "empty");
}

#[test]
fn test_choose_with_esi_tags_in_otherwise() {
    init_logs();
    let input = r#"
        <esi:choose>
            <esi:when test="$(QUERY_STRING{group}) == 'member'">
                Member content
            </esi:when>
            <esi:otherwise>
                <esi:assign name="redirect" value="'welcome.html'" />
                Redirecting to $(redirect)
            </esi:otherwise>
        </esi:choose>
    "#;
    let req = Request::get("http://example.com?group=guest");
    let result = process_esi_document(input, req).expect("Processing should succeed");
    assert!(
        result.contains("Redirecting to welcome.html"),
        "Otherwise should support ESI tags like assign. Got: {}",
        result
    );
}

// Test that configuration.is_escaped_content controls HTML entity decoding
#[test]
fn test_configuration_is_escaped_content() {
    init_logs();

    // Test with HTML-escaped URL (default behavior)
    let input = r#"<esi:include src="http://example.com/path?param=value&amp;other=test"/>"#;

    let reader = std::io::BufReader::new(std::io::Cursor::new(input.as_bytes()));
    let mut output = Vec::new();

    // Custom dispatcher that captures the URL
    use std::cell::RefCell;
    use std::rc::Rc;
    let captured_url = Rc::new(RefCell::new(String::new()));
    let captured_url_clone = captured_url.clone();
    let dispatcher =
        move |req: Request, _maxwait: Option<u32>| -> esi::Result<esi::PendingFragmentContent> {
            *captured_url_clone.borrow_mut() = req.get_url_str().to_string();
            Ok(esi::PendingFragmentContent::CompletedRequest(Box::new(
                fastly::Response::from_body("fragment content"),
            )))
        };

    let mut processor = Processor::new(
        Some(Request::get("http://example.com/")),
        Configuration::default(), // is_escaped_content = true by default
    );

    processor
        .process_stream(reader, &mut output, Some(&dispatcher), None)
        .expect("Processing should succeed");

    // With is_escaped_content=true, &amp; should be decoded to &
    let url = captured_url.borrow();
    assert!(
        url.contains("param=value&other=test"),
        "URL should have &amp; decoded to &. Got: {}",
        url
    );
}

#[test]
fn test_configuration_is_escaped_content_disabled() {
    init_logs();

    // Test with HTML-escaped URL but with is_escaped_content = false
    let input = r#"<esi:include src="http://example.com/path?param=value&amp;other=test"/>"#;

    let reader = std::io::BufReader::new(std::io::Cursor::new(input.as_bytes()));
    let mut output = Vec::new();

    // Custom dispatcher that captures the URL
    use std::cell::RefCell;
    use std::rc::Rc;
    let captured_url = Rc::new(RefCell::new(String::new()));
    let captured_url_clone = captured_url.clone();
    let dispatcher =
        move |req: Request, _maxwait: Option<u32>| -> esi::Result<esi::PendingFragmentContent> {
            *captured_url_clone.borrow_mut() = req.get_url_str().to_string();
            Ok(esi::PendingFragmentContent::CompletedRequest(Box::new(
                fastly::Response::from_body("fragment content"),
            )))
        };

    let mut processor = Processor::new(
        Some(Request::get("http://example.com/")),
        Configuration::default().with_escaped(false), // Disable HTML entity decoding
    );

    processor
        .process_stream(reader, &mut output, Some(&dispatcher), None)
        .expect("Processing should succeed");

    // With is_escaped_content=false, &amp; should NOT be decoded
    let url = captured_url.borrow();
    assert!(
        url.contains("&amp;"),
        "URL should keep &amp; as-is. Got: {}",
        url
    );
}

// Test that process_fragment_response callback is invoked
#[test]
fn test_process_fragment_response_callback() {
    init_logs();

    let input = r#"<esi:include src="http://example.com/fragment"/>"#;

    let reader = std::io::BufReader::new(std::io::Cursor::new(input.as_bytes()));
    let mut output = Vec::new();

    // Dispatcher returns a response
    let dispatcher =
        |_req: Request, _maxwait: Option<u32>| -> esi::Result<esi::PendingFragmentContent> {
            let mut resp = fastly::Response::from_body("original content");
            resp.set_header("X-Custom-Header", "original-value");
            Ok(esi::PendingFragmentContent::CompletedRequest(Box::new(
                resp,
            )))
        };

    // Response processor that modifies the response
    use std::cell::RefCell;
    use std::rc::Rc;
    let callback_invoked = Rc::new(RefCell::new(false));
    let callback_invoked_clone = callback_invoked.clone();
    let processor_callback =
        move |_req: &mut Request, mut resp: fastly::Response| -> esi::Result<fastly::Response> {
            *callback_invoked_clone.borrow_mut() = true;
            // Modify the response body
            resp.set_body("modified content");
            // Add a header to prove we processed it
            resp.set_header("X-Processed", "true");
            Ok(resp)
        };

    let mut processor = Processor::new(
        Some(Request::get("http://example.com/")),
        Configuration::default(),
    );

    processor
        .process_stream(
            reader,
            &mut output,
            Some(&dispatcher),
            Some(&processor_callback),
        )
        .expect("Processing should succeed");

    let result = String::from_utf8(output).unwrap();

    // Should contain the modified content
    assert!(
        result.contains("modified content"),
        "Output should contain modified content from processor callback. Got: {}",
        result
    );
    assert!(
        !result.contains("original content"),
        "Output should NOT contain original content. Got: {}",
        result
    );
    assert!(
        *callback_invoked.borrow(),
        "Response processor callback should have been invoked"
    );
}

// Test that process_fragment_response is also called for alt URLs
#[test]
fn test_process_fragment_response_on_alt() {
    init_logs();

    let input = r#"<esi:include src="http://example.com/main" alt="http://example.com/fallback" onerror="continue"/>"#;

    let reader = std::io::BufReader::new(std::io::Cursor::new(input.as_bytes()));
    let mut output = Vec::new();

    // Dispatcher that fails for main, succeeds for alt
    let dispatcher =
        |req: Request, _maxwait: Option<u32>| -> esi::Result<esi::PendingFragmentContent> {
            if req.get_url_str().contains("/main") {
                // Main request fails
                Err(esi::ESIError::FragmentRequestError("main failed".into()))
            } else {
                // Alt request succeeds
                Ok(esi::PendingFragmentContent::CompletedRequest(Box::new(
                    fastly::Response::from_body("alt content"),
                )))
            }
        };

    // Response processor that should be called for the alt response
    use std::cell::RefCell;
    use std::rc::Rc;
    let alt_processed = Rc::new(RefCell::new(false));
    let alt_processed_clone = alt_processed.clone();
    let processor_callback =
        move |req: &mut Request, mut resp: fastly::Response| -> esi::Result<fastly::Response> {
            if req.get_url_str().contains("/fallback") {
                *alt_processed_clone.borrow_mut() = true;
                resp.set_body("processed alt content");
            }
            Ok(resp)
        };

    let mut processor = Processor::new(
        Some(Request::get("http://example.com/")),
        Configuration::default(),
    );

    processor
        .process_stream(
            reader,
            &mut output,
            Some(&dispatcher),
            Some(&processor_callback),
        )
        .expect("Processing should succeed");

    let result = String::from_utf8(output).unwrap();

    assert!(
        result.contains("processed alt content"),
        "Output should contain processed alt content. Got: {}",
        result
    );
    assert!(
        *alt_processed.borrow(),
        "Response processor should have been invoked for alt URL"
    );
}

// Test that process_fragment_response can return errors
#[test]
fn test_process_fragment_response_error_handling() {
    init_logs();

    let input = r#"<esi:include src="http://example.com/fragment"/>"#;

    let reader = std::io::BufReader::new(std::io::Cursor::new(input.as_bytes()));
    let mut output = Vec::new();

    // Dispatcher returns a response
    let dispatcher =
        |_req: Request, _maxwait: Option<u32>| -> esi::Result<esi::PendingFragmentContent> {
            Ok(esi::PendingFragmentContent::CompletedRequest(Box::new(
                fastly::Response::from_body("content"),
            )))
        };

    // Response processor that returns an error
    let processor_callback =
        |_req: &mut Request, _resp: fastly::Response| -> esi::Result<fastly::Response> {
            Err(esi::ESIError::FragmentRequestError(
                "processing failed".into(),
            ))
        };

    let mut processor = Processor::new(
        Some(Request::get("http://example.com/")),
        Configuration::default(),
    );

    let result = processor.process_stream(
        reader,
        &mut output,
        Some(&dispatcher),
        Some(&processor_callback),
    );

    // Should propagate the error from the processor
    assert!(
        result.is_err(),
        "Should return error from processor callback"
    );
    assert!(
        result
            .unwrap_err()
            .to_string()
            .contains("processing failed"),
        "Error should be from the processor callback"
    );
}

// Test that alt URLs support interpolation (variables from request)
#[test]
fn test_alt_url_with_interpolation() {
    init_logs();

    // Test with interpolated variable in alt URL using QUERY_STRING
    let input = r#"
        <esi:include src="http://example.com/main" alt="http://example.com/fallback?id=$(QUERY_STRING{fallback_id})" onerror="continue"/>
    "#;

    let reader = std::io::BufReader::new(std::io::Cursor::new(input.as_bytes()));
    let mut output = Vec::new();

    // Dispatcher that fails for main, succeeds for alt
    use std::cell::RefCell;
    use std::rc::Rc;
    let captured_alt_url = Rc::new(RefCell::new(String::new()));
    let captured_alt_url_clone = captured_alt_url.clone();
    let dispatcher =
        move |req: Request, _maxwait: Option<u32>| -> esi::Result<esi::PendingFragmentContent> {
            if req.get_url_str().contains("/main") {
                // Main request fails
                Err(esi::ESIError::FragmentRequestError("main failed".into()))
            } else {
                // Alt request succeeds - capture the URL
                *captured_alt_url_clone.borrow_mut() = req.get_url_str().to_string();
                Ok(esi::PendingFragmentContent::CompletedRequest(Box::new(
                    fastly::Response::from_body("alt content"),
                )))
            }
        };

    let mut processor = Processor::new(
        Some(Request::get("http://example.com/?fallback_id=12345")),
        Configuration::default(),
    );

    processor
        .process_stream(reader, &mut output, Some(&dispatcher), None)
        .expect("Processing should succeed");

    let result = String::from_utf8(output).unwrap();

    // Verify the alt URL was interpolated correctly
    let alt_url = captured_alt_url.borrow();
    assert!(
        alt_url.contains("id=12345"),
        "Alt URL should have interpolated variable. Got: {}",
        alt_url
    );

    // Verify content from alt was used
    assert!(
        result.contains("alt content"),
        "Output should contain alt content. Got: {}",
        result
    );
}

// Test that alt URLs support function calls in interpolation
#[test]
fn test_alt_url_with_function_interpolation() {
    init_logs();

    // Test with function call in alt URL (similar to spec example) using HTTP_HOST
    let input = r#"
        <esi:include src="http://example.com/main" alt="http://example.com/fallback?host=$lower($(HTTP_HOST))" onerror="continue"/>
    "#;

    let reader = std::io::BufReader::new(std::io::Cursor::new(input.as_bytes()));
    let mut output = Vec::new();

    // Dispatcher that fails for main, succeeds for alt
    use std::cell::RefCell;
    use std::rc::Rc;
    let captured_alt_url = Rc::new(RefCell::new(String::new()));
    let captured_alt_url_clone = captured_alt_url.clone();
    let dispatcher =
        move |req: Request, _maxwait: Option<u32>| -> esi::Result<esi::PendingFragmentContent> {
            if req.get_url_str().contains("/main") {
                // Main request fails
                Err(esi::ESIError::FragmentRequestError("main failed".into()))
            } else {
                // Alt request succeeds - capture the URL
                *captured_alt_url_clone.borrow_mut() = req.get_url_str().to_string();
                Ok(esi::PendingFragmentContent::CompletedRequest(Box::new(
                    fastly::Response::from_body("alt with function"),
                )))
            }
        };

    let mut req = Request::get("http://Example.COM/");
    req.set_header("Host", "Example.COM");

    let mut processor = Processor::new(Some(req), Configuration::default());

    processor
        .process_stream(reader, &mut output, Some(&dispatcher), None)
        .expect("Processing should succeed");

    let result = String::from_utf8(output).unwrap();

    // Verify the alt URL was interpolated with function call (lower case)
    let alt_url = captured_alt_url.borrow();
    assert!(
        alt_url.contains("host=example.com"),
        "Alt URL should have interpolated and lowercased HTTP_HOST. Got: {}",
        alt_url
    );

    // Verify content from alt was used
    assert!(
        result.contains("alt with function"),
        "Output should contain alt content. Got: {}",
        result
    );
}

// Test interpolated compound expressions in long form assign
#[test]
fn test_assign_long_form_interpolation() {
    init_logs();
    let input = r#"
        <esi:assign name="greeting">Hello $(HTTP_HOST)!</esi:assign>
        <esi:vars>$(greeting)</esi:vars>
    "#;
    let mut req = Request::get("http://example.com/test");
    req.set_header("Host", "example.com");
    let result = process_esi_document(input, req).expect("Processing should succeed");
    assert_eq!(
        result.trim(),
        "Hello example.com!",
        "Long form assign with interpolation should concatenate text and variables"
    );
}

// Test multiple variables in long form assign
#[test]
fn test_assign_long_form_multiple_variables() {
    init_logs();
    let input = r#"
        <esi:assign name="first" value="'John'" />
        <esi:assign name="last" value="'Doe'" />
        <esi:assign name="full_name">$(first) $(last)</esi:assign>
        <esi:vars>$(full_name)</esi:vars>
    "#;
    let req = Request::get("http://example.com/test");
    let result = process_esi_document(input, req).expect("Processing should succeed");
    assert_eq!(
        result.trim(),
        "John Doe",
        "Long form assign should handle multiple variables in compound expression"
    );
}

// Test streaming input parsing with realistic document
// Verifies that chunked reading works correctly
#[test]
fn test_streaming_input_with_small_chunks() {
    init_logs();

    // Create a document that demonstrates streaming works
    let input = r#"<html><body><esi:assign name="v" value="'test'" /><esi:vars>$(v)</esi:vars></body></html>"#;

    let req = Request::get("http://example.com/test");
    let result = process_esi_document(input, req).expect("Processing should succeed");

    // Verify the output contains expected content
    assert!(
        result.contains("test"),
        "Should contain assigned variable value"
    );
}
// Test foreach with a list variable
#[test]
fn test_foreach_with_list() {
    init_logs();
    let input = r#"
        <esi:assign name="nums" value="$string_split('1,2,3', ',')" />
        <esi:foreach collection="$(nums)" item="n">[$(n)]</esi:foreach>
    "#;
    let req = Request::get("http://example.com/test");
    let result = process_esi_document(input, req).expect("Processing should succeed");
    assert!(
        result.contains("[1][2][3]"),
        "Should iterate through list items"
    );
}

// Test foreach with default item variable name
#[test]
fn test_foreach_default_item_name() {
    init_logs();
    let input = r#"
        <esi:assign name="items" value="$string_split('a,b', ',')" />
        <esi:foreach collection="$(items)">$(item)</esi:foreach>
    "#;
    let req = Request::get("http://example.com/test");
    let result = process_esi_document(input, req).expect("Processing should succeed");
    assert!(result.contains("ab"), "Should use default 'item' variable");
}

// Test foreach with break
#[test]
fn test_foreach_with_break() {
    init_logs();
    let input = r#"
        <esi:assign name="nums" value="$string_split('1,2,3,4,5', ',')" />
        <esi:foreach collection="$(nums)" item="n"><esi:choose>
            <esi:when test="$(n) == '3'"><esi:break /></esi:when>
            <esi:otherwise>[$(n)]</esi:otherwise>
        </esi:choose></esi:foreach>
    "#;
    let req = Request::get("http://example.com/test");
    let result = process_esi_document(input, req).expect("Processing should succeed");
    let trimmed = result.trim();
    assert!(trimmed.contains("[1]"), "Should have first item");
    assert!(trimmed.contains("[2]"), "Should have second item");
    assert!(!trimmed.contains("[3]"), "Should break before third item");
    assert!(!trimmed.contains("[4]"), "Should not have fourth item");
}

// Test foreach with dictionary
#[test]
fn test_foreach_with_dict() {
    init_logs();
    let input = r#"
        <esi:assign name="dict" value="$(QUERY_STRING)" />
        <esi:foreach collection="$(dict)" item="val">x</esi:foreach>
    "#;
    let req = Request::get("http://example.com/test?a=1&b=2");
    let result = process_esi_document(input, req).expect("Processing should succeed");
    assert!(result.contains("xx"), "Should iterate through dict values");
}

// Test foreach with dictionary literal
#[test]
fn test_foreach_dict_literal() {
    init_logs();
    let input = r#"A list of Fruits: <esi:foreach collection="{1:'apples',2:'oranges',3:'bananas',4:'grapefruits'}" item="item">$(item) -- $(item{0}) = $(item{1})<br>
</esi:foreach>"#;
    let req = Request::get("http://example.com/test");
    let result = process_esi_document(input, req).expect("Processing should succeed");

    // Should contain all fruit entries
    assert!(result.contains("apples"), "Should have apples");
    assert!(result.contains("oranges"), "Should have oranges");
    assert!(result.contains("bananas"), "Should have bananas");
    assert!(result.contains("grapefruits"), "Should have grapefruits");

    // Should have key-value access
    assert!(result.contains(" -- "), "Should have separator");
    assert!(result.contains(" = "), "Should have equals");

    // Verify specific key-value pairs
    assert!(result.contains("1 = apples"), "Should have key 1 = apples");
    assert!(
        result.contains("2 = oranges"),
        "Should have key 2 = oranges"
    );
    assert!(
        result.contains("3 = bananas"),
        "Should have key 3 = bananas"
    );
    assert!(
        result.contains("4 = grapefruits"),
        "Should have key 4 = grapefruits"
    );
}

// Test foreach with range operator
#[test]
fn test_foreach_with_range() {
    init_logs();
    let input = r#"<esi:foreach collection="[1..10]" item="n">$(n) </esi:foreach>"#;
    let req = Request::get("http://example.com/test");
    let result = process_esi_document(input, req).expect("Processing should succeed");
    assert_eq!(
        result, "1 2 3 4 5 6 7 8 9 10 ",
        "Should iterate from 1 to 10"
    );
}

// Test foreach with descending range
#[test]
fn test_foreach_with_range_descending() {
    init_logs();
    let input = r#"<esi:foreach collection="[5..1]" item="n">$(n),</esi:foreach>"#;
    let req = Request::get("http://example.com/test");
    let result = process_esi_document(input, req).expect("Processing should succeed");
    assert_eq!(result, "5,4,3,2,1,", "Should iterate from 5 down to 1");
}

// Test foreach with range and variables
#[test]
fn test_foreach_with_range_variables() {
    init_logs();
    let input = r#"
        <esi:assign name="start" value="1" />
        <esi:assign name="end" value="5" />
        <esi:foreach collection="[$(start)..$(end)]" item="i">$(i) </esi:foreach>
    "#;
    let req = Request::get("http://example.com/test");
    let result = process_esi_document(input, req).expect("Processing should succeed");
    assert!(
        result.contains("1 2 3 4 5"),
        "Should use variable-based range"
    );
}

// Test nested foreach with break - ensure break only affects inner loop
#[test]
fn test_nested_foreach_with_break() {
    init_logs();
    let input = r#"
        <esi:assign name="outer" value="['A','B','C']" />
        <esi:assign name="inner" value="['1','2','3']" />
        <esi:foreach collection="$(outer)" item="o">
Outer[$(o)]:
<esi:foreach collection="$(inner)" item="i"><esi:choose>
<esi:when test="$(i) == '2'"><esi:break /></esi:when>
<esi:otherwise>$(o)-$(i) </esi:otherwise>
</esi:choose></esi:foreach>
</esi:foreach>
    "#;
    let req = Request::get("http://example.com/test");
    let result = process_esi_document(input, req).expect("Processing should succeed");

    // Each outer iteration should show inner loop breaking after first item
    assert!(result.contains("Outer[A]:"), "Should have outer A");
    assert!(result.contains("Outer[B]:"), "Should have outer B");
    assert!(result.contains("Outer[C]:"), "Should have outer C");

    // Inner loop should process first item for each outer iteration
    assert!(result.contains("A-1"), "Should have A-1");
    assert!(result.contains("B-1"), "Should have B-1");
    assert!(result.contains("C-1"), "Should have C-1");

    // Inner loop should break before second item (when i == '2')
    assert!(!result.contains("A-2"), "Should NOT have A-2 (broke)");
    assert!(!result.contains("B-2"), "Should NOT have B-2 (broke)");
    assert!(!result.contains("C-2"), "Should NOT have C-2 (broke)");

    // Inner loop should not reach third item
    assert!(!result.contains("A-3"), "Should NOT have A-3");
    assert!(!result.contains("B-3"), "Should NOT have B-3");
    assert!(!result.contains("C-3"), "Should NOT have C-3");
}

// Test simpler dict literal with assign
#[test]
fn test_simple_dict_literal() {
    init_logs();
    let input =
        r#"<esi:assign name="test" value="{1:'a',2:'b'}" /><esi:vars>Result: $(test)</esi:vars>"#;
    let req = Request::get("http://example.com/test");
    let result = process_esi_document(input, req).expect("Processing should succeed");

    // The dict should have been assigned and displayed
    assert!(result.contains("Result:"), "Should have result label");
    assert!(
        !result.contains("$(test)"),
        "Variable should be substituted"
    );
    assert!(result.contains("1=a"), "Should have key-value pair 1=a");
    assert!(result.contains("2=b"), "Should have key-value pair 2=b");
}

// Test list literal - basic
#[test]
fn test_simple_list_literal() {
    init_logs();
    let input =
        r#"<esi:foreach item="x" collection="[1,2,3]"><esi:vars>$(x),</esi:vars></esi:foreach>"#;
    let req = Request::get("http://example.com/test");
    let result = process_esi_document(input, req).expect("Processing should succeed");

    assert!(result.contains("1"), "Should have 1");
    assert!(result.contains("2"), "Should have 2");
    assert!(result.contains("3"), "Should have 3");
}

// Test list literal with strings
#[test]
fn test_string_list_literal() {
    init_logs();
    let input = r#"<esi:foreach item="x" collection="['a','b','c']"><esi:vars>$(x),</esi:vars></esi:foreach>"#;
    let req = Request::get("http://example.com/test");
    let result = process_esi_document(input, req).expect("Processing should succeed");

    assert!(result.contains("a"), "Should have a");
    assert!(result.contains("b"), "Should have b");
    assert!(result.contains("c"), "Should have c");
}

// Test nested foreach with list literals and break
#[test]
fn test_list_literal_nested_foreach() {
    init_logs();
    let input = r#"<esi:foreach item="bar" collection="[1,2,3]">
[<esi:foreach item="foo" collection="['a','b','c']">
<esi:vars>$(foo)</esi:vars><esi:break/>
</esi:foreach>]<esi:vars>$(bar) </esi:vars>
</esi:foreach>"#;
    let req = Request::get("http://example.com/test");
    let result = process_esi_document(input, req).expect("Processing should succeed");

    // Remove whitespace for easier testing
    let clean = result.replace(char::is_whitespace, "");

    // Should show [a]1, [a]2, [a]3 (break after first 'a' in each inner loop)
    assert!(clean.contains("[a]1"), "Should have [a]1");
    assert!(clean.contains("[a]2"), "Should have [a]2");
    assert!(clean.contains("[a]3"), "Should have [a]3");

    // Should NOT have b or c due to break
    assert!(
        !result.contains("b"),
        "Should not have 'b' - break should prevent it"
    );
    assert!(
        !result.contains("c"),
        "Should not have 'c' - break should prevent it"
    );
}

// Test list subscript assignment - from ESI spec
#[test]
fn test_list_subscript_assignment() {
    init_logs();
    let input = r#"<esi:assign name="colors" value="[ 'red', 'blue', 'green' ]"/>
<esi:assign name="colors{0}" value="purple"/>
<esi:vars>$(colors)</esi:vars>"#;
    let req = Request::get("http://example.com/test");
    let result = process_esi_document(input, req).expect("Processing should succeed");

    // Should output the list with first element replaced
    assert!(result.contains("purple"), "Should have purple");
    assert!(result.contains("blue"), "Should have blue");
    assert!(result.contains("green"), "Should have green");
    assert!(
        !result.contains("red"),
        "Should not have red - it was replaced"
    );
}

// Test dictionary subscript assignment - from ESI spec
#[test]
fn test_dict_subscript_assignment() {
    init_logs();
    let input = r#"<esi:assign name="ages" value="{ 'bob' : 34, 'joan' : 27, 'ed' : 23 }"/>
<esi:assign name="ages{joan}" value="28"/>
<esi:vars>$(ages)</esi:vars>"#;
    let req = Request::get("http://example.com/test");
    let result = process_esi_document(input, req).expect("Processing should succeed");

    // Should have joan's age updated to 28
    assert!(result.contains("joan"), "Should have joan key");
    assert!(result.contains("28"), "Should have updated value 28");
    assert!(!result.contains("27"), "Should not have old value 27");
    assert!(result.contains("bob"), "Should have bob key");
    assert!(result.contains("34"), "Should have bob's value");
    assert!(result.contains("ed"), "Should have ed key");
    assert!(result.contains("23"), "Should have ed's value");
}

// Test dictionary subscript assignment with expression - from ESI spec
#[test]
fn test_dict_subscript_assignment_with_expression() {
    init_logs();
    let input = r#"<esi:assign name="ages" value="{ 'bob' : 34, 'joan' : 27, 'ed' : 23 }"/>
<esi:assign name="ages{joan}" value="$(ages{joan}) + 1"/>
<esi:vars>$(ages)</esi:vars>"#;
    let req = Request::get("http://example.com/test");
    let result = process_esi_document(input, req).expect("Processing should succeed");

    // Should have joan's age incremented to 28
    assert!(result.contains("28"), "Should have incremented value 28");
    assert!(!result.contains("27"), "Should not have old value 27");
}

// Test nested foreach loops
#[test]
fn test_foreach_nested() {
    init_logs();
    let input = r#"
        <esi:assign name="outer" value="$string_split('A,B,C', ',')" />
        <esi:assign name="inner" value="$string_split('1,2,3', ',')" />
        <esi:foreach collection="$(outer)" item="letter">
            <esi:foreach collection="$(inner)" item="number">$(letter)$(number) </esi:foreach>
        </esi:foreach>
    "#;
    let req = Request::get("http://example.com/test");
    let result = process_esi_document(input, req).expect("Processing should succeed");

    // Each outer iteration should produce 3 inner iterations
    assert!(result.contains("A1"), "Should have A1");
    assert!(result.contains("A2"), "Should have A2");
    assert!(result.contains("A3"), "Should have A3");
    assert!(result.contains("B1"), "Should have B1");
    assert!(result.contains("B2"), "Should have B2");
    assert!(result.contains("B3"), "Should have B3");
    assert!(result.contains("C1"), "Should have C1");
    assert!(result.contains("C2"), "Should have C2");
    assert!(result.contains("C3"), "Should have C3");
}

// Test nested foreach with break only affects inner loop
#[test]
fn test_foreach_nested_break_inner_only() {
    init_logs();
    let input = r#"
        <esi:assign name="outer" value="$string_split('X,Y', ',')" />
        <esi:assign name="inner" value="$string_split('1,2,3', ',')" />
        <esi:foreach collection="$(outer)" item="letter">
            [<esi:foreach collection="$(inner)" item="num"><esi:choose>
                <esi:when test="$(num) == '2'"><esi:break /></esi:when>
                <esi:otherwise>$(letter)$(num)</esi:otherwise>
            </esi:choose></esi:foreach>]
        </esi:foreach>
    "#;
    let req = Request::get("http://example.com/test");
    let result = process_esi_document(input, req).expect("Processing should succeed");

    // Each outer iteration should produce X1, then break at 2
    assert!(result.contains("X1"), "Should have X1 before break");
    assert!(!result.contains("X2"), "Should not have X2 (break)");
    assert!(!result.contains("X3"), "Should not have X3 (after break)");

    // Second outer iteration should also produce Y1, then break at 2
    assert!(
        result.contains("Y1"),
        "Should have Y1 (outer loop continues)"
    );
    assert!(!result.contains("Y2"), "Should not have Y2 (break)");
    assert!(!result.contains("Y3"), "Should not have Y3 (after break)");
}

// Test that assigning to non-existent list index fails per ESI spec
#[test]
fn test_list_index_must_exist() {
    init_logs();
    let input = r#"
        <esi:assign name="colors" value="['red', 'blue', 'green']" />
        <esi:assign name="colors{3}" value="'yellow'" />
        <esi:vars>$(colors{3})</esi:vars>
    "#;
    let req = Request::get("http://example.com/test");
    let result = process_esi_document(input, req);

    // Should fail because index 3 doesn't exist (only 0, 1, 2)
    assert!(
        result.is_err(),
        "Should error on out-of-bounds list assignment"
    );
}

// Test that you can assign to existing list indices
#[test]
fn test_list_index_assignment_when_exists() {
    init_logs();
    let input = r#"
        <esi:comment value="Create a list of size 4" />
        <esi:assign name="newlist" value="[ 0, 0, 0, 0 ]" />
        <esi:assign name="newlist{0}" value="'yellow'" />
        <esi:vars>$(newlist{0})</esi:vars>
    "#;
    let req = Request::get("http://example.com/test");
    let result = process_esi_document(input, req).expect("Processing should succeed");

    assert!(
        result.contains("yellow"),
        "Should assign to existing list index"
    );
}

// Test that dictionary keys can be created on the fly
#[test]
fn test_dict_keys_created_on_fly() {
    init_logs();
    let input = r#"
        <esi:assign name="ages{'bob'}" value="34" />
        <esi:assign name="ages{'joan'}" value="28" />
        <esi:vars>bob:$(ages{'bob'}), joan:$(ages{'joan'})</esi:vars>
    "#;
    let req = Request::get("http://example.com/test");
    let result = process_esi_document(input, req).expect("Processing should succeed");

    assert!(
        result.contains("bob:34"),
        "Should create dict keys on the fly. Got: {}",
        result
    );
    assert!(
        result.contains("joan:28"),
        "Should create multiple dict keys. Got: {}",
        result
    );
}

// Test that you cannot assign string key to a list
#[test]
fn test_cannot_assign_string_key_to_list() {
    init_logs();
    let input = r#"
        <esi:assign name="colors" value="['red', 'blue']" />
        <esi:assign name="colors{joe}" value="'black'" />
        <esi:vars>$(colors{joe})</esi:vars>
    "#;
    let req = Request::get("http://example.com/test");
    let result = process_esi_document(input, req);

    // Should fail because can't assign string key to list
    assert!(
        result.is_err(),
        "Should error when assigning string key to list"
    );
}

// Test nested lists work correctly
#[test]
fn test_nested_lists() {
    init_logs();
    let input = r#"
        <esi:assign name="complex" value="[ 'one', [ 'a', 'x', 'c' ], 'three' ]" />
        <esi:assign name="inner" value="$(complex{1})" />
        <esi:vars>$(complex{0}),$(inner{1}),$(complex{2})</esi:vars>
    "#;
    let req = Request::get("http://example.com/test");
    let result = process_esi_document(input, req).expect("Processing should succeed");

    assert!(result.contains("one"), "Should access first element");
    assert!(result.contains("x"), "Should access nested list element");
    assert!(result.contains("three"), "Should access third element");
}

// Test has operator - case-sensitive substring matching
#[test]
fn test_has_operator() {
    init_logs();
    let input = r#"
        <esi:choose>
            <esi:when test="'Hello World' has 'World'">found</esi:when>
            <esi:otherwise>not found</esi:otherwise>
        </esi:choose>
    "#;
    let req = Request::get("http://example.com/test");
    let result = process_esi_document(input, req).expect("Processing should succeed");
    assert!(
        result.contains("found"),
        "Should find 'World' in 'Hello World'"
    );

    // Test case sensitivity - should NOT match
    let input2 = r#"
        <esi:choose>
            <esi:when test="'Hello World' has 'world'">found</esi:when>
            <esi:otherwise>not found</esi:otherwise>
        </esi:choose>
    "#;
    let req2 = Request::get("http://example.com/test");
    let result2 = process_esi_document(input2, req2).expect("Processing should succeed");
    assert!(
        result2.contains("not found"),
        "Should NOT find 'world' (wrong case)"
    );
}

// Test has_i operator - case-insensitive substring matching
#[test]
fn test_has_i_operator() {
    init_logs();
    let input = r#"
        <esi:choose>
            <esi:when test="'Hello World' has_i 'world'">found</esi:when>
            <esi:otherwise>not found</esi:otherwise>
        </esi:choose>
    "#;
    let req = Request::get("http://example.com/test");
    let result = process_esi_document(input, req).expect("Processing should succeed");
    assert!(
        result.contains("found"),
        "Should find 'world' case-insensitively"
    );

    // Test with different case variations
    let input2 = r#"
        <esi:choose>
            <esi:when test="'HELLO WORLD' has_i 'HeLLo'">found</esi:when>
            <esi:otherwise>not found</esi:otherwise>
        </esi:choose>
    "#;
    let req2 = Request::get("http://example.com/test");
    let result2 = process_esi_document(input2, req2).expect("Processing should succeed");
    assert!(result2.contains("found"), "Should match case-insensitively");
}

// Test has with HTTP_COOKIE variable (from ESI spec example)
#[test]
fn test_has_with_cookie_variable() {
    init_logs();
    let input = r#"
        <esi:assign name="test_cookie" value="'first_name=Sam&last_name=Samuelson'" />
        <esi:choose>
            <esi:when test="$(test_cookie) has 'Sam'">has Sam</esi:when>
            <esi:otherwise>no Sam</esi:otherwise>
        </esi:choose>
    "#;
    let req = Request::get("http://example.com/test");
    let result = process_esi_document(input, req).expect("Processing should succeed");
    assert!(
        result.contains("has Sam"),
        "Should find Sam in cookie string"
    );
}

// Test has_i with subscript access (from ESI spec example)
#[test]
fn test_has_i_with_subscript() {
    init_logs();
    let input = r#"
        <esi:assign name="cookies" value="{'first_name':'Sam','last_name':'Smith'}" />
        <esi:choose>
            <esi:when test="$(cookies{'first_name'}) has_i 'sam'">matched</esi:when>
            <esi:otherwise>not matched</esi:otherwise>
        </esi:choose>
    "#;
    let req = Request::get("http://example.com/test");
    let result = process_esi_document(input, req).expect("Processing should succeed");
    assert!(
        result.contains("matched"),
        "Should match 'sam' case-insensitively in 'Sam'"
    );
}

// Test default values for undefined variables
#[test]
fn test_variable_default_values() {
    init_logs();

    // Test 1: Simple string default for undefined variable (inside esi:vars)
    let input1 = r#"<esi:vars>Value: $(UNDEFINED|'default_value')</esi:vars>"#;
    let req1 = Request::get("http://example.com/test");
    let result1 = process_esi_document(input1, req1).expect("Processing should succeed");
    assert!(
        result1.contains("Value: default_value"),
        "Should use default value for undefined variable. Got: {}",
        result1
    );

    // Test 2: Integer default for undefined variable
    let input2 = r#"<esi:vars>Count: $(UNDEFINED|42)</esi:vars>"#;
    let req2 = Request::get("http://example.com/test");
    let result2 = process_esi_document(input2, req2).expect("Processing should succeed");
    assert!(
        result2.contains("Count: 42"),
        "Should use integer default value. Got: {}",
        result2
    );

    // Test 3: Default value for missing cookie (from ESI spec example)
    // This include will fail because the backend doesn't exist, but the URL construction
    // should still work (use default value to construct the URL)
    let input3 =
        r#"<esi:include src="http://www.xyz.com/$(HTTP_COOKIE{'cobrand'}|'akamai').htm"/>"#;
    let req3 = Request::get("http://example.com/test");
    // The include will fail but parsing/evaluation should succeed
    // We're just checking that the default value syntax is parsed correctly
    let _ = process_esi_document(input3, req3); // May fail due to missing backend, that's ok

    // Test 4: Default value for missing dictionary key
    let input4 = r#"
        <esi:assign name="mydict" value="{'a':'value_a'}" />
        <esi:vars>Result: $(mydict{'missing_key'}|'default_key_value')</esi:vars>
    "#;
    let req4 = Request::get("http://example.com/test");
    let result4 = process_esi_document(input4, req4).expect("Processing should succeed");
    assert!(
        result4.contains("Result: default_key_value"),
        "Should use default for missing dict key. Got: {}",
        result4
    );

    // Test 5: Variable with value should not use default
    let input5 = r#"
        <esi:assign name="defined" value="'actual_value'" />
        <esi:vars>Result: $(defined|'default_value')</esi:vars>
    "#;
    let req5 = Request::get("http://example.com/test");
    let result5 = process_esi_document(input5, req5).expect("Processing should succeed");
    assert!(
        result5.contains("Result: actual_value"),
        "Should use actual value, not default. Got: {}",
        result5
    );

    // Test 6: Default value can be another variable
    let input6 = r#"
        <esi:assign name="fallback" value="'fallback_value'" />
        <esi:vars>Result: $(UNDEFINED|$(fallback))</esi:vars>
    "#;
    let req6 = Request::get("http://example.com/test");
    let result6 = process_esi_document(input6, req6).expect("Processing should succeed");
    assert!(
        result6.contains("Result: fallback_value"),
        "Should use variable as default. Got: {}",
        result6
    );

    // Test 7: Default value with HTTP_ACCEPT_LANGUAGE example from spec
    let input7 = r#"<esi:vars><esi:assign name="lang">$(HTTP_ACCEPT_LANGUAGE{'en-gb'}|'en-us')</esi:assign></esi:vars>"#;
    let req7 = Request::get("http://example.com/test");
    let result7 = process_esi_document(input7, req7).expect("Processing should succeed");
    // Should complete without error even if header not present
    assert!(
        !result7.is_empty() || result7.is_empty(),
        "Processing completed"
    );
}

// Test default values in esi:include src attribute
#[test]
fn test_default_in_include_src() {
    init_logs();

    // From ESI spec: setting default language for HTTP_ACCEPT_LANGUAGE
    let input = r#"
        <esi:vars>
            <esi:assign name="user_lang">$(HTTP_ACCEPT_LANGUAGE|'en-us')</esi:assign>
            Language: $(user_lang)
        </esi:vars>
    "#;
    let req = Request::get("http://example.com/test");
    let result = process_esi_document(input, req).expect("Processing should succeed");
    assert!(
        result.contains("Language: en-us"),
        "Should use default language 'en-us'. Got: {}",
        result
    );
}

// Test compound expressions with multiple operators (from ESI spec example)
#[test]
fn test_compound_expression_from_spec() {
    init_logs();

    // Test case 1: Cookie doesn't exist - should go to when branch
    let input1 = r#"
        <esi:choose>
            <esi:when test="!$exists($(HTTP_COOKIE{'UserInfo'})) | !($(HTTP_COOKIE{'UserInfo'}) matches '''UserId=[0-9]''')">
                some file
            </esi:when>
            <esi:otherwise>
                some other file
            </esi:otherwise>
        </esi:choose>
    "#;
    let req1 = Request::get("http://example.com/test");
    // No cookie set, so first part of OR should be true
    let result1 = process_esi_document(input1, req1).expect("Processing should succeed");
    assert!(
        result1.contains("some file"),
        "Should include 'some file' when cookie doesn't exist. Got: {}",
        result1
    );
    assert!(
        !result1.contains("some other file"),
        "Should not include 'some other file'. Got: {}",
        result1
    );

    // Test case 2: Cookie exists with matching pattern - should go to otherwise
    let input2 = r#"
        <esi:choose>
            <esi:when test="!$exists($(HTTP_COOKIE{'UserInfo'})) | !($(HTTP_COOKIE{'UserInfo'}) matches '''UserId=[0-9]''')">
                some file
            </esi:when>
            <esi:otherwise>
                some other file
            </esi:otherwise>
        </esi:choose>
    "#;
    let mut req2 = Request::get("http://example.com/test");
    req2.set_header("Cookie", "UserInfo=UserId=5");
    let result2 = process_esi_document(input2, req2).expect("Processing should succeed");
    assert!(
        result2.contains("some other file"),
        "Should include 'some other file' when cookie exists with valid pattern. Got: {}",
        result2
    );
    assert!(
        !result2.contains("some file"),
        "Should not include 'some file'. Got: {}",
        result2
    );

    // Test case 3: Cookie exists but doesn't match pattern - should go to when branch
    let input3 = r#"
        <esi:choose>
            <esi:when test="!$exists($(HTTP_COOKIE{'UserInfo'})) | !($(HTTP_COOKIE{'UserInfo'}) matches '''UserId=[0-9]''')">
                some file
            </esi:when>
            <esi:otherwise>
                some other file
            </esi:otherwise>
        </esi:choose>
    "#;
    let mut req3 = Request::get("http://example.com/test");
    req3.set_header("Cookie", "UserInfo=NoMatch");
    let result3 = process_esi_document(input3, req3).expect("Processing should succeed");
    assert!(
        result3.contains("some file"),
        "Should include 'some file' when cookie doesn't match pattern. Got: {}",
        result3
    );
    assert!(
        !result3.contains("some other file"),
        "Should not include 'some other file'. Got: {}",
        result3
    );

    // Test case 4: Cookie exists with empty value - should go to when branch (doesn't exist)
    let input4 = r#"
        <esi:choose>
            <esi:when test="!$exists($(HTTP_COOKIE{'UserInfo'})) | !($(HTTP_COOKIE{'UserInfo'}) matches '''UserId=[0-9]''')">
                some file
            </esi:when>
            <esi:otherwise>
                some other file
            </esi:otherwise>
        </esi:choose>
    "#;
    let mut req4 = Request::get("http://example.com/test");
    req4.set_header("Cookie", "OtherCookie=value");
    let result4 = process_esi_document(input4, req4).expect("Processing should succeed");
    assert!(
        result4.contains("some file"),
        "Should include 'some file' when UserInfo key doesn't exist. Got: {}",
        result4
    );
}

// Test arithmetic operators with ESI variables and expressions
// This demonstrates the left-to-right evaluation behavior from the ESI spec
#[test]
fn test_arithmetic_operators_in_esi() {
    init_logs();

    // Test 1: Basic arithmetic with left-to-right evaluation
    // 2 + 3 * 4 should evaluate left-to-right as (2 + 3) * 4 = 20, not 14
    let input1 = r#"
        <esi:assign name="result" value="2 + 3 * 4" />
        <esi:vars>$(result)</esi:vars>
    "#;
    let req1 = Request::get("http://example.com");
    let result1 = process_esi_document(input1, req1).expect("Processing should succeed");
    assert_eq!(
        result1.trim(),
        "20",
        "2 + 3 * 4 with left-to-right evaluation should be 20"
    );

    // Test 2: Subtraction chain with left-to-right
    // 10 - 3 - 2 should be (10 - 3) - 2 = 5, not 10 - (3 - 2) = 9
    let input2 = r#"
        <esi:assign name="result" value="10 - 3 - 2" />
        <esi:vars>$(result)</esi:vars>
    "#;
    let req2 = Request::get("http://example.com");
    let result2 = process_esi_document(input2, req2).expect("Processing should succeed");
    assert_eq!(
        result2.trim(),
        "5",
        "10 - 3 - 2 with left-to-right evaluation should be 5"
    );

    // Test 3: Division and modulo
    let input3 = r#"
        <esi:assign name="div" value="20 / 4" />
        <esi:assign name="mod" value="10 % 3" />
        <esi:vars>$(div),$(mod)</esi:vars>
    "#;
    let req3 = Request::get("http://example.com");
    let result3 = process_esi_document(input3, req3).expect("Processing should succeed");
    assert_eq!(
        result3.trim(),
        "5,1",
        "Division and modulo should work correctly"
    );

    // Test 4: Arithmetic in conditions
    // 5 + 3 > 7 should evaluate as (5 + 3) > 7 = true
    let input4 = r#"
        <esi:choose>
            <esi:when test="5 + 3 > 7">
                arithmetic true
            </esi:when>
            <esi:otherwise>
                arithmetic false
            </esi:otherwise>
        </esi:choose>
    "#;
    let req4 = Request::get("http://example.com");
    let result4 = process_esi_document(input4, req4).expect("Processing should succeed");
    assert!(
        result4.contains("arithmetic true"),
        "5 + 3 > 7 should evaluate to true"
    );

    // Test 5: Parentheses override left-to-right
    // 2 * (3 + 4) should respect parentheses = 2 * 7 = 14
    let input5 = r#"
        <esi:assign name="result" value="2 * (3 + 4)" />
        <esi:vars>$(result)</esi:vars>
    "#;
    let req5 = Request::get("http://example.com");
    let result5 = process_esi_document(input5, req5).expect("Processing should succeed");
    assert_eq!(
        result5.trim(),
        "14",
        "2 * (3 + 4) should respect parentheses and equal 14"
    );

    // Test 6: Complex arithmetic expression
    // 100 / 5 - 2 * 3 with left-to-right should be ((100 / 5) - 2) * 3 = (20 - 2) * 3 = 54
    let input6 = r#"
        <esi:assign name="result" value="100 / 5 - 2 * 3" />
        <esi:vars>$(result)</esi:vars>
    "#;
    let req6 = Request::get("http://example.com");
    let result6 = process_esi_document(input6, req6).expect("Processing should succeed");
    assert_eq!(
        result6.trim(),
        "54",
        "100 / 5 - 2 * 3 with left-to-right evaluation should be 54"
    );
}

#[test]
fn test_user_defined_function_basic() {
    init_logs();

    let input = r#"
        <esi:function name="greet">Hello, World!</esi:function>
        <esi:vars>$greet()</esi:vars>
    "#;
    let req = Request::get("http://example.com");
    let result = process_esi_document(input, req).expect("Processing should succeed");

    // Function should output accumulated text
    assert!(result.contains("Hello, World!"), "Result was: {}", result);
}

#[test]
fn test_user_defined_function_add() {
    init_logs();

    let input = r#"
        <esi:function name="add">
            <esi:return value="$(ARGS{0}) + $(ARGS{1})"/>
        </esi:function>
        <esi:vars>$add( 5, 7 )</esi:vars>
    "#;
    let req = Request::get("http://example.com");
    let result = process_esi_document(input, req).expect("Processing should succeed");

    assert!(result.contains("12"), "Result was: {}", result);
}

#[test]
fn test_user_defined_function_multiply() {
    init_logs();

    let input = r#"
        <esi:function name="multiply">
            <esi:return value="$(ARGS{0}) * $(ARGS{1})"/>
        </esi:function>
        <esi:vars>Result: $multiply(6, 7)</esi:vars>
    "#;
    let req = Request::get("http://example.com");
    let result = process_esi_document(input, req).expect("Processing should succeed");

    assert!(result.contains("42"), "Result was: {}", result);
}

#[test]
fn test_user_defined_function_is_odd() {
    init_logs();

    let input = r#"
        <esi:function name="is_odd">
            <esi:choose>
                <esi:when test="$(ARGS{0}) % 2 == 1">
                    <esi:return value="'yes'"/>
                </esi:when>
                <esi:otherwise>
                    <esi:return value="'no'"/>
                </esi:otherwise>
            </esi:choose>
        </esi:function>
        <esi:vars>$is_odd(3)</esi:vars>
    "#;
    let req = Request::get("http://example.com");
    let result = process_esi_document(input, req).expect("Processing should succeed");

    assert!(result.contains("yes"), "Result was: {}", result);
}

#[test]
fn test_user_defined_function_sum_with_foreach() {
    init_logs();

    let input = r#"
        <esi:function name="sum">
            <esi:assign name="total" value="0"/>
            <esi:foreach collection="$(ARGS)" item="arg">
                <esi:assign name="total" value="$(total) + $(arg)"/>
            </esi:foreach>
            <esi:return value="$(total)"/>
        </esi:function>
        <esi:vars>$sum(1, 2, 3, 4)</esi:vars>
    "#;
    let req = Request::get("http://example.com");
    let result = process_esi_document(input, req).expect("Processing should succeed");

    assert!(result.contains("10"), "Result was: {}", result);
}

#[test]
fn test_user_defined_function_recursive_addv() {
    init_logs();

    let input = r#"
        <esi:function name="addv">
            <esi:choose>
                <esi:when test="$(ARGS) == []">
                    <esi:return value="0"/>
                </esi:when>
                <esi:otherwise>
                    <esi:assign name="sum" value="0"/>
                    <esi:foreach collection="$(ARGS)" item="arg">
                        <esi:assign name="sum" value="$(sum) + $(arg)"/>
                    </esi:foreach>
                    <esi:return value="$(sum)"/>
                </esi:otherwise>
            </esi:choose>
        </esi:function>
        <esi:vars>$addv(5, 10, 15)</esi:vars>
    "#;
    let req = Request::get("http://example.com");
    let result = process_esi_document(input, req).expect("Processing should succeed");

    assert!(result.contains("30"), "Result was: {}", result);
}

#[test]
fn test_user_defined_function_recursive_factorial() {
    init_logs();

    let input = r#"
        <esi:function name="factorial">
            <esi:choose>
                <esi:when test="$(ARGS{0}) <= 1">
                    <esi:return value="1"/>
                </esi:when>
                <esi:otherwise>
                    <esi:return value="$(ARGS{0}) * $factorial($(ARGS{0}) - 1)"/>
                </esi:otherwise>
            </esi:choose>
        </esi:function>
        <esi:vars>$factorial(5)</esi:vars>
    "#;
    let req = Request::get("http://example.com");
    let result = process_esi_document(input, req).expect("Processing should succeed");

    assert!(result.contains("120"), "Result was: {}", result);
}
// ──────────────────────────────────────────────────────────────────────────────
// Tests for ESI tags inside <esi:try> attempt/except blocks (fix #9 / #2)
// Previously, Choose, Foreach, Assign and Vars were silently dropped when they
// appeared inside an attempt or except block because build_attempt_queue only
// handled Text, Html, Expr, Include, and a hard-coded Choose/Try branch that
// routed output to the wrong queue.
// ──────────────────────────────────────────────────────────────────────────────

#[test]
fn test_try_attempt_with_vars() {
    init_logs();

    let input = r#"<esi:assign name="x" value="'hello'"/>
<esi:try>
  <esi:attempt><esi:vars>$(x)</esi:vars></esi:attempt>
  <esi:except>fallback</esi:except>
</esi:try>"#;

    let result = process_esi_document(input, Request::get("http://example.com/"))
        .expect("Processing should succeed");

    assert!(
        result.contains("hello"),
        "vars inside try attempt should render. Got: {result}"
    );
    assert!(
        !result.contains("fallback"),
        "fallback should NOT appear. Got: {result}"
    );
}

#[test]
fn test_try_attempt_with_choose() {
    init_logs();

    let input = r#"<esi:assign name="flag" value="'yes'"/>
<esi:try>
  <esi:attempt>
    <esi:choose>
      <esi:when test="$(flag)=='yes'">chosen</esi:when>
      <esi:otherwise>other</esi:otherwise>
    </esi:choose>
  </esi:attempt>
  <esi:except>fallback</esi:except>
</esi:try>"#;

    let result = process_esi_document(input, Request::get("http://example.com/"))
        .expect("Processing should succeed");

    assert!(
        result.contains("chosen"),
        "choose inside try attempt should evaluate. Got: {result}"
    );
    assert!(
        !result.contains("other"),
        "non-matching branch should not appear. Got: {result}"
    );
    assert!(
        !result.contains("fallback"),
        "fallback should NOT appear. Got: {result}"
    );
}

#[test]
fn test_try_attempt_with_foreach() {
    init_logs();

    let input = r#"<esi:try>
  <esi:attempt><esi:foreach collection="['a','b','c']" item="i">$(i)</esi:foreach></esi:attempt>
  <esi:except>fallback</esi:except>
</esi:try>"#;

    let result = process_esi_document(input, Request::get("http://example.com/"))
        .expect("Processing should succeed");

    assert_eq!(
        result.trim(),
        "abc",
        "foreach inside try attempt should iterate. Got: {result}"
    );
}

#[test]
fn test_try_attempt_with_assign() {
    init_logs();

    let input = r#"<esi:try>
  <esi:attempt>
    <esi:assign name="val" value="'computed'"/>
    <esi:vars>$(val)</esi:vars>
  </esi:attempt>
  <esi:except>fallback</esi:except>
</esi:try>"#;

    let result = process_esi_document(input, Request::get("http://example.com/"))
        .expect("Processing should succeed");

    assert!(
        result.contains("computed"),
        "assign+vars inside try attempt should work. Got: {result}"
    );
    assert!(
        !result.contains("fallback"),
        "fallback should NOT appear. Got: {result}"
    );
}

#[test]
fn test_try_except_with_vars() {
    init_logs();

    // Attempt dispatches an include that returns 500 (no onerror=continue, so it raises Err
    // and the try machinery falls through to the except block).
    let input = r#"<esi:assign name="msg" value="'except-rendered'"/>
<esi:try>
  <esi:attempt><esi:include src="http://example.com/fails"/></esi:attempt>
  <esi:except><esi:vars>$(msg)</esi:vars></esi:except>
</esi:try>"#;

    // Dispatcher that always returns a 500 so the attempt fails
    let dispatcher = |_req: Request, _: Option<u32>| -> esi::Result<esi::PendingFragmentContent> {
        let mut resp = fastly::Response::new();
        resp.set_status(fastly::http::StatusCode::INTERNAL_SERVER_ERROR);
        Ok(esi::PendingFragmentContent::CompletedRequest(Box::new(
            resp,
        )))
    };

    let reader = std::io::BufReader::new(std::io::Cursor::new(input.as_bytes()));
    let mut output = Vec::new();
    let mut processor = Processor::new(
        Some(Request::get("http://example.com/")),
        Configuration::default(),
    );
    processor
        .process_stream(reader, &mut output, Some(&dispatcher), None)
        .expect("Processing should succeed");

    let result = String::from_utf8(output).unwrap();
    assert!(
        result.contains("except-rendered"),
        "vars inside except block should render. Got: {result}"
    );
}

// ──────────────────────────────────────────────────────────────────────────────
// Multi-include document ordering (fix #7)
// With simplified drain_queue (sequential wait), includes must appear in the
// same order they appear in the document regardless of which finishes first.
// ──────────────────────────────────────────────────────────────────────────────

#[test]
fn test_multi_include_document_order() {
    init_logs();

    let input = r#"<esi:include src="http://example.com/first"/><esi:include src="http://example.com/second"/><esi:include src="http://example.com/third"/>"#;

    let dispatcher = |req: Request, _: Option<u32>| -> esi::Result<esi::PendingFragmentContent> {
        let body = if req.get_url_str().contains("/first") {
            "FIRST"
        } else if req.get_url_str().contains("/second") {
            "SECOND"
        } else {
            "THIRD"
        };
        Ok(esi::PendingFragmentContent::CompletedRequest(Box::new(
            fastly::Response::from_body(body),
        )))
    };

    let reader = std::io::BufReader::new(std::io::Cursor::new(input.as_bytes()));
    let mut output = Vec::new();
    let mut processor = Processor::new(
        Some(Request::get("http://example.com/")),
        Configuration::default(),
    );
    processor
        .process_stream(reader, &mut output, Some(&dispatcher), None)
        .expect("Processing should succeed");

    let result = String::from_utf8(output).unwrap();
    assert_eq!(
        result, "FIRSTSECONDTHIRD",
        "Includes must appear in document order. Got: {result}"
    );
}

// ──────────────────────────────────────────────────────────────────────────────
// Try block after an include in the same document (fix #11)
// Previously, process_queue skipped Try blocks entirely, so a Try
// that reached the head of the queue (after a preceding include was consumed)
// would stall until drain_queue ran at the end - never an outright bug in tests
// using CompletedRequest, but wrong for real async requests.  The fix makes
// process_queue process Try blocks inline.
// ──────────────────────────────────────────────────────────────────────────────

#[test]
fn test_include_followed_by_try_block() {
    init_logs();

    let input = r#"<esi:include src="http://example.com/first"/>
<esi:try>
  <esi:attempt><esi:include src="http://example.com/attempt"/></esi:attempt>
  <esi:except>except-content</esi:except>
</esi:try>"#;

    let dispatcher = |req: Request, _: Option<u32>| -> esi::Result<esi::PendingFragmentContent> {
        let body = if req.get_url_str().contains("/first") {
            "first-content"
        } else {
            "attempt-content"
        };
        Ok(esi::PendingFragmentContent::CompletedRequest(Box::new(
            fastly::Response::from_body(body),
        )))
    };

    let reader = std::io::BufReader::new(std::io::Cursor::new(input.as_bytes()));
    let mut output = Vec::new();
    let mut processor = Processor::new(
        Some(Request::get("http://example.com/")),
        Configuration::default(),
    );
    processor
        .process_stream(reader, &mut output, Some(&dispatcher), None)
        .expect("Processing should succeed");

    let result = String::from_utf8(output).unwrap();
    assert!(
        result.contains("first-content"),
        "Include before try should appear. Got: {result}"
    );
    assert!(
        result.contains("attempt-content"),
        "Try attempt should execute after include. Got: {result}"
    );
    assert!(
        !result.contains("except-content"),
        "Except should NOT appear when attempt succeeds. Got: {result}"
    );
}

#[test]
fn test_content_order_around_try_block() {
    // Verifies that text before and after a <esi:try> block appears in the
    // correct position in the output, even when the attempt contains an include.
    init_logs();

    let input = r#"before<esi:try>
  <esi:attempt><esi:include src="http://example.com/fragment"/></esi:attempt>
  <esi:except>fallback</esi:except>
</esi:try>after"#;

    let dispatcher = |_req: Request, _: Option<u32>| -> esi::Result<esi::PendingFragmentContent> {
        Ok(esi::PendingFragmentContent::CompletedRequest(Box::new(
            fastly::Response::from_body("fragment-content"),
        )))
    };

    let reader = std::io::BufReader::new(std::io::Cursor::new(input.as_bytes()));
    let mut output = Vec::new();
    let mut processor = Processor::new(
        Some(Request::get("http://example.com/")),
        Configuration::default(),
    );
    processor
        .process_stream(reader, &mut output, Some(&dispatcher), None)
        .expect("Processing should succeed");

    let result = String::from_utf8(output).unwrap();
    assert_eq!(result, "beforefragment-contentafter", "Got: {result:?}");
}

#[test]
fn test_try_block_at_queue_head_uses_except_on_failure() {
    init_logs();

    // An include followed by a try whose attempt fails -> except should show
    let input = r#"<esi:include src="http://example.com/first"/>
<esi:try>
  <esi:attempt><esi:include src="http://example.com/attempt"/></esi:attempt>
  <esi:except>except-content</esi:except>
</esi:try>"#;

    let dispatcher = |req: Request, _: Option<u32>| -> esi::Result<esi::PendingFragmentContent> {
        if req.get_url_str().contains("/first") {
            Ok(esi::PendingFragmentContent::CompletedRequest(Box::new(
                fastly::Response::from_body("first-content"),
            )))
        } else {
            // Attempt fails with 500
            let mut resp = fastly::Response::new();
            resp.set_status(fastly::http::StatusCode::INTERNAL_SERVER_ERROR);
            Ok(esi::PendingFragmentContent::CompletedRequest(Box::new(
                resp,
            )))
        }
    };

    let reader = std::io::BufReader::new(std::io::Cursor::new(input.as_bytes()));
    let mut output = Vec::new();
    let mut processor = Processor::new(
        Some(Request::get("http://example.com/")),
        Configuration::default(),
    );
    processor
        .process_stream(reader, &mut output, Some(&dispatcher), None)
        .expect("Processing should succeed");

    let result = String::from_utf8(output).unwrap();
    assert!(
        result.contains("first-content"),
        "Include before try should appear. Got: {result}"
    );
    assert!(
        result.contains("except-content"),
        "Except should appear when attempt fails. Got: {result}"
    );
}

// ---------------------------------------------------------------------------
// Reference semantics for lists and dictionaries (ESI spec: "Lists and
// Dictionaries are Referenced, Not Copied")
// ---------------------------------------------------------------------------

/// Spec example: assigning a list to new names creates aliases, not copies.
/// Mutating through any alias is visible from every other alias.
///
/// ```esi
/// <esi:assign name="list" value="[1, 2, 3]"/>
/// <esi:assign name="copy1" value="list"/>   <!-- Does not copy! -->
/// <esi:assign name="copy2" value="list"/>   <!-- Does not copy! -->
/// <esi:assign name="copy1{2}" value="9"/>
/// ```
///
/// Expected output for $(list), $(copy1), $(copy2): all `1,2,9`
#[test]
fn test_list_reference_semantics() -> Result<(), Error> {
    let input = r#"<esi:assign name="list" value="[1, 2, 3]"/>
<esi:assign name="copy1" value="$(list)"/>
<esi:assign name="copy2" value="$(list)"/>
<esi:assign name="copy1{2}" value="9"/>
<esi:vars>$(list)
$(copy1)
$(copy2)</esi:vars>"#;

    let dispatcher =
        |_req: Request, _maxwait: Option<u32>| -> esi::Result<esi::PendingFragmentContent> {
            unreachable!("no fragments in this test")
        };

    let reader = std::io::BufReader::new(std::io::Cursor::new(input.as_bytes()));
    let mut output = Vec::new();
    let mut processor = Processor::new(None, Configuration::default());
    processor.process_stream(reader, &mut output, Some(&dispatcher), None)?;

    let result = String::from_utf8(output).unwrap();
    // All three variables refer to the same list — mutation through copy1 is
    // visible in list and copy2.
    assert_eq!(
        result.trim(),
        "1,2,9\n1,2,9\n1,2,9",
        "Lists should be assigned by reference, not copied"
    );
    Ok(())
}

/// Spec example: using foreach to iterate a dict and build a real copy,
/// then mutating the copy — original should be unaffected.
///
/// ```esi
/// <esi:assign name="dict" value="{1 : 'one', 2 : 'two', 3 : 'three'}"/>
/// <esi:foreach collection="$(dict)">
///   <esi:assign name="copy{$(item{0})}" value="$(item{1})"/>
/// </esi:foreach>
/// <esi:assign name="copy{2}" value="Second"/>
/// ```
///
/// Expected: dict unchanged, copy has key 2 = "Second"
#[test]
fn test_dict_copy_by_iteration() -> Result<(), Error> {
    let input = r#"<esi:assign name="dict" value="{1 : 'one', 2 : 'two', 3 : 'three'}"/>
<esi:foreach collection="$(dict)">
<esi:assign name="copy{$(item{0})}" value="$(item{1})"/>
</esi:foreach>
<esi:assign name="copy{2}" value="'Second'"/>
<esi:vars>$(dict)
$(copy)</esi:vars>"#;

    let dispatcher =
        |_req: Request, _maxwait: Option<u32>| -> esi::Result<esi::PendingFragmentContent> {
            unreachable!("no fragments in this test")
        };

    let reader = std::io::BufReader::new(std::io::Cursor::new(input.as_bytes()));
    let mut output = Vec::new();
    let mut processor = Processor::new(None, Configuration::default());
    processor.process_stream(reader, &mut output, Some(&dispatcher), None)?;

    let result = String::from_utf8(output).unwrap();
    let lines: Vec<&str> = result.trim().lines().collect();

    // dict should be unchanged: {1: 'one', 2: 'two', 3: 'three'}
    // dict_to_string sorts by key and formats as k=v&k=v
    assert_eq!(
        lines[0], "1=one&2=two&3=three",
        "Original dict should be unchanged"
    );

    // copy should have key 2 replaced: {1: 'one', 2: 'Second', 3: 'three'}
    assert_eq!(
        lines[1], "1=one&2=Second&3=three",
        "Copy should have key 2 = 'Second'"
    );

    Ok(())
}

/// Dict reference semantics: assigning a dict to another name creates an alias.
/// Mutating through the alias is visible from the original.
#[test]
fn test_dict_reference_semantics() -> Result<(), Error> {
    let input = r#"<esi:assign name="orig" value="{1 : 'one', 2 : 'two'}"/>
<esi:assign name="alias" value="$(orig)"/>
<esi:assign name="alias{2}" value="'TWO'"/>
<esi:vars>$(orig)
$(alias)</esi:vars>"#;

    let dispatcher =
        |_req: Request, _maxwait: Option<u32>| -> esi::Result<esi::PendingFragmentContent> {
            unreachable!("no fragments in this test")
        };

    let reader = std::io::BufReader::new(std::io::Cursor::new(input.as_bytes()));
    let mut output = Vec::new();
    let mut processor = Processor::new(None, Configuration::default());
    processor.process_stream(reader, &mut output, Some(&dispatcher), None)?;

    let result = String::from_utf8(output).unwrap();
    // Both should reflect the mutation
    assert_eq!(
        result.trim(),
        "1=one&2=TWO\n1=one&2=TWO",
        "Dicts should be assigned by reference, not copied"
    );
    Ok(())
}

/// Mutating the original list is visible through the alias.
#[test]
fn test_list_mutation_visible_through_alias() -> Result<(), Error> {
    let input = r#"<esi:assign name="a" value="[10, 20, 30]"/>
<esi:assign name="b" value="$(a)"/>
<esi:assign name="a{0}" value="99"/>
<esi:vars>$(b{0})</esi:vars>"#;

    let dispatcher =
        |_req: Request, _maxwait: Option<u32>| -> esi::Result<esi::PendingFragmentContent> {
            unreachable!("no fragments in this test")
        };

    let reader = std::io::BufReader::new(std::io::Cursor::new(input.as_bytes()));
    let mut output = Vec::new();
    let mut processor = Processor::new(None, Configuration::default());
    processor.process_stream(reader, &mut output, Some(&dispatcher), None)?;

    let result = String::from_utf8(output).unwrap();
    assert_eq!(
        result.trim(),
        "99",
        "Mutation through original should be visible via alias"
    );
    Ok(())
}