k2f_core 0.3.2

K2F semantic tree, lock types, and hashes
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
use serde::{Deserialize, Serialize};
use std::fmt;
use std::ops::{Add, AddAssign, Div, Mul, Sub, SubAssign};
use thiserror::Error;

mod appearance_hash;
mod break_policy;
mod canonical_json;
mod columns;
mod compositing;
mod content_hash;
pub mod effects;
mod engine_identity;
mod hit_test;
mod layout_hints;
mod nfc;
mod node_edit;
mod node_ids;
mod node_walk;
mod paint_plan;
mod paint_types;
mod role_variant_validation;
mod running_blocks;
mod running_blocks_validation;
mod search;
mod selection;
mod semantic_code_blocks;
mod semantic_form_fields;
mod semantic_lists;
mod semantic_math;
mod sha256_hex;
mod svg_text;
mod table_assets;
mod table_span;
mod theme_vocab;
pub mod visual_primitives;

#[cfg(test)]
mod semantic_code_blocks_tests;
#[cfg(test)]
mod semantic_form_fields_tests;
#[cfg(test)]
mod semantic_math_tests;

pub use appearance_hash::{hash_appearance_binding, AppearanceHashInput};
pub use break_policy::{BreakBefore, BreakInside};
pub use canonical_json::{canonical_json_string, canonicalize_json_value};
pub use columns::ColumnSpan;
pub use compositing::*;
pub use content_hash::{hash_content, hash_manifest_semantic};
pub use engine_identity::{engine_commit_sha, engine_version};
pub use hit_test::{
    box_contains, clusters_usable, collect_boxes, hit_char_range, hit_geometry, hit_layout,
    hit_page, semantic_ids, with_text_range, Hit,
};
pub use layout_hints::*;

/// True when `path` is a TrueType/OpenType face (filename `.ttf` / `.otf`), case-insensitive.
/// Sidecar files such as `licenses/Roboto-Apache.txt` are not faces.
/// The in-memory key `"default"` used by compile/paint helpers counts as a face.
pub fn is_font_face_path(path: &str) -> bool {
    let name = path.rsplit(['/', '\\']).next().unwrap_or(path);
    if name.eq_ignore_ascii_case("default") {
        return true;
    }
    let ext = name.rsplit('.').next().unwrap_or("");
    ext.eq_ignore_ascii_case("ttf") || ext.eq_ignore_ascii_case("otf")
}
pub use nfc::{nfc, normalize_manifest_nfc};
pub use node_edit::{
    apply_role, collect_ids_under, find_in_trees, find_in_trees_mut, insert_child, node_text,
    remove_node, replace_node_text, tree_contains_id, NodeEditError,
};
pub use node_ids::{
    collect_sorted_node_ids, is_valid_node_id, validate_manifest_node_ids, NODE_ID_PATTERN,
};
pub use node_walk::{find_node, find_node_mut, for_each_node, for_each_node_mut};
pub use paint_plan::*;
pub use paint_types::*;
pub use role_variant_validation::validate_semantic_tree_with_theme_vocab;
pub use running_blocks::*;
pub use running_blocks_validation::validate_manifest_running_blocks;
pub use search::{search_tree, search_trees};
pub use selection::{clipboard_of, selection_of, selection_with_ids, Clipboard, Selection};
pub use semantic_code_blocks::CodeBlockValue;
pub use semantic_form_fields::{
    for_each_form_field, for_each_form_field_in_trees, FormFieldKind, FormFieldSpec,
    CHECKBOX_CHECKED, CHECKBOX_UNCHECKED, ROLE_FORM_FIELD,
};
pub use semantic_lists::ListMarkerType;
pub use semantic_math::ROLE_MATH;
pub use sha256_hex::sha256_hex;
pub use svg_text::{
    looks_like_svg, svg_bytes_contain_text_element, svg_image_path, validate_svg_assets,
    SVG_TEXT_FORBIDDEN_MSG,
};
pub use table_assets::{
    collapse_tables_to_assets, expand_manifest_tables_with_assets, semantic_tree_needs_assets,
    table_asset_sources, AssetsMap,
};
pub use table_span::{
    table_cell_colspan, table_row_cover, table_row_slots, table_rows_on_page, TableCellSlot,
};
pub use theme_vocab::ThemeVocab;
pub use visual_primitives::*;

/// Fixed-point coordinate type (1/1000th of a point).
/// Wraps an i128 to prevent overflow and ensure determinism.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
pub struct Pt(pub i128);

impl Pt {
    pub const ZERO: Pt = Pt(0);

    pub fn new(val: i128) -> Self {
        Pt(val)
    }

    /// Lossy conversion from float, useful for debugging or initial inputs
    pub fn from_f64_pt(val: f64) -> Self {
        Pt((val * 1000.0) as i128)
    }

    pub fn as_f64_pt(&self) -> f64 {
        self.0 as f64 / 1000.0
    }
}

// JSON numbers are effectively i64/u64. Keep `Pt` internal arithmetic as i128, but
// serialize/deserialize using i64 for compatibility with serde_json.
impl Serialize for Pt {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let v: i64 = self
            .0
            .try_into()
            .map_err(|_| serde::ser::Error::custom("Pt value out of i64 range"))?;
        serializer.serialize_i64(v)
    }
}

impl<'de> Deserialize<'de> for Pt {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let v = i64::deserialize(deserializer)?;
        Ok(Pt(v as i128))
    }
}

impl fmt::Display for Pt {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}pt", self.as_f64_pt())
    }
}

impl Add for Pt {
    type Output = Pt;
    fn add(self, rhs: Pt) -> Pt {
        Pt(self.0 + rhs.0)
    }
}

impl Sub for Pt {
    type Output = Pt;
    fn sub(self, rhs: Pt) -> Pt {
        Pt(self.0 - rhs.0)
    }
}

// Multiplication by scalar
impl Mul<i128> for Pt {
    type Output = Pt;
    fn mul(self, rhs: i128) -> Pt {
        Pt(self.0 * rhs)
    }
}

// Division by scalar
impl Div<i128> for Pt {
    type Output = Pt;
    fn div(self, rhs: i128) -> Pt {
        Pt(self.0 / rhs)
    }
}

impl AddAssign for Pt {
    fn add_assign(&mut self, rhs: Pt) {
        self.0 += rhs.0;
    }
}

impl SubAssign for Pt {
    fn sub_assign(&mut self, rhs: Pt) {
        self.0 -= rhs.0;
    }
}

/// Represents a semantic node in the K2F document tree (State A).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SemanticNode {
    /// Hierarchical ID, e.g., "financials.q3.table"
    pub id: String,
    /// Semantic role, e.g., "critical_warning"
    pub role: String,
    /// Optional visual variant name for this role.
    ///
    /// The allowed variants are defined by the theme (role-driven).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub variant: Option<String>,
    /// Optional whitespace preservation hint.
    ///
    /// When role is "code_block", engine validation requires this to be true (or omitted).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub preserve_whitespace: Option<bool>,
    /// Optional list group identifier (required by validation when role == "list_item").
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub list_id: Option<String>,
    /// Optional nesting depth (defaults to 0 when omitted).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub depth: Option<u32>,
    /// Optional marker style ("bullet" | "number").
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub marker_type: Option<ListMarkerType>,
    /// Content of the node
    pub content: NodeContent,
    /// Semantic modifiers (max 50)
    #[serde(default)]
    pub modifiers: Vec<Modifier>,
    /// Optional deterministic layout hint for containers (stack/grid). If absent, engine uses defaults.
    #[serde(default, deserialize_with = "layout_hints::deserialize_layout_hint")]
    pub layout: Option<LayoutHint>,
    /// Page-split policy. Agents choose an enum; they cannot invent break math.
    #[serde(default, skip_serializing_if = "BreakInside::is_auto")]
    pub break_inside: BreakInside,
    /// If true, this node and the next sibling must start on the same page when possible.
    #[serde(default, skip_serializing_if = "break_policy::is_false")]
    pub keep_with_next: bool,
    /// When `page`, start this node on a new page when not already at the content top.
    #[serde(default, skip_serializing_if = "BreakBefore::is_auto")]
    pub break_before: BreakBefore,
    /// When `all`, this node spans the full width of an enclosing columns container.
    #[serde(default, skip_serializing_if = "ColumnSpan::is_none")]
    pub column_span: ColumnSpan,
    /// Table-cell column occupancy (same row only). Omit or `1` = one track.
    /// Illegal outside a table cell (`COLSPAN_OUTSIDE_TABLE`).
    #[serde(
        default = "default_colspan",
        skip_serializing_if = "is_default_colspan"
    )]
    pub colspan: u32,
}

fn default_colspan() -> u32 {
    1
}

fn is_default_colspan(v: &u32) -> bool {
    *v == 1
}

impl Default for SemanticNode {
    fn default() -> Self {
        Self {
            id: String::new(),
            role: "body".to_string(),
            variant: None,
            preserve_whitespace: None,
            list_id: None,
            depth: None,
            marker_type: None,
            content: NodeContent::Text(String::new()),
            modifiers: vec![],
            layout: None,
            break_inside: BreakInside::Auto,
            keep_with_next: false,
            break_before: BreakBefore::Auto,
            column_span: ColumnSpan::None,
            colspan: 1,
        }
    }
}

/// Deterministic layout hint for container nodes.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum LayoutHint {
    Stack {
        #[serde(default)]
        direction: StackDirection,
        /// Gap between children in fixed-point units (1/1000th of a point).
        ///
        /// NOTE: This is stored as an integer (not `Pt`) to avoid deserialization paths
        /// that go through `serde_json::Value` (internally tagged enums), where `i128`
        /// is not supported. Layout computations convert this to `Pt` at the boundary.
        #[serde(default)]
        gap: i64,
        /// Cross-axis alignment for stack children.
        #[serde(default)]
        align_items: Align,
        /// Main-axis distribution for stack children.
        #[serde(default)]
        justify_content: JustifyContent,
        /// Optional fixed outer size for the container.
        #[serde(flatten, default)]
        size: FixedSizeHint,
    },
    Grid {
        columns: Vec<GridTrack>,
        /// Omitted or empty: engine fills `{auto:true}` rows to fit children.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        rows: Vec<GridTrack>,
        /// Gap between tracks in fixed-point units (1/1000th of a point).
        #[serde(default)]
        gap: i64,
        /// Optional row gap override. Falls back to `gap` when omitted.
        #[serde(default)]
        row_gap: Option<i64>,
        /// Optional column gap override. Falls back to `gap` when omitted.
        #[serde(default)]
        column_gap: Option<i64>,
        /// Default per-cell alignment for grid children.
        #[serde(default)]
        cell_align: Option<CellAlign>,
        /// Optional fixed outer size (needed for `fr` tracks in unbounded flow).
        #[serde(flatten, default)]
        size: FixedSizeHint,
    },
    /// Children are visually stacked in source order (first = back, last = front).
    ///
    /// This exists to model deterministic layering without numeric z-index semantics.
    Overlay {
        /// Optional fixed outer size for the container.
        #[serde(flatten, default)]
        size: FixedSizeHint,
    },
    /// Continuous multi-column flow: children pack left-to-right across equal-width columns.
    Columns {
        /// Number of columns (engine validates 2..=4).
        count: u32,
        /// Gap between columns in fixed-point Pt (1/1000 pt units).
        #[serde(default)]
        gap: i64,
    },
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum StackDirection {
    Vertical,
    Horizontal,
}

impl Default for StackDirection {
    fn default() -> Self {
        StackDirection::Vertical
    }
}

/// Explicit deterministic track sizes (`pt`, `fr`, or content-sized `auto`).
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum GridTrack {
    /// Fixed track size in Pt (1/1000 pt units)
    Pt { pt: i64 },
    /// Fractional track size (fr units). Distributed from remaining space.
    Fr { fr: i64 },
    /// Content-sized track. `{ "auto": true }` only. Measure cells, then give leftover to `fr`.
    Auto { auto: bool },
}

impl GridTrack {
    pub fn is_auto(&self) -> bool {
        matches!(self, GridTrack::Auto { auto: true })
    }
}

/// When `rows` is omitted (empty), synthesize `{auto:true}` tracks so every child has a cell:
/// `max(1, ceil(n_children / n_columns))`. Declared `rows` are used as-is (not CSS implicit growth).
pub fn grid_rows_for_children(
    columns: &[GridTrack],
    rows: &[GridTrack],
    n_children: usize,
) -> Vec<GridTrack> {
    if !rows.is_empty() {
        return rows.to_vec();
    }
    let n_cols = columns.len().max(1);
    let n_rows = n_children.div_ceil(n_cols).max(1);
    vec![GridTrack::Auto { auto: true }; n_rows]
}

/// Strict table payload for `content.type = "table"` (State A).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TableSpec {
    /// Explicit deterministic column tracks (Pt/Fr). Must be non-empty.
    pub column_widths: Vec<GridTrack>,
    /// Number of initial rows to repeat at page breaks in paged mode.
    #[serde(default)]
    pub header_rows: usize,
    /// Fixed-point Pt gap between columns/rows (1/1000 pt units).
    ///
    /// Stored as i64 for serde_json compatibility (same rationale as LayoutHint::Stack.gap).
    /// Omitted `row_gap` / `column_gap` fall back to this value (same as grid).
    #[serde(default)]
    pub gap: i64,
    /// Optional row gap override. Falls back to `gap` when omitted.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub row_gap: Option<i64>,
    /// Optional column gap override. Falls back to `gap` when omitted.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub column_gap: Option<i64>,
    /// Table data source (v1: inline rows only).
    pub data: TableDataSource,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum TableDataSource {
    /// Inline rows (AI-friendly): each cell is a normal SemanticNode.
    Inline { rows: Vec<Vec<SemanticNode>> },
    /// Asset-backed rows: callers must provide an explicit assets map at compile time.
    ///
    /// The `source` string is a logical key into the assets map (e.g. `"assets/data/table.json"`).
    Asset { source: String },
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type", content = "value", rename_all = "snake_case")]
pub enum NodeContent {
    Text(String),
    CodeBlock(CodeBlockValue),
    /// TeX-subset math source (NFC-normalized). Display formulas use role `"math"`.
    Math(String),
    /// Fillable field. Declared box size; `value` does not drive measure.
    FormField(FormFieldSpec),
    /// Deterministic image sizing (in Pt). The engine does not inspect binary image assets.
    /// Callers must provide a stable size hint to eliminate placeholders.
    Image {
        src: String,
        width: Pt,
        height: Pt,
    },
    Container {
        #[serde(default)]
        children: Vec<SemanticNode>,
    },
    /// Native strict table node (v1: inline rows only).
    Table(TableSpec),
    /// Deterministic table sizing (in Pt). The engine does not load external table datasets at layout time.
    /// Callers must provide a stable size hint to eliminate placeholders.
    TableReference {
        source: String,
        view_mode: String,
        width: Pt,
        height: Pt,
    },
}

impl NodeContent {
    /// JSON `content.type` tag for this variant.
    pub fn type_name(&self) -> &'static str {
        match self {
            NodeContent::Text(_) => "text",
            NodeContent::CodeBlock(_) => "code_block",
            NodeContent::Math(_) => "math",
            NodeContent::FormField(_) => "form_field",
            NodeContent::Image { .. } => "image",
            NodeContent::Container { .. } => "container",
            NodeContent::Table(_) => "table",
            NodeContent::TableReference { .. } => "table_reference",
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Modifier {
    pub range: [usize; 2],
    #[serde(rename = "type")]
    pub mod_type: String,
    pub intent: String,
}

/// `link` modifier `intent` is a URL (spec). Theme variant keys such as
/// `default` are style lookups, not hrefs, and must not become Office targets.
pub fn hyperlink_href(intent: &str) -> Option<&str> {
    let t = intent.trim();
    if t.is_empty() {
        return None;
    }
    let lower = t.to_ascii_lowercase();
    if lower == "default" {
        return None;
    }
    if lower.contains("://")
        || lower.starts_with("mailto:")
        || lower.starts_with("tel:")
        || lower.starts_with("www.")
        || t.starts_with('#')
        || t.starts_with('/')
    {
        Some(t)
    } else {
        None
    }
}

/// Solid fill rectangle in page coordinates (millipt). Used for math fraction/radical rules.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct FillRect {
    pub x: Pt,
    pub y: Pt,
    pub width: Pt,
    pub height: Pt,
}

/// Represents a geometry node in the K2F layout tree (State C).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct GeometryNode {
    pub id: String,
    pub x: Pt,
    pub y: Pt,
    pub width: Pt,
    pub height: Pt,
    #[serde(default)]
    pub glyphs: Vec<GlyphPosition>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub text_runs: Vec<TextGlyphRun>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub fill_rects: Vec<FillRect>,
    #[serde(default)]
    pub children: Vec<GeometryNode>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct GlyphPosition {
    pub glyph_id: u32,
    /// UTF-8 **character** index into the node's source string (not a byte offset).
    /// rustybuzz reports byte clusters; layout converts at shape time so this matches
    /// `Selection.char_range`. `CLUSTER_NOT_SOURCE` marks decorative glyphs (list markers).
    /// Old locks without the field deserialize as `0`; all-zero clusters mean "unknown".
    #[serde(default)]
    pub cluster: u32,
    pub x_offset: Pt,
    pub y_offset: Pt,
    pub x_advance: Pt,
    pub y_advance: Pt,
}

impl GlyphPosition {
    /// Glyph is not from the node's source string (e.g. a list marker).
    pub const CLUSTER_NOT_SOURCE: u32 = u32::MAX;
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum CanvasMode {
    Paged,
    Infinite,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PageConfig {
    pub width: Pt,
    pub height: Pt,
    // Top, Right, Bottom, Left
    pub margin: [Pt; 4],
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Page {
    pub index: usize,
    pub width: Pt,
    pub height: Pt,
    pub root: GeometryNode,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct LayoutResult {
    pub pages: Vec<Page>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Manifest {
    pub title: String,
    pub canvas_mode: CanvasMode,
    pub page_config: PageConfig,
    pub root: SemanticNode,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub running_blocks: Vec<RunningBlockNode>,
}

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

    #[test]
    fn test_pt_math() {
        let a = Pt(1000); // 1.0pt
        let b = Pt(2000); // 2.0pt
        assert_eq!(a + b, Pt(3000));
        assert_eq!(b - a, Pt(1000));
        assert_eq!(a * 2, Pt(2000));
        assert_eq!(b / 2, Pt(1000));
    }

    #[test]
    fn font_face_path_accepts_ttf_otf_and_default_skips_sidecars() {
        assert!(is_font_face_path("assets/fonts/Roboto-Regular.ttf"));
        assert!(is_font_face_path("assets/fonts/Noto.OTF"));
        assert!(is_font_face_path("default"));
        assert!(!is_font_face_path(
            "assets/fonts/licenses/Roboto-Apache.txt"
        ));
        assert!(!is_font_face_path("assets/fonts/licenses/LICENSE"));
        assert!(!is_font_face_path("assets/fonts/readme.md"));
    }

    #[test]
    fn omitted_grid_rows_fill_auto_tracks_to_fit_children() {
        let cols = vec![GridTrack::Fr { fr: 1 }, GridTrack::Fr { fr: 1 }];
        let one = grid_rows_for_children(&cols, &[], 2);
        assert_eq!(one, vec![GridTrack::Auto { auto: true }]);
        let two = grid_rows_for_children(&cols, &[], 4);
        assert_eq!(
            two,
            vec![
                GridTrack::Auto { auto: true },
                GridTrack::Auto { auto: true }
            ]
        );
        let declared = vec![GridTrack::Fr { fr: 1 }];
        assert_eq!(grid_rows_for_children(&cols, &declared, 4), declared);
    }

    fn grid_node(n_children: usize, columns: Vec<GridTrack>, rows: Vec<GridTrack>) -> SemanticNode {
        SemanticNode {
            id: "g".to_string(),
            role: "section".to_string(),
            content: NodeContent::Container {
                children: (0..n_children)
                    .map(|i| make_cell_text(&format!("g.c{i}")))
                    .collect(),
            },
            layout: Some(LayoutHint::Grid {
                columns,
                rows,
                gap: 0,
                row_gap: None,
                column_gap: None,
                cell_align: None,
                size: Default::default(),
            }),
            ..Default::default()
        }
    }

    #[test]
    fn omitted_grid_rows_pass_validate_when_children_fit_derived_auto_rows() {
        validate_semantic_tree(&grid_node(
            4,
            vec![GridTrack::Fr { fr: 1 }, GridTrack::Fr { fr: 1 }],
            vec![],
        ))
        .unwrap();
    }

    #[test]
    fn declared_grid_rows_still_reject_overflow_children() {
        let err = validate_semantic_tree(&grid_node(
            4,
            vec![GridTrack::Fr { fr: 1 }, GridTrack::Fr { fr: 1 }],
            vec![GridTrack::Auto { auto: true }],
        ))
        .unwrap_err();
        assert!(matches!(
            err,
            K2FError::GridTooManyChildren {
                children: 4,
                cells: 2,
                ..
            }
        ));
        let msg = err.to_string();
        assert!(
            msg.contains("omit rows to wrap"),
            "error should tell authors to omit rows: {msg}"
        );
    }

    #[test]
    fn test_pt_serialization() {
        let pt = Pt(1500);
        let json = serde_json::to_string(&pt).unwrap();
        assert_eq!(json, "1500");
    }

    #[test]
    fn link_intent_default_is_not_an_href() {
        assert_eq!(hyperlink_href("default"), None);
        assert_eq!(hyperlink_href(""), None);
        assert_eq!(hyperlink_href("bold"), None);
        assert_eq!(
            hyperlink_href("https://example.com"),
            Some("https://example.com")
        );
        assert_eq!(hyperlink_href("mailto:a@b.c"), Some("mailto:a@b.c"));
        assert_eq!(hyperlink_href("#section"), Some("#section"));
    }

    #[test]
    fn test_semantic_node_determinism() {
        let node = SemanticNode {
            id: "test".to_string(),
            role: "body".to_string(),
            variant: None,
            preserve_whitespace: None,
            list_id: None,
            depth: None,
            marker_type: None,
            content: NodeContent::Text("Hello".to_string()),
            modifiers: vec![],
            layout: None,
            ..Default::default()
        };

        let json1 = serde_json::to_string(&node).unwrap();
        let json2 = serde_json::to_string(&node).unwrap();
        assert_eq!(json1, json2);
    }

    #[test]
    fn test_hash_content_determinism() {
        let node = SemanticNode {
            id: "test".to_string(),
            role: "body".to_string(),
            variant: None,
            preserve_whitespace: None,
            list_id: None,
            depth: None,
            marker_type: None,
            content: NodeContent::Text("Hello World".to_string()),
            modifiers: vec![],
            layout: None,
            ..Default::default()
        };

        let hash1 = hash_content(&node);
        let hash2 = hash_content(&node);
        assert_eq!(hash1, hash2);
        assert_eq!(hash1.len(), 64); // SHA256 hex string
    }

    #[test]
    fn test_validate_semantic_tree_rejects_non_positive_image_size() {
        let node = SemanticNode {
            id: "img".to_string(),
            role: "body".to_string(),
            variant: None,
            preserve_whitespace: None,
            list_id: None,
            depth: None,
            marker_type: None,
            content: NodeContent::Image {
                src: "a.png".to_string(),
                width: Pt(0),
                height: Pt(1000),
            },
            modifiers: vec![],
            layout: None,
            ..Default::default()
        };

        let err = validate_semantic_tree(&node).unwrap_err();
        match err {
            K2FError::InvalidImageSize { .. } => {}
            other => panic!("expected InvalidImageSize, got {:?}", other),
        }
    }

    #[test]
    fn test_validate_semantic_tree_rejects_non_positive_table_reference_size() {
        let node = SemanticNode {
            id: "tbl".to_string(),
            role: "table".to_string(),
            variant: None,
            preserve_whitespace: None,
            list_id: None,
            depth: None,
            marker_type: None,
            content: NodeContent::TableReference {
                source: "asset://data/table.csv".to_string(),
                view_mode: "full".to_string(),
                width: Pt(2000),
                height: Pt(0),
            },
            modifiers: vec![],
            layout: None,
            ..Default::default()
        };

        let err = validate_semantic_tree(&node).unwrap_err();
        match err {
            K2FError::InvalidTableReferenceSize { .. } => {}
            other => panic!("expected InvalidTableReferenceSize, got {:?}", other),
        }
    }

    #[test]
    fn test_validate_semantic_tree_rejects_negative_fixed_size() {
        let node = SemanticNode {
            id: "box".to_string(),
            role: "body".to_string(),
            variant: None,
            preserve_whitespace: None,
            list_id: None,
            depth: None,
            marker_type: None,
            content: NodeContent::Container { children: vec![] },
            modifiers: vec![],
            layout: Some(LayoutHint::Overlay {
                size: FixedSizeHint {
                    width: Some(Pt(-1)),
                    height: None,
                },
            }),
            ..Default::default()
        };

        let err = validate_semantic_tree(&node).unwrap_err();
        match err {
            K2FError::InvalidFixedSize { .. } => {}
            other => panic!("expected InvalidFixedSize, got {:?}", other),
        }
    }

    #[test]
    fn test_validate_role_vocab_rejects_unknown_role() {
        let vocab: ThemeVocab = serde_json::from_str(r#"{ "roles": { "body": {} } }"#).unwrap();
        let node = SemanticNode {
            id: "n".to_string(),
            role: "unknown".to_string(),
            variant: None,
            preserve_whitespace: None,
            list_id: None,
            depth: None,
            marker_type: None,
            content: NodeContent::Text("x".to_string()),
            modifiers: vec![],
            layout: None,
            ..Default::default()
        };

        let err = validate_semantic_tree_with_theme_vocab(&node, &vocab).unwrap_err();
        match err {
            K2FError::UnknownRole { .. } => {}
            other => panic!("expected UnknownRole, got {:?}", other),
        }
    }

    #[test]
    fn test_validate_role_vocab_rejects_unknown_variant() {
        let vocab: ThemeVocab =
            serde_json::from_str(r#"{ "roles": { "body": { "variants": { "glass": {} } } } }"#)
                .unwrap();
        let node = SemanticNode {
            id: "n".to_string(),
            role: "body".to_string(),
            variant: Some("not_defined".to_string()),
            preserve_whitespace: None,
            list_id: None,
            depth: None,
            marker_type: None,
            content: NodeContent::Text("x".to_string()),
            modifiers: vec![],
            layout: None,
            ..Default::default()
        };

        let err = validate_semantic_tree_with_theme_vocab(&node, &vocab).unwrap_err();
        match err {
            K2FError::UnknownVariant { .. } => {}
            other => panic!("expected UnknownVariant, got {:?}", other),
        }
    }

    #[test]
    fn test_validate_role_vocab_allows_defined_variant() {
        let vocab: ThemeVocab =
            serde_json::from_str(r#"{ "roles": { "body": { "variants": { "glass": {} } } } }"#)
                .unwrap();
        let node = SemanticNode {
            id: "n".to_string(),
            role: "body".to_string(),
            variant: Some("glass".to_string()),
            preserve_whitespace: None,
            list_id: None,
            depth: None,
            marker_type: None,
            content: NodeContent::Text("x".to_string()),
            modifiers: vec![],
            layout: None,
            ..Default::default()
        };

        validate_semantic_tree_with_theme_vocab(&node, &vocab).unwrap();
    }

    fn make_cell_text(id: &str) -> SemanticNode {
        SemanticNode {
            id: id.to_string(),
            role: "body".to_string(),
            variant: None,
            preserve_whitespace: None,
            list_id: None,
            depth: None,
            marker_type: None,
            content: NodeContent::Text("x".to_string()),
            modifiers: vec![],
            layout: None,
            ..Default::default()
        }
    }

    #[test]
    fn test_validate_semantic_tree_rejects_table_with_empty_column_widths() {
        let node = SemanticNode {
            id: "t".to_string(),
            role: "table".to_string(),
            variant: None,
            preserve_whitespace: None,
            list_id: None,
            depth: None,
            marker_type: None,
            content: NodeContent::Table(TableSpec {
                column_widths: vec![],
                header_rows: 0,
                gap: 0,
                row_gap: None,
                column_gap: None,
                data: TableDataSource::Inline { rows: vec![] },
            }),
            modifiers: vec![],
            layout: None,
            ..Default::default()
        };

        let err = validate_semantic_tree(&node).unwrap_err();
        match err {
            K2FError::TableRequiresColumns { .. } => {}
            other => panic!("expected TableRequiresColumns, got {:?}", other),
        }
    }

    #[test]
    fn grid_track_auto_roundtrips_json() {
        let t: GridTrack = serde_json::from_str(r#"{"auto":true}"#).unwrap();
        assert!(t.is_auto());
        let back = serde_json::to_string(&t).unwrap();
        assert!(back.contains("auto"));
        let pt: GridTrack = serde_json::from_str(r#"{"pt":1000}"#).unwrap();
        assert_eq!(pt, GridTrack::Pt { pt: 1000 });
    }

    #[test]
    fn test_validate_semantic_tree_rejects_table_auto_column() {
        let node = SemanticNode {
            id: "t".to_string(),
            role: "table".to_string(),
            variant: None,
            preserve_whitespace: None,
            list_id: None,
            depth: None,
            marker_type: None,
            content: NodeContent::Table(TableSpec {
                column_widths: vec![GridTrack::Auto { auto: true }],
                header_rows: 0,
                gap: 0,
                row_gap: None,
                column_gap: None,
                data: TableDataSource::Inline {
                    rows: vec![vec![make_cell_text("c0")]],
                },
            }),
            modifiers: vec![],
            layout: None,
            ..Default::default()
        };
        let err = validate_semantic_tree(&node).unwrap_err();
        match err {
            K2FError::TableAutoTrack { .. } => {}
            other => panic!("expected TableAutoTrack, got {other:?}"),
        }
    }

    #[test]
    fn test_validate_semantic_tree_rejects_table_row_len_mismatch() {
        let node = SemanticNode {
            id: "t".to_string(),
            role: "table".to_string(),
            variant: None,
            preserve_whitespace: None,
            list_id: None,
            depth: None,
            marker_type: None,
            content: NodeContent::Table(TableSpec {
                column_widths: vec![GridTrack::Pt { pt: 1000 }, GridTrack::Pt { pt: 1000 }],
                header_rows: 0,
                gap: 0,
                row_gap: None,
                column_gap: None,
                data: TableDataSource::Inline {
                    rows: vec![vec![make_cell_text("c0")]], // should be 2 cells
                },
            }),
            modifiers: vec![],
            layout: None,
            ..Default::default()
        };

        let err = validate_semantic_tree(&node).unwrap_err();
        match err {
            K2FError::TableRowLengthMismatch {
                expected: 2,
                got: 1,
                ..
            } => {}
            other => panic!(
                "expected TableRowLengthMismatch cover 1 vs 2, got {:?}",
                other
            ),
        }
    }

    #[test]
    fn test_validate_semantic_tree_accepts_row_colspan_cover() {
        let mut left = make_cell_text("c0");
        left.colspan = 2;
        let node = SemanticNode {
            id: "t".to_string(),
            role: "table".to_string(),
            variant: None,
            preserve_whitespace: None,
            list_id: None,
            depth: None,
            marker_type: None,
            content: NodeContent::Table(TableSpec {
                column_widths: vec![
                    GridTrack::Pt { pt: 1000 },
                    GridTrack::Pt { pt: 1000 },
                    GridTrack::Pt { pt: 1000 },
                ],
                header_rows: 0,
                gap: 0,
                row_gap: None,
                column_gap: None,
                data: TableDataSource::Inline {
                    rows: vec![vec![left, make_cell_text("c2")]],
                },
            }),
            modifiers: vec![],
            layout: None,
            ..Default::default()
        };
        validate_semantic_tree(&node).unwrap();
    }

    #[test]
    fn test_validate_semantic_tree_rejects_colspan_outside_table() {
        let mut node = make_cell_text("n");
        node.colspan = 2;
        let err = validate_semantic_tree(&node).unwrap_err();
        match err {
            K2FError::ColspanOutsideTable { .. } => {}
            other => panic!("expected ColspanOutsideTable, got {:?}", other),
        }
    }

    #[test]
    fn test_colspan_omits_one_in_json() {
        let n = make_cell_text("c");
        let v: serde_json::Value = serde_json::to_value(&n).unwrap();
        assert!(v.get("colspan").is_none());
        let mut spanned = make_cell_text("c");
        spanned.colspan = 2;
        let v: serde_json::Value = serde_json::to_value(&spanned).unwrap();
        assert_eq!(v["colspan"], 2);
    }

    #[test]
    fn test_validate_semantic_tree_rejects_table_header_rows_too_large() {
        let node = SemanticNode {
            id: "t".to_string(),
            role: "table".to_string(),
            variant: None,
            preserve_whitespace: None,
            list_id: None,
            depth: None,
            marker_type: None,
            content: NodeContent::Table(TableSpec {
                column_widths: vec![GridTrack::Pt { pt: 1000 }],
                header_rows: 1,
                gap: 0,
                row_gap: None,
                column_gap: None,
                data: TableDataSource::Inline { rows: vec![] },
            }),
            modifiers: vec![],
            layout: None,
            ..Default::default()
        };

        let err = validate_semantic_tree(&node).unwrap_err();
        match err {
            K2FError::TableHeaderRowsTooLarge { .. } => {}
            other => panic!("expected TableHeaderRowsTooLarge, got {:?}", other),
        }
    }

    #[test]
    fn test_validate_semantic_tree_recurses_into_table_cells() {
        let bad_cell = SemanticNode {
            id: "bad_img".to_string(),
            role: "body".to_string(),
            variant: None,
            preserve_whitespace: None,
            list_id: None,
            depth: None,
            marker_type: None,
            content: NodeContent::Image {
                src: "a.png".to_string(),
                width: Pt(1000),
                height: Pt(0), // invalid
            },
            modifiers: vec![],
            layout: None,
            ..Default::default()
        };

        let node = SemanticNode {
            id: "t".to_string(),
            role: "table".to_string(),
            variant: None,
            preserve_whitespace: None,
            list_id: None,
            depth: None,
            marker_type: None,
            content: NodeContent::Table(TableSpec {
                column_widths: vec![GridTrack::Pt { pt: 1000 }],
                header_rows: 0,
                gap: 0,
                row_gap: None,
                column_gap: None,
                data: TableDataSource::Inline {
                    rows: vec![vec![bad_cell]],
                },
            }),
            modifiers: vec![],
            layout: None,
            ..Default::default()
        };

        let err = validate_semantic_tree(&node).unwrap_err();
        match err {
            K2FError::InvalidImageSize { .. } => {}
            other => panic!("expected InvalidImageSize, got {:?}", other),
        }
    }

    #[test]
    fn test_validate_semantic_tree_rejects_list_item_missing_list_id() {
        let node = SemanticNode {
            id: "li".to_string(),
            role: semantic_lists::ROLE_LIST_ITEM.to_string(),
            variant: None,
            preserve_whitespace: None,
            list_id: None,
            depth: None,
            marker_type: None,
            content: NodeContent::Text("Item".to_string()),
            modifiers: vec![],
            layout: None,
            ..Default::default()
        };

        let err = validate_semantic_tree(&node).unwrap_err();
        match err {
            K2FError::ListItemMissingListId { .. } => {}
            other => panic!("expected ListItemMissingListId, got {:?}", other),
        }
    }

    #[test]
    fn test_validate_semantic_tree_rejects_list_item_non_text_content() {
        let node = SemanticNode {
            id: "li".to_string(),
            role: semantic_lists::ROLE_LIST_ITEM.to_string(),
            variant: None,
            preserve_whitespace: None,
            list_id: Some("list_a".to_string()),
            depth: Some(0),
            marker_type: None,
            content: NodeContent::Image {
                src: "a.png".to_string(),
                width: Pt(1000),
                height: Pt(1000),
            },
            modifiers: vec![],
            layout: None,
            ..Default::default()
        };

        let err = validate_semantic_tree(&node).unwrap_err();
        match err {
            K2FError::ListItemRequiresTextContent { .. } => {}
            other => panic!("expected ListItemRequiresTextContent, got {:?}", other),
        }
    }

    #[test]
    fn test_validate_semantic_tree_allows_list_item_with_default_depth() {
        let node = SemanticNode {
            id: "li".to_string(),
            role: semantic_lists::ROLE_LIST_ITEM.to_string(),
            variant: None,
            preserve_whitespace: None,
            list_id: Some("list_a".to_string()),
            depth: None,
            marker_type: Some(ListMarkerType::Bullet),
            content: NodeContent::Text("Item".to_string()),
            modifiers: vec![],
            layout: None,
            ..Default::default()
        };

        validate_semantic_tree(&node).unwrap();
    }
}

/// A "Geometry Lock" file representing the final compiled state of a document.
/// It cryptographically binds the semantic input (Content Hash) to the geometric output.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct LockFile {
    pub engine_version: String,
    pub engine_commit_sha: String,
    pub content_hash: String,
    /// Semantic hash + theme + fonts + page_config + engine identity.
    /// Official VALID for sign-off is this binding, not content_hash alone.
    pub appearance_hash: String,
    pub geometry: LayoutResult,
    #[serde(default)]
    pub render_plan: RenderPlan,
}

impl LockFile {
    pub fn has_unknown_paint_ops(&self) -> bool {
        crate::render_plan_has_unknown_ops(&self.render_plan)
    }
}

#[derive(Debug, Error)]
pub enum K2FError {
    #[error("modifier limit exceeded: {count} (max {max}) on node '{node_id}'")]
    ModifierLimitExceeded {
        node_id: String,
        count: usize,
        max: usize,
    },
    #[error("invalid modifier range {range:?} on node '{node_id}'")]
    InvalidModifierRange { node_id: String, range: [usize; 2] },
    #[error("modifier range is not on UTF-8 char boundary {range:?} on node '{node_id}'")]
    ModifierRangeNotOnCharBoundary { node_id: String, range: [usize; 2] },
    #[error("grid layout requires at least 1 column and 1 row on node '{node_id}'")]
    GridRequiresTracks { node_id: String },
    #[error("grid layout has more children ({children}) than cells ({cells}) on node '{node_id}'; omit rows to wrap, or add row tracks (declared rows do not grow)")]
    GridTooManyChildren {
        node_id: String,
        children: usize,
        cells: usize,
    },
    #[error("image node '{node_id}' must have positive size (width={width}, height={height})")]
    InvalidImageSize {
        node_id: String,
        width: Pt,
        height: Pt,
    },
    #[error(
        "table_reference node '{node_id}' must have positive size (width={width}, height={height})"
    )]
    InvalidTableReferenceSize {
        node_id: String,
        width: Pt,
        height: Pt,
    },
    #[error("table node '{node_id}' must have non-negative gap (gap={gap})")]
    InvalidTableGap { node_id: String, gap: i64 },
    #[error("table node '{node_id}' must have at least 1 column_widths track")]
    TableRequiresColumns { node_id: String },
    #[error("table node '{node_id}' column_widths do not support auto tracks; use pt or fr")]
    TableAutoTrack { node_id: String },
    #[error("table node '{node_id}' has header_rows={header_rows} but only {rows} rows")]
    TableHeaderRowsTooLarge {
        node_id: String,
        header_rows: usize,
        rows: usize,
    },
    #[error("table node '{node_id}' row {row} covers {got} columns but expected {expected}")]
    TableRowLengthMismatch {
        node_id: String,
        row: usize,
        expected: usize,
        got: usize,
    },
    #[error("COLSPAN_OUTSIDE_TABLE: node '{node_id}' has colspan outside a table cell")]
    ColspanOutsideTable { node_id: String },
    #[error("table node '{node_id}' uses asset-backed data source '{asset_source}', but assets were not provided")]
    TableAssetDataRequiresAssets {
        node_id: String,
        asset_source: String,
    },
    #[error("fixed container size must be non-negative on node '{node_id}' (width={width:?}, height={height:?})")]
    InvalidFixedSize {
        node_id: String,
        width: Option<Pt>,
        height: Option<Pt>,
    },
    #[error("unknown role '{role}' on node '{node_id}'")]
    UnknownRole { node_id: String, role: String },
    #[error("unknown variant '{variant}' for role '{role}' on node '{node_id}'")]
    UnknownVariant {
        node_id: String,
        role: String,
        variant: String,
    },
    #[error("list item node '{node_id}' is missing required list_id")]
    ListItemMissingListId { node_id: String },
    #[error("list item node '{node_id}' has an empty list_id")]
    ListItemEmptyListId { node_id: String },
    #[error("list item node '{node_id}' must have text content (got {got})")]
    ListItemRequiresTextContent { node_id: String, got: String },
    #[error("code block node '{node_id}' requires content.type = \"code_block\" (got {got})")]
    CodeBlockRoleRequiresCodeBlockContent { node_id: String, got: String },
    #[error("node '{node_id}' has content.type = \"code_block\" but role is '{role}' (expected role \"code_block\")")]
    CodeBlockContentRequiresCodeBlockRole { node_id: String, role: String },
    #[error("code block node '{node_id}' must have preserve_whitespace=true (or omitted)")]
    CodeBlockPreserveWhitespaceMustBeTrue { node_id: String },
    #[error("code block node '{node_id}' cannot specify layout (must be omitted/null)")]
    CodeBlockLayoutNotAllowed { node_id: String },
    #[error("code block node '{node_id}' has disallowed modifier type '{mod_type}' (only \"syntax_highlight\" is allowed)")]
    CodeBlockDisallowedModifierType { node_id: String, mod_type: String },
    #[error("math node '{node_id}' requires content.type = \"math\" (got {got})")]
    MathRoleRequiresMathContent { node_id: String, got: String },
    #[error("node '{node_id}' has content.type = \"math\" but role is '{role}' (expected role \"math\")")]
    MathContentRequiresMathRole { node_id: String, role: String },
    #[error("math node '{node_id}' cannot specify layout (must be omitted/null)")]
    MathLayoutNotAllowed { node_id: String },
    #[error("math node '{node_id}' cannot have modifiers in v1")]
    MathModifiersNotAllowed { node_id: String },
    #[error("math node '{node_id}' has empty TeX source")]
    MathEmpty { node_id: String },
    #[error(
        "FORM_FIELD_ROLE: node '{node_id}' requires content.type = \"form_field\" (got {got})"
    )]
    FormFieldRoleRequiresFormFieldContent { node_id: String, got: String },
    #[error("FORM_FIELD_CONTENT: node '{node_id}' has content.type = \"form_field\" but role is '{role}' (expected role \"form_field\")")]
    FormFieldContentRequiresFormFieldRole { node_id: String, role: String },
    #[error("FORM_FIELD_LAYOUT: form field node '{node_id}' cannot specify layout (must be omitted/null)")]
    FormFieldLayoutNotAllowed { node_id: String },
    #[error("FORM_FIELD_MODIFIERS: form field node '{node_id}' cannot have modifiers")]
    FormFieldModifiersNotAllowed { node_id: String },
    #[error("FORM_FIELD_CHECKBOX_VALUE: form field node '{node_id}' checkbox value must be \"\" or \"true\" (got {got})")]
    FormFieldCheckboxValue { node_id: String, got: String },
    #[error("FORM_FIELD_LINES: form field node '{node_id}' lines must be >= 1 (got {got})")]
    FormFieldLines { node_id: String, got: u32 },
    #[error("FORM_FIELD_SIZE: form field node '{node_id}' width/height must be > 0")]
    FormFieldSize { node_id: String },
    #[error("FORM_FIELD_MAX_LENGTH: form field node '{node_id}' value length {got} exceeds max_length {max}")]
    FormFieldMaxLength {
        node_id: String,
        max: u32,
        got: usize,
    },
    #[error("FORM_FIELD_IN_RUNNING: form field node '{node_id}' cannot appear in a running block")]
    FormFieldInRunning { node_id: String },
    #[error("running blocks are only supported when canvas_mode is 'paged'")]
    RunningBlocksRequirePagedMode,
    #[error("running block node '{node_id}' uses unknown placeholder '{{{{{token}}}}}'")]
    RunningBlockInvalidPlaceholder { node_id: String, token: String },
    #[error("running block node '{node_id}' has unbalanced placeholder braces")]
    RunningBlockUnbalancedPlaceholders { node_id: String },
    #[error("node id is empty")]
    EmptyNodeId,
    #[error("invalid node id '{node_id}' (use dotted ASCII letters, digits, underscore)")]
    InvalidNodeId { node_id: String },
    #[error("duplicate node id '{node_id}'")]
    DuplicateNodeId { node_id: String },
    #[error("COLUMNS_INVALID: node '{node_id}': {reason}")]
    ColumnsInvalid { node_id: String, reason: String },
    #[error("COLUMNS_NESTED: nested columns layout on node '{node_id}'")]
    ColumnsNested { node_id: String },
    #[error("COLUMN_SPAN_OUTSIDE_COLUMNS: node '{node_id}' has column_span all outside a columns container")]
    ColumnSpanOutsideColumns { node_id: String },
}

/// Structural validation that is required by the spec:
/// - max 50 modifiers per node
/// - modifier ranges must be valid (for Text nodes)
pub fn validate_semantic_tree(root: &SemanticNode) -> Result<(), K2FError> {
    validate_node(root)?;
    columns::validate_columns_tree(root)?;
    Ok(())
}

fn validate_node(node: &SemanticNode) -> Result<(), K2FError> {
    validate_node_ctx(node, false)
}

fn validate_node_ctx(node: &SemanticNode, is_table_cell: bool) -> Result<(), K2FError> {
    if node.colspan != 1 && !is_table_cell {
        return Err(K2FError::ColspanOutsideTable {
            node_id: node.id.clone(),
        });
    }

    const MAX_MODIFIERS: usize = 50;
    if node.modifiers.len() > MAX_MODIFIERS {
        return Err(K2FError::ModifierLimitExceeded {
            node_id: node.id.clone(),
            count: node.modifiers.len(),
            max: MAX_MODIFIERS,
        });
    }

    semantic_lists::validate_list_item_invariants(node)?;
    semantic_code_blocks::validate_code_block_invariants(node)?;
    semantic_math::validate_math_invariants(node)?;
    semantic_form_fields::validate_form_field_invariants(node)?;

    match &node.content {
        NodeContent::Text(text) => {
            validate_modifier_ranges_on_text(&node.id, text, &node.modifiers)?
        }
        NodeContent::CodeBlock(value) => {
            let canonical = value.to_canonical_text();
            validate_modifier_ranges_on_text(&node.id, canonical.as_ref(), &node.modifiers)?;
        }
        _ => {}
    }

    match &node.content {
        NodeContent::Image { width, height, .. } => {
            if width.0 <= 0 || height.0 <= 0 {
                return Err(K2FError::InvalidImageSize {
                    node_id: node.id.clone(),
                    width: *width,
                    height: *height,
                });
            }
        }
        NodeContent::Container { children } => {
            // Validate layout hints that are statically checkable
            if let Some(LayoutHint::Stack { size, .. }) = &node.layout {
                validate_fixed_size_hint(&node.id, size)?;
            }
            if let Some(LayoutHint::Overlay { size }) = &node.layout {
                validate_fixed_size_hint(&node.id, size)?;
            }
            if let Some(LayoutHint::Grid {
                columns,
                rows,
                size,
                ..
            }) = &node.layout
            {
                validate_fixed_size_hint(&node.id, size)?;
                if columns.is_empty() {
                    return Err(K2FError::GridRequiresTracks {
                        node_id: node.id.clone(),
                    });
                }
                if !rows.is_empty() {
                    let cells = columns.len() * rows.len();
                    if children.len() > cells {
                        return Err(K2FError::GridTooManyChildren {
                            node_id: node.id.clone(),
                            children: children.len(),
                            cells,
                        });
                    }
                }
            }
            if let Some(LayoutHint::Columns { count, gap }) = &node.layout {
                if !(2..=4).contains(count) {
                    return Err(K2FError::ColumnsInvalid {
                        node_id: node.id.clone(),
                        reason: format!("count must be 2..=4 (got {count})"),
                    });
                }
                if *gap < 0 {
                    return Err(K2FError::ColumnsInvalid {
                        node_id: node.id.clone(),
                        reason: format!("gap must be >= 0 (got {gap})"),
                    });
                }
            }

            for c in children {
                validate_node_ctx(c, false)?;
            }
        }
        NodeContent::Table(spec) => {
            for gap in [Some(spec.gap), spec.row_gap, spec.column_gap]
                .into_iter()
                .flatten()
            {
                if gap < 0 {
                    return Err(K2FError::InvalidTableGap {
                        node_id: node.id.clone(),
                        gap,
                    });
                }
            }
            if spec.column_widths.is_empty() {
                return Err(K2FError::TableRequiresColumns {
                    node_id: node.id.clone(),
                });
            }
            if spec
                .column_widths
                .iter()
                .any(|t| matches!(t, GridTrack::Auto { .. }))
            {
                return Err(K2FError::TableAutoTrack {
                    node_id: node.id.clone(),
                });
            }

            let rows = match &spec.data {
                TableDataSource::Inline { rows } => rows,
                TableDataSource::Asset { source } => {
                    return Err(K2FError::TableAssetDataRequiresAssets {
                        node_id: node.id.clone(),
                        asset_source: source.clone(),
                    });
                }
            };

            if spec.header_rows > rows.len() {
                return Err(K2FError::TableHeaderRowsTooLarge {
                    node_id: node.id.clone(),
                    header_rows: spec.header_rows,
                    rows: rows.len(),
                });
            }

            let expected_cols = spec.column_widths.len();
            for (r, row) in rows.iter().enumerate() {
                for cell in row {
                    if cell.colspan < 1 {
                        return Err(K2FError::TableRowLengthMismatch {
                            node_id: node.id.clone(),
                            row: r,
                            expected: expected_cols,
                            got: 0,
                        });
                    }
                }
                let covered = crate::table_row_cover(row);
                if covered != expected_cols {
                    return Err(K2FError::TableRowLengthMismatch {
                        node_id: node.id.clone(),
                        row: r,
                        expected: expected_cols,
                        got: covered,
                    });
                }
                for cell in row {
                    validate_node_ctx(cell, true)?;
                }
            }
        }
        NodeContent::TableReference { width, height, .. } => {
            if width.0 <= 0 || height.0 <= 0 {
                return Err(K2FError::InvalidTableReferenceSize {
                    node_id: node.id.clone(),
                    width: *width,
                    height: *height,
                });
            }
        }
        _ => {}
    }

    Ok(())
}

fn validate_modifier_ranges_on_text(
    node_id: &str,
    text: &str,
    modifiers: &[Modifier],
) -> Result<(), K2FError> {
    let len = text.len();
    for m in modifiers {
        let [s, e] = m.range;
        if s >= e || e > len {
            return Err(K2FError::InvalidModifierRange {
                node_id: node_id.to_string(),
                range: m.range,
            });
        }
        if !text.is_char_boundary(s) || !text.is_char_boundary(e) {
            return Err(K2FError::ModifierRangeNotOnCharBoundary {
                node_id: node_id.to_string(),
                range: m.range,
            });
        }
    }
    Ok(())
}

fn validate_fixed_size_hint(node_id: &str, size: &FixedSizeHint) -> Result<(), K2FError> {
    let width = size.width;
    let height = size.height;
    if width.map_or(false, |w| w.0 < 0) || height.map_or(false, |h| h.0 < 0) {
        return Err(K2FError::InvalidFixedSize {
            node_id: node_id.to_string(),
            width,
            height,
        });
    }
    Ok(())
}