zentinel-config 0.6.7

Configuration loading and validation for Zentinel reverse proxy
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
//! Route KDL parsing.

use anyhow::Result;
use std::collections::HashMap;
use std::path::PathBuf;
use tracing::{trace, warn};

use zentinel_common::budget::{
    BudgetPeriod, CostAttributionConfig, ModelPricing, TokenBudgetConfig,
};

use crate::routes::*;

use super::helpers::{
    get_bool_entry, get_first_arg_string, get_float_entry, get_int_entry, get_string_entry,
};

/// Recognized child node names inside a `route` block.
/// Any child node not in this set will produce a warning during parsing.
const RECOGNIZED_ROUTE_CHILDREN: &[&str] = &[
    "matches",
    "priority",
    "upstream",
    "static-files",
    "api-schema",
    "inference",
    "filters",
    "builtin-handler",
    "cache",
    "shadow",
    "waf-enabled",
    "websocket",
    "websocket-inspection",
    "fallback",
    "policies",
    "service-type",
];

/// Parse routes configuration block
pub fn parse_routes(node: &kdl::KdlNode) -> Result<Vec<RouteConfig>> {
    trace!("Parsing routes configuration block");
    let mut routes = Vec::new();

    if let Some(children) = node.children() {
        for child in children.nodes() {
            if child.name().value() == "route" {
                let id = get_first_arg_string(child).ok_or_else(|| {
                    anyhow::anyhow!("Route requires an ID argument, e.g., route \"api\" {{ ... }}")
                })?;

                trace!(route_id = %id, "Parsing route");

                // Parse matches
                let matches = parse_match_conditions(child)?;

                // Parse priority
                let priority = parse_priority(child);

                // Parse upstream
                let upstream = parse_upstream_ref(child);

                // Parse static-files
                let static_files = parse_static_file_config_opt(child)?;

                // Parse api-schema
                let api_schema = parse_api_schema_config_opt(child)?;

                // Parse inference config
                let inference = parse_inference_config_opt(child)?;

                // Parse filters
                let filters = parse_route_filter_refs(child)?;

                // Parse builtin-handler
                let builtin_handler =
                    get_string_entry(child, "builtin-handler").and_then(|s| match s.as_str() {
                        "status" => Some(BuiltinHandler::Status),
                        "health" => Some(BuiltinHandler::Health),
                        "metrics" => Some(BuiltinHandler::Metrics),
                        "not-found" | "not_found" => Some(BuiltinHandler::NotFound),
                        "config" => Some(BuiltinHandler::Config),
                        "upstreams" => Some(BuiltinHandler::Upstreams),
                        "cache-purge" | "cache_purge" => Some(BuiltinHandler::CachePurge),
                        "cache-stats" | "cache_stats" => Some(BuiltinHandler::CacheStats),
                        _ => None,
                    });

                // Parse cache configuration
                let cache_config = parse_cache_config_opt(child)?;

                // Parse shadow (traffic mirroring) configuration
                let shadow = parse_shadow_config_opt(child)?;

                // Determine service type
                let service_type = if static_files.is_some() {
                    ServiceType::Static
                } else if builtin_handler.is_some() {
                    ServiceType::Builtin
                } else if api_schema.is_some() {
                    ServiceType::Api
                } else if inference.is_some() {
                    ServiceType::Inference
                } else {
                    ServiceType::Web
                };

                trace!(
                    route_id = %id,
                    service_type = ?service_type,
                    match_count = matches.len(),
                    filter_count = filters.len(),
                    has_upstream = upstream.is_some(),
                    "Parsed route"
                );

                // Parse policies block (request-headers, response-headers, etc.)
                let (request_headers, response_headers) = parse_route_header_policies(child)?;

                // Warn about unrecognized child nodes
                if let Some(route_children) = child.children() {
                    for child_node in route_children.nodes() {
                        let name = child_node.name().value();
                        if !RECOGNIZED_ROUTE_CHILDREN.contains(&name) {
                            warn!(
                                route_id = %id,
                                directive = %name,
                                "Unrecognized directive in route block (will be ignored). \
                                 Agents must be configured in a top-level \"agents\" block \
                                 and referenced via filters."
                            );
                        }
                    }
                }

                // Build route policies with optional cache config
                let policies = RoutePolicies {
                    request_headers,
                    response_headers,
                    cache: cache_config,
                    ..RoutePolicies::default()
                };

                routes.push(RouteConfig {
                    id,
                    priority,
                    matches,
                    upstream,
                    service_type,
                    policies,
                    filters,
                    builtin_handler,
                    waf_enabled: get_bool_entry(child, "waf-enabled").unwrap_or(false),
                    circuit_breaker: None,
                    retry_policy: None,
                    static_files,
                    api_schema,
                    inference,
                    error_pages: None,
                    websocket: get_bool_entry(child, "websocket").unwrap_or(false),
                    websocket_inspection: get_bool_entry(child, "websocket-inspection")
                        .unwrap_or(false),
                    shadow,
                    fallback: parse_fallback_config_opt(child)?,
                });
            }
        }
    }

    trace!(route_count = routes.len(), "Finished parsing routes");
    Ok(routes)
}

fn parse_match_conditions(node: &kdl::KdlNode) -> Result<Vec<MatchCondition>> {
    let mut matches = Vec::new();

    if let Some(route_children) = node.children() {
        if let Some(matches_node) = route_children.get("matches") {
            if let Some(match_children) = matches_node.children() {
                for match_node in match_children.nodes() {
                    match match_node.name().value() {
                        "path-prefix" => {
                            if let Some(prefix) = get_first_arg_string(match_node) {
                                matches.push(MatchCondition::PathPrefix(prefix));
                            }
                        }
                        "path" => {
                            if let Some(path) = get_first_arg_string(match_node) {
                                matches.push(MatchCondition::Path(path));
                            }
                        }
                        "path-regex" => {
                            if let Some(regex) = get_first_arg_string(match_node) {
                                matches.push(MatchCondition::PathRegex(regex));
                            }
                        }
                        "host" => {
                            if let Some(host) = get_first_arg_string(match_node) {
                                matches.push(MatchCondition::Host(host));
                            }
                        }
                        "header" => {
                            let entries: Vec<_> = match_node.entries().iter().collect();
                            if let Some(name) = entries.first().and_then(|e| e.value().as_string())
                            {
                                let value = entries
                                    .get(1)
                                    .and_then(|e| e.value().as_string())
                                    .map(|s| s.to_string());
                                matches.push(MatchCondition::Header {
                                    name: name.to_string(),
                                    value,
                                });
                            }
                        }
                        "method" => {
                            if let Some(method) = get_first_arg_string(match_node) {
                                matches.push(MatchCondition::Method(vec![method]));
                            }
                        }
                        "query-param" => {
                            let entries: Vec<_> = match_node.entries().iter().collect();
                            if let Some(name) = entries.first().and_then(|e| e.value().as_string())
                            {
                                let value = entries
                                    .get(1)
                                    .and_then(|e| e.value().as_string())
                                    .map(|s| s.to_string());
                                matches.push(MatchCondition::QueryParam {
                                    name: name.to_string(),
                                    value,
                                });
                            }
                        }
                        _ => {}
                    }
                }
            }
        }
    }

    Ok(matches)
}

/// Parse a `priority` child node into a [`Priority`](zentinel_common::types::Priority).
///
/// Accepts either:
/// - An integer: `priority 100` → `Priority(100)`
/// - A named string alias: `priority "high"` → `Priority::HIGH`
///
/// Supported string aliases (case-insensitive): `"low"`, `"normal"`, `"high"`,
/// `"critical"`. Unrecognized strings and missing values fall back to
/// [`Priority::NORMAL`](zentinel_common::types::Priority::NORMAL).
fn parse_priority(node: &kdl::KdlNode) -> zentinel_common::types::Priority {
    use zentinel_common::types::Priority;

    // Integer form takes precedence: `priority 100`
    if let Some(n) = get_int_entry(node, "priority") {
        return Priority(n as i32);
    }

    // Named string alias: `priority "high"`
    match get_string_entry(node, "priority")
        .as_deref()
        .map(str::to_ascii_lowercase)
        .as_deref()
    {
        Some("critical") => Priority::CRITICAL,
        Some("high") => Priority::HIGH,
        Some("low") => Priority::LOW,
        Some("normal") => Priority::NORMAL,
        _ => Priority::NORMAL,
    }
}

fn parse_upstream_ref(node: &kdl::KdlNode) -> Option<String> {
    if let Some(route_children) = node.children() {
        if let Some(upstream_node) = route_children.get("upstream") {
            let entry = upstream_node.entries().first();
            if let Some(s) = entry.and_then(|e| e.value().as_string()) {
                return Some(s.to_string());
            }
        }
    }
    None
}

fn parse_static_file_config_opt(node: &kdl::KdlNode) -> Result<Option<StaticFileConfig>> {
    if let Some(route_children) = node.children() {
        if let Some(static_node) = route_children.get("static-files") {
            return Ok(Some(parse_static_file_config(static_node)?));
        }
    }
    Ok(None)
}

fn parse_route_filter_refs(node: &kdl::KdlNode) -> Result<Vec<String>> {
    let mut filter_ids = Vec::new();

    if let Some(route_children) = node.children() {
        if let Some(filters_node) = route_children.get("filters") {
            for entry in filters_node.entries() {
                if let Some(id) = entry.value().as_string() {
                    filter_ids.push(id.to_string());
                }
            }
        }
    }

    Ok(filter_ids)
}

/// Parse route-level header policies from the `policies` block.
///
/// Example KDL:
/// ```kdl
/// policies {
///     request-headers {
///         rename {
///             X-Old-Name "X-New-Name"
///         }
///         set {
///             X-Custom "value"
///         }
///         add {
///             X-Extra "extra"
///         }
///         remove "X-Internal"
///     }
///     response-headers {
///         set {
///             X-Powered-By "Zentinel"
///         }
///     }
/// }
/// ```
fn parse_route_header_policies(
    node: &kdl::KdlNode,
) -> Result<(HeaderModifications, HeaderModifications)> {
    let mut request_headers = HeaderModifications::default();
    let mut response_headers = HeaderModifications::default();

    if let Some(route_children) = node.children() {
        if let Some(policies_node) = route_children.get("policies") {
            if let Some(policy_children) = policies_node.children() {
                if let Some(req_node) = policy_children.get("request-headers") {
                    request_headers = parse_header_modifications(req_node)?;
                }
                if let Some(resp_node) = policy_children.get("response-headers") {
                    response_headers = parse_header_modifications(resp_node)?;
                }
            }
        }
    }

    Ok((request_headers, response_headers))
}

/// Parse a header modifications block (rename, set, add, remove).
fn parse_header_modifications(node: &kdl::KdlNode) -> Result<HeaderModifications> {
    let mut rename = HashMap::new();
    let mut set = HashMap::new();
    let mut add = HashMap::new();
    let mut remove = Vec::new();

    if let Some(children) = node.children() {
        if let Some(rename_node) = children.get("rename") {
            if let Some(rename_children) = rename_node.children() {
                for entry_node in rename_children.nodes() {
                    let old_name = entry_node.name().value().to_string();
                    if let Some(new_name) = get_first_arg_string(entry_node) {
                        rename.insert(old_name, new_name);
                    }
                }
            }
        }
        if let Some(set_node) = children.get("set") {
            if let Some(set_children) = set_node.children() {
                for entry_node in set_children.nodes() {
                    let name = entry_node.name().value().to_string();
                    if let Some(value) = get_first_arg_string(entry_node) {
                        set.insert(name, value);
                    }
                }
            }
        }
        if let Some(add_node) = children.get("add") {
            if let Some(add_children) = add_node.children() {
                for entry_node in add_children.nodes() {
                    let name = entry_node.name().value().to_string();
                    if let Some(value) = get_first_arg_string(entry_node) {
                        add.insert(name, value);
                    }
                }
            }
        }
        if let Some(remove_node) = children.get("remove") {
            for entry in remove_node.entries() {
                if let Some(name) = entry.value().as_string() {
                    remove.push(name.to_string());
                }
            }
        }
    }

    Ok(HeaderModifications {
        rename,
        set,
        add,
        remove,
    })
}

/// Parse static file configuration block
pub fn parse_static_file_config(node: &kdl::KdlNode) -> Result<StaticFileConfig> {
    let root = get_string_entry(node, "root").ok_or_else(|| {
        anyhow::anyhow!(
            "Static files configuration requires a 'root' directory, e.g., root \"/var/www/html\""
        )
    })?;

    Ok(StaticFileConfig {
        root: PathBuf::from(root),
        index: get_string_entry(node, "index").unwrap_or_else(|| "index.html".to_string()),
        directory_listing: get_bool_entry(node, "directory-listing").unwrap_or(false),
        cache_control: get_string_entry(node, "cache-control")
            .unwrap_or_else(|| "public, max-age=3600".to_string()),
        compress: get_bool_entry(node, "compress").unwrap_or(true),
        mime_types: HashMap::new(),
        fallback: get_string_entry(node, "fallback"),
    })
}

/// Parse optional cache configuration from a route
fn parse_cache_config_opt(node: &kdl::KdlNode) -> Result<Option<RouteCacheConfig>> {
    if let Some(route_children) = node.children() {
        if let Some(cache_node) = route_children.get("cache") {
            return Ok(Some(parse_cache_config(cache_node)?));
        }
    }
    Ok(None)
}

/// Parse cache configuration block
///
/// Example KDL:
/// ```kdl
/// cache {
///     enabled true
///     default-ttl-secs 3600
///     max-size-bytes 10485760
///     cache-private false
///     stale-while-revalidate-secs 60
///     stale-if-error-secs 300
///     cacheable-methods "GET" "HEAD"
///     cacheable-status-codes 200 203 204 206 300 301 308 404 410
///     vary-headers "Accept" "Accept-Encoding"
///     ignore-query-params "utm_source" "utm_medium"
/// }
/// ```
fn parse_cache_config(node: &kdl::KdlNode) -> Result<RouteCacheConfig> {
    let enabled = get_bool_entry(node, "enabled").unwrap_or(false);
    let default_ttl_secs = get_int_entry(node, "default-ttl-secs").unwrap_or(3600) as u64;
    let max_size_bytes = get_int_entry(node, "max-size-bytes").unwrap_or(10 * 1024 * 1024) as usize;
    let cache_private = get_bool_entry(node, "cache-private").unwrap_or(false);
    let stale_while_revalidate_secs =
        get_int_entry(node, "stale-while-revalidate-secs").unwrap_or(60) as u64;
    let stale_if_error_secs = get_int_entry(node, "stale-if-error-secs").unwrap_or(300) as u64;

    // Parse cacheable methods (string arguments)
    let cacheable_methods = if let Some(children) = node.children() {
        if let Some(methods_node) = children.get("cacheable-methods") {
            methods_node
                .entries()
                .iter()
                .filter_map(|e| e.value().as_string().map(|s| s.to_string()))
                .collect()
        } else {
            vec!["GET".to_string(), "HEAD".to_string()]
        }
    } else {
        vec!["GET".to_string(), "HEAD".to_string()]
    };

    // Parse cacheable status codes (integer arguments)
    let cacheable_status_codes = if let Some(children) = node.children() {
        if let Some(codes_node) = children.get("cacheable-status-codes") {
            codes_node
                .entries()
                .iter()
                .filter_map(|e| e.value().as_integer().map(|v| v as u16))
                .collect()
        } else {
            vec![200, 203, 204, 206, 300, 301, 308, 404, 410]
        }
    } else {
        vec![200, 203, 204, 206, 300, 301, 308, 404, 410]
    };

    // Parse vary headers
    let vary_headers = if let Some(children) = node.children() {
        if let Some(vary_node) = children.get("vary-headers") {
            vary_node
                .entries()
                .iter()
                .filter_map(|e| e.value().as_string().map(|s| s.to_string()))
                .collect()
        } else {
            Vec::new()
        }
    } else {
        Vec::new()
    };

    // Parse ignore query params
    let ignore_query_params = if let Some(children) = node.children() {
        if let Some(ignore_node) = children.get("ignore-query-params") {
            ignore_node
                .entries()
                .iter()
                .filter_map(|e| e.value().as_string().map(|s| s.to_string()))
                .collect()
        } else {
            Vec::new()
        }
    } else {
        Vec::new()
    };

    // Parse exclude extensions (file extensions to skip caching)
    let exclude_extensions = if let Some(children) = node.children() {
        if let Some(ext_node) = children.get("exclude-extensions") {
            ext_node
                .entries()
                .iter()
                .filter_map(|e| e.value().as_string().map(|s| s.to_string()))
                .collect()
        } else {
            Vec::new()
        }
    } else {
        Vec::new()
    };

    // Parse exclude paths (glob patterns to skip caching)
    let exclude_paths = if let Some(children) = node.children() {
        if let Some(paths_node) = children.get("exclude-paths") {
            paths_node
                .entries()
                .iter()
                .filter_map(|e| e.value().as_string().map(|s| s.to_string()))
                .collect()
        } else {
            Vec::new()
        }
    } else {
        Vec::new()
    };

    trace!(
        enabled = enabled,
        default_ttl = default_ttl_secs,
        max_size = max_size_bytes,
        "Parsed cache configuration"
    );

    Ok(RouteCacheConfig {
        enabled,
        default_ttl_secs,
        max_size_bytes,
        cache_private,
        stale_while_revalidate_secs,
        stale_if_error_secs,
        cacheable_methods,
        cacheable_status_codes,
        vary_headers,
        ignore_query_params,
        exclude_extensions,
        exclude_paths,
    })
}

/// Parse optional API schema configuration from a route
fn parse_api_schema_config_opt(node: &kdl::KdlNode) -> Result<Option<ApiSchemaConfig>> {
    if let Some(route_children) = node.children() {
        if let Some(api_schema_node) = route_children.get("api-schema") {
            return Ok(Some(parse_api_schema_config(api_schema_node)?));
        }
    }
    Ok(None)
}

/// Parse API schema configuration block
///
/// Example KDL with external file:
/// ```kdl
/// api-schema {
///     schema-file "/etc/zentinel/schemas/api-v1.yaml"
///     validate-requests #true
///     validate-responses #false
///     strict-mode #false
/// }
/// ```
///
/// Example KDL with inline OpenAPI spec:
/// ```kdl
/// api-schema {
///     validate-requests #true
///     schema-content r#"
/// openapi: 3.0.0
/// info:
///   title: User API
///   version: 1.0.0
/// paths:
///   /api/users:
///     post:
///       requestBody:
///         content:
///           application/json:
///             schema:
///               type: object
///               required: [email, password]
///               properties:
///                 email: { type: string, format: email }
///                 password: { type: string, minLength: 8 }
///     "#
/// }
/// ```
///
/// Example KDL with inline JSON schema:
/// ```kdl
/// api-schema {
///     validate-requests #true
///     request-schema {
///         type "object"
///         properties {
///             email {
///                 type "string"
///             }
///             password {
///                 type "string"
///                 minLength 8
///             }
///         }
///         required "email" "password"
///     }
/// }
/// ```
fn parse_api_schema_config(node: &kdl::KdlNode) -> Result<ApiSchemaConfig> {
    let schema_file = get_string_entry(node, "schema-file").map(PathBuf::from);
    let schema_content = get_string_entry(node, "schema-content");
    let validate_requests = get_bool_entry(node, "validate-requests").unwrap_or(true);
    let validate_responses = get_bool_entry(node, "validate-responses").unwrap_or(false);
    let strict_mode = get_bool_entry(node, "strict-mode").unwrap_or(false);

    // Validate mutually exclusive options
    if schema_file.is_some() && schema_content.is_some() {
        return Err(anyhow::anyhow!(
            "schema-file and schema-content are mutually exclusive. Use one or the other."
        ));
    }

    // Parse inline request schema if present
    let request_schema = if let Some(children) = node.children() {
        if let Some(schema_node) = children.get("request-schema") {
            Some(super::kdl_to_json(schema_node)?)
        } else {
            None
        }
    } else {
        None
    };

    // Parse inline response schema if present
    let response_schema = if let Some(children) = node.children() {
        if let Some(schema_node) = children.get("response-schema") {
            Some(super::kdl_to_json(schema_node)?)
        } else {
            None
        }
    } else {
        None
    };

    trace!(
        has_schema_file = schema_file.is_some(),
        has_schema_content = schema_content.is_some(),
        has_request_schema = request_schema.is_some(),
        has_response_schema = response_schema.is_some(),
        validate_requests = validate_requests,
        validate_responses = validate_responses,
        strict_mode = strict_mode,
        "Parsed API schema configuration"
    );

    Ok(ApiSchemaConfig {
        schema_file,
        schema_content,
        request_schema,
        response_schema,
        validate_requests,
        validate_responses,
        strict_mode,
    })
}

/// Parse optional shadow (traffic mirroring) configuration from a route
fn parse_shadow_config_opt(node: &kdl::KdlNode) -> Result<Option<ShadowConfig>> {
    if let Some(route_children) = node.children() {
        if let Some(shadow_node) = route_children.get("shadow") {
            return Ok(Some(parse_shadow_config(shadow_node)?));
        }
    }
    Ok(None)
}

/// Parse shadow (traffic mirroring) configuration block
///
/// Example KDL:
/// ```kdl
/// shadow {
///     upstream "canary"
///     percentage 10.0
///     sample-header "X-Debug-Shadow" "true"
///     timeout-ms 5000
///     buffer-body #true
///     max-body-bytes 1048576
/// }
/// ```
fn parse_shadow_config(node: &kdl::KdlNode) -> Result<ShadowConfig> {
    // Upstream is required
    let upstream = get_string_entry(node, "upstream").ok_or_else(|| {
        anyhow::anyhow!(
            "Shadow configuration requires an 'upstream' field, e.g., upstream \"canary\""
        )
    })?;

    let percentage = if let Some(pct_str) = get_string_entry(node, "percentage") {
        pct_str.parse::<f64>().unwrap_or(100.0)
    } else {
        get_int_entry(node, "percentage")
            .map(|v| v as f64)
            .unwrap_or(100.0)
    };

    let timeout_ms = get_int_entry(node, "timeout-ms").unwrap_or(5000) as u64;
    let buffer_body = get_bool_entry(node, "buffer-body").unwrap_or(false);
    let max_body_bytes = get_int_entry(node, "max-body-bytes").unwrap_or(1048576) as usize;

    // Parse sample-header if present (tuple of name, value)
    let sample_header = if let Some(children) = node.children() {
        if let Some(header_node) = children.get("sample-header") {
            let entries: Vec<_> = header_node.entries().iter().collect();
            if entries.len() >= 2 {
                let name = entries[0]
                    .value()
                    .as_string()
                    .ok_or_else(|| anyhow::anyhow!("sample-header name must be a string"))?;
                let value = entries[1]
                    .value()
                    .as_string()
                    .ok_or_else(|| anyhow::anyhow!("sample-header value must be a string"))?;
                Some((name.to_string(), value.to_string()))
            } else {
                None
            }
        } else {
            None
        }
    } else {
        None
    };

    trace!(
        upstream = %upstream,
        percentage = percentage,
        timeout_ms = timeout_ms,
        buffer_body = buffer_body,
        max_body_bytes = max_body_bytes,
        has_sample_header = sample_header.is_some(),
        "Parsed shadow configuration"
    );

    Ok(ShadowConfig {
        upstream,
        percentage,
        sample_header,
        timeout_ms,
        buffer_body,
        max_body_bytes,
    })
}

/// Parse optional fallback configuration from a route
fn parse_fallback_config_opt(node: &kdl::KdlNode) -> Result<Option<FallbackConfig>> {
    if let Some(route_children) = node.children() {
        if let Some(fallback_node) = route_children.get("fallback") {
            return Ok(Some(parse_fallback_config(fallback_node)?));
        }
    }
    Ok(None)
}

/// Parse fallback configuration block
///
/// Example KDL:
/// ```kdl
/// fallback {
///     max-attempts 2
///
///     triggers {
///         on-health-failure true
///         on-budget-exhausted true
///         on-latency-threshold-ms 5000
///         on-error-codes 429 500 502 503 504
///         on-connection-error true
///     }
///
///     fallback-upstream "anthropic-fallback" {
///         provider "anthropic"
///         skip-if-unhealthy true
///
///         model-mapping {
///             "gpt-4" "claude-3-opus"
///             "gpt-4o" "claude-3-5-sonnet"
///         }
///     }
/// }
/// ```
fn parse_fallback_config(node: &kdl::KdlNode) -> Result<FallbackConfig> {
    let max_attempts = get_int_entry(node, "max-attempts").unwrap_or(3) as u32;

    // Parse triggers
    let triggers = if let Some(children) = node.children() {
        if let Some(triggers_node) = children.get("triggers") {
            parse_fallback_triggers(triggers_node)?
        } else {
            FallbackTriggers::default()
        }
    } else {
        FallbackTriggers::default()
    };

    // Parse fallback upstreams
    let upstreams = parse_fallback_upstreams(node)?;

    trace!(
        max_attempts = max_attempts,
        upstream_count = upstreams.len(),
        on_health_failure = triggers.on_health_failure,
        on_connection_error = triggers.on_connection_error,
        "Parsed fallback configuration"
    );

    Ok(FallbackConfig {
        upstreams,
        triggers,
        max_attempts,
    })
}

/// Parse fallback triggers block
fn parse_fallback_triggers(node: &kdl::KdlNode) -> Result<FallbackTriggers> {
    let on_health_failure = get_bool_entry(node, "on-health-failure").unwrap_or(true);
    let on_budget_exhausted = get_bool_entry(node, "on-budget-exhausted").unwrap_or(false);
    let on_latency_threshold_ms = get_int_entry(node, "on-latency-threshold-ms").map(|v| v as u64);
    let on_connection_error = get_bool_entry(node, "on-connection-error").unwrap_or(true);

    // Parse error codes (integer arguments)
    let on_error_codes = if let Some(children) = node.children() {
        if let Some(codes_node) = children.get("on-error-codes") {
            codes_node
                .entries()
                .iter()
                .filter_map(|e| e.value().as_integer().map(|v| v as u16))
                .collect()
        } else {
            Vec::new()
        }
    } else {
        // Also check for inline arguments
        node.children()
            .and_then(|c| c.get("on-error-codes"))
            .map(|n| {
                n.entries()
                    .iter()
                    .filter_map(|e| e.value().as_integer().map(|v| v as u16))
                    .collect()
            })
            .unwrap_or_default()
    };

    Ok(FallbackTriggers {
        on_health_failure,
        on_budget_exhausted,
        on_latency_threshold_ms,
        on_error_codes,
        on_connection_error,
    })
}

/// Parse fallback upstreams from fallback block
fn parse_fallback_upstreams(node: &kdl::KdlNode) -> Result<Vec<FallbackUpstream>> {
    let mut upstreams = Vec::new();

    if let Some(children) = node.children() {
        for child in children.nodes() {
            if child.name().value() == "fallback-upstream" {
                let upstream_id = get_first_arg_string(child).ok_or_else(|| {
                    anyhow::anyhow!(
                        "fallback-upstream requires an upstream ID, e.g., fallback-upstream \"anthropic\" {{ ... }}"
                    )
                })?;

                let provider = parse_inference_provider(child);
                let skip_if_unhealthy = get_bool_entry(child, "skip-if-unhealthy").unwrap_or(false);
                let model_mapping = parse_model_mapping(child)?;

                trace!(
                    upstream = %upstream_id,
                    provider = ?provider,
                    skip_if_unhealthy = skip_if_unhealthy,
                    model_mapping_count = model_mapping.len(),
                    "Parsed fallback upstream"
                );

                upstreams.push(FallbackUpstream {
                    upstream: upstream_id,
                    provider,
                    model_mapping,
                    skip_if_unhealthy,
                });
            }
        }
    }

    Ok(upstreams)
}

/// Parse model mapping block
///
/// Example KDL:
/// ```kdl
/// model-mapping {
///     "gpt-4" "claude-3-opus"
///     "gpt-4o" "claude-3-5-sonnet"
/// }
/// ```
fn parse_model_mapping(node: &kdl::KdlNode) -> Result<HashMap<String, String>> {
    let mut mapping = HashMap::new();

    if let Some(children) = node.children() {
        if let Some(mapping_node) = children.get("model-mapping") {
            if let Some(mapping_children) = mapping_node.children() {
                for entry_node in mapping_children.nodes() {
                    // Each node is like: "gpt-4" "claude-3-opus"
                    let entries: Vec<_> = entry_node
                        .entries()
                        .iter()
                        .filter_map(|e| e.value().as_string().map(|s| s.to_string()))
                        .collect();

                    // The node name is the source model, first entry is target
                    let source = entry_node.name().value().to_string();
                    if let Some(target) = entries.first() {
                        mapping.insert(source, target.clone());
                    }
                }
            }

            // Also handle inline format: model-mapping { "gpt-4" "claude-3-opus" }
            // where entries are pairs
            let entries: Vec<_> = mapping_node
                .entries()
                .iter()
                .filter_map(|e| e.value().as_string().map(|s| s.to_string()))
                .collect();

            // Process pairs
            for chunk in entries.chunks(2) {
                if chunk.len() == 2 {
                    mapping.insert(chunk[0].clone(), chunk[1].clone());
                }
            }
        }
    }

    Ok(mapping)
}

/// Parse inference provider from node
fn parse_inference_provider(node: &kdl::KdlNode) -> InferenceProvider {
    match get_string_entry(node, "provider").as_deref() {
        Some("openai") => InferenceProvider::OpenAi,
        Some("anthropic") => InferenceProvider::Anthropic,
        _ => InferenceProvider::Generic,
    }
}

/// Parse optional model routing configuration from an inference block.
///
/// Example KDL:
/// ```kdl
/// model-routing {
///     model "gpt-4" upstream="openai-primary"
///     model "gpt-4*" upstream="openai-primary"
///     model "claude-*" upstream="anthropic-backend" provider="anthropic"
///     default-upstream "openai-primary"
/// }
/// ```
fn parse_model_routing_config_opt(node: &kdl::KdlNode) -> Result<Option<ModelRoutingConfig>> {
    if let Some(children) = node.children() {
        if let Some(routing_node) = children.get("model-routing") {
            return Ok(Some(parse_model_routing_config(routing_node)?));
        }
    }
    Ok(None)
}

/// Parse model routing configuration block.
fn parse_model_routing_config(node: &kdl::KdlNode) -> Result<ModelRoutingConfig> {
    let mut mappings = Vec::new();
    let mut default_upstream = None;

    // Get default-upstream if present (as entry or child)
    if let Some(def) = get_string_entry(node, "default-upstream") {
        default_upstream = Some(def);
    }

    // Parse children
    if let Some(children) = node.children() {
        // Check for default-upstream as a child node
        if let Some(def_node) = children.get("default-upstream") {
            if let Some(first_entry) = def_node.entries().first() {
                if let Some(val) = first_entry.value().as_string() {
                    default_upstream = Some(val.to_string());
                }
            }
        }

        // Parse model entries
        for model_node in children.nodes() {
            if model_node.name().value() == "model" {
                if let Some(mapping) = parse_model_upstream_mapping(model_node)? {
                    mappings.push(mapping);
                }
            }
        }
    }

    tracing::trace!(
        mappings_count = mappings.len(),
        default_upstream = ?default_upstream,
        "Parsed model routing configuration"
    );

    Ok(ModelRoutingConfig {
        mappings,
        default_upstream,
    })
}

/// Parse a single model-to-upstream mapping entry.
///
/// Example KDL:
/// ```kdl
/// model "gpt-4" upstream="openai-primary"
/// model "claude-*" upstream="anthropic-backend" provider="anthropic"
/// ```
fn parse_model_upstream_mapping(node: &kdl::KdlNode) -> Result<Option<ModelUpstreamMapping>> {
    // Get the model pattern from the first positional entry (no name)
    let model_pattern = node
        .entries()
        .iter()
        .find(|e| e.name().is_none())
        .and_then(|e| e.value().as_string())
        .map(|s| s.to_string());

    let model_pattern = match model_pattern {
        Some(p) => p,
        None => return Ok(None), // No model pattern specified
    };

    // Get upstream from inline entry (e.g., upstream="openai-primary")
    let upstream = node
        .entries()
        .iter()
        .find(|e| e.name().map(|n| n.value()) == Some("upstream"))
        .and_then(|e| e.value().as_string())
        .map(|s| s.to_string())
        .ok_or_else(|| anyhow::anyhow!("Model mapping requires 'upstream' attribute"))?;

    // Get optional provider override from inline entry
    let provider_str = node
        .entries()
        .iter()
        .find(|e| e.name().map(|n| n.value()) == Some("provider"))
        .and_then(|e| e.value().as_string());

    let provider = match provider_str {
        Some("openai") => Some(InferenceProvider::OpenAi),
        Some("anthropic") => Some(InferenceProvider::Anthropic),
        Some("generic") => Some(InferenceProvider::Generic),
        Some(_) | None => None,
    };

    tracing::trace!(
        model_pattern = %model_pattern,
        upstream = %upstream,
        provider = ?provider,
        "Parsed model upstream mapping"
    );

    Ok(Some(ModelUpstreamMapping {
        model_pattern,
        upstream,
        provider,
    }))
}

/// Parse optional inference configuration from a route
fn parse_inference_config_opt(node: &kdl::KdlNode) -> Result<Option<InferenceConfig>> {
    if let Some(route_children) = node.children() {
        if let Some(inference_node) = route_children.get("inference") {
            return Ok(Some(parse_inference_config(inference_node)?));
        }
    }
    Ok(None)
}

/// Parse inference configuration block
///
/// Example KDL:
/// ```kdl
/// inference {
///     provider "openai"
///     model-header "x-model"
///
///     rate-limit {
///         tokens-per-minute 100000
///         requests-per-minute 500
///         burst-tokens 10000
///         estimation-method "chars"
///     }
///
///     routing {
///         strategy "least-tokens-queued"
///         queue-depth-header "x-queue-depth"
///     }
/// }
/// ```
fn parse_inference_config(node: &kdl::KdlNode) -> Result<InferenceConfig> {
    // Parse provider
    let provider = match get_string_entry(node, "provider").as_deref() {
        Some("openai") | Some("open-ai") | Some("open_ai") => InferenceProvider::OpenAi,
        Some("anthropic") => InferenceProvider::Anthropic,
        Some("generic") | None => InferenceProvider::Generic,
        Some(other) => {
            return Err(anyhow::anyhow!(
                "Unknown inference provider '{}'. Valid providers: openai, anthropic, generic",
                other
            ));
        }
    };

    let model_header = get_string_entry(node, "model-header");

    // Parse rate-limit sub-block
    let rate_limit = if let Some(children) = node.children() {
        if let Some(rl_node) = children.get("rate-limit") {
            Some(parse_token_rate_limit(rl_node)?)
        } else {
            None
        }
    } else {
        None
    };

    // Parse routing sub-block
    let routing = if let Some(children) = node.children() {
        if let Some(routing_node) = children.get("routing") {
            Some(parse_inference_routing(routing_node)?)
        } else {
            None
        }
    } else {
        None
    };

    // Parse budget sub-block
    let budget = if let Some(children) = node.children() {
        if let Some(budget_node) = children.get("budget") {
            Some(parse_token_budget(budget_node)?)
        } else {
            None
        }
    } else {
        None
    };

    // Parse cost-attribution sub-block
    let cost_attribution = if let Some(children) = node.children() {
        if let Some(cost_node) = children.get("cost-attribution") {
            Some(parse_cost_attribution(cost_node)?)
        } else {
            None
        }
    } else {
        None
    };

    trace!(
        provider = ?provider,
        has_rate_limit = rate_limit.is_some(),
        has_routing = routing.is_some(),
        has_budget = budget.is_some(),
        has_cost = cost_attribution.is_some(),
        "Parsed inference configuration"
    );

    // Parse model-routing block if present
    let model_routing = parse_model_routing_config_opt(node)?;

    // Parse guardrails block if present
    let guardrails = parse_guardrails_config_opt(node)?;

    Ok(InferenceConfig {
        provider,
        model_header,
        rate_limit,
        budget,
        cost_attribution,
        routing,
        model_routing,
        guardrails,
    })
}

/// Parse token rate limit configuration
fn parse_token_rate_limit(node: &kdl::KdlNode) -> Result<TokenRateLimit> {
    let tokens_per_minute = get_int_entry(node, "tokens-per-minute")
        .ok_or_else(|| anyhow::anyhow!("Token rate limit requires 'tokens-per-minute'"))?
        as u64;

    let requests_per_minute = get_int_entry(node, "requests-per-minute").map(|v| v as u64);

    let burst_tokens = get_int_entry(node, "burst-tokens").unwrap_or(10000) as u64;

    let estimation_method = match get_string_entry(node, "estimation-method").as_deref() {
        Some("chars") | Some("characters") | None => TokenEstimation::Chars,
        Some("words") => TokenEstimation::Words,
        Some("tiktoken") => TokenEstimation::Tiktoken,
        Some(other) => {
            return Err(anyhow::anyhow!(
                "Unknown token estimation method '{}'. Valid methods: chars, words, tiktoken",
                other
            ));
        }
    };

    Ok(TokenRateLimit {
        tokens_per_minute,
        requests_per_minute,
        burst_tokens,
        estimation_method,
    })
}

/// Parse inference routing configuration
fn parse_inference_routing(node: &kdl::KdlNode) -> Result<InferenceRouting> {
    let strategy = match get_string_entry(node, "strategy").as_deref() {
        Some("least-tokens-queued") | Some("least_tokens_queued") | None => {
            InferenceRoutingStrategy::LeastTokensQueued
        }
        Some("round-robin") | Some("round_robin") => InferenceRoutingStrategy::RoundRobin,
        Some("least-latency") | Some("least_latency") => InferenceRoutingStrategy::LeastLatency,
        Some(other) => {
            return Err(anyhow::anyhow!(
                "Unknown inference routing strategy '{}'. Valid strategies: least-tokens-queued, round-robin, least-latency",
                other
            ));
        }
    };

    let queue_depth_header = get_string_entry(node, "queue-depth-header");

    Ok(InferenceRouting {
        strategy,
        queue_depth_header,
    })
}

/// Parse token budget configuration
///
/// KDL format:
/// ```kdl
/// budget {
///     period "daily"
///     limit 1000000
///     alert-thresholds 0.80 0.90 0.95
///     enforce true
///     rollover false
///     burst-allowance 0.10
/// }
/// ```
fn parse_token_budget(node: &kdl::KdlNode) -> Result<TokenBudgetConfig> {
    let period = match get_string_entry(node, "period").as_deref() {
        Some("hourly") => BudgetPeriod::Hourly,
        Some("daily") | None => BudgetPeriod::Daily,
        Some("monthly") => BudgetPeriod::Monthly,
        Some(other) => {
            // Try to parse as custom seconds
            if let Ok(seconds) = other.parse::<u64>() {
                BudgetPeriod::Custom { seconds }
            } else {
                return Err(anyhow::anyhow!(
                    "Unknown budget period '{}'. Valid periods: hourly, daily, monthly, or a number of seconds",
                    other
                ));
            }
        }
    };

    let limit = get_int_entry(node, "limit")
        .ok_or_else(|| anyhow::anyhow!("Token budget requires 'limit'"))? as u64;

    // Parse alert-thresholds as a list of floats from arguments
    let alert_thresholds = if let Some(children) = node.children() {
        if let Some(threshold_node) = children.get("alert-thresholds") {
            threshold_node
                .entries()
                .iter()
                .filter_map(|e| {
                    e.value()
                        .as_float()
                        .or_else(|| e.value().as_integer().map(|i| i as f64))
                })
                .collect()
        } else {
            vec![0.80, 0.90, 0.95]
        }
    } else {
        vec![0.80, 0.90, 0.95]
    };

    let enforce = get_bool_entry(node, "enforce").unwrap_or(true);
    let rollover = get_bool_entry(node, "rollover").unwrap_or(false);
    let burst_allowance = get_float_entry(node, "burst-allowance");

    trace!(
        period = ?period,
        limit = limit,
        alert_thresholds = ?alert_thresholds,
        enforce = enforce,
        rollover = rollover,
        burst_allowance = ?burst_allowance,
        "Parsed token budget configuration"
    );

    Ok(TokenBudgetConfig {
        period,
        limit,
        alert_thresholds,
        enforce,
        rollover,
        burst_allowance,
    })
}

/// Parse cost attribution configuration
///
/// KDL format:
/// ```kdl
/// cost-attribution {
///     enabled true
///     default-input-cost 1.0
///     default-output-cost 2.0
///     currency "USD"
///
///     pricing {
///         model "gpt-4*" {
///             input-cost-per-million 30.0
///             output-cost-per-million 60.0
///         }
///         model "gpt-3.5*" {
///             input-cost-per-million 0.5
///             output-cost-per-million 1.5
///         }
///     }
/// }
/// ```
fn parse_cost_attribution(node: &kdl::KdlNode) -> Result<CostAttributionConfig> {
    let enabled = get_bool_entry(node, "enabled").unwrap_or(true);
    let default_input_cost = get_float_entry(node, "default-input-cost").unwrap_or(1.0);
    let default_output_cost = get_float_entry(node, "default-output-cost").unwrap_or(2.0);
    let currency = get_string_entry(node, "currency").unwrap_or_else(|| "USD".to_string());

    // Parse pricing sub-block
    let pricing = if let Some(children) = node.children() {
        if let Some(pricing_node) = children.get("pricing") {
            parse_model_pricing_list(pricing_node)?
        } else {
            Vec::new()
        }
    } else {
        Vec::new()
    };

    trace!(
        enabled = enabled,
        default_input_cost = default_input_cost,
        default_output_cost = default_output_cost,
        currency = %currency,
        pricing_rules = pricing.len(),
        "Parsed cost attribution configuration"
    );

    Ok(CostAttributionConfig {
        enabled,
        pricing,
        default_input_cost,
        default_output_cost,
        currency,
    })
}

/// Parse model pricing list
fn parse_model_pricing_list(node: &kdl::KdlNode) -> Result<Vec<ModelPricing>> {
    let mut pricing = Vec::new();

    if let Some(children) = node.children() {
        for child in children.nodes() {
            if child.name().value() == "model" {
                let pattern = get_first_arg_string(child)
                    .ok_or_else(|| anyhow::anyhow!("Model pricing requires a pattern argument"))?;

                let input_cost =
                    get_float_entry(child, "input-cost-per-million").ok_or_else(|| {
                        anyhow::anyhow!("Model pricing requires 'input-cost-per-million'")
                    })?;

                let output_cost =
                    get_float_entry(child, "output-cost-per-million").ok_or_else(|| {
                        anyhow::anyhow!("Model pricing requires 'output-cost-per-million'")
                    })?;

                let currency = get_string_entry(child, "currency");

                pricing.push(ModelPricing {
                    model_pattern: pattern,
                    input_cost_per_million: input_cost,
                    output_cost_per_million: output_cost,
                    currency,
                });
            }
        }
    }

    Ok(pricing)
}

// ============================================================================
// Guardrails Configuration Parsing
// ============================================================================

/// Parse optional guardrails configuration from an inference block.
///
/// Example KDL:
/// ```kdl
/// guardrails {
///     prompt-injection {
///         enabled true
///         agent "prompt-guard"
///         action "block"
///         block-status 400
///         block-message "Request blocked: potential prompt injection detected"
///         timeout-ms 500
///         failure-mode "open"
///     }
///
///     pii-detection {
///         enabled true
///         agent "pii-scanner"
///         action "log"
///         categories "ssn" "credit-card" "email" "phone"
///         timeout-ms 1000
///         failure-mode "open"
///     }
/// }
/// ```
fn parse_guardrails_config_opt(node: &kdl::KdlNode) -> Result<Option<GuardrailsConfig>> {
    if let Some(children) = node.children() {
        if let Some(guardrails_node) = children.get("guardrails") {
            return Ok(Some(parse_guardrails_config(guardrails_node)?));
        }
    }
    Ok(None)
}

/// Parse guardrails configuration block.
fn parse_guardrails_config(node: &kdl::KdlNode) -> Result<GuardrailsConfig> {
    // Parse prompt-injection sub-block
    let prompt_injection = if let Some(children) = node.children() {
        if let Some(pi_node) = children.get("prompt-injection") {
            Some(parse_prompt_injection_config(pi_node)?)
        } else {
            None
        }
    } else {
        None
    };

    // Parse pii-detection sub-block
    let pii_detection = if let Some(children) = node.children() {
        if let Some(pii_node) = children.get("pii-detection") {
            Some(parse_pii_detection_config(pii_node)?)
        } else {
            None
        }
    } else {
        None
    };

    trace!(
        has_prompt_injection = prompt_injection.is_some(),
        has_pii_detection = pii_detection.is_some(),
        "Parsed guardrails configuration"
    );

    Ok(GuardrailsConfig {
        prompt_injection,
        pii_detection,
    })
}

/// Parse prompt injection detection configuration.
fn parse_prompt_injection_config(node: &kdl::KdlNode) -> Result<PromptInjectionConfig> {
    let enabled = get_bool_entry(node, "enabled").unwrap_or(false);

    let agent = get_string_entry(node, "agent")
        .ok_or_else(|| anyhow::anyhow!("Prompt injection config requires 'agent' field"))?;

    let action = match get_string_entry(node, "action").as_deref() {
        Some("block") => GuardrailAction::Block,
        Some("log") | None => GuardrailAction::Log,
        Some("warn") => GuardrailAction::Warn,
        Some(other) => {
            return Err(anyhow::anyhow!(
                "Unknown guardrail action '{}'. Valid actions: block, log, warn",
                other
            ));
        }
    };

    let block_status = get_int_entry(node, "block-status").unwrap_or(400) as u16;
    let block_message = get_string_entry(node, "block-message");
    let timeout_ms = get_int_entry(node, "timeout-ms").unwrap_or(500) as u64;

    let failure_mode = match get_string_entry(node, "failure-mode").as_deref() {
        Some("open") | None => GuardrailFailureMode::Open,
        Some("closed") => GuardrailFailureMode::Closed,
        Some(other) => {
            return Err(anyhow::anyhow!(
                "Unknown failure mode '{}'. Valid modes: open, closed",
                other
            ));
        }
    };

    trace!(
        enabled = enabled,
        agent = %agent,
        action = ?action,
        block_status = block_status,
        timeout_ms = timeout_ms,
        failure_mode = ?failure_mode,
        "Parsed prompt injection configuration"
    );

    Ok(PromptInjectionConfig {
        enabled,
        agent,
        action,
        block_status,
        block_message,
        timeout_ms,
        failure_mode,
    })
}

/// Parse PII detection configuration.
fn parse_pii_detection_config(node: &kdl::KdlNode) -> Result<PiiDetectionConfig> {
    let enabled = get_bool_entry(node, "enabled").unwrap_or(false);

    let agent = get_string_entry(node, "agent")
        .ok_or_else(|| anyhow::anyhow!("PII detection config requires 'agent' field"))?;

    let action = match get_string_entry(node, "action").as_deref() {
        Some("log") | None => PiiAction::Log,
        Some("redact") => PiiAction::Redact,
        Some("block") => PiiAction::Block,
        Some(other) => {
            return Err(anyhow::anyhow!(
                "Unknown PII action '{}'. Valid actions: log, redact, block",
                other
            ));
        }
    };

    // Parse categories as string arguments
    let categories = if let Some(children) = node.children() {
        if let Some(cat_node) = children.get("categories") {
            cat_node
                .entries()
                .iter()
                .filter_map(|e| e.value().as_string().map(|s| s.to_string()))
                .collect()
        } else {
            Vec::new()
        }
    } else {
        Vec::new()
    };

    let timeout_ms = get_int_entry(node, "timeout-ms").unwrap_or(1000) as u64;

    let failure_mode = match get_string_entry(node, "failure-mode").as_deref() {
        Some("open") | None => GuardrailFailureMode::Open,
        Some("closed") => GuardrailFailureMode::Closed,
        Some(other) => {
            return Err(anyhow::anyhow!(
                "Unknown failure mode '{}'. Valid modes: open, closed",
                other
            ));
        }
    };

    trace!(
        enabled = enabled,
        agent = %agent,
        action = ?action,
        categories = ?categories,
        timeout_ms = timeout_ms,
        failure_mode = ?failure_mode,
        "Parsed PII detection configuration"
    );

    Ok(PiiDetectionConfig {
        enabled,
        agent,
        action,
        categories,
        timeout_ms,
        failure_mode,
    })
}

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

    /// Parse a KDL fragment like `route "test" { priority ... }` and return
    /// the resulting `Priority`. The parser expects a `route` parent node, so
    /// we wrap the priority directive in a minimal route block.
    fn parse_priority_from(kdl: &str) -> Priority {
        let doc: ::kdl::KdlDocument = kdl.parse().expect("KDL parses");
        let route_node = doc.get("route").expect("route node present");
        parse_priority(route_node)
    }

    #[test]
    fn priority_accepts_integer() {
        assert_eq!(
            parse_priority_from(r#"route "r" { priority 100 }"#),
            Priority(100)
        );
        assert_eq!(
            parse_priority_from(r#"route "r" { priority 1000 }"#),
            Priority::CRITICAL
        );
        assert_eq!(
            parse_priority_from(r#"route "r" { priority 1 }"#),
            Priority(1)
        );
    }

    #[test]
    fn priority_accepts_large_and_negative_integers() {
        assert_eq!(
            parse_priority_from(r#"route "r" { priority 999999 }"#),
            Priority(999_999)
        );
        assert_eq!(
            parse_priority_from(r#"route "r" { priority -50 }"#),
            Priority(-50)
        );
    }

    #[test]
    fn priority_accepts_all_string_aliases() {
        assert_eq!(
            parse_priority_from(r#"route "r" { priority "critical" }"#),
            Priority::CRITICAL
        );
        assert_eq!(
            parse_priority_from(r#"route "r" { priority "high" }"#),
            Priority::HIGH
        );
        assert_eq!(
            parse_priority_from(r#"route "r" { priority "normal" }"#),
            Priority::NORMAL
        );
        assert_eq!(
            parse_priority_from(r#"route "r" { priority "low" }"#),
            Priority::LOW
        );
    }

    #[test]
    fn priority_string_aliases_are_case_insensitive() {
        assert_eq!(
            parse_priority_from(r#"route "r" { priority "HIGH" }"#),
            Priority::HIGH
        );
        assert_eq!(
            parse_priority_from(r#"route "r" { priority "Critical" }"#),
            Priority::CRITICAL
        );
    }

    #[test]
    fn priority_unknown_string_falls_back_to_normal() {
        assert_eq!(
            parse_priority_from(r#"route "r" { priority "medium" }"#),
            Priority::NORMAL
        );
    }

    #[test]
    fn priority_missing_is_normal() {
        assert_eq!(
            parse_priority_from(r#"route "r" { upstream "backend" }"#),
            Priority::NORMAL
        );
    }

    #[test]
    fn numeric_priorities_sort_before_named_aliases() {
        // Regression: documentation-style gap-based priorities must preserve
        // the numeric ordering the docs advertise (e.g. 500 > HIGH > 50).
        assert!(Priority(500) > Priority::HIGH);
        assert!(Priority::HIGH > Priority(75));
        assert!(Priority(75) > Priority::NORMAL);
        assert!(Priority::NORMAL > Priority(25));
        assert!(Priority(25) > Priority::LOW);
    }
}