kazam 1.13.2

Local infrastructure for coding agents: context, visibility, durable execution. One Rust binary, no cloud.
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
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

// ── Shell ────────────────────────────────────────────

#[derive(Deserialize, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum Shell {
    Standard,
    Document,
    Deck,
    Hub,
}

impl Shell {
    pub fn class(&self) -> &'static str {
        match self {
            Shell::Standard => "shell-standard",
            Shell::Document => "shell-document",
            Shell::Deck => "shell-deck",
            Shell::Hub => "shell-hub",
        }
    }
}

// ── Hub shell config ─────────────────────────────────

/// Groups sibling pages (a customer's account plan, priorities, deployment
/// tracker, notes…) under a persistent masthead with tab navigation. Every
/// page in the group declares the same `hub:` block; the active tab is
/// detected from the page being rendered.
#[derive(Deserialize, Clone)]
pub struct HubConfig {
    /// Hub identity shown in the masthead — usually the customer name.
    pub name: String,
    /// Small label above the name, e.g. "CUSTOMER" or the segment.
    #[serde(default)]
    pub eyebrow: Option<String>,
    /// Status badge next to the name, e.g. "Deploying" or "Healthy".
    #[serde(default)]
    pub status: Option<String>,
    #[serde(default)]
    pub status_color: Option<SemColor>,
    /// Tabs, in order. Hrefs resolve like any page link.
    #[serde(default)]
    pub pages: Vec<HubLink>,
}

#[derive(Deserialize, Clone)]
pub struct HubLink {
    pub label: String,
    pub href: String,
}

/// `pack:` block on a page — marks it as an AI tool pack.
#[derive(Deserialize)]
pub struct PackMeta {
    /// Which tool config files to write. Empty = all supported targets.
    /// Valid values: claude, cursor, agents, windsurf, copilot, gemini, aider.
    #[serde(default)]
    pub targets: Vec<String>,
    /// Declarative guardrail hooks. Packs never ship executable code; each hook
    /// is data the trusted kazam runner interprets. Deny/inject/review only.
    #[serde(default)]
    pub hooks: Vec<PackHook>,
}

/// Which tool call a PreToolUse/PostToolUse hook applies to. `tool` is a
/// matcher pattern passed through verbatim to the harness, so any matcher the
/// harness understands works: a single tool ("Write"), a pipe alternation
/// ("Write|Edit"), or an MCP tool name / prefix
/// ("mcp__claude_ai_Slack__slack_send_message", "mcp__.*").
#[derive(Deserialize, Serialize, Clone)]
pub struct HookMatch {
    pub tool: String,
}

#[derive(Deserialize, Serialize, Clone, Copy, Default, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum MatchMode {
    #[default]
    Substring,
    /// Substring match constrained to word boundaries: the pattern only matches
    /// when the characters on either side are non-word (not alphanumeric or
    /// `_`). Blocks "delve" but not "fostering" for a "foster" pattern.
    Word,
    Regex,
}

#[derive(Deserialize, Serialize, Clone, Copy, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum InjectEvent {
    SessionStart,
    UserPromptSubmit,
}

/// A declarative guardrail primitive. Tagged by `kind`. None of these can read
/// arbitrary files, make network calls, or write data anywhere: the runner that
/// executes them has no egress capability, so a hostile pack can at worst block
/// the user's own tool calls or inject visible text.
#[derive(Deserialize, Serialize, Clone)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum PackHook {
    /// Block a tool call if the content matches any pattern.
    BlockOnMatch {
        on: HookMatch,
        #[serde(default)]
        mode: MatchMode,
        /// Which `tool_input` field to scan. Unset = scan the whole serialized
        /// `tool_input` (fine for Write/Edit `content`). Set it to target one
        /// field on an MCP tool, e.g. `text` for a Slack message body, so the
        /// scan doesn't false-positive on other args or field names.
        #[serde(default)]
        field: Option<String>,
        patterns: Vec<String>,
        message: String,
    },
    /// Block a tool call unless the content matches a required pattern.
    BlockUnlessMatch {
        on: HookMatch,
        require: String,
        message: String,
    },
    /// Block unless a named tool_input field is in an allowed set.
    Allowlist {
        on: HookMatch,
        field: String,
        allow: Vec<String>,
        message: String,
    },
    /// Add static or templated text to context (supports {{date}}).
    Inject { event: InjectEvent, text: String },
    /// Run an LLM review with a supplied prompt (harness runs the model).
    ReviewPrompt {
        on: HookMatch,
        prompt: String,
        #[serde(default)]
        model_tier: Option<String>,
    },
}

// ── Page ─────────────────────────────────────────────

#[derive(Deserialize)]
pub struct Page {
    pub title: String,
    pub shell: Shell,
    pub eyebrow: Option<String>,
    pub subtitle: Option<String>,
    pub components: Option<Vec<Component>>,
    pub slides: Option<Vec<Slide>>,
    /// Exclude this page from llms.txt. Useful for drafts.
    #[serde(default)]
    pub unlisted: bool,
    /// Override the site-wide `texture` on this page. `Some(Texture::None)`
    /// turns the texture off on this page; any other `Some(_)` swaps in a
    /// different preset. `None` (unset) means inherit the site-wide value.
    #[serde(default)]
    pub texture: Option<Texture>,
    /// Override the site-wide `glow` on this page. Same semantics as `texture`
    /// above: unset = inherit, any Some value wins over the site config.
    #[serde(default)]
    pub glow: Option<Glow>,
    /// How `shell: deck` pages export to PDF. `slides` (default): one slide per
    /// landscape page, Keynote-style. `continuous`: all slides flow on a single
    /// scrolling document with a thin separator between them — nicer for
    /// sharing as a readable artifact rather than a presentation. `square`:
    /// one slide per square page, sized for LinkedIn-style document carousels
    /// where the viewport is near-square and landscape PDFs letterbox badly.
    #[serde(default)]
    pub print_flow: Option<PrintFlow>,
    /// Hub-shell grouping config. Required when `shell: hub`; ignored on
    /// other shells.
    #[serde(default)]
    pub hub: Option<HubConfig>,
    /// Extra search keywords that don't appear in rendered content.
    /// Useful for aliases, acronyms, internal jargon.
    #[serde(default)]
    pub search_terms: Vec<String>,
    /// Optional freshness metadata: owner, last content update, review cadence,
    /// and sources of truth the agent / reader can consult to refresh the
    /// page. When the page is past its review window, a banner is injected
    /// at the top of the rendered output and the build reports the page as
    /// stale. Zero runtime JS — staleness is computed at `kazam build` time.
    /// Set to `"never"` to explicitly opt out of freshness checks with no
    /// warning emitted.
    #[serde(default)]
    pub freshness: Option<FreshnessValue>,
    /// Who is responsible for this page. Free-form string — email, Slack
    /// handle, or team name. Serves as a fallback for `freshness.owner` in
    /// the stale-page report when no freshness block is present.
    #[serde(default)]
    pub owner: Option<String>,
    /// AI tool pack marker. Present = this page is installable via
    /// `kazam install` — its markdown components compile into local AI
    /// config files. Validation requires at least one non-empty markdown
    /// component (top-level or inside a section) when this is set.
    #[serde(default)]
    pub pack: Option<PackMeta>,
    /// Links to sources of truth that inform this page's content.
    /// Each entry has a URL and an optional note explaining what it references.
    #[serde(default)]
    pub references: Vec<Reference>,
    /// Role-based persona tags for this page. Values are freeform strings
    /// matching roles defined in kazam.yaml (e.g. "everyone", "engineering",
    /// "gtm", "product", "ops"). Pages with no personas default to being
    /// visible to everyone. Used by nav filtering and role-map components.
    #[serde(default)]
    pub personas: Vec<String>,
    /// Manually archive this page. Archived pages are still rendered (accessible
    /// via direct URL) but excluded from nav, search, llms.txt, and sitemap.
    /// A banner is injected at build time. Pages past their `freshness.expires`
    /// date are auto-archived without needing this flag.
    #[serde(default)]
    pub archived: bool,
    /// Mark this page as a draft. Drafts are excluded from nav, search,
    /// llms.txt, and sitemap and get a "Draft" banner at build time.
    /// Drafts that sit unchanged for 30+ days are auto-archived.
    #[serde(default)]
    pub draft: bool,
    /// Override the site-wide `nav_layout` on this page. Unset = inherit.
    #[serde(default)]
    pub nav_layout: Option<NavLayout>,
    /// Override the site-wide `nav` on this page. Unset = inherit.
    #[serde(default)]
    pub nav: Option<Vec<NavLink>>,
}

impl Page {
    pub fn is_archived(&self, today: &str) -> bool {
        if self.archived {
            return true;
        }
        let freshness = self.freshness.as_ref().and_then(|fv| fv.as_full());
        if crate::freshness::is_expired(freshness, today) {
            return true;
        }
        if self.draft {
            return crate::freshness::is_stale_draft(freshness, today);
        }
        false
    }
}

/// Freshness value: either the bare string `"never"` (explicit opt-out —
/// no decay checks, no warning) or a full metadata struct.
#[derive(Deserialize, Clone)]
#[serde(untagged)]
pub enum FreshnessValue {
    /// Bare string `"never"` — page explicitly opts out of freshness checks.
    Never(FreshnessNever),
    /// Full freshness metadata struct.
    Full(Freshness),
}

impl FreshnessValue {
    /// Return the inner `Freshness` struct if this is a `Full` variant.
    pub fn as_full(&self) -> Option<&Freshness> {
        match self {
            FreshnessValue::Full(f) => Some(f),
            FreshnessValue::Never(_) => None,
        }
    }

    /// True when the value is `"never"`.
    pub fn is_never(&self) -> bool {
        matches!(self, FreshnessValue::Never(_))
    }
}

/// Captures the bare `"never"` string via serde rename.
#[derive(Deserialize, Clone)]
pub enum FreshnessNever {
    #[serde(rename = "never")]
    Never,
}

/// One reference entry. A URL pointing to a source of truth for this page's
/// content, with an optional short note explaining what it covers.
#[derive(Deserialize, Clone)]
pub struct Reference {
    /// URL to the source (PR, Slack thread, meeting notes, doc, etc.)
    pub url: String,
    /// Short description of what this reference covers
    #[serde(default)]
    pub note: Option<String>,
}

/// Freshness metadata for a page — when was it last updated, who owns it,
/// how often should it be reviewed, and where are the sources of truth.
#[derive(Deserialize, Clone)]
pub struct Freshness {
    /// ISO date (YYYY-MM-DD) of the last content update.
    pub updated: Option<String>,
    /// Review cadence. Accepts `Nd` (days), `Nw` (weeks), `Nm` (months,
    /// 30-day approximation), `Ny` (years, 365-day approximation), or the
    /// string shortcuts `weekly`, `monthly`, `quarterly`, `yearly`,
    /// `annually`.
    pub review_every: Option<String>,
    /// Who should be contacted before changes land. Free-form — email,
    /// Slack handle, or team name.
    pub owner: Option<String>,
    /// Pointers the agent / reader should consult to refresh the content.
    /// Shorthand form is a bare URL string; expanded form accepts a label
    /// alongside the href.
    #[serde(default)]
    pub sources_of_truth: Option<Vec<SourceOfTruth>>,
    /// Hard expiration date (ISO YYYY-MM-DD). Pages past this date are
    /// treated as expired — excluded from nav/search, rendered with an
    /// "expired" banner. For time-bound content like event materials or
    /// campaign pages.
    #[serde(default)]
    pub expires: Option<String>,
    /// How this page gets refreshed — bare string (prompt shorthand) or
    /// full config with mode + steps. Not used by the build.
    #[serde(default)]
    pub refresh: Option<RefreshValue>,
}

/// One source-of-truth entry. Either a bare URL or a labeled link.
#[derive(Deserialize, Clone)]
#[serde(untagged)]
pub enum SourceOfTruth {
    Simple(String),
    Full { label: String, href: String },
}

impl SourceOfTruth {
    pub fn href(&self) -> &str {
        match self {
            SourceOfTruth::Simple(h) => h,
            SourceOfTruth::Full { href, .. } => href,
        }
    }
    pub fn label(&self) -> &str {
        match self {
            SourceOfTruth::Simple(h) => h,
            SourceOfTruth::Full { label, .. } => label,
        }
    }
}

/// How a page gets refreshed: human-only, fully automated, or
/// script + LLM + human review.
#[derive(Debug, Deserialize, Clone)]
#[serde(untagged)]
pub enum RefreshValue {
    /// Bare string shorthand — assisted mode with a single prompt step.
    Prompt(String),
    /// Full refresh configuration with mode and steps.
    Full(RefreshConfig),
}

/// Full refresh configuration.
#[derive(Debug, Deserialize, Clone)]
pub struct RefreshConfig {
    /// human | auto | assisted. Defaults to assisted.
    #[serde(default)]
    pub mode: RefreshMode,
    /// Ordered recipe: run (shell), prompt (LLM), review (human checkpoint).
    #[serde(default)]
    pub steps: Vec<RefreshStep>,
}

/// Refresh mode.
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(rename_all = "lowercase")]
pub enum RefreshMode {
    Human,
    Auto,
    #[default]
    Assisted,
}

/// One step in a refresh recipe.
#[derive(Debug, Deserialize, Clone)]
#[serde(rename_all = "lowercase")]
pub enum RefreshStep {
    /// Shell command to run (e.g. a data-gathering script).
    Run(String),
    /// Prompt for an LLM agent.
    Prompt(String),
    /// Human review checkpoint. Value is who reviews (e.g. "owner").
    Review(String),
}

#[derive(Deserialize, Clone, Copy, Default)]
#[serde(rename_all = "snake_case")]
pub enum PrintFlow {
    #[default]
    Slides,
    Continuous,
    Square,
}

#[derive(Deserialize)]
pub struct Slide {
    pub label: String,
    pub components: Vec<Component>,
    /// Slide heading, rendered left-aligned by default. When set, the slide
    /// owns its title directly and no nested section is needed.
    #[serde(default)]
    pub title: Option<String>,
    /// Kicker above the title (e.g. "STAGE 1").
    #[serde(default)]
    pub eyebrow: Option<String>,
    /// Optional supporting line under the title.
    #[serde(default)]
    pub subtitle: Option<String>,
    /// Content alignment: "left" (default) or "center".
    #[serde(default)]
    pub align: Option<String>,
    /// Vertical alignment of slide content: "center" (default) or "top".
    #[serde(default)]
    pub valign: Option<String>,
    /// Cover/title slide: centered, oversized hero layout.
    #[serde(default)]
    pub cover: bool,
    /// Hide the nav label from the slide body. Does NOT affect alignment;
    /// use `cover` or `align: center` for centered layouts.
    #[serde(default)]
    pub hide_label: bool,
}

// ── Components ───────────────────────────────────────

#[derive(Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Component {
    Header {
        title: String,
        subtitle: Option<String>,
        eyebrow: Option<String>,
        #[serde(default)]
        align: Align,
        /// Optional stable anchor id on the rendered wrapper. When unset,
        /// kazam auto-slugs from `title` (lowercase, hyphens, punctuation
        /// stripped) so `#deep-link` URLs Just Work. An explicit id wins
        /// over the auto-slug so copy changes don't break existing
        /// bookmarks. Collisions on the same page suffix `-2`, `-3`, etc.
        #[serde(default)]
        id: Option<String>,
    },
    HeroBanner {
        title: String,
        eyebrow: Option<String>,
        subtitle: Option<String>,
        buttons: Option<Vec<ButtonConfig>>,
    },
    Meta {
        fields: Vec<MetaField>,
    },
    CardGrid {
        cards: Vec<Card>,
        #[serde(default)]
        min_width: Option<u32>,
        #[serde(default)]
        connector: Connector,
    },
    SelectableGrid {
        cards: Vec<SelectableCard>,
        #[serde(default)]
        interaction: Interaction,
        #[serde(default)]
        connector: Connector,
    },
    Timeline {
        items: Vec<TimelineItem>,
    },
    StatGrid {
        stats: Vec<Stat>,
        #[serde(default = "default_stat_columns")]
        columns: u32,
    },
    BeforeAfter {
        items: Vec<BeforeAfterItem>,
        #[serde(default)]
        before_label: Option<String>,
        #[serde(default)]
        after_label: Option<String>,
    },
    SplitCompare {
        left: ComparePanel,
        right: ComparePanel,
    },
    Steps {
        items: Vec<Step>,
        #[serde(default = "default_true")]
        numbered: bool,
    },
    Markdown {
        body: String,
    },
    Table {
        columns: Vec<TableColumn>,
        rows: Vec<HashMap<String, serde_yaml::Value>>,
        #[serde(default)]
        filterable: bool,
        #[serde(default)]
        summary: Option<TableSummary>,
    },
    Callout {
        #[serde(default)]
        variant: CalloutVariant,
        title: Option<String>,
        body: String,
        links: Option<Vec<ButtonConfig>>,
    },
    Code {
        language: Option<String>,
        code: String,
    },
    Tabs {
        tabs: Vec<Tab>,
    },
    Section {
        heading: Option<String>,
        eyebrow: Option<String>,
        components: Vec<Component>,
        #[serde(default)]
        align: Align,
        /// Optional stable anchor id on the rendered wrapper. When unset
        /// and `heading` is present, kazam auto-slugs from the heading
        /// text. Explicit id wins. Same collision handling as `header`.
        /// No heading and no explicit id → no id attribute emitted.
        #[serde(default)]
        id: Option<String>,
    },
    Columns {
        columns: Vec<Vec<Component>>,
        #[serde(default)]
        equal_heights: bool,
    },
    Accordion {
        items: Vec<AccordionItem>,
    },
    EventTimeline {
        events: Vec<EventItem>,
        #[serde(default)]
        default_filter: EventFilter,
        #[serde(default)]
        show_filter_toggle: bool,
        #[serde(default)]
        limit: Option<u32>,
        #[serde(default)]
        filter_by: Vec<String>,
        #[serde(default)]
        group_by: Option<EventGroupBy>,
    },
    Tree {
        nodes: Vec<TreeNode>,
        #[serde(default)]
        default_filter: TreeFilter,
        #[serde(default)]
        show_filter_toggle: bool,
        #[serde(default)]
        default_collapsed: bool,
        #[serde(default)]
        default_depth: Option<u32>,
        #[serde(default)]
        show_counts: bool,
        #[serde(default)]
        show_summary: bool,
        #[serde(default)]
        default_view: TreeDefaultView,
    },
    PriorityQueue {
        items: Vec<QueueItem>,
        #[serde(default)]
        group_by: QueueGroup,
        #[serde(default = "default_true")]
        show_dates: bool,
        #[serde(default = "default_true")]
        show_counts: bool,
        #[serde(default)]
        filterable: bool,
        #[serde(default)]
        title: Option<String>,
    },
    Venn {
        sets: Vec<VennSet>,
        #[serde(default)]
        overlaps: Vec<VennOverlap>,
        #[serde(default)]
        title: Option<String>,
    },
    Image {
        src: String,
        alt: Option<String>,
        caption: Option<String>,
        max_width: Option<u32>,
        #[serde(default)]
        align: Align,
    },
    /// Responsive iframe embed for Loom, YouTube, Vimeo, etc.
    Embed {
        src: String,
        title: Option<String>,
        aspect: Option<String>,
    },
    /// Structured link collection with per-item metadata. Consolidates
    /// the "page that's just a few links" pattern into a reviewable list.
    Resources {
        items: Vec<ResourceItem>,
    },
    Badge {
        label: String,
        #[serde(default)]
        color: SemColor,
    },
    Tag {
        label: String,
        #[serde(default)]
        color: SemColor,
    },
    Divider {
        label: Option<String>,
    },
    Kbd {
        keys: Vec<String>,
    },
    Status {
        label: String,
        #[serde(default)]
        color: SemColor,
    },
    Breadcrumb {
        items: Vec<BreadcrumbItem>,
    },
    ButtonGroup {
        buttons: Vec<ButtonConfig>,
    },
    DefinitionList {
        items: Vec<DefinitionItem>,
    },
    Blockquote {
        body: String,
        attribution: Option<String>,
    },
    Avatar {
        name: String,
        src: Option<String>,
        #[serde(default)]
        size: AvatarSize,
        subtitle: Option<String>,
    },
    AvatarGroup {
        avatars: Vec<AvatarConfig>,
        #[serde(default)]
        size: AvatarSize,
        #[serde(default = "default_avatar_max")]
        max: usize,
    },
    ProgressBar {
        value: u8,
        label: Option<String>,
        #[serde(default)]
        color: SemColor,
        detail: Option<String>,
        #[serde(default)]
        target: Option<u8>,
        #[serde(default)]
        thresholds: HashMap<String, SemColor>,
    },
    EmptyState {
        title: String,
        body: Option<String>,
        action: Option<EmptyStateAction>,
        #[serde(default)]
        icon: Option<String>,
    },
    Icon {
        name: String,
        #[serde(default)]
        size: IconSize,
        #[serde(default)]
        color: SemColor,
    },
    Chart {
        kind: ChartKind,
        title: Option<String>,
        /// Pixel height of the chart area. Width is fluid (SVG scales to the
        /// container). Defaults depend on `kind` — see the renderer.
        #[serde(default)]
        height: Option<u32>,
        /// Axis labels. Ignored by `pie`.
        #[serde(default)]
        x_label: Option<String>,
        #[serde(default)]
        y_label: Option<String>,
        /// Bar charts only: lay bars horizontally instead of vertically.
        #[serde(default)]
        orientation: ChartOrientation,
        /// Single-series data. Use for pie slices, or for bar/timeseries
        /// without a second dimension. Mutually exclusive with `series`.
        #[serde(default)]
        data: Option<Vec<ChartPoint>>,
        /// Multi-series data (one extra dimension). For bar → stacked bars.
        /// For timeseries → multi-line. Ignored by pie.
        #[serde(default)]
        series: Option<Vec<ChartSeries>>,
    },
    /// Grid of role cards read from the site's `roles:` config in kazam.yaml.
    /// Each card links to `?role=<id>` to activate persona filtering.
    RoleMap {
        #[serde(default)]
        title: Option<String>,
    },
    Sankey {
        title: Option<String>,
        #[serde(default)]
        height: Option<u32>,
        flows: Vec<SankeyFlow>,
        #[serde(default)]
        colors: HashMap<String, SemColor>,
    },
    Radar {
        title: Option<String>,
        #[serde(default)]
        height: Option<u32>,
        axes: Vec<String>,
        curves: Vec<RadarCurve>,
        #[serde(default)]
        max: Option<f64>,
    },
    Quadrant {
        title: Option<String>,
        #[serde(default)]
        height: Option<u32>,
        x_axis: String,
        y_axis: String,
        quadrants: Vec<String>,
        points: Vec<QuadrantPoint>,
    },
    Architecture {
        title: Option<String>,
        #[serde(default)]
        height: Option<u32>,
        #[serde(default)]
        direction: ArchDirection,
        nodes: Vec<ArchNode>,
        connections: Vec<ArchConnection>,
    },
    Pipeline {
        title: Option<String>,
        #[serde(default)]
        height: Option<u32>,
        inputs: Vec<PipelineItem>,
        stages: Vec<PipelineStage>,
        outputs: Vec<PipelineItem>,
        #[serde(default)]
        context: Vec<PipelineItem>,
    },
    Graph {
        title: Option<String>,
        #[serde(default)]
        height: Option<u32>,
        #[serde(default)]
        direction: ArchDirection,
        nodes: Vec<GraphNode>,
        #[serde(default)]
        edges: Vec<GraphEdge>,
        #[serde(default)]
        groups: Vec<GraphGroup>,
    },
    OrgChart {
        title: Option<String>,
        people: Vec<OrgPerson>,
        #[serde(default)]
        default_open_depth: Option<u32>,
    },
    Aside {
        body: String,
    },
    RuleList {
        items: Vec<RuleItem>,
    },
    Gauge {
        items: Vec<GaugeItem>,
        #[serde(default)]
        title: Option<String>,
        #[serde(default = "default_gauge_columns")]
        columns: u32,
        #[serde(default = "default_gauge_max")]
        max: f64,
    },
}

// ── Supporting types ─────────────────────────────────

#[derive(Deserialize)]
pub struct MetaField {
    pub key: String,
    pub value: String,
}

#[derive(Deserialize)]
pub struct Card {
    pub title: String,
    pub badge: Option<Badge>,
    pub description: Option<String>,
    pub links: Option<Vec<Link>>,
    pub href: Option<String>,
    #[serde(default)]
    pub color: SemColor,
}

#[derive(Deserialize)]
pub struct Badge {
    pub label: String,
    #[serde(default)]
    pub color: SemColor,
}

/// Unified semantic color palette used by badge, tag, status, progress_bar,
/// and the stat color accents. Keeps all colored decoration consistent.
#[derive(Deserialize, Default, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum SemColor {
    #[default]
    Default,
    Green,
    Yellow,
    Red,
    Teal,
}

impl SemColor {
    pub fn class_suffix(&self) -> &'static str {
        match self {
            SemColor::Default => "default",
            SemColor::Green => "green",
            SemColor::Yellow => "yellow",
            SemColor::Red => "red",
            SemColor::Teal => "teal",
        }
    }

    pub fn hex(&self) -> &'static str {
        match self {
            SemColor::Default => "#3CCECE",
            SemColor::Green => "#34D399",
            SemColor::Yellow => "#FBBF24",
            SemColor::Red => "#F87171",
            SemColor::Teal => "#3CCECE",
        }
    }
}

#[derive(Deserialize)]
pub struct Link {
    pub label: String,
    pub href: String,
}

#[derive(Deserialize)]
pub struct SelectableCard {
    pub title: String,
    pub eyebrow: Option<String>,
    pub bullets: Option<Vec<String>>,
    pub body: Option<String>,
    #[serde(default)]
    pub color: SemColor,
}

#[derive(Deserialize, Default, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum Interaction {
    #[default]
    SingleSelect,
    MultiSelect,
    None,
}

#[derive(Deserialize, Default, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum Connector {
    #[default]
    None,
    DotsLine,
    Arrow,
}

#[derive(Deserialize)]
pub struct TimelineItem {
    pub name: String,
    pub status: TimelineStatus,
}

#[derive(Deserialize, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum TimelineStatus {
    Completed,
    Active,
    Upcoming,
}

#[derive(Deserialize)]
pub struct Stat {
    pub label: String,
    pub value: String,
    pub detail: Option<String>,
    #[serde(default)]
    pub color: SemColor,
    #[serde(default)]
    pub trend: Option<Trend>,
    #[serde(default)]
    pub previous: Option<String>,
    #[serde(default)]
    pub history: Option<Vec<f64>>,
}

#[derive(Deserialize, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum Trend {
    Up,
    Down,
    Flat,
}

impl Trend {
    pub fn class(&self) -> &'static str {
        match self {
            Trend::Up => "trend-up",
            Trend::Down => "trend-down",
            Trend::Flat => "trend-flat",
        }
    }

    pub fn arrow(&self) -> &'static str {
        match self {
            Trend::Up => "↑",
            Trend::Down => "↓",
            Trend::Flat => "→",
        }
    }
}

#[derive(Deserialize)]
pub struct BeforeAfterItem {
    pub title: String,
    pub before: String,
    pub after: String,
    pub after_context: Option<String>,
}

#[derive(Deserialize, Clone)]
pub struct ComparePanel {
    #[serde(default)]
    pub eyebrow: Option<String>,
    pub title: String,
    pub stats: Vec<CompareStat>,
}

#[derive(Deserialize, Clone)]
pub struct CompareStat {
    pub label: String,
    pub value: String,
    #[serde(default)]
    pub color: SemColor,
}

#[derive(Deserialize)]
pub struct Step {
    pub title: String,
    pub detail: Option<String>,
}

#[derive(Deserialize)]
pub struct TableColumn {
    pub key: String,
    pub label: String,
    #[serde(default)]
    pub sortable: bool,
    #[serde(default)]
    pub align: Align,
    #[serde(default)]
    pub color_map: HashMap<String, SemColor>,
}

#[derive(Deserialize, Default, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum Align {
    #[default]
    Left,
    Right,
    Center,
}

impl Align {
    pub fn class(&self) -> &'static str {
        match self {
            Align::Left => "align-left",
            Align::Right => "align-right",
            Align::Center => "align-center",
        }
    }
}

#[derive(Deserialize, Default, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum CalloutVariant {
    #[default]
    Info,
    Warn,
    Success,
    Danger,
}

impl CalloutVariant {
    pub fn class(&self) -> &'static str {
        match self {
            CalloutVariant::Info => "c-callout-info",
            CalloutVariant::Warn => "c-callout-warn",
            CalloutVariant::Success => "c-callout-success",
            CalloutVariant::Danger => "c-callout-danger",
        }
    }
}

#[derive(Deserialize)]
pub struct Tab {
    pub label: String,
    pub components: Vec<Component>,
}

#[derive(Deserialize)]
pub struct AccordionItem {
    pub title: String,
    pub components: Vec<Component>,
}

#[derive(Deserialize)]
pub struct EventItem {
    pub date: String,
    pub title: String,
    #[serde(default)]
    pub summary: Option<String>,
    #[serde(default)]
    pub severity: EventSeverity,
    #[serde(default)]
    pub source: Option<String>,
    #[serde(default)]
    pub link: Option<String>,
    #[serde(default)]
    pub tags: Vec<String>,
}

#[derive(Deserialize, Default, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum EventSeverity {
    Major,
    #[default]
    Minor,
    Info,
}

impl EventSeverity {
    pub fn class(&self) -> &'static str {
        match self {
            EventSeverity::Major => "severity-major",
            EventSeverity::Minor => "severity-minor",
            EventSeverity::Info => "severity-info",
        }
    }

    pub fn label(&self) -> &'static str {
        match self {
            EventSeverity::Major => "major",
            EventSeverity::Minor => "minor",
            EventSeverity::Info => "info",
        }
    }
}

#[derive(Deserialize, Default, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum EventFilter {
    #[default]
    All,
    Major,
}

impl EventFilter {
    pub fn class(&self) -> &'static str {
        match self {
            EventFilter::All => "filter-all",
            EventFilter::Major => "filter-major",
        }
    }

    pub fn label(&self) -> &'static str {
        match self {
            EventFilter::All => "all",
            EventFilter::Major => "major",
        }
    }
}

#[derive(Deserialize, Default, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum EventGroupBy {
    #[default]
    Month,
    Quarter,
    Source,
}

#[derive(Deserialize, Clone)]
pub struct TreeNode {
    pub label: String,
    #[serde(default)]
    pub status: TreeStatus,
    #[serde(default)]
    pub note: Option<String>,
    #[serde(default)]
    pub children: Vec<TreeNode>,
    #[serde(default)]
    pub owner: Option<String>,
    #[serde(default)]
    pub due: Option<String>,
    #[serde(default)]
    pub original_due: Option<String>,
}

#[derive(Deserialize, Default, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum TreeStatus {
    #[default]
    Default,
    Completed,
    Active,
    Blocked,
    Priority,
    Upcoming,
}

#[derive(Deserialize, Default, Clone, Copy, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum TreeFilter {
    #[default]
    All,
    Incomplete,
    Blocked,
    Priority,
    Overdue,
}

#[derive(Deserialize, Serialize, Default, Clone, Copy, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum TreeDefaultView {
    #[default]
    Tree,
    Summary,
}

#[derive(Deserialize, Default, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum QueueGroup {
    #[default]
    Urgency,
    Horizon,
    Owner,
    Status,
    None,
}

#[derive(Debug, Deserialize, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum QueueHorizon {
    Now,
    Next,
    Later,
}

#[derive(Deserialize, Clone)]
pub struct QueueTag {
    pub label: String,
    #[serde(default)]
    pub color: SemColor,
    #[serde(default)]
    pub emphasis: bool,
}

#[derive(Deserialize, Clone)]
pub struct QueueItem {
    pub label: String,
    #[serde(default)]
    pub detail: Option<String>,
    #[serde(default)]
    pub due: Option<String>,
    #[serde(default)]
    pub original_due: Option<String>,
    #[serde(default)]
    pub owner: Option<String>,
    #[serde(default)]
    pub status: TreeStatus,
    #[serde(default)]
    pub tags: Vec<QueueTag>,
    #[serde(default)]
    pub href: Option<String>,
    #[serde(default)]
    pub horizon: Option<QueueHorizon>,
}

impl TreeFilter {
    pub fn class(&self) -> &'static str {
        match self {
            TreeFilter::All => "filter-all",
            TreeFilter::Incomplete => "filter-incomplete",
            TreeFilter::Blocked => "filter-blocked",
            TreeFilter::Priority => "filter-priority",
            TreeFilter::Overdue => "filter-overdue",
        }
    }

    pub fn label(&self) -> &'static str {
        match self {
            TreeFilter::All => "all",
            TreeFilter::Incomplete => "incomplete",
            TreeFilter::Blocked => "blocked",
            TreeFilter::Priority => "priority",
            TreeFilter::Overdue => "overdue",
        }
    }
}

impl TreeStatus {
    pub fn class(&self) -> &'static str {
        match self {
            TreeStatus::Default => "status-default",
            TreeStatus::Completed => "status-completed",
            TreeStatus::Active => "status-active",
            TreeStatus::Blocked => "status-blocked",
            TreeStatus::Priority => "status-priority",
            TreeStatus::Upcoming => "status-upcoming",
        }
    }

    pub fn glyph(&self) -> &'static str {
        match self {
            TreeStatus::Default => "•",
            TreeStatus::Completed => "✓",
            TreeStatus::Active => "▸",
            TreeStatus::Blocked => "⚠",
            TreeStatus::Priority => "★",
            TreeStatus::Upcoming => "○",
        }
    }

    pub fn label(&self) -> &'static str {
        match self {
            TreeStatus::Default => "default",
            TreeStatus::Completed => "completed",
            TreeStatus::Active => "active",
            TreeStatus::Blocked => "blocked",
            TreeStatus::Priority => "priority",
            TreeStatus::Upcoming => "upcoming",
        }
    }
}

#[derive(Deserialize)]
pub struct TableSummary {
    pub group_by: String,
    #[serde(default)]
    pub colors: HashMap<String, SemColor>,
}

#[derive(Deserialize)]
pub struct GaugeItem {
    pub label: String,
    pub value: f64,
    #[serde(default)]
    pub color: SemColor,
}

#[derive(Deserialize)]
pub struct RuleItem {
    pub label: String,
    pub body: String,
    #[serde(default)]
    pub color: SemColor,
}

#[derive(Deserialize)]
pub struct VennSet {
    pub label: String,
    #[serde(default)]
    pub color: SemColor,
}

#[derive(Deserialize)]
pub struct VennOverlap {
    /// Indices into `sets[]`. Length 2 or 3.
    pub sets: Vec<usize>,
    #[serde(default)]
    pub label: Option<String>,
}

// ── New component supporting types ───────────────────

#[derive(Deserialize)]
pub struct BreadcrumbItem {
    pub label: String,
    pub href: Option<String>,
}

#[derive(Deserialize, Default, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum ButtonVariant {
    #[default]
    Primary,
    Secondary,
    Ghost,
}

#[derive(Deserialize)]
pub struct ButtonConfig {
    pub label: String,
    pub href: String,
    #[serde(default)]
    pub variant: ButtonVariant,
    #[serde(default)]
    pub external: bool,
    pub icon: Option<String>,
}

#[derive(Deserialize, Default, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum IconSize {
    Xs,
    Sm,
    #[default]
    Md,
    Lg,
    Xl,
}

impl IconSize {
    pub fn pixels(&self) -> u32 {
        match self {
            IconSize::Xs => 12,
            IconSize::Sm => 14,
            IconSize::Md => 16,
            IconSize::Lg => 20,
            IconSize::Xl => 24,
        }
    }
}

#[derive(Deserialize)]
pub struct DefinitionItem {
    pub term: String,
    pub definition: String,
}

#[derive(Deserialize)]
pub struct AvatarConfig {
    pub name: String,
    pub src: Option<String>,
}

#[derive(Deserialize, Default, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum AvatarSize {
    Sm,
    #[default]
    Md,
    Lg,
    Xl,
}

impl AvatarSize {
    pub fn class_suffix(&self) -> &'static str {
        match self {
            AvatarSize::Sm => "sm",
            AvatarSize::Md => "md",
            AvatarSize::Lg => "lg",
            AvatarSize::Xl => "xl",
        }
    }
}

#[derive(Deserialize)]
pub struct EmptyStateAction {
    pub label: String,
    pub href: String,
}

// ── Chart supporting types ───────────────────────────

#[derive(Deserialize, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum ChartKind {
    Pie,
    Bar,
    Timeseries,
}

#[derive(Deserialize, Default, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ChartOrientation {
    #[default]
    Vertical,
    Horizontal,
}

#[derive(Deserialize)]
pub struct ChartPoint {
    pub label: String,
    pub value: f64,
    /// Optional slice/bar tint. Only meaningful for single-series charts —
    /// multi-series charts color by series instead.
    #[serde(default)]
    pub color: Option<SemColor>,
}

#[derive(Deserialize)]
pub struct ChartSeries {
    pub label: String,
    /// Series tint. Defaults cycle through teal → green → yellow → red.
    #[serde(default)]
    pub color: Option<SemColor>,
    pub points: Vec<ChartPoint>,
}

// ── Sankey supporting types ─────────────────────────

#[derive(Deserialize)]
pub struct SankeyFlow {
    pub source: String,
    pub target: String,
    pub value: f64,
}

// ── Radar supporting types ──────────────────────────

#[derive(Deserialize)]
pub struct RadarCurve {
    pub label: String,
    pub values: Vec<f64>,
    #[serde(default)]
    pub color: Option<SemColor>,
}

// ── Quadrant supporting types ───────────────────────

#[derive(Deserialize)]
pub struct QuadrantPoint {
    pub label: String,
    pub x: f64,
    pub y: f64,
    #[serde(default)]
    pub color: Option<SemColor>,
}

// ── Architecture supporting types ───────────────────

#[derive(Deserialize, Default, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum ArchDirection {
    #[default]
    LeftToRight,
    TopToBottom,
}

#[derive(Deserialize)]
pub struct ArchNode {
    pub id: String,
    pub label: String,
    #[serde(default)]
    pub detail: Option<String>,
    #[allow(dead_code)]
    #[serde(default)]
    pub icon: Option<String>,
    #[serde(default)]
    pub color: SemColor,
}

#[derive(Deserialize)]
pub struct ArchConnection {
    pub from: String,
    pub to: String,
    #[serde(default)]
    pub label: Option<String>,
}

// ── Pipeline supporting types ───────────────────────

#[derive(Deserialize)]
pub struct PipelineItem {
    pub label: String,
    #[serde(default)]
    pub detail: Option<String>,
    #[serde(default)]
    pub color: SemColor,
    #[serde(default)]
    pub dim: bool,
}

#[derive(Deserialize)]
pub struct PipelineStage {
    pub label: String,
    #[serde(default)]
    pub detail: Option<String>,
    #[serde(default)]
    pub capabilities: Vec<PipelineCapability>,
}

#[derive(Deserialize)]
pub struct PipelineCapability {
    pub label: String,
    #[serde(default)]
    pub detail: Option<String>,
    #[serde(default)]
    pub dim: bool,
}

// ── Graph supporting types ───────────────────────────

#[derive(Deserialize, Default, Clone, Copy, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum GraphShape {
    #[default]
    Box,
    Diamond,
    Pill,
}

#[derive(Deserialize, Default, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum GraphEdgeStyle {
    #[default]
    Solid,
    Dashed,
}

#[derive(Deserialize, Clone)]
pub struct OrgPerson {
    #[serde(default)]
    #[allow(dead_code)]
    pub id: Option<String>,
    pub name: String,
    #[serde(default)]
    pub title: Option<String>,
    #[serde(default)]
    pub color: SemColor,
    #[serde(default)]
    pub email: Option<String>,
    #[serde(default)]
    pub linkedin: Option<String>,
    #[serde(default)]
    pub tags: Vec<OrgTag>,
    #[serde(default)]
    pub reports: Vec<OrgPerson>,
}

#[derive(Deserialize, Clone)]
pub struct OrgTag {
    pub label: String,
    #[serde(default)]
    pub color: SemColor,
}

#[derive(Deserialize)]
pub struct GraphNode {
    pub id: String,
    pub label: String,
    #[serde(default)]
    pub detail: Option<String>,
    #[serde(default)]
    pub color: SemColor,
    #[serde(default)]
    pub shape: GraphShape,
    #[serde(default)]
    pub group: Option<String>,
    #[serde(default)]
    pub width: Option<u32>,
    #[serde(default)]
    pub height: Option<u32>,
    #[serde(default)]
    pub ports: Vec<PortLabel>,
}

#[derive(Deserialize)]
pub struct GraphEdge {
    pub from: String,
    pub to: String,
    #[serde(default)]
    pub label: Option<String>,
    #[serde(default)]
    pub style: GraphEdgeStyle,
    #[serde(default)]
    pub color: Option<SemColor>,
}

#[derive(Deserialize)]
pub struct GraphGroup {
    pub id: String,
    #[serde(default)]
    pub label: Option<String>,
    #[serde(default)]
    pub parent: Option<String>,
    #[serde(default)]
    pub color: Option<SemColor>,
}

#[derive(Deserialize, Default, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum PortSide {
    #[default]
    Right,
    Left,
    Top,
    Bottom,
}

#[derive(Deserialize)]
pub struct PortLabel {
    pub side: PortSide,
    pub label: String,
}

// ── Site config ──────────────────────────────────────

#[derive(Deserialize)]
pub struct NavLink {
    pub label: String,
    /// Leaf href. Optional only so that a parent grouping entry with `children`
    /// can be a pure label (e.g. "Components ▾" with a dropdown of leaves).
    pub href: Option<String>,
    /// Nested children render as a top-nav dropdown or as nested sidebar
    /// entries depending on `SiteConfig.nav_layout`.
    #[serde(default)]
    pub children: Option<Vec<NavLink>>,
    /// Persona filter. When set, this link is only visible to the listed
    /// roles. Rendered as `data-personas` attributes for client-side
    /// filtering via `?role=` query param.
    #[serde(default)]
    pub personas: Vec<String>,
    /// When true, child subsections render collapsed by default. Users can
    /// click the subsection label to expand. Only meaningful on section-level
    /// entries that have children with their own children.
    #[serde(default)]
    pub collapsed: bool,
}

impl NavLink {
    /// Ensure hrefs are root-relative so sidebar links work from any page depth.
    /// Bare paths like `scanners/wiz.html` become `/scanners/wiz.html`.
    /// Already-absolute (`/…`) and external (`http…`) hrefs are left alone.
    pub fn normalize_hrefs(&mut self) {
        if let Some(ref mut h) = self.href {
            if !h.starts_with('/') && !h.starts_with("http") {
                *h = format!("/{h}");
            }
        }
        if let Some(ref mut kids) = self.children {
            for child in kids.iter_mut() {
                child.normalize_hrefs();
            }
        }
    }
}

/// How the sticky nav is laid out on `shell: standard` pages. Other shells
/// ignore this.
#[derive(Deserialize, Default, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum NavLayout {
    /// Horizontal top-bar nav (default). Nested entries render as dropdowns.
    #[default]
    Top,
    /// Fixed left-side sidebar. Nested entries render as labeled sections.
    Sidebar,
}

/// Base tone for the site. Only affects rainbow themes (`red`/`orange`/…/
/// `violet`), which pick up the accent color on top of either a dark or
/// light neutral base. `theme: dark` and `theme: light` are self-contained
/// and ignore this field.
#[derive(Deserialize, Default, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum Mode {
    #[default]
    Dark,
    Light,
}

#[derive(Deserialize)]
pub struct SiteConfig {
    pub name: String,
    pub theme: Option<String>,
    #[serde(default)]
    pub colors: std::collections::HashMap<String, String>,
    pub nav: Option<Vec<NavLink>>,
    pub favicon: Option<Favicon>,
    /// Optional logo image shown in the site bar's brand slot, replacing the
    /// text `name:` treatment. Accepts either a path (shorthand) or an
    /// object with `src`, optional `height`, and optional `alt`. The image's
    /// `src` resolves via the depth-aware rewriter so relative paths work
    /// from any subfolder page.
    #[serde(default)]
    pub logo: Option<Logo>,
    /// Source pill with edit prompt, GitHub link, and source view. On by
    /// default. Set `view_source: false` to opt out.
    #[serde(default)]
    pub view_source: Option<bool>,
    /// Subtle background pattern painted behind every page. Tinted via the
    /// theme's `--text-rgb` so it stays consistent across light/dark.
    /// Defaults to `none`.
    #[serde(default)]
    pub texture: Texture,
    /// Soft accent-colored glow painted behind the page header area.
    /// Defaults to `none`.
    #[serde(default)]
    pub glow: Glow,
    /// Nav layout for `shell: standard` pages. Defaults to `top`.
    #[serde(default)]
    pub nav_layout: NavLayout,
    /// Base tone for rainbow themes — dark (default) or light. Ignored when
    /// `theme:` is already `dark` or `light`.
    #[serde(default)]
    pub mode: Mode,
    /// Fallback `<meta name="description">` and `og:description` used when a
    /// page has no subtitle of its own. Keep it short — one sentence is ideal.
    #[serde(default)]
    pub description: Option<String>,
    /// Canonical base URL for the site, e.g. `https://tdiderich.github.io/kazam`.
    /// When set, each page gets a `<link rel="canonical">` and populated
    /// `og:url` / `twitter:url` meta. Leave unset on sites that don't care
    /// about social unfurls.
    #[serde(default)]
    pub url: Option<String>,
    #[serde(default)]
    pub edit_url: Option<String>,
    /// Site-wide social card image (Open Graph + Twitter card). Path is
    /// resolved relative to the site root. 1200×630 PNG is the standard;
    /// SVG works on modern platforms. Optional.
    #[serde(default)]
    pub og_image: Option<String>,
    /// Brand voice rules for consistent content authoring across agents and humans.
    #[serde(default)]
    pub voice: Option<Voice>,
    /// Persona role taxonomy. Defines the roles that pages can be tagged
    /// with via their `personas:` field. Order determines display order in
    /// the role-map component and nav filter.
    #[serde(default)]
    pub roles: Vec<Role>,
    /// Mapping from source-of-truth URL prefixes to local repo paths.
    /// Used by `kazam freshness drift` to check git history.
    #[serde(default)]
    pub drift: Option<DriftConfig>,
}

/// Brand voice configuration — tone, reading level, and terminology preferences.
/// All fields are optional; add what you want. This is config only — kazam does
/// not enforce these rules at build time.
#[derive(Deserialize, Clone, Default)]
pub struct Voice {
    /// Tone description, e.g. "direct, technical, no marketing fluff"
    #[serde(default)]
    pub tone: Option<String>,
    /// Target reading level, e.g. "senior engineer", "general audience"
    #[serde(default)]
    pub reading_level: Option<String>,
    /// Terminology preferences
    #[serde(default)]
    pub terminology: Option<Terminology>,
}

/// Preferred and avoided terms for consistent language across content authors.
#[derive(Deserialize, Clone, Default)]
pub struct Terminology {
    /// Preferred term replacements: key = avoid, value = use instead
    #[serde(default)]
    pub prefer: std::collections::HashMap<String, String>,
    /// Terms to avoid entirely
    #[serde(default)]
    pub avoid: Vec<String>,
}

/// Mapping from source-of-truth URL prefixes to local repo paths.
/// Used by `kazam freshness drift` to check git history.
#[derive(Deserialize, Clone, Default)]
pub struct DriftConfig {
    #[serde(default)]
    pub repos: Vec<DriftRepo>,
}

/// One repo mapping entry for drift detection.
#[derive(Deserialize, Clone)]
pub struct DriftRepo {
    /// URL prefix to match against sources_of_truth hrefs
    pub prefix: String,
    /// Local filesystem path to the git repo
    pub local: String,
}

/// One role in the site's persona taxonomy.
#[derive(Deserialize, Clone)]
pub struct Role {
    /// Machine identifier, matches values in page `personas:` fields.
    pub id: String,
    /// Human-readable label.
    pub label: String,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub icon: Option<String>,
    /// Landing page for this role. Rendered as the card href in the role_map
    /// component. When unset, the card links to `?role=<id>`.
    #[serde(default)]
    pub href: Option<String>,
}

/// One item in a `resources` component.
#[derive(Deserialize)]
pub struct ResourceItem {
    pub title: String,
    pub href: String,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub owner: Option<String>,
}

/// Site-wide background pattern. All variants are subtle by design.
#[derive(Deserialize, Default, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum Texture {
    #[default]
    None,
    /// 1px dots on a 24px grid.
    Dots,
    /// Thin gridlines on a 40px grid.
    Grid,
    /// SVG fractal-noise grain.
    Grain,
    /// Wavy contour-line topography.
    Topography,
    /// 45° diagonal stripes.
    Diagonal,
}

/// Soft accent-tinted radial gradient. Sits above the texture, below content.
#[derive(Deserialize, Default, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum Glow {
    #[default]
    None,
    /// Wide soft glow centered above the fold.
    Accent,
    /// Tighter glow tucked into the top-right corner.
    Corner,
}

/// Logo image for the site-bar brand slot. Accepts either a shorthand
/// string (a path to the image) or an object with `src`, optional
/// `height` (px — upper bound on rendered height; defaults to the
/// site-bar content height), and optional `alt` (defaults to the site
/// `name`).
#[derive(Deserialize)]
#[serde(untagged)]
pub enum Logo {
    Simple(String),
    Full {
        src: String,
        #[serde(default)]
        height: Option<u32>,
        #[serde(default)]
        alt: Option<String>,
    },
}

impl Logo {
    pub fn src(&self) -> &str {
        match self {
            Logo::Simple(p) => p,
            Logo::Full { src, .. } => src,
        }
    }
    pub fn height(&self) -> Option<u32> {
        match self {
            Logo::Simple(_) => None,
            Logo::Full { height, .. } => *height,
        }
    }
    pub fn alt<'a>(&'a self, site_name: &'a str) -> &'a str {
        match self {
            Logo::Simple(_) => site_name,
            Logo::Full { alt, .. } => alt.as_deref().unwrap_or(site_name),
        }
    }
}

/// Favicon config: either a single path, or a struct with named slots.
#[derive(Deserialize)]
#[serde(untagged)]
pub enum Favicon {
    Simple(String),
    Full {
        svg: Option<String>,
        png: Option<String>,
        ico: Option<String>,
        apple_touch_icon: Option<String>,
    },
}

impl Favicon {
    /// Render <link> tags (already resolved against base path).
    pub fn render(&self, base: &str) -> String {
        let resolve = |p: &str| crate::render::resolve_href(p, base);
        match self {
            Favicon::Simple(path) => {
                let mime = mime_for(path);
                format!(
                    r#"<link rel="icon" type="{}" href="{}">"#,
                    mime,
                    resolve(path)
                )
            }
            Favicon::Full {
                svg,
                png,
                ico,
                apple_touch_icon,
            } => {
                let mut out = String::new();
                if let Some(p) = svg {
                    out.push_str(&format!(
                        r#"<link rel="icon" type="image/svg+xml" href="{}">"#,
                        resolve(p)
                    ));
                }
                if let Some(p) = png {
                    out.push_str(&format!(
                        r#"<link rel="icon" type="image/png" href="{}">"#,
                        resolve(p)
                    ));
                }
                if let Some(p) = ico {
                    out.push_str(&format!(
                        r#"<link rel="icon" type="image/x-icon" href="{}">"#,
                        resolve(p)
                    ));
                }
                if let Some(p) = apple_touch_icon {
                    out.push_str(&format!(
                        r#"<link rel="apple-touch-icon" href="{}">"#,
                        resolve(p)
                    ));
                }
                out
            }
        }
    }
}

fn mime_for(path: &str) -> &'static str {
    let lower = path.to_lowercase();
    if lower.ends_with(".svg") {
        "image/svg+xml"
    } else if lower.ends_with(".png") {
        "image/png"
    } else if lower.ends_with(".ico") {
        "image/x-icon"
    } else if lower.ends_with(".jpg") || lower.ends_with(".jpeg") {
        "image/jpeg"
    } else {
        "image/png"
    }
}

impl SiteConfig {
    pub fn resolved_theme(&self) -> crate::theme::Theme {
        let base = self.theme.as_deref().unwrap_or("dark");
        crate::theme::Theme::named(base, self.mode).with_overrides(&self.colors)
    }
}

impl Default for SiteConfig {
    fn default() -> Self {
        SiteConfig {
            name: String::from("My Site"),
            theme: None,
            colors: std::collections::HashMap::new(),
            nav: None,
            favicon: None,
            logo: None,
            view_source: None,
            texture: Texture::None,
            glow: Glow::None,
            nav_layout: NavLayout::Top,
            mode: Mode::Dark,
            description: None,
            url: None,
            edit_url: None,
            og_image: None,
            voice: None,
            roles: Vec::new(),
            drift: None,
        }
    }
}

// ── Defaults ─────────────────────────────────────────

fn default_stat_columns() -> u32 {
    3
}
fn default_true() -> bool {
    true
}
fn default_avatar_max() -> usize {
    5
}
fn default_gauge_columns() -> u32 {
    3
}
fn default_gauge_max() -> f64 {
    100.0
}

// ── Annotations ─────────────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Annotation {
    pub id: String,
    pub text: String,
    pub author: String,
    #[serde(default)]
    pub section: Option<String>,
    pub added: String,
    #[serde(default)]
    pub status: AnnotationStatus,
    #[serde(default)]
    pub source: AnnotationSource,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum AnnotationStatus {
    #[default]
    Pending,
    Incorporated,
    Ignored,
    Stale,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum AnnotationSource {
    #[default]
    Cli,
    Agent,
    Web,
}

pub fn value_to_string(v: &serde_yaml::Value) -> String {
    match v {
        serde_yaml::Value::Null => String::new(),
        serde_yaml::Value::Bool(b) => b.to_string(),
        serde_yaml::Value::Number(n) => n.to_string(),
        serde_yaml::Value::String(s) => s.clone(),
        serde_yaml::Value::Sequence(_) | serde_yaml::Value::Mapping(_) => {
            serde_yaml::to_string(v).unwrap_or_default()
        }
        serde_yaml::Value::Tagged(t) => value_to_string(&t.value),
    }
}

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

    #[test]
    fn value_to_string_handles_all_scalar_types() {
        use serde_yaml::Value;
        assert_eq!(value_to_string(&Value::Null), "");
        assert_eq!(value_to_string(&Value::Bool(true)), "true");
        assert_eq!(value_to_string(&Value::Number(42.into())), "42");
        assert_eq!(value_to_string(&Value::String("hi".into())), "hi");
    }

    #[test]
    fn sem_color_class_suffix() {
        assert_eq!(SemColor::Default.class_suffix(), "default");
        assert_eq!(SemColor::Green.class_suffix(), "green");
        assert_eq!(SemColor::Yellow.class_suffix(), "yellow");
        assert_eq!(SemColor::Red.class_suffix(), "red");
        assert_eq!(SemColor::Teal.class_suffix(), "teal");
    }

    #[test]
    fn sem_color_hex_values() {
        assert_eq!(SemColor::Green.hex(), "#34D399");
        assert_eq!(SemColor::Red.hex(), "#F87171");
        assert_eq!(SemColor::Default.hex(), "#3CCECE");
    }
}