esi 0.7.0-beta.4

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
use bytes::Bytes;
use fastly::http::Method;
use fastly::Request;
use regex::RegexBuilder;
use std::{borrow::Cow, cell::RefCell, collections::HashMap, fmt::Display, rc::Rc};

use crate::{
    element_handler::{ElementHandler, Flow},
    functions,
    literals::*,
    parser_types::{Element, Expr, IncludeAttributes, Operator},
    ESIError, Result,
};

/// Registry for user-defined ESI functions
/// Functions are defined using <esi:function> tags and can be called within expressions
#[derive(Debug, Clone, Default)]
pub struct FunctionRegistry {
    /// Map from function name to function body (Vec<Element>)
    functions: HashMap<String, Vec<Element>>,
}

impl FunctionRegistry {
    pub fn new() -> Self {
        Self {
            functions: HashMap::new(),
        }
    }

    pub fn register(&mut self, name: String, body: Vec<Element>) {
        self.functions.insert(name, body);
    }

    pub fn get(&self, name: &str) -> Option<&Vec<Element>> {
        self.functions.get(name)
    }
}

/// Evaluates a parsed expression directly without re-lexing/parsing
///
/// This function takes an expression that was already parsed by the parser
/// and evaluates it using the full expression evaluator, supporting all operators,
/// comparisons, and functions.
///
/// # Arguments
/// * `expr` - The parsed expression from the parser
/// * `ctx` - Evaluation context containing variables and state
///
/// # Returns
/// * `Result<Value>` - The evaluated expression result or an error
pub fn eval_expr(expr: &Expr, ctx: &mut EvalContext) -> Result<Value> {
    match expr {
        Expr::Integer(i) => Ok(Value::Integer(*i)),
        Expr::String(Some(b)) => Ok(Value::Text(b.clone())),
        Expr::String(None) => Ok(Value::Text(Bytes::new())),
        Expr::Variable(name, key, default) => {
            // Evaluate the key expression if present
            let evaluated_key = if let Some(key_expr) = key {
                let key_result = eval_expr(key_expr, ctx)?;
                Some(key_result.to_string())
            } else {
                None
            };

            let value = ctx.get_variable(name, evaluated_key.as_deref());

            // If value is Null and we have a default, evaluate and use the default
            if matches!(value, Value::Null) {
                if let Some(default_expr) = default {
                    return eval_expr(default_expr, ctx);
                }
            }

            Ok(value)
        }
        Expr::Comparison {
            left,
            operator,
            right,
        } => {
            // Short-circuit evaluation for logical operators per ESI spec
            if *operator == Operator::And {
                let left_val = eval_expr(left, ctx)?;
                if !left_val.to_bool() {
                    return Ok(Value::Boolean(false));
                }
                return Ok(Value::Boolean(eval_expr(right, ctx)?.to_bool()));
            }
            if *operator == Operator::Or {
                let left_val = eval_expr(left, ctx)?;
                if left_val.to_bool() {
                    return Ok(Value::Boolean(true));
                }
                return Ok(Value::Boolean(eval_expr(right, ctx)?.to_bool()));
            }

            let left_val = eval_expr(left, ctx)?;
            let right_val = eval_expr(right, ctx)?;
            eval_comparison(&left_val, &right_val, operator, ctx)
        }
        Expr::Call(func_name, args) => {
            let mut values = Vec::with_capacity(args.len());
            for arg in args {
                values.push(eval_expr(arg, ctx)?);
            }
            call_dispatch(func_name, &values, ctx)
        }
        Expr::Not(expr) => {
            let inner_value = eval_expr(expr, ctx)?;
            Ok(Value::Boolean(!inner_value.to_bool()))
        }
        Expr::DictLiteral(pairs) => {
            let mut map = HashMap::with_capacity(pairs.len());
            for (key_expr, val_expr) in pairs {
                let key = eval_expr(key_expr, ctx)?;
                let val = eval_expr(val_expr, ctx)?;
                map.insert(key.to_string(), val);
            }
            Ok(Value::new_dict(map))
        }
        Expr::ListLiteral(items) => {
            let mut values = Vec::with_capacity(items.len());
            for item_expr in items {
                values.push(eval_expr(item_expr, ctx)?);
            }
            Ok(Value::new_list(values))
        }
        Expr::Interpolated(elements) => {
            // Evaluate each element and concatenate the results
            // This handles compound expressions like: prefix$(VAR)suffix
            let mut result = String::new();
            for element in elements {
                match element {
                    Element::Content(text) => {
                        result.push_str(&String::from_utf8_lossy(text.as_ref()));
                    }
                    Element::Html(html) => {
                        result.push_str(&String::from_utf8_lossy(html.as_ref()));
                    }
                    Element::Expr(expr) => {
                        let value = eval_expr(expr, ctx)?;
                        result.push_str(&value.to_string());
                    }
                    Element::Esi(_) => {
                        // ESI tags in interpolated expressions should not happen
                        // but if they do, ignore them
                    }
                }
            }
            Ok(Value::Text(Bytes::from(result)))
        }
    }
}

/// Evaluates a comparison/operator expression
///
/// This helper function handles all binary operators including comparison, logical,
/// arithmetic, string matching, and containment operators. It applies the appropriate
/// evaluation logic based on the operator type and operand values.
///
/// # Arguments
/// * `left_val` - The evaluated left operand
/// * `right_val` - The evaluated right operand
/// * `operator` - The operator to apply
/// * `ctx` - Evaluation context (needed for regex captures)
///
/// # Returns
/// * `Result<Value>` - The result of applying the operator
fn eval_comparison(
    left_val: &Value,
    right_val: &Value,
    operator: &Operator,
    ctx: &mut EvalContext,
) -> Result<Value> {
    match operator {
        Operator::Range => {
            // Range operator creates a list: [start..end]
            // Both operands must be integers
            match (left_val, right_val) {
                (Value::Integer(start), Value::Integer(end)) => {
                    let values: Vec<Value> = if start <= end {
                        // Ascending range: [1..5] -> [1, 2, 3, 4, 5]
                        (*start..=*end).map(Value::Integer).collect()
                    } else {
                        // Descending range: [5..1] -> [5, 4, 3, 2, 1]
                        (*end..=*start).rev().map(Value::Integer).collect()
                    };
                    Ok(Value::new_list(values))
                }
                _ => Err(ESIError::ExpressionError(
                    "Range operator (..) requires integer operands".to_string(),
                )),
            }
        }
        Operator::Matches | Operator::MatchesInsensitive => {
            let test = left_val.as_cow_str();
            let pattern = right_val.as_cow_str();

            let re = if *operator == Operator::Matches {
                RegexBuilder::new(&pattern).build()?
            } else {
                RegexBuilder::new(&pattern).case_insensitive(true).build()?
            };

            if let Some(captures) = re.captures(&test) {
                let match_name = ctx.match_name.clone();
                let mut idx_buf = String::new();
                for (i, cap) in captures.iter().enumerate() {
                    let capval = cap.map_or(Value::Null, |s| {
                        Value::Text(Bytes::copy_from_slice(s.as_str().as_bytes()))
                    });
                    idx_buf.clear();
                    use std::fmt::Write;
                    let _ = write!(idx_buf, "{i}");
                    ctx.set_variable(&match_name, Some(&idx_buf), capval)?;
                }
                Ok(Value::Boolean(true))
            } else {
                Ok(Value::Boolean(false))
            }
        }
        Operator::Has => {
            let haystack: &str = &left_val.as_cow_str();
            let needle: &str = &right_val.as_cow_str();
            Ok(Value::Boolean(haystack.contains(needle)))
        }
        Operator::HasInsensitive => {
            let haystack: String = left_val.as_cow_str().to_lowercase();
            let needle: &str = &right_val.as_cow_str().to_lowercase();
            Ok(Value::Boolean(haystack.as_str().contains(needle)))
        }
        Operator::Equals => match (left_val, right_val) {
            (Value::Integer(l), Value::Integer(r)) => Ok(Value::Boolean(l == r)),
            (Value::Text(l), Value::Text(r)) => Ok(Value::Boolean(l == r)),
            _ => Ok(Value::Boolean(
                left_val.as_cow_str() == right_val.as_cow_str(),
            )),
        },
        Operator::NotEquals => match (left_val, right_val) {
            (Value::Integer(l), Value::Integer(r)) => Ok(Value::Boolean(l != r)),
            (Value::Text(l), Value::Text(r)) => Ok(Value::Boolean(l != r)),
            _ => Ok(Value::Boolean(
                left_val.as_cow_str() != right_val.as_cow_str(),
            )),
        },
        Operator::LessThan => match (left_val, right_val) {
            (Value::Integer(l), Value::Integer(r)) => Ok(Value::Boolean(l < r)),
            (Value::Text(l), Value::Text(r)) => Ok(Value::Boolean(l < r)),
            _ => Ok(Value::Boolean(
                left_val.as_cow_str() < right_val.as_cow_str(),
            )),
        },
        Operator::LessThanOrEqual => match (left_val, right_val) {
            (Value::Integer(l), Value::Integer(r)) => Ok(Value::Boolean(l <= r)),
            (Value::Text(l), Value::Text(r)) => Ok(Value::Boolean(l <= r)),
            _ => Ok(Value::Boolean(
                left_val.as_cow_str() <= right_val.as_cow_str(),
            )),
        },
        Operator::GreaterThan => match (left_val, right_val) {
            (Value::Integer(l), Value::Integer(r)) => Ok(Value::Boolean(l > r)),
            (Value::Text(l), Value::Text(r)) => Ok(Value::Boolean(l > r)),
            _ => Ok(Value::Boolean(
                left_val.as_cow_str() > right_val.as_cow_str(),
            )),
        },
        Operator::GreaterThanOrEqual => match (left_val, right_val) {
            (Value::Integer(l), Value::Integer(r)) => Ok(Value::Boolean(l >= r)),
            (Value::Text(l), Value::Text(r)) => Ok(Value::Boolean(l >= r)),
            _ => Ok(Value::Boolean(
                left_val.as_cow_str() >= right_val.as_cow_str(),
            )),
        },
        Operator::And | Operator::Or => {
            // Short-circuit handled in eval_expr; this branch is unreachable
            unreachable!("And/Or are short-circuit evaluated in eval_expr")
        }
        // Arithmetic operators
        Operator::Add => {
            // Integer addition, list concatenation, or string concatenation
            match (left_val, right_val) {
                (Value::Integer(l), Value::Integer(r)) => l.checked_add(*r).map_or_else(
                    || {
                        Err(ESIError::ExpressionError(format!(
                            "Integer overflow in addition: {l} + {r}"
                        )))
                    },
                    |result| Ok(Value::Integer(result)),
                ),
                (Value::List(a), Value::List(b)) => {
                    let mut items = a.borrow().clone();
                    items.extend(b.borrow().iter().cloned());
                    Ok(Value::new_list(items))
                }
                _ => {
                    // String concatenation for all other type combinations
                    let result = format!("{left_val}{right_val}");
                    Ok(Value::Text(Bytes::from(result)))
                }
            }
        }
        Operator::Subtract => {
            if let (Value::Integer(l), Value::Integer(r)) = (left_val, right_val) {
                l.checked_sub(*r).map_or_else(
                    || {
                        Err(ESIError::ExpressionError(format!(
                            "Integer overflow in subtraction: {l} - {r}"
                        )))
                    },
                    |result| Ok(Value::Integer(result)),
                )
            } else {
                Err(ESIError::ExpressionError(format!(
                    "Subtraction requires numeric operands, got {left_val} - {right_val}"
                )))
            }
        }
        Operator::Multiply => {
            match (left_val, right_val) {
                (Value::Integer(l), Value::Integer(r)) => l.checked_mul(*r).map_or_else(
                    || {
                        Err(ESIError::ExpressionError(format!(
                            "Integer overflow in multiplication: {l} * {r}"
                        )))
                    },
                    |result| Ok(Value::Integer(result)),
                ),
                // String repetition: n * 'string' or 'string' * n
                (Value::Integer(n), Value::Text(s)) | (Value::Text(s), Value::Integer(n)) => {
                    if *n < 0 {
                        Err(ESIError::ExpressionError(format!(
                            "String repetition count must be non-negative, got {n}"
                        )))
                    } else {
                        let text = String::from_utf8_lossy(s.as_ref());
                        let result = text.repeat(*n as usize);
                        Ok(Value::Text(Bytes::from(result)))
                    }
                }
                // List repetition: n * [list] or [list] * n
                (Value::Integer(n), Value::List(items))
                | (Value::List(items), Value::Integer(n)) => {
                    if *n < 0 {
                        Err(ESIError::ExpressionError(format!(
                            "List repetition count must be non-negative, got {n}"
                        )))
                    } else {
                        let borrowed = items.borrow();
                        let mut result = Vec::with_capacity(borrowed.len() * (*n as usize));
                        for _ in 0..*n {
                            result.extend(borrowed.iter().cloned());
                        }
                        Ok(Value::new_list(result))
                    }
                }
                _ => Err(ESIError::ExpressionError(format!(
                    "Multiplication requires numeric operands, or integer with string/list, got {left_val} * {right_val}"
                ))),
            }
        }
        Operator::Divide => {
            if let (Value::Integer(l), Value::Integer(r)) = (left_val, right_val) {
                if *r == 0 {
                    Err(ESIError::ExpressionError(format!(
                        "Division by zero: {l} / 0"
                    )))
                } else {
                    Ok(Value::Integer(l / r))
                }
            } else {
                Err(ESIError::ExpressionError(format!(
                    "Division requires numeric operands, got {left_val} / {right_val}"
                )))
            }
        }
        Operator::Modulo => {
            if let (Value::Integer(l), Value::Integer(r)) = (left_val, right_val) {
                if *r == 0 {
                    Err(ESIError::ExpressionError(format!(
                        "Modulo by zero: {l} % 0"
                    )))
                } else {
                    Ok(Value::Integer(l % r))
                }
            } else {
                Err(ESIError::ExpressionError(format!(
                    "Modulo requires numeric operands, got {left_val} % {right_val}"
                )))
            }
        }
    }
}

/// Evaluation context for ESI expression processing
///
/// This context holds all runtime state needed during ESI document processing,
/// including variables, request metadata, response manipulation state, and cache tracking.
/// The context is mutable and updated as ESI directives are processed.
pub struct EvalContext {
    /// User-defined variables set by ESI assign directives
    vars: HashMap<String, Value>,
    /// Name of the variable to store regex match captures (default: "MATCHES")
    match_name: String,
    /// HTTP request metadata (method, path, headers, query params) for variable resolution
    request: Request,
    /// Custom headers to add to the response (set by $`add_header()` function)
    response_headers: Vec<(String, String)>,
    /// Last random value generated by $`rand()` function (for $`last_rand()` function)
    last_rand: Option<i32>,
    /// HTTP status code override (set by $`set_response_code()` or $`set_redirect()` functions)
    response_status: Option<i32>,
    /// Complete response body override (set by $`set_response_code()` function)
    response_body_override: Option<Bytes>,
    /// Cached parsed query string parameters (lazy-loaded for performance)
    query_params_cache: std::cell::RefCell<Option<HashMap<String, Vec<Bytes>>>>,
    /// Cached parsed HTTP headers (lazy-loaded for performance)
    http_headers_cache: std::cell::RefCell<HashMap<String, Option<HashMap<String, Value>>>>,
    /// Minimum TTL seen across all cached includes (in seconds) for rendered document cacheability
    min_ttl: Option<u32>,
    /// Flag indicating if the rendered document should not be cached (due to `private`/`no-cache`/`Set-Cookie` in any include)
    is_uncacheable: bool,
    /// Stack of function call arguments for user-defined functions (supports nested calls)
    args_stack: Vec<Vec<Value>>,
    /// Registry for user-defined ESI functions
    function_registry: FunctionRegistry,
    /// Maximum recursion depth for user-defined function calls (per ESI spec, default: 5)
    function_recursion_depth: usize,
}
impl Default for EvalContext {
    fn default() -> Self {
        Self {
            vars: HashMap::new(),
            match_name: VAR_MATCHES.to_string(),
            request: Request::new(Method::GET, URL_LOCALHOST),
            response_headers: Vec::new(),
            last_rand: None,
            response_status: None,
            response_body_override: None,
            query_params_cache: std::cell::RefCell::new(None),
            http_headers_cache: std::cell::RefCell::new(HashMap::new()),
            min_ttl: None,
            is_uncacheable: false,
            args_stack: Vec::new(),
            function_registry: FunctionRegistry::new(),
            function_recursion_depth: 5,
        }
    }
}
impl EvalContext {
    pub fn new() -> Self {
        Self::default()
    }
    pub fn new_with_vars(vars: HashMap<String, Value>) -> Self {
        Self {
            vars,
            ..Self::default()
        }
    }

    pub fn add_response_header(&mut self, name: String, value: String) {
        self.response_headers.push((name, value));
    }

    pub const fn set_last_rand(&mut self, v: i32) {
        self.last_rand = Some(v);
    }

    pub const fn last_rand(&self) -> Option<i32> {
        self.last_rand
    }

    pub fn response_headers(&self) -> &[(String, String)] {
        &self.response_headers
    }

    pub const fn set_response_status(&mut self, status: i32) {
        self.response_status = Some(status);
    }

    pub const fn response_status(&self) -> Option<i32> {
        self.response_status
    }

    pub fn set_response_body_override(&mut self, body: Option<Bytes>) {
        self.response_body_override = body;
    }

    pub const fn response_body_override(&self) -> Option<&Bytes> {
        self.response_body_override.as_ref()
    }

    fn parse_query_params(&self) -> HashMap<String, Vec<Bytes>> {
        let mut params: HashMap<String, Vec<Bytes>> = HashMap::new();

        if let Some(query) = self.request.get_query_str() {
            for pair in query.split('&') {
                if let Some((key, value)) = pair.split_once('=') {
                    params
                        .entry(key.to_string())
                        .or_default()
                        .push(Bytes::from(value.to_string()));
                } else if !pair.is_empty() {
                    // Handle keys without values (e.g., ?flag)
                    params
                        .entry(pair.to_string())
                        .or_default()
                        .push(Bytes::new());
                }
            }
        }

        params
    }

    fn get_query_params(&self) -> std::cell::Ref<'_, Option<HashMap<String, Vec<Bytes>>>> {
        if self.query_params_cache.borrow().is_none() {
            *self.query_params_cache.borrow_mut() = Some(self.parse_query_params());
        }
        self.query_params_cache.borrow()
    }

    fn parse_http_header(&self, header: &str) -> Option<HashMap<String, Value>> {
        let value = self.request.get_header(header)?.to_str().ok()?;

        // Cookie: semicolon-separated key=value pairs
        if header.eq_ignore_ascii_case("cookie") {
            let mut dict = HashMap::new();
            for pair in value.split(';') {
                let trimmed = pair.trim();
                if let Some((k, v)) = trimmed.split_once('=') {
                    dict.insert(
                        k.trim().to_string(),
                        Value::Text(v.trim().to_owned().into()),
                    );
                }
            }
            return if dict.is_empty() { None } else { Some(dict) };
        }

        // All other headers: comma-separated values (strip quality params like ;q=0.9)
        // Creates Dict where key=value for membership testing: {"gzip": "gzip", "br": "br"}
        let mut dict = HashMap::new();
        for item in value.split(',') {
            // Strip quality value: "gzip;q=0.9" -> "gzip"
            let item_value = item.split(';').next().unwrap_or("").trim();
            if !item_value.is_empty() {
                dict.insert(
                    item_value.to_string(),
                    Value::Text(item_value.to_owned().into()),
                );
            }
        }

        if dict.is_empty() {
            None // Plain text header
        } else {
            Some(dict)
        }
    }

    fn get_http_header_dict(
        &self,
        header: &str,
    ) -> std::cell::Ref<'_, HashMap<String, Option<HashMap<String, Value>>>> {
        // Check if we've already parsed this header
        if !self.http_headers_cache.borrow().contains_key(header) {
            let parsed = self.parse_http_header(header);
            self.http_headers_cache
                .borrow_mut()
                .insert(header.to_string(), parsed);
        }
        self.http_headers_cache.borrow()
    }

    pub fn get_variable(&self, key: &str, subkey: Option<&str>) -> Value {
        match key {
            VAR_ARGS => {
                // Handle $(ARGS) and $(ARGS{n})
                self.current_args().map_or_else(
                    || Value::Null,
                    |args| {
                        subkey.map_or_else(
                            || {
                                // $(ARGS) without subscript - return list of all arguments
                                Value::new_list(args.clone())
                            },
                            |sub| {
                                // $(ARGS{n}) - return nth argument (0-indexed per ESI spec)
                                sub.parse::<usize>().map_or(Value::Null, |index| {
                                    args.get(index).cloned().unwrap_or(Value::Null)
                                })
                            },
                        )
                    },
                )
            }
            VAR_REQUEST_METHOD => Value::Text(self.request.get_method_str().to_string().into()),
            VAR_REQUEST_PATH => Value::Text(self.request.get_path().to_string().into()),
            VAR_REMOTE_ADDR => Value::Text(
                self.request
                    .get_client_ip_addr()
                    .map_or_else(String::new, |ip| ip.to_string())
                    .into(),
            ),
            VAR_QUERY_STRING => {
                let params_ref = self.get_query_params();
                let Some(params) = params_ref.as_ref() else {
                    return Value::Null;
                };

                subkey.map_or_else(
                    || {
                        // Return Dict of all query params when no subkey specified
                        if params.is_empty() {
                            Value::Null
                        } else {
                            let mut dict = HashMap::with_capacity(params.len());
                            for (key, values) in params {
                                let value = match values.len() {
                                    0 => Value::Null,
                                    1 => Value::Text(values[0].clone()),
                                    _ => Value::new_list(
                                        values.iter().map(|v| Value::Text(v.clone())).collect(),
                                    ),
                                };
                                dict.insert(key.clone(), value);
                            }
                            Value::new_dict(dict)
                        }
                    },
                    // Look up the field in parsed params
                    |field| match params.get(field) {
                        None => Value::Null,
                        Some(values) if values.is_empty() => Value::Null,
                        Some(values) if values.len() == 1 => Value::Text(values[0].clone()),
                        Some(values) => {
                            Value::new_list(values.iter().map(|v| Value::Text(v.clone())).collect())
                        }
                    },
                )
            }
            _ if key.starts_with(VAR_HTTP_PREFIX) => {
                let header = key.strip_prefix(VAR_HTTP_PREFIX).unwrap_or_default();

                // Get raw header value
                let raw_value = self
                    .request
                    .get_header(header)
                    .and_then(|h| h.to_str().ok())
                    .unwrap_or("");

                if raw_value.is_empty() {
                    return Value::Null;
                }

                subkey.map_or_else(
                    || {
                        // Without subkey: return raw header value as Text
                        Value::Text(raw_value.to_owned().into())
                    },
                    |field| {
                        // With subkey: parse and look up specific field
                        let cache = self.get_http_header_dict(header);
                        if let Some(Some(dict)) = cache.get(header) {
                            dict.get(field).cloned().unwrap_or(Value::Null)
                        } else {
                            Value::Null
                        }
                    },
                )
            }
            _ => {
                let stored = self.vars.get(key).cloned().unwrap_or(Value::Null);
                match subkey {
                    None => stored,
                    Some(sub) => get_subvalue(&stored, sub),
                }
            }
        }
    }

    pub fn set_variable(&mut self, key: &str, subkey: Option<&str>, value: Value) -> Result<()> {
        if matches!(value, Value::Null) {
            return Ok(());
        }

        match subkey {
            None => {
                self.vars.insert(key.to_string(), value);
                Ok(())
            }
            Some(sub) => {
                // If variable exists and is a list with numeric subscript, handle list assignment
                // Otherwise create/use dict (dicts can have numeric string keys)
                let entry = self
                    .vars
                    .entry(key.to_string())
                    .or_insert_with(|| Value::new_dict(HashMap::new()));
                set_subvalue(entry, sub, value)
            }
        }
    }

    pub fn set_match_name(&mut self, match_name: &str) {
        self.match_name = match_name.to_string();
    }

    pub fn set_request(&mut self, request: Request) {
        self.request = request;
        // Clear cached query params and headers when request changes
        *self.query_params_cache.borrow_mut() = None;
        self.http_headers_cache.borrow_mut().clear();
    }

    pub const fn get_request(&self) -> &Request {
        &self.request
    }

    /// Update the minimum TTL for cache tracking
    pub fn update_cache_min_ttl(&mut self, ttl: u32) {
        self.min_ttl = Some(self.min_ttl.map_or(ttl, |current_min| current_min.min(ttl)));
    }

    /// Mark the rendered document as uncacheable (e.g., when an include has Set-Cookie or Cache-Control: private)
    pub const fn mark_document_uncacheable(&mut self) {
        self.is_uncacheable = true;
    }

    /// Get the cache control header value for the rendered document
    pub fn cache_control_header(&self, rendered_ttl: Option<u32>) -> Option<String> {
        // If any include was uncacheable (private, no-cache, set-cookie), mark document as uncacheable
        if self.is_uncacheable {
            return Some("private, no-cache".to_string());
        }
        let ttl = rendered_ttl.or(self.min_ttl)?;
        Some(format!("public, max-age={ttl}"))
    }

    /// Push a new set of function arguments onto the stack (for user-defined function calls)
    pub fn push_args(&mut self, args: Vec<Value>) {
        self.args_stack.push(args);
    }

    /// Pop the current function arguments from the stack
    pub fn pop_args(&mut self) {
        self.args_stack.pop();
    }

    /// Get the current function arguments (if any)
    pub fn current_args(&self) -> Option<&Vec<Value>> {
        self.args_stack.last()
    }

    /// Register a user-defined function
    pub fn register_function(&mut self, name: String, body: Vec<Element>) {
        self.function_registry.register(name, body);
    }

    /// Get a user-defined function body
    pub fn get_function(&self, name: &str) -> Option<&Vec<Element>> {
        self.function_registry.get(name)
    }

    /// Set maximum recursion depth for user-defined function calls
    pub const fn set_max_function_recursion_depth(&mut self, depth: usize) {
        self.function_recursion_depth = depth;
    }
}

impl<const N: usize> From<[(String, Value); N]> for EvalContext {
    fn from(data: [(String, Value); N]) -> Self {
        Self::new_with_vars(HashMap::from(data))
    }
}

fn get_subvalue(parent: &Value, subkey: &str) -> Value {
    if let Ok(idx) = subkey.parse::<usize>() {
        // Try list index first
        if let Value::List(items) = parent {
            return items.borrow().get(idx).cloned().unwrap_or(Value::Null);
        }

        // String-as-list: byte access by index — zero-copy via Bytes::slice
        if let Value::Text(s) = parent {
            return if idx < s.len() {
                Value::Text(s.slice(idx..=idx))
            } else {
                Value::Null
            };
        }
    }

    // Dict string-key lookup
    if let Value::Dict(map) = parent {
        return map.borrow().get(subkey).cloned().unwrap_or(Value::Null);
    }

    Value::Null
}

fn set_subvalue(parent: &mut Value, subkey: &str, value: Value) -> Result<()> {
    // Check if subscript is a numeric index
    if let Ok(idx) = subkey.parse::<usize>() {
        match parent {
            Value::List(items) => {
                let mut items = items.borrow_mut();
                // For existing lists, index must exist - no auto-expansion
                if idx >= items.len() {
                    return Err(ESIError::VariableError(format!(
                        "list index {} out of range (list has {} elements)",
                        idx,
                        items.len()
                    )));
                }
                items[idx] = value;
                return Ok(());
            }
            Value::Dict(map) => {
                // For dicts, numeric indices are just string keys - allow creation
                map.borrow_mut().insert(subkey.to_string(), value);
                return Ok(());
            }
            _ => {
                // Per ESI spec: cannot create list on the fly
                return Err(ESIError::VariableError(
                    "cannot create list on the fly - list must already exist".to_string(),
                ));
            }
        }
    }

    // Non-numeric subscript - dictionary key
    match parent {
        Value::Dict(map) => {
            map.borrow_mut().insert(subkey.to_string(), value);
            Ok(())
        }
        Value::List(_) => {
            // Per ESI spec: cannot assign string key to a list
            Err(ESIError::VariableError(
                "cannot assign string key to a list".to_string(),
            ))
        }
        _ => {
            // Create new dict for non-numeric keys (per ESI spec, dicts can be created on the fly)
            let mut map = HashMap::new();
            map.insert(subkey.to_string(), value);
            *parent = Value::new_dict(map);
            Ok(())
        }
    }
}

/// Represents a value in an ESI expression.
///
/// Values can be of different types:
/// - `Integer`: A 32-bit signed integer
/// - `String`: A UTF-8 string
/// - `Boolean`: A boolean value (true/false)
/// - `List`: A list of values (also used for dict iteration as 2-element lists)
/// - `Dict`: A dictionary/map of string keys to values
/// - `Null`: Represents an absence of value
#[derive(Debug, Clone)]
pub enum Value {
    Integer(i32),
    Text(Bytes),
    Boolean(bool),
    List(Rc<RefCell<Vec<Value>>>),
    Dict(Rc<RefCell<HashMap<String, Value>>>),
    Null,
}

impl PartialEq for Value {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Integer(a), Self::Integer(b)) => a == b,
            (Self::Text(a), Self::Text(b)) => a == b,
            (Self::Boolean(a), Self::Boolean(b)) => a == b,
            (Self::List(a), Self::List(b)) => *a.borrow() == *b.borrow(),
            (Self::Dict(a), Self::Dict(b)) => *a.borrow() == *b.borrow(),
            (Self::Null, Self::Null) => true,
            _ => false,
        }
    }
}

impl Eq for Value {}

impl Value {
    /// Create a new `Value::List` wrapping the given vec in `Rc<RefCell<…>>`.
    pub fn new_list(items: Vec<Self>) -> Self {
        Self::List(Rc::new(RefCell::new(items)))
    }

    /// Create a new `Value::Dict` wrapping the given map in `Rc<RefCell<…>>`.
    pub fn new_dict(map: HashMap<String, Self>) -> Self {
        Self::Dict(Rc::new(RefCell::new(map)))
    }

    /// Try to interpret this value as an `i32`.
    /// `ctx` is used only for error messages (typically the calling function name).
    pub fn as_i32(&self, ctx: &str) -> Result<i32> {
        match self {
            Self::Integer(i) => Ok(*i),
            Self::Text(b) => atoi::atoi::<i32>(b.as_ref().trim_ascii())
                .ok_or_else(|| ESIError::FunctionError(format!("{ctx}: invalid integer"))),
            Self::Null => Ok(0),
            _ => Err(ESIError::FunctionError(format!("{ctx}: invalid integer"))),
        }
    }

    /// Try to interpret this value as a `&str`.
    /// `ctx` is used only for error messages (typically the calling function name).
    pub fn as_str(&self, ctx: &str) -> Result<&str> {
        if let Self::Text(b) = self {
            std::str::from_utf8(b)
                .map_err(|_| ESIError::FunctionError(format!("{ctx}: invalid string")))
        } else {
            Err(ESIError::FunctionError(format!("{ctx}: invalid string")))
        }
    }

    pub(crate) fn to_bool(&self) -> bool {
        match self {
            &Self::Integer(n) => !matches!(n, 0),
            Self::Text(s) => !s.is_empty(),
            Self::Boolean(b) => *b,
            Self::List(items) => !items.borrow().is_empty(),
            Self::Dict(map) => !map.borrow().is_empty(),
            &Self::Null => false,
        }
    }

    /// Convert Value to Bytes - zero-copy for Text variant
    pub(crate) fn to_bytes(&self) -> Bytes {
        match self {
            Self::Integer(i) => Bytes::from(i.to_string()),
            Self::Text(b) => b.clone(), // Cheap refcount increment
            Self::Boolean(b) => {
                if *b {
                    Bytes::from_static(BOOL_TRUE)
                } else {
                    Bytes::from_static(BOOL_FALSE)
                }
            }
            Self::List(items) => Bytes::from(items_to_string(&items.borrow())),
            Self::Dict(map) => Bytes::from(dict_to_string(&map.borrow())),
            Self::Null => Bytes::new(),
        }
    }

    /// Returns the value as a `Cow<str>`, avoiding allocation when the inner
    /// bytes are valid UTF-8.  Prefer this over `to_string()` when only a
    /// `&str` reference is needed.
    pub fn as_cow_str(&self) -> Cow<'_, str> {
        match self {
            Self::Text(b) => String::from_utf8_lossy(b.as_ref()),
            _ => Cow::Owned(self.to_string()),
        }
    }
}

impl From<String> for Value {
    fn from(s: String) -> Self {
        Self::Text(Bytes::from(s))
    }
}

impl From<&str> for Value {
    fn from(s: &str) -> Self {
        // Copy the string data into a Bytes buffer
        // This is necessary because we can't guarantee the lifetime of &str
        Self::Text(Bytes::copy_from_slice(s.as_bytes()))
    }
}

impl From<Bytes> for Value {
    fn from(b: Bytes) -> Self {
        Self::Text(b)
    }
}

impl Display for Value {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Integer(i) => write!(f, "{i}"),
            Self::Text(b) => write!(f, "{}", String::from_utf8_lossy(b.as_ref())),
            Self::Boolean(b) => write!(f, "{}", if *b { "true" } else { "false" }),
            Self::List(items) => write!(f, "{}", items_to_string(&items.borrow())),
            Self::Dict(map) => write!(f, "{}", dict_to_string(&map.borrow())),
            Self::Null => Ok(()), // Empty string for Null
        }
    }
}

fn items_to_string(items: &[Value]) -> String {
    let mut out = String::new();
    for (i, v) in items.iter().enumerate() {
        if i > 0 {
            out.push(',');
        }
        out.push_str(&v.as_cow_str());
    }
    out
}

fn dict_to_string(map: &HashMap<String, Value>) -> String {
    let mut parts: Vec<_> = map
        .iter()
        .map(|(k, v)| format!("{k}={}", v.as_cow_str()))
        .collect();
    parts.sort();
    parts.join("&")
}

/// Element handler for user-defined function bodies.
///
/// Writes evaluated output to an in-memory `Vec<u8>`; signals `Return` or
/// `Break` back to the caller via `Flow`.
struct FunctionHandler<'a> {
    ctx: &'a mut EvalContext,
    output: &'a mut Vec<u8>,
}

impl ElementHandler for FunctionHandler<'_> {
    fn ctx(&mut self) -> &mut EvalContext {
        self.ctx
    }

    fn write_bytes(&mut self, bytes: bytes::Bytes) -> Result<()> {
        self.output.extend_from_slice(&bytes);
        Ok(())
    }

    /// Evaluate the return expression and signal an early exit from the function body.
    fn on_return(&mut self, value: &Expr) -> Result<Flow> {
        let val = eval_expr(value, self.ctx)?;
        Ok(Flow::Return(val))
    }

    /// Per ESI spec: `esi:include` is not allowed inside function bodies.
    fn on_include(&mut self, _attrs: &IncludeAttributes) -> Result<Flow> {
        Err(ESIError::FunctionError(
            "esi:include is not allowed in function bodies".to_string(),
        ))
    }

    /// Per ESI spec: `esi:eval` is not allowed inside function bodies.
    fn on_eval(&mut self, _attrs: &IncludeAttributes) -> Result<Flow> {
        Err(ESIError::FunctionError(
            "esi:eval is not allowed in function bodies".to_string(),
        ))
    }

    /// `esi:try` requires a dispatcher; silently ignore inside function bodies.
    fn on_try(
        &mut self,
        _attempt_events: Vec<Vec<Element>>,
        _except_events: Vec<Element>,
    ) -> Result<Flow> {
        // Try/Except would require dispatcher context which isn't available in expression evaluation
        // Silently ignore for now (could also error)
        Ok(Flow::Continue)
    }

    /// Per ESI spec: nested function definitions are not supported.
    fn on_function(&mut self, _name: String, _body: Vec<Element>) -> Result<Flow> {
        Err(ESIError::FunctionError(
            "esi:function is not allowed in function bodies (nested function definitions are not supported)".to_string(),
        ))
    }
}

/// Execute a user-defined ESI function
///
/// Processes the function body elements, handling variable assignments and return statements.
/// Functions can access arguments via $(ARGS) variable.
/// Enforces maximum recursion depth per ESI specification.
///
/// # Arguments
/// * `name` - Function name (for error messages)
/// * `body` - Function body elements to execute
/// * `args` - Function call arguments
/// * `ctx` - Evaluation context
///
/// # Returns
/// * `Result<Value>` - The return value (from <esi:return>) or accumulated text output
fn call_user_function(
    name: &str,
    body: &[Element],
    args: &[Value],
    ctx: &mut EvalContext,
) -> Result<Value> {
    // Check recursion depth before proceeding
    if ctx.args_stack.len() >= ctx.function_recursion_depth {
        return Err(ESIError::FunctionError(format!(
            "Maximum recursion depth ({}) exceeded for function '{}'",
            ctx.function_recursion_depth, name
        )));
    }

    // Push arguments onto the stack for $(ARGS) access
    ctx.push_args(args.to_vec());

    // Process function body via the shared ElementHandler trait, catching any
    // errors to ensure cleanup
    let result = (|| {
        let mut output = Vec::new();
        let mut handler = FunctionHandler {
            ctx,
            output: &mut output,
        };

        for element in body {
            match handler.process(element)? {
                Flow::Continue => continue,
                Flow::Return(value) => return Ok(value),
                Flow::Break => continue, // Break at top level - ignore
            }
        }

        // No explicit return - return accumulated output as text
        Ok(Value::Text(Bytes::from(output)))
    })();

    // Always pop arguments, even if there was an error
    ctx.pop_args();

    result
}

fn call_dispatch(identifier: &str, args: &[Value], ctx: &mut EvalContext) -> Result<Value> {
    // First check if this is a user-defined function
    // Clone the function body to avoid borrowing issues
    if let Some(function_body) = ctx.get_function(identifier).cloned() {
        return call_user_function(identifier, &function_body, args, ctx);
    }

    // Fall back to built-in functions
    match identifier {
        FN_LOWER => functions::lower(args),
        FN_UPPER => functions::upper(args),
        FN_HTML_ENCODE => functions::html_encode(args),
        FN_HTML_DECODE => functions::html_decode(args),
        FN_CONVERT_TO_UNICODE => functions::convert_to_unicode(args),
        FN_CONVERT_FROM_UNICODE => functions::convert_from_unicode(args),
        FN_REPLACE => functions::replace(args),
        FN_STR => functions::to_str(args),
        FN_LSTRIP => functions::lstrip(args),
        FN_RSTRIP => functions::rstrip(args),
        FN_STRIP => functions::strip(args),
        FN_SUBSTR => functions::substr(args),
        FN_DOLLAR => functions::dollar(args),
        FN_DQUOTE => functions::dquote(args),
        FN_SQUOTE => functions::squote(args),
        FN_BASE64_ENCODE => functions::base64_encode(args),
        FN_BASE64_DECODE => functions::base64_decode(args),
        FN_URL_ENCODE => functions::url_encode(args),
        FN_URL_DECODE => functions::url_decode(args),
        FN_EXISTS => functions::exists(args),
        FN_IS_EMPTY => functions::is_empty(args),
        FN_STRING_SPLIT => functions::string_split(args),
        FN_JOIN => functions::join(args),
        FN_LIST_DELITEM => functions::list_delitem(args),
        FN_INT => functions::int(args),
        FN_LEN => functions::len(args),
        FN_INDEX => functions::index(args),
        FN_RINDEX => functions::rindex(args),
        FN_DIGEST_MD5 => functions::digest_md5(args),
        FN_DIGEST_MD5_HEX => functions::digest_md5_hex(args),
        FN_BIN_INT => functions::bin_int(args),
        FN_TIME => functions::time(args),
        FN_HTTP_TIME => functions::http_time(args),
        FN_STRFTIME => functions::strftime(args),
        FN_RAND => functions::rand(args, ctx),
        FN_LAST_RAND => functions::last_rand(args, ctx),
        FN_ADD_HEADER => functions::add_header(args, ctx),
        FN_SET_RESPONSE_CODE => functions::set_response_code(args, ctx),
        FN_SET_REDIRECT => functions::set_redirect(args, ctx),
        _ => Err(ESIError::FunctionError(format!(
            "unknown function: {identifier}"
        ))),
    }
}

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

    // Helper function for testing expression evaluation
    // Parses and evaluates a raw expression string
    //
    // # Arguments
    // * `raw_expr` - Raw expression string to evaluate
    // * `ctx` - Evaluation context containing variables and state
    //
    // # Returns
    // * `Result<Value>` - The evaluated expression result or an error
    fn evaluate_expression(raw_expr: &str, ctx: &mut EvalContext) -> Result<Value> {
        let (_, expr) = crate::parser::parse_expression(raw_expr)
            .map_err(|e| ESIError::ParseError(format!("failed to parse expression: {e}")))?;
        eval_expr(&expr, ctx).map_err(|e| {
            ESIError::ExpressionError(format!("error occurred during expression evaluation: {e}"))
        })
    }

    #[test]
    fn test_eval_matches_comparison() -> Result<()> {
        let result = evaluate_expression(
            "$(hello) matches '^foo'",
            &mut EvalContext::from([("hello".to_string(), Value::Text("foobar".into()))]),
        )?;
        assert_eq!(result, Value::Boolean(true));
        Ok(())
    }
    #[test]
    fn test_eval_matches_i_comparison() -> Result<()> {
        let result = evaluate_expression(
            "$(hello) matches_i '^foo'",
            &mut EvalContext::from([("hello".to_string(), Value::Text("FOOBAR".into()))]),
        )?;
        assert_eq!(result, Value::Boolean(true));
        Ok(())
    }
    #[test]
    fn test_eval_matches_with_captures() -> Result<()> {
        let ctx = &mut EvalContext::from([("hello".to_string(), Value::Text("foobar".into()))]);

        let result = evaluate_expression("$(hello) matches '^(fo)o'", ctx)?;
        assert_eq!(result, Value::Boolean(true));

        let result = evaluate_expression("$(MATCHES{1})", ctx)?;
        assert_eq!(result, Value::Text("fo".into()));
        Ok(())
    }
    #[test]
    fn test_eval_matches_with_captures_and_match_name() -> Result<()> {
        let ctx = &mut EvalContext::from([("hello".to_string(), Value::Text("foobar".into()))]);

        ctx.set_match_name("my_custom_name");
        let result = evaluate_expression("$(hello) matches '^(fo)o'", ctx)?;
        assert_eq!(result, Value::Boolean(true));

        let result = evaluate_expression("$(my_custom_name{1})", ctx)?;
        assert_eq!(result, Value::Text("fo".into()));
        Ok(())
    }
    #[test]
    fn test_eval_matches_comparison_negative() -> Result<()> {
        let result = evaluate_expression(
            "$(hello) matches '^foo'",
            &mut EvalContext::from([("hello".to_string(), Value::Text("nope".into()))]),
        )?;
        assert_eq!(result, Value::Boolean(false));
        Ok(())
    }
    #[test]
    fn test_eval_lower_call() -> Result<()> {
        let result = evaluate_expression("$lower('FOO')", &mut EvalContext::new())?;
        assert_eq!(result, Value::Text("foo".into()));
        Ok(())
    }
    #[test]
    fn test_eval_html_encode_call() -> Result<()> {
        let result = evaluate_expression("$html_encode('a > b < c')", &mut EvalContext::new())?;
        assert_eq!(result, Value::Text("a &gt; b &lt; c".into()));
        Ok(())
    }
    #[test]
    fn test_eval_replace_call() -> Result<()> {
        let result = evaluate_expression(
            "$replace('abc-def-ghi-', '-', '==')",
            &mut EvalContext::new(),
        )?;
        assert_eq!(result, Value::Text("abc==def==ghi==".into()));
        Ok(())
    }
    #[test]
    fn test_eval_replace_call_with_empty_string() -> Result<()> {
        let result =
            evaluate_expression("$replace('abc-def-ghi-', '-', '')", &mut EvalContext::new())?;
        assert_eq!(result, Value::Text("abcdefghi".into()));
        Ok(())
    }

    #[test]
    fn test_eval_replace_call_with_count() -> Result<()> {
        let result = evaluate_expression(
            "$replace('abc-def-ghi-', '-', '==', 2)",
            &mut EvalContext::new(),
        )?;
        assert_eq!(result, Value::Text("abc==def==ghi-".into()));
        Ok(())
    }

    #[test]
    fn test_context_nested_vars() {
        let mut ctx = EvalContext::new();
        ctx.set_variable("foo", Some("bar"), Value::Text("baz".into()))
            .unwrap();
        assert_eq!(
            ctx.get_variable("foo", Some("bar")),
            Value::Text("baz".into())
        );

        // Per ESI spec: must create list first, then assign to indices
        ctx.set_variable(
            "arr",
            None,
            Value::new_list(vec![Value::Null, Value::Null, Value::Null]),
        )
        .unwrap();
        ctx.set_variable("arr", Some("0"), Value::Integer(1))
            .unwrap();
        ctx.set_variable("arr", Some("2"), Value::Integer(3))
            .unwrap();

        match ctx.get_variable("arr", None) {
            Value::List(items) => {
                let items = items.borrow();
                assert_eq!(items.len(), 3);
                assert_eq!(items[0], Value::Integer(1));
                assert_eq!(items[1], Value::Null);
                assert_eq!(items[2], Value::Integer(3));
            }
            other => panic!("Unexpected value: {:?}", other),
        }

        assert_eq!(ctx.get_variable("arr", Some("1")), Value::Null);
        assert_eq!(ctx.get_variable("arr", Some("2")), Value::Integer(3));
    }

    #[test]
    fn test_list_index_out_of_bounds() {
        let mut ctx = EvalContext::new();
        // Create a list with 3 elements
        ctx.set_variable(
            "colors",
            None,
            Value::new_list(vec![
                Value::Text("red".into()),
                Value::Text("blue".into()),
                Value::Text("green".into()),
            ]),
        )
        .unwrap();

        // Trying to assign to index 3 should fail (only indices 0, 1, 2 exist)
        let result = ctx.set_variable("colors", Some("3"), Value::Text("yellow".into()));
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("out of range"));
    }

    #[test]
    fn test_cannot_assign_string_key_to_list() {
        let mut ctx = EvalContext::new();
        // Create a list
        ctx.set_variable(
            "mylist",
            None,
            Value::new_list(vec![Value::Integer(1), Value::Integer(2)]),
        )
        .unwrap();

        // Trying to assign a string key to a list should fail
        let result = ctx.set_variable("mylist", Some("foo"), Value::Text("bar".into()));
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("cannot assign string key to a list"));
    }

    #[test]
    fn test_dict_created_on_fly() {
        let mut ctx = EvalContext::new();
        // Assign to non-existent variable with string key - should create dict
        ctx.set_variable("ages", Some("bob"), Value::Integer(34))
            .unwrap();
        ctx.set_variable("ages", Some("joan"), Value::Integer(28))
            .unwrap();

        // Verify retrieval
        let bob_age = ctx.get_variable("ages", Some("bob"));
        assert_eq!(bob_age, Value::Integer(34), "Should retrieve bob's age");

        let joan_age = ctx.get_variable("ages", Some("joan"));
        assert_eq!(joan_age, Value::Integer(28), "Should retrieve joan's age");

        // Verify the dict itself
        let ages_dict = ctx.get_variable("ages", None);
        if let Value::Dict(map) = ages_dict {
            let map = map.borrow();
            assert_eq!(map.len(), 2, "Dict should have 2 keys");
            assert_eq!(map.get("bob"), Some(&Value::Integer(34)));
            assert_eq!(map.get("joan"), Some(&Value::Integer(28)));
        } else {
            panic!("ages should be a Dict, got {:?}", ages_dict);
        }
    }

    #[test]
    fn test_eval_get_request_method() -> Result<()> {
        let mut ctx = EvalContext::new();
        let result = evaluate_expression("$(REQUEST_METHOD)", &mut ctx)?;
        assert_eq!(result, Value::Text("GET".into()));
        Ok(())
    }

    #[test]
    fn test_nested_lists() -> Result<()> {
        let mut ctx = EvalContext::new();
        // Test nested list literal: [ 'one', [ 'a', 'x', 'c' ], 'three' ]
        let result = evaluate_expression("[ 'one', [ 'a', 'x', 'c' ], 'three' ]", &mut ctx)?;

        match result {
            Value::List(items) => {
                let items = items.borrow();
                assert_eq!(items.len(), 3);
                assert_eq!(items[0], Value::Text("one".into()));
                assert_eq!(items[2], Value::Text("three".into()));

                // Check nested list
                match &items[1] {
                    Value::List(nested) => {
                        let nested = nested.borrow();
                        assert_eq!(nested.len(), 3);
                        assert_eq!(nested[0], Value::Text("a".into()));
                        assert_eq!(nested[1], Value::Text("x".into()));
                        assert_eq!(nested[2], Value::Text("c".into()));
                    }
                    other => panic!("Expected nested list, got {:?}", other),
                }
            }
            other => panic!("Expected list, got {:?}", other),
        }
        Ok(())
    }

    #[test]
    fn test_eval_get_request_path() -> Result<()> {
        let mut ctx = EvalContext::new();
        ctx.set_request(Request::new(Method::GET, "http://localhost/hello/there"));

        let result = evaluate_expression("$(REQUEST_PATH)", &mut ctx)?;
        assert_eq!(result, Value::Text("/hello/there".into()));
        Ok(())
    }
    #[test]
    fn test_eval_get_request_query() -> Result<()> {
        let mut ctx = EvalContext::new();
        ctx.set_request(Request::new(Method::GET, "http://localhost?hello"));

        let result = evaluate_expression("$(QUERY_STRING)", &mut ctx)?;
        // Should return Dict with one entry: "hello" -> empty Text
        match result {
            Value::Dict(map) => {
                let map = map.borrow();
                assert_eq!(map.len(), 1);
                assert_eq!(map.get("hello"), Some(&Value::Text(Bytes::new())));
            }
            other => panic!("Expected Dict, got {:?}", other),
        }
        Ok(())
    }
    #[test]
    fn test_eval_get_request_query_field() -> Result<()> {
        let mut ctx = EvalContext::new();
        ctx.set_request(Request::new(Method::GET, "http://localhost?hello=goodbye"));

        let result = evaluate_expression("$(QUERY_STRING{'hello'})", &mut ctx)?;
        assert_eq!(result, Value::Text("goodbye".into()));
        let result = evaluate_expression("$(QUERY_STRING{'nonexistent'})", &mut ctx)?;
        assert_eq!(result, Value::Null);
        Ok(())
    }
    #[test]
    fn test_eval_get_request_query_field_unquoted() -> Result<()> {
        let mut ctx = EvalContext::new();
        ctx.set_request(Request::new(Method::GET, "http://localhost?hello=goodbye"));

        let result = evaluate_expression("$(QUERY_STRING{hello})", &mut ctx)?;
        assert_eq!(result, Value::Text("goodbye".into()));
        let result = evaluate_expression("$(QUERY_STRING{nonexistent})", &mut ctx)?;
        assert_eq!(result, Value::Null);
        Ok(())
    }
    #[test]
    fn test_eval_get_request_query_duplicate_params() -> Result<()> {
        let mut ctx = EvalContext::new();
        ctx.set_request(Request::new(
            Method::GET,
            "http://localhost?x=1&x=2&x=3&y=single",
        ));

        // Multiple values for 'x' should return a List
        let result = evaluate_expression("$(QUERY_STRING{x})", &mut ctx)?;
        match result {
            Value::List(items) => {
                let items = items.borrow();
                assert_eq!(items.len(), 3);
                assert_eq!(items[0], Value::Text("1".into()));
                assert_eq!(items[1], Value::Text("2".into()));
                assert_eq!(items[2], Value::Text("3".into()));
            }
            other => panic!("Expected List, got {:?}", other),
        }

        // Single value for 'y' should return Text
        let result = evaluate_expression("$(QUERY_STRING{y})", &mut ctx)?;
        assert_eq!(result, Value::Text("single".into()));

        // No subkey should return Dict with all params
        let result = evaluate_expression("$(QUERY_STRING)", &mut ctx)?;

        // Verify stringification uses & separator (clone before match to avoid borrow issues)
        let stringified = result.to_string();
        assert!(stringified.contains("&"));
        // The list [1,2,3] stringifies as "1,2,3", so we get "x=1,2,3&y=single" (or reversed due to HashMap)
        assert!(stringified == "x=1,2,3&y=single" || stringified == "y=single&x=1,2,3");

        match result {
            Value::Dict(map) => {
                let map = map.borrow();
                assert_eq!(map.len(), 2);
                // 'x' should be a list
                match map.get("x") {
                    Some(Value::List(items)) => {
                        let items = items.borrow();
                        assert_eq!(items.len(), 3);
                        assert_eq!(items[0], Value::Text("1".into()));
                        assert_eq!(items[1], Value::Text("2".into()));
                        assert_eq!(items[2], Value::Text("3".into()));
                    }
                    other => panic!("Expected List for 'x', got {:?}", other),
                }
                // 'y' should be text
                assert_eq!(map.get("y"), Some(&Value::Text("single".into())));
            }
            other => panic!("Expected Dict, got {:?}", other),
        }

        Ok(())
    }
    #[test]
    fn test_eval_get_remote_addr() -> Result<()> {
        // This is kind of a useless test as this will always return an empty string.
        let mut ctx = EvalContext::new();
        ctx.set_request(Request::new(Method::GET, "http://localhost?hello"));

        let result = evaluate_expression("$(REMOTE_ADDR)", &mut ctx)?;
        assert_eq!(result, Value::Text("".into()));
        Ok(())
    }
    #[test]
    fn test_eval_get_header() -> Result<()> {
        // This is kind of a useless test as this will always return an empty string.
        let mut ctx = EvalContext::new();
        let mut req = Request::new(Method::GET, URL_LOCALHOST);
        req.set_header("host", "hello.com");
        req.set_header("foobar", "baz");
        ctx.set_request(req);

        let result = evaluate_expression("$(HTTP_HOST)", &mut ctx)?;
        assert_eq!(result, Value::Text("hello.com".into()));
        let result = evaluate_expression("$(HTTP_FOOBAR)", &mut ctx)?;
        assert_eq!(result, Value::Text("baz".into()));
        Ok(())
    }
    #[test]
    fn test_eval_get_header_field() -> Result<()> {
        // This is kind of a useless test as this will always return an empty string.
        let mut ctx = EvalContext::new();
        let mut req = Request::new(Method::GET, URL_LOCALHOST);
        req.set_header("Cookie", "foo=bar; bar=baz");
        ctx.set_request(req);

        let result = evaluate_expression("$(HTTP_COOKIE{'foo'})", &mut ctx)?;
        assert_eq!(result, Value::Text("bar".into()));
        let result = evaluate_expression("$(HTTP_COOKIE{'bar'})", &mut ctx)?;
        assert_eq!(result, Value::Text("baz".into()));
        let result = evaluate_expression("$(HTTP_COOKIE{'baz'})", &mut ctx)?;
        assert_eq!(result, Value::Null);
        Ok(())
    }

    #[test]
    fn test_eval_get_header_as_dict() -> Result<()> {
        let mut ctx = EvalContext::new();
        let mut req = Request::new(Method::GET, URL_LOCALHOST);
        req.set_header("Cookie", "id=571; visits=42");
        ctx.set_request(req);

        // Without subkey, should return raw Text
        let result = evaluate_expression("$(HTTP_COOKIE)", &mut ctx)?;
        assert_eq!(result, Value::Text("id=571; visits=42".into()));

        // With subkey, should parse and return the field value
        let result = evaluate_expression("$(HTTP_COOKIE{'visits'})", &mut ctx)?;
        assert_eq!(result, Value::Text("42".into()));

        let result = evaluate_expression("$(HTTP_COOKIE{'id'})", &mut ctx)?;
        assert_eq!(result, Value::Text("571".into()));

        // Non-existent field returns Null
        let result = evaluate_expression("$(HTTP_COOKIE{'nonexistent'})", &mut ctx)?;
        assert_eq!(result, Value::Null);

        // Plain text headers still work
        let mut req2 = Request::new(Method::GET, URL_LOCALHOST);
        req2.set_header("host", "example.com");
        ctx.set_request(req2);
        let result = evaluate_expression("$(HTTP_HOST)", &mut ctx)?;
        assert_eq!(result, Value::Text("example.com".into()));

        Ok(())
    }

    #[test]
    fn test_string_as_list_character_access() -> Result<()> {
        let mut ctx = EvalContext::new();
        ctx.set_variable("a_string", None, Value::Text("abcde".into()))?;

        // Access individual characters by index
        let result = evaluate_expression("$(a_string{0})", &mut ctx)?;
        assert_eq!(result, Value::Text("a".into()));

        let result = evaluate_expression("$(a_string{3})", &mut ctx)?;
        assert_eq!(result, Value::Text("d".into()));

        let result = evaluate_expression("$(a_string{4})", &mut ctx)?;
        assert_eq!(result, Value::Text("e".into()));

        // Out of bounds returns Null
        let result = evaluate_expression("$(a_string{10})", &mut ctx)?;
        assert_eq!(result, Value::Null);

        Ok(())
    }

    #[test]
    fn test_logical_operators_with_parentheses() {
        let mut ctx = EvalContext::new();

        // Test (1==1)|('abc'=='def')
        let result = evaluate_expression("(1==1)|('abc'=='def')", &mut ctx).unwrap();
        assert_eq!(result.to_string(), "true");

        // Test (4!=5)&(4==5)
        let result = evaluate_expression("(4!=5)&(4==5)", &mut ctx).unwrap();
        assert_eq!(result.to_string(), "false");
    }
    #[test]
    fn test_negation_operations() -> Result<()> {
        let mut ctx = EvalContext::new();

        // Test simple negation
        assert_eq!(
            evaluate_expression("!(1 == 2)", &mut ctx)?,
            Value::Boolean(true)
        );
        assert_eq!(
            evaluate_expression("!(1 == 1)", &mut ctx)?,
            Value::Boolean(false)
        );

        // Test negation with other operators
        assert_eq!(
            evaluate_expression("!('a' <= 'c')", &mut ctx)?,
            Value::Boolean(false)
        );
        // Test double negation
        assert_eq!(
            evaluate_expression("!!(1 == 1)", &mut ctx)?,
            Value::Boolean(true)
        );
        // Test complex logical expressions with parentheses
        assert_eq!(
            evaluate_expression("!((1==1)&(2==2))", &mut ctx)?,
            Value::Boolean(false)
        );
        assert_eq!(
            evaluate_expression("(!(1==1))|(!(2!=2))", &mut ctx)?,
            Value::Boolean(true)
        );

        Ok(())
    }
    #[test]
    fn test_bool_coercion() -> Result<()> {
        assert!(Value::Boolean(true).to_bool());
        assert!(!Value::Boolean(false).to_bool());
        assert!(Value::Integer(1).to_bool());
        assert!(!Value::Integer(0).to_bool());
        assert!(!Value::Text("".into()).to_bool());
        assert!(Value::Text("hello".into()).to_bool());
        assert!(!Value::Null.to_bool());

        Ok(())
    }
    #[test]
    fn test_numeric_vs_lexicographic_comparison() -> Result<()> {
        // ESI spec: "If both operands are numeric, the expression is evaluated numerically.
        // If either binary operand is non-numeric, both operands are evaluated lexicographically as strings."

        // Both numeric - numeric comparison
        let result = evaluate_expression("5 > 3", &mut EvalContext::new())?;
        assert_eq!(result, Value::Boolean(true));

        let result = evaluate_expression("10 == 10", &mut EvalContext::new())?;
        assert_eq!(result, Value::Boolean(true));

        // Both strings - lexicographic comparison
        let result = evaluate_expression("'5' > '3'", &mut EvalContext::new())?;
        assert_eq!(result, Value::Boolean(true)); // "5" > "3" lexicographically

        let result = evaluate_expression("'10' < '9'", &mut EvalContext::new())?;
        assert_eq!(result, Value::Boolean(true)); // "10" < "9" lexicographically (starts with "1")

        // Mixed (numeric and string) - lexicographic comparison
        // When one operand is numeric and one is string, both are compared as strings
        let mut ctx = EvalContext::new();
        ctx.set_variable("numVar", None, Value::Integer(10))
            .unwrap();
        let result = evaluate_expression("$(numVar) > '9'", &mut ctx)?;
        // "10" > "9" lexicographically = false (because "1" < "9")
        assert_eq!(result, Value::Boolean(false));

        // String versions that look numeric
        let result = evaluate_expression("'10' == '10'", &mut EvalContext::new())?;
        assert_eq!(result, Value::Boolean(true));

        // Per spec: "a version reported as 3.01.23 or 1.05a will not test as a number"
        // These should be treated as strings, not parsed as numbers
        // Store version string in variable and compare - proves it's not parsed as number
        let mut ctx = EvalContext::new();
        ctx.set_variable("version", None, Value::Text("3.01.23".into()))
            .unwrap();
        // Compare "3.01.23" stored as a text value with "3.01.23" literal - should be equal
        // This proves stored text values are not coerced to numbers
        let result = evaluate_expression("$(version) == '3.01.23'", &mut ctx)?;
        assert_eq!(result, Value::Boolean(true));

        // Test that version string comparison is lexicographic, not numeric
        // If parsed as number: 3.01 < 3.2 would be TRUE
        // As string: "3.01.23" < "3.2" is FALSE (lexicographic: after "3.", '0' < '2' is true,
        // but we compare "01.23" vs "2", and "01.23" > "2" because '0' > nothing after '2')
        ctx.set_variable("version", None, Value::Text("3.01.23".into()))
            .unwrap();
        let result = evaluate_expression("$(version) < '3.2'", &mut ctx)?;
        assert_eq!(result, Value::Boolean(true)); // Lexicographic: "3.01.23" < "3.2"

        // Test lexicographic comparison of version strings (not numeric parsing)
        // '2.0' < '10.0' is FALSE lexicographically (because '2' > '1')
        // but would be TRUE if parsed numerically (2.0 < 10.0)
        let result = evaluate_expression("'2.0' < '10.0'", &mut EvalContext::new())?;
        assert_eq!(result, Value::Boolean(false)); // Lexicographic: '2' > '1'

        Ok(())
    }

    #[test]
    fn test_empty_null_undefined_evaluate_to_false() -> Result<()> {
        // ESI spec: "If any operand is empty or undefined, the expression is evaluated to be false."

        // Empty string evaluates to false
        let mut ctx = EvalContext::new();
        ctx.set_variable("empty", None, Value::Text("".into()))
            .unwrap();
        let result = evaluate_expression("$(empty)", &mut ctx)?;
        assert_eq!(result.to_bool(), false);

        // Null evaluates to false
        let result = evaluate_expression("$(nonexistent)", &mut EvalContext::new())?;
        assert_eq!(result, Value::Null);
        assert_eq!(result.to_bool(), false);

        // Empty in logical expressions
        let result = evaluate_expression("'' & 'something'", &mut EvalContext::new())?;
        assert_eq!(result, Value::Boolean(false));

        let result = evaluate_expression("'' | 'something'", &mut EvalContext::new())?;
        assert_eq!(result, Value::Boolean(true));

        // Zero evaluates to false (per to_bool implementation)
        let result = evaluate_expression("0", &mut EvalContext::new())?;
        assert_eq!(result.to_bool(), false);

        let result = evaluate_expression("1", &mut EvalContext::new())?;
        assert_eq!(result.to_bool(), true);

        Ok(())
    }

    #[test]
    fn test_triple_quoted_strings() -> Result<()> {
        // ESI spec: "Single or triple (three single) quotes must be used to delimit string literals"

        // Single quotes
        let result = evaluate_expression("'hello'", &mut EvalContext::new())?;
        assert_eq!(result, Value::Text("hello".into()));

        // Triple quotes
        let result = evaluate_expression("'''hello'''", &mut EvalContext::new())?;
        assert_eq!(result, Value::Text("hello".into()));

        // Triple quotes with single quotes inside
        let result = evaluate_expression("'''it's working'''", &mut EvalContext::new())?;
        assert_eq!(result, Value::Text("it's working".into()));

        // Comparison using triple quotes
        let result = evaluate_expression("'''test''' == 'test'", &mut EvalContext::new())?;
        assert_eq!(result, Value::Boolean(true));

        Ok(())
    }
    #[test]
    fn test_string_coercion() -> Result<()> {
        assert_eq!(Value::Boolean(true).to_string(), "true");
        assert_eq!(Value::Boolean(false).to_string(), "false");
        assert_eq!(Value::Integer(1).to_string(), "1");
        assert_eq!(Value::Integer(0).to_string(), "0");
        assert_eq!(Value::Text("".into()).to_string(), "");
        assert_eq!(Value::Text("hello".into()).to_string(), "hello");
        assert_eq!(Value::Null.to_string(), ""); // Null converts to empty string

        Ok(())
    }
    #[test]
    fn test_get_variable_query_string() {
        let mut ctx = EvalContext::new();
        let req = Request::new(Method::GET, "http://localhost?param=value");
        ctx.set_request(req);

        // Test without subkey - should return Dict
        let result = ctx.get_variable("QUERY_STRING", None);
        match result {
            Value::Dict(map) => {
                let map = map.borrow();
                assert_eq!(map.len(), 1);
                assert_eq!(map.get("param"), Some(&Value::Text("value".into())));
            }
            other => panic!("Expected Dict, got {:?}", other),
        }

        // Test with subkey
        let result = ctx.get_variable("QUERY_STRING", Some("param"));
        assert_eq!(result, Value::Text("value".into()));

        // Test with non-existent subkey
        let result = ctx.get_variable("QUERY_STRING", Some("nonexistent"));
        assert_eq!(result, Value::Null);
    }

    #[test]
    fn test_cache_control_header_uncacheable() {
        let mut ctx = EvalContext::new();

        // Test that marking document uncacheable returns private, no-cache
        ctx.mark_document_uncacheable();
        assert_eq!(
            ctx.cache_control_header(None),
            Some("private, no-cache".to_string())
        );

        // Even with rendered_ttl set, uncacheable should take precedence
        assert_eq!(
            ctx.cache_control_header(Some(600)),
            Some("private, no-cache".to_string())
        );
    }

    #[test]
    fn test_cache_control_header_with_min_ttl() {
        let mut ctx = EvalContext::new();

        // Test with no TTL set
        assert_eq!(ctx.cache_control_header(None), None);

        // Test with min_ttl set
        ctx.update_cache_min_ttl(300);
        assert_eq!(
            ctx.cache_control_header(None),
            Some("public, max-age=300".to_string())
        );

        // Test with rendered_ttl override
        assert_eq!(
            ctx.cache_control_header(Some(600)),
            Some("public, max-age=600".to_string())
        );

        // Test that min_ttl tracks minimum across updates
        ctx.update_cache_min_ttl(600);
        ctx.update_cache_min_ttl(200);
        assert_eq!(
            ctx.cache_control_header(None),
            Some("public, max-age=200".to_string())
        );
    }

    #[test]
    fn test_range_operator_ascending() -> Result<()> {
        let result = evaluate_expression("[1..5]", &mut EvalContext::new())?;
        assert_eq!(
            result,
            Value::new_list(vec![
                Value::Integer(1),
                Value::Integer(2),
                Value::Integer(3),
                Value::Integer(4),
                Value::Integer(5),
            ])
        );
        Ok(())
    }

    #[test]
    fn test_range_operator_descending() -> Result<()> {
        let result = evaluate_expression("[5..1]", &mut EvalContext::new())?;
        assert_eq!(
            result,
            Value::new_list(vec![
                Value::Integer(5),
                Value::Integer(4),
                Value::Integer(3),
                Value::Integer(2),
                Value::Integer(1),
            ])
        );
        Ok(())
    }

    #[test]
    fn test_range_operator_single_element() -> Result<()> {
        let result = evaluate_expression("[3..3]", &mut EvalContext::new())?;
        assert_eq!(result, Value::new_list(vec![Value::Integer(3)]));
        Ok(())
    }

    #[test]
    fn test_range_operator_with_variables() -> Result<()> {
        let result = evaluate_expression(
            "[$(start)..$(end)]",
            &mut EvalContext::from([
                ("start".to_string(), Value::Integer(1)),
                ("end".to_string(), Value::Integer(10)),
            ]),
        )?;
        assert_eq!(
            result,
            Value::new_list(vec![
                Value::Integer(1),
                Value::Integer(2),
                Value::Integer(3),
                Value::Integer(4),
                Value::Integer(5),
                Value::Integer(6),
                Value::Integer(7),
                Value::Integer(8),
                Value::Integer(9),
                Value::Integer(10),
            ])
        );
        Ok(())
    }

    #[test]
    fn test_range_operator_in_expression() -> Result<()> {
        // Test that range can be part of a list literal expression
        let result = evaluate_expression("[1..3]", &mut EvalContext::new())?;
        if let Value::List(items) = result {
            let items = items.borrow();
            assert_eq!(items.len(), 3);
            assert_eq!(items[0], Value::Integer(1));
            assert_eq!(items[1], Value::Integer(2));
            assert_eq!(items[2], Value::Integer(3));
        } else {
            panic!("Expected a list");
        }
        Ok(())
    }

    #[test]
    fn test_range_operator_negative_numbers() -> Result<()> {
        let result = evaluate_expression("[-2..2]", &mut EvalContext::new())?;
        assert_eq!(
            result,
            Value::new_list(vec![
                Value::Integer(-2),
                Value::Integer(-1),
                Value::Integer(0),
                Value::Integer(1),
                Value::Integer(2),
            ])
        );
        Ok(())
    }

    #[test]
    fn test_range_operator_requires_integers() {
        let result = evaluate_expression("['a'..'z']", &mut EvalContext::new());
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("requires integer operands"));
    }

    #[test]
    fn test_args_variable_no_args() -> Result<()> {
        // Without any args pushed, ARGS should be null
        let ctx = &mut EvalContext::new();
        let result = ctx.get_variable("ARGS", None);
        assert_eq!(result, Value::Null);
        Ok(())
    }

    #[test]
    fn test_args_variable_with_args() -> Result<()> {
        // Push some arguments and test ARGS access
        let mut ctx = EvalContext::new();
        ctx.push_args(vec![
            Value::Text("hello".into()),
            Value::Integer(42),
            Value::Text("world".into()),
        ]);

        // Test $(ARGS) - should return list of all arguments
        let result = ctx.get_variable("ARGS", None);
        if let Value::List(items) = result {
            let items = items.borrow();
            assert_eq!(items.len(), 3);
            assert_eq!(items[0], Value::Text("hello".into()));
            assert_eq!(items[1], Value::Integer(42));
            assert_eq!(items[2], Value::Text("world".into()));
        } else {
            panic!("Expected a list");
        }

        // Test $(ARGS{0}) - should return first argument (0-indexed per ESI spec)
        let result = ctx.get_variable("ARGS", Some("0"));
        assert_eq!(result, Value::Text("hello".into()));

        // Test $(ARGS{1}) - should return second argument
        let result = ctx.get_variable("ARGS", Some("1"));
        assert_eq!(result, Value::Integer(42));

        // Test $(ARGS{2}) - should return third argument
        let result = ctx.get_variable("ARGS", Some("2"));
        assert_eq!(result, Value::Text("world".into()));

        // Test $(ARGS{3}) - out of bounds, should be null
        let result = ctx.get_variable("ARGS", Some("3"));
        assert_eq!(result, Value::Null);

        // Test $(ARGS{4}) - out of bounds, should be null
        let result = ctx.get_variable("ARGS", Some("4"));
        assert_eq!(result, Value::Null);

        // Pop arguments
        ctx.pop_args();

        // After popping, ARGS should be null again
        let result = ctx.get_variable("ARGS", None);
        assert_eq!(result, Value::Null);

        Ok(())
    }

    #[test]
    fn test_args_variable_nested_calls() -> Result<()> {
        // Test nested function calls with different args
        let mut ctx = EvalContext::new();

        // First call with args [10, 20]
        ctx.push_args(vec![Value::Integer(10), Value::Integer(20)]);
        let result = ctx.get_variable("ARGS", Some("1"));
        assert_eq!(result, Value::Integer(20));

        // Nested call with args [30, 40, 50]
        ctx.push_args(vec![
            Value::Integer(30),
            Value::Integer(40),
            Value::Integer(50),
        ]);
        let result = ctx.get_variable("ARGS", Some("0"));
        assert_eq!(result, Value::Integer(30));
        let result = ctx.get_variable("ARGS", Some("2"));
        assert_eq!(result, Value::Integer(50));

        // Pop nested call
        ctx.pop_args();

        // Should be back to first call's args
        let result = ctx.get_variable("ARGS", Some("0"));
        assert_eq!(result, Value::Integer(10));
        let result = ctx.get_variable("ARGS", Some("1"));
        assert_eq!(result, Value::Integer(20));

        Ok(())
    }

    // --- Tests for checked arithmetic (integer overflow protection) ---

    #[test]
    fn test_integer_overflow_add() {
        let ctx = &mut EvalContext::default();
        let result = evaluate_expression(&format!("{} + 1", i64::MAX), ctx);
        assert!(result.is_err(), "i64::MAX + 1 should overflow");
    }

    #[test]
    fn test_integer_overflow_sub() {
        let ctx = &mut EvalContext::default();
        let result = evaluate_expression(&format!("{} - 1", i64::MIN), ctx);
        assert!(result.is_err(), "i64::MIN - 1 should overflow");
    }

    #[test]
    fn test_integer_overflow_mul() {
        let ctx = &mut EvalContext::default();
        let result = evaluate_expression(&format!("{} * 2", i64::MAX), ctx);
        assert!(result.is_err(), "i64::MAX * 2 should overflow");
    }

    #[test]
    fn test_integer_no_overflow() -> Result<()> {
        let ctx = &mut EvalContext::default();
        let result = evaluate_expression("100 + 200", ctx)?;
        assert_eq!(result, Value::Integer(300));
        let result = evaluate_expression("100 - 200", ctx)?;
        assert_eq!(result, Value::Integer(-100));
        let result = evaluate_expression("100 * 200", ctx)?;
        assert_eq!(result, Value::Integer(20000));
        Ok(())
    }

    // --- Tests for short-circuit And/Or ---

    #[test]
    fn test_short_circuit_and_false() -> Result<()> {
        // 0 (false) & anything — should short-circuit
        let ctx = &mut EvalContext::default();
        let result = evaluate_expression("0 & 1", ctx)?;
        assert_eq!(result, Value::Boolean(false));
        Ok(())
    }

    #[test]
    fn test_short_circuit_or_true() -> Result<()> {
        // 1 (true) | anything — should short-circuit
        let ctx = &mut EvalContext::default();
        let result = evaluate_expression("1 | 0", ctx)?;
        assert_eq!(result, Value::Boolean(true));
        Ok(())
    }

    #[test]
    fn test_and_both_true() -> Result<()> {
        let ctx = &mut EvalContext::default();
        let result = evaluate_expression("1 & 1", ctx)?;
        assert_eq!(result, Value::Boolean(true));
        Ok(())
    }

    #[test]
    fn test_or_both_false() -> Result<()> {
        let ctx = &mut EvalContext::default();
        let result = evaluate_expression("0 | 0", ctx)?;
        assert_eq!(result, Value::Boolean(false));
        Ok(())
    }

    // --- Tests for + (list concatenation) ---

    #[test]
    fn test_list_concatenation() -> Result<()> {
        let ctx = &mut EvalContext::from([
            (
                "a".to_string(),
                Value::new_list(vec![Value::Integer(1), Value::Integer(2)]),
            ),
            (
                "b".to_string(),
                Value::new_list(vec![Value::Integer(3), Value::Integer(4)]),
            ),
        ]);
        let result = evaluate_expression("$(a) + $(b)", ctx)?;
        if let Value::List(items) = result {
            let items = items.borrow();
            assert_eq!(items.len(), 4);
            assert_eq!(items[0], Value::Integer(1));
            assert_eq!(items[1], Value::Integer(2));
            assert_eq!(items[2], Value::Integer(3));
            assert_eq!(items[3], Value::Integer(4));
        } else {
            panic!("Expected list, got {result:?}");
        }
        Ok(())
    }

    #[test]
    fn test_list_concat_does_not_alias() -> Result<()> {
        // Concatenating two lists should produce a new list, not alias either input
        let ctx = &mut EvalContext::from([
            ("a".to_string(), Value::new_list(vec![Value::Integer(1)])),
            ("b".to_string(), Value::new_list(vec![Value::Integer(2)])),
        ]);
        let result = evaluate_expression("$(a) + $(b)", ctx)?;
        if let Value::List(items) = &result {
            assert_eq!(items.borrow().len(), 2);
        } else {
            panic!("Expected list");
        }
        // Original lists should be unchanged
        let a = ctx.get_variable("a", None);
        if let Value::List(items) = a {
            assert_eq!(items.borrow().len(), 1);
        } else {
            panic!("Expected list for a");
        }
        Ok(())
    }

    // --- Tests for * (string/list repetition) ---

    #[test]
    fn test_string_repetition() -> Result<()> {
        let ctx = &mut EvalContext::default();
        let result = evaluate_expression("3 * 'ab'", ctx)?;
        assert_eq!(result, Value::Text(Bytes::from("ababab")));
        Ok(())
    }

    #[test]
    fn test_string_repetition_reversed() -> Result<()> {
        let ctx = &mut EvalContext::default();
        let result = evaluate_expression("'ab' * 3", ctx)?;
        assert_eq!(result, Value::Text(Bytes::from("ababab")));
        Ok(())
    }

    #[test]
    fn test_string_repetition_zero() -> Result<()> {
        let ctx = &mut EvalContext::default();
        let result = evaluate_expression("0 * 'hello'", ctx)?;
        assert_eq!(result, Value::Text(Bytes::from("")));
        Ok(())
    }

    #[test]
    fn test_string_repetition_negative() {
        let ctx = &mut EvalContext::default();
        let result = evaluate_expression("-1 * 'hello'", ctx);
        assert!(result.is_err(), "Negative repetition should error");
    }

    #[test]
    fn test_list_repetition() -> Result<()> {
        let ctx = &mut EvalContext::from([(
            "a".to_string(),
            Value::new_list(vec![Value::Integer(1), Value::Integer(2)]),
        )]);
        let result = evaluate_expression("3 * $(a)", ctx)?;
        if let Value::List(items) = result {
            let items = items.borrow();
            assert_eq!(items.len(), 6);
            assert_eq!(items[0], Value::Integer(1));
            assert_eq!(items[1], Value::Integer(2));
            assert_eq!(items[2], Value::Integer(1));
            assert_eq!(items[3], Value::Integer(2));
            assert_eq!(items[4], Value::Integer(1));
            assert_eq!(items[5], Value::Integer(2));
        } else {
            panic!("Expected list, got {result:?}");
        }
        Ok(())
    }

    #[test]
    fn test_list_repetition_zero() -> Result<()> {
        let ctx =
            &mut EvalContext::from([("a".to_string(), Value::new_list(vec![Value::Integer(1)]))]);
        let result = evaluate_expression("0 * $(a)", ctx)?;
        if let Value::List(items) = result {
            assert_eq!(items.borrow().len(), 0);
        } else {
            panic!("Expected empty list");
        }
        Ok(())
    }
}