quillmark-core 0.41.0

Core types and functionality for Quillmark
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
//! # Parsing Module
//!
//! Parsing functionality for markdown documents with YAML frontmatter.
//!
//! ## Overview
//!
//! The `parse` module provides the [`ParsedDocument::from_markdown`] function for parsing markdown documents
//!
//! ## Key Types
//!
//! - [`ParsedDocument`]: Container for parsed frontmatter fields and body content
//! - [`BODY_FIELD`]: Constant for the field name storing document body
//!
//! ## Examples
//!
//! ### Basic Parsing
//!
//! ```
//! use quillmark_core::ParsedDocument;
//!
//! let markdown = r#"---
//! title: My Document
//! author: John Doe
//! ---
//!
//! # Introduction
//!
//! Document content here.
//! "#;
//!
//! let doc = ParsedDocument::from_markdown(markdown).unwrap();
//! let title = doc.get_field("title")
//!     .and_then(|v| v.as_str())
//!     .unwrap_or("Untitled");
//! ```
//!
//! ## Error Handling
//!
//! The [`ParsedDocument::from_markdown`] function returns errors for:
//! - Malformed YAML syntax
//! - Unclosed frontmatter blocks
//! - Multiple global frontmatter blocks
//! - Both QUILL and CARD specified in the same block
//! - Reserved field name usage
//! - Name collisions
//!
//! See [PARSE.md](https://github.com/nibsbin/quillmark/blob/main/designs/PARSE.md) for comprehensive documentation of the Extended YAML Metadata Standard.

use std::collections::HashMap;
use std::str::FromStr;

use crate::error::ParseError;
use crate::value::QuillValue;
use crate::version::QuillReference;

/// The field name used to store the document body
pub const BODY_FIELD: &str = "BODY";

/// A parsed markdown document with frontmatter
#[derive(Debug, Clone)]
pub struct ParsedDocument {
    fields: HashMap<String, QuillValue>,
    quill_ref: QuillReference,
}

impl ParsedDocument {
    /// Create a new ParsedDocument with the given fields
    pub fn new(fields: HashMap<String, QuillValue>) -> Self {
        Self {
            fields,
            quill_ref: QuillReference::latest("__default__".to_string()),
        }
    }

    /// Create a ParsedDocument from fields and quill reference
    pub fn with_quill_ref(fields: HashMap<String, QuillValue>, quill_ref: QuillReference) -> Self {
        Self { fields, quill_ref }
    }

    /// Create a ParsedDocument from markdown string
    pub fn from_markdown(markdown: &str) -> Result<Self, crate::error::ParseError> {
        decompose(markdown)
    }

    /// Get the quill reference (name + version selector)
    pub fn quill_reference(&self) -> &QuillReference {
        &self.quill_ref
    }

    /// Get the document body
    pub fn body(&self) -> Option<&str> {
        self.fields.get(BODY_FIELD).and_then(|v| v.as_str())
    }

    /// Get a specific field
    pub fn get_field(&self, name: &str) -> Option<&QuillValue> {
        self.fields.get(name)
    }

    /// Get all fields (including body)
    pub fn fields(&self) -> &HashMap<String, QuillValue> {
        &self.fields
    }

    /// Create a new ParsedDocument with default values applied
    ///
    /// This method creates a new ParsedDocument with default values applied for any
    /// fields that are missing from the original document but have defaults specified.
    /// Existing fields are preserved and not overwritten.
    ///
    /// # Arguments
    ///
    /// * `defaults` - A HashMap of field names to their default QuillValues
    ///
    /// # Returns
    ///
    /// A new ParsedDocument with defaults applied for missing fields
    pub fn with_defaults(&self, defaults: &HashMap<String, QuillValue>) -> Self {
        let mut fields = self.fields.clone();

        for (field_name, default_value) in defaults {
            // Only apply default if field is missing
            if !fields.contains_key(field_name) {
                fields.insert(field_name.clone(), default_value.clone());
            }
        }

        Self {
            fields,
            quill_ref: self.quill_ref.clone(),
        }
    }

    /// Create a new ParsedDocument with coerced field values
    ///
    /// This method applies type coercions to field values based on the schema.
    /// Coercions include:
    /// - Singular values to arrays when schema expects array
    /// - String "true"/"false" to boolean
    /// - Numbers to boolean (0=false, non-zero=true)
    /// - String numbers to number type
    /// - Boolean to number (true=1, false=0)
    ///
    /// # Arguments
    ///
    /// * `schema` - A JSON Schema object defining expected field types
    ///
    /// # Returns
    ///
    /// A new ParsedDocument with coerced field values
    pub fn with_coercion(&self, schema: &QuillValue) -> Self {
        use crate::schema::coerce_document;

        let coerced_fields = coerce_document(schema, &self.fields);

        Self {
            fields: coerced_fields,
            quill_ref: self.quill_ref.clone(),
        }
    }
}

#[derive(Debug)]
struct MetadataBlock {
    start: usize,                          // Position of opening "---"
    end: usize,                            // Position after closing "---\n"
    yaml_value: Option<serde_json::Value>, // Parsed YAML as JSON (None if empty or parse failed)
    tag: Option<String>,                   // Field name from CARD key
    quill_ref: Option<String>,             // Quill reference from QUILL key
}

/// Validate tag name follows pattern [a-z_][a-z0-9_]*
fn is_valid_tag_name(name: &str) -> bool {
    if name.is_empty() {
        return false;
    }

    let mut chars = name.chars();
    let first = chars.next().unwrap();

    if !first.is_ascii_lowercase() && first != '_' {
        return false;
    }

    for ch in chars {
        if !ch.is_ascii_lowercase() && !ch.is_ascii_digit() && ch != '_' {
            return false;
        }
    }

    true
}

/// Check if a position is inside a fenced code block
///
/// This uses strict fence detection per EXTENDED_MARKDOWN.md specification:
/// - Only exactly 3 backticks (```) are valid fences
/// - Tildes (~~~) are NOT treated as fences
/// - 4+ backticks are NOT treated as fences
fn is_inside_fenced_block(markdown: &str, pos: usize) -> bool {
    let before = &markdown[..pos];
    let mut in_fence = false;

    // Check if document starts with exactly ```
    if is_exact_fence_at(before, 0) {
        in_fence = !in_fence;
    }

    // Scan for fence toggles after newlines
    for (i, _) in before.match_indices('\n') {
        if is_exact_fence_at(before, i + 1) {
            in_fence = !in_fence;
        }
    }

    in_fence
}

/// Check if position starts exactly 3 backticks (not 2, not 4+)
///
/// Strict specification: only exactly ``` is a valid fence marker.
fn is_exact_fence_at(text: &str, pos: usize) -> bool {
    if pos >= text.len() {
        return false;
    }
    let remaining = &text[pos..];
    if !remaining.starts_with("```") {
        return false;
    }
    // Ensure it's exactly 3 backticks (4th char is not a backtick)
    remaining.len() == 3 || remaining.as_bytes().get(3) != Some(&b'`')
}

/// Creates serde_saphyr Options with security budgets configured.
///
/// Uses MAX_YAML_DEPTH from error.rs to limit nesting depth at the parser level,
/// which is more robust than heuristic-based pre-parse checks.
fn yaml_parse_options() -> serde_saphyr::Options {
    let budget = serde_saphyr::Budget {
        max_depth: crate::error::MAX_YAML_DEPTH,
        ..Default::default()
    };
    serde_saphyr::Options {
        budget: Some(budget),
        ..Default::default()
    }
}

/// Find all metadata blocks in the document
fn find_metadata_blocks(markdown: &str) -> Result<Vec<MetadataBlock>, crate::error::ParseError> {
    let mut blocks = Vec::new();
    let mut pos = 0;

    while pos < markdown.len() {
        // Look for opening "---\n" or "---\r\n"
        let search_str = &markdown[pos..];
        let delimiter_result = search_str
            .find("---\n")
            .map(|p| (p, 4, "\n"))
            .or_else(|| search_str.find("---\r\n").map(|p| (p, 5, "\r\n")));

        if let Some((delimiter_pos, delimiter_len, _line_ending)) = delimiter_result {
            let abs_pos = pos + delimiter_pos;

            // Check if the delimiter is at the start of a line
            let is_start_of_line = if abs_pos == 0 {
                true
            } else {
                let char_before = markdown.as_bytes()[abs_pos - 1];
                char_before == b'\n' || char_before == b'\r'
            };

            if !is_start_of_line {
                pos = abs_pos + 1;
                continue;
            }

            // Skip if inside a fenced code block
            if is_inside_fenced_block(markdown, abs_pos) {
                pos = abs_pos + 3;
                continue;
            }

            let content_start = abs_pos + delimiter_len; // After "---\n" or "---\r\n"

            // Check if this --- is a horizontal rule (blank lines above AND below)
            let preceded_by_blank = if abs_pos > 0 {
                // Check if there's a blank line before the ---
                let before = &markdown[..abs_pos];
                before.ends_with("\n\n") || before.ends_with("\r\n\r\n")
            } else {
                false
            };

            let followed_by_blank = if content_start < markdown.len() {
                markdown[content_start..].starts_with('\n')
                    || markdown[content_start..].starts_with("\r\n")
            } else {
                false
            };

            // Horizontal rule: blank lines both above and below
            if preceded_by_blank && followed_by_blank {
                // This is a horizontal rule in the body, skip it
                pos = abs_pos + 3; // Skip past "---"
                continue;
            }

            // Check if followed by non-blank line (or if we're at document start)
            // This starts a metadata block
            if followed_by_blank {
                // --- followed by blank line but NOT preceded by blank line
                // This is NOT a metadata block opening, skip it
                pos = abs_pos + 3;
                continue;
            }

            // Found potential metadata block opening (followed by non-blank line)
            // Look for closing "\n---\n" or "\r\n---\r\n" etc., OR "\n---" / "\r\n---" at end of document
            let rest = &markdown[content_start..];

            // First try to find delimiters with trailing newlines
            let closing_patterns = ["\n---\n", "\r\n---\r\n", "\n---\r\n", "\r\n---\n"];
            let closing_with_newline = closing_patterns
                .iter()
                .filter_map(|delim| rest.find(delim).map(|p| (p, delim.len())))
                .min_by_key(|(p, _)| *p);

            // Also check for closing at end of document (no trailing newline)
            let closing_at_eof = ["\n---", "\r\n---"]
                .iter()
                .filter_map(|delim| {
                    rest.find(delim).and_then(|p| {
                        if p + delim.len() == rest.len() {
                            Some((p, delim.len()))
                        } else {
                            None
                        }
                    })
                })
                .min_by_key(|(p, _)| *p);

            let closing_result = match (closing_with_newline, closing_at_eof) {
                (Some((p1, _l1)), Some((p2, _))) if p2 < p1 => closing_at_eof,
                (Some(_), Some(_)) => closing_with_newline,
                (Some(_), None) => closing_with_newline,
                (None, Some(_)) => closing_at_eof,
                (None, None) => None,
            };

            if let Some((closing_pos, closing_len)) = closing_result {
                let abs_closing_pos = content_start + closing_pos;
                let content = &markdown[content_start..abs_closing_pos];

                // Check YAML size limit
                if content.len() > crate::error::MAX_YAML_SIZE {
                    return Err(crate::error::ParseError::InputTooLarge {
                        size: content.len(),
                        max: crate::error::MAX_YAML_SIZE,
                    });
                }

                // Parse YAML content to check for reserved keys (QUILL, CARD)
                // Uses configured budget to limit nesting depth (prevents stack overflow)
                // Normalize: treat whitespace-only content as empty frontmatter
                let content = content.trim();
                let (tag, quill_ref, yaml_value) = if !content.is_empty() {
                    // Try to parse the YAML with security budgets
                    match serde_saphyr::from_str_with_options::<serde_json::Value>(
                        content,
                        yaml_parse_options(),
                    ) {
                        Ok(parsed_yaml) => {
                            if let Some(mapping) = parsed_yaml.as_object() {
                                let quill_key = "QUILL";
                                let card_key = "CARD";

                                let has_quill = mapping.contains_key(quill_key);
                                let has_card = mapping.contains_key(card_key);

                                if has_quill && has_card {
                                    return Err(crate::error::ParseError::InvalidStructure(
                                        "Cannot specify both QUILL and CARD in the same block"
                                            .to_string(),
                                    ));
                                }

                                // Check for reserved field names (BODY, CARDS)
                                const RESERVED_FIELDS: &[&str] = &["BODY", "CARDS"];
                                for reserved in RESERVED_FIELDS {
                                    if mapping.contains_key(*reserved) {
                                        return Err(crate::error::ParseError::InvalidStructure(
                                            format!(
                                                "Reserved field name '{}' cannot be used in YAML frontmatter",
                                                reserved
                                            ),
                                        ));
                                    }
                                }

                                if has_quill {
                                    // Extract and parse quill reference
                                    let quill_value = mapping.get(quill_key).unwrap();
                                    let quill_ref_str = quill_value
                                        .as_str()
                                        .ok_or("QUILL value must be a string")?;

                                    // Parse as QuillReference to validate name and version
                                    let _quill_ref =
                                        quill_ref_str.parse::<QuillReference>().map_err(|e| {
                                            crate::error::ParseError::InvalidStructure(format!(
                                                "Invalid QUILL reference '{}': {}",
                                                quill_ref_str, e
                                            ))
                                        })?;

                                    // Remove QUILL from the YAML value for processing
                                    let mut new_mapping = mapping.clone();
                                    new_mapping.remove(quill_key);
                                    let new_value = if new_mapping.is_empty() {
                                        None
                                    } else {
                                        Some(serde_json::Value::Object(new_mapping))
                                    };

                                    (None, Some(quill_ref_str.to_string()), new_value)
                                } else if has_card {
                                    // Extract card field name
                                    let card_value = mapping.get(card_key).unwrap();
                                    let field_name =
                                        card_value.as_str().ok_or("CARD value must be a string")?;

                                    if !is_valid_tag_name(field_name) {
                                        return Err(crate::error::ParseError::InvalidStructure(format!(
                                            "Invalid card field name '{}': must match pattern [a-z_][a-z0-9_]*",
                                            field_name
                                        )));
                                    }

                                    // Remove CARD from the YAML value for processing
                                    let mut new_mapping = mapping.clone();
                                    new_mapping.remove(card_key);
                                    let new_value = if new_mapping.is_empty() {
                                        None
                                    } else {
                                        Some(serde_json::Value::Object(new_mapping))
                                    };

                                    (Some(field_name.to_string()), None, new_value)
                                } else {
                                    // No reserved keys, keep the parsed YAML
                                    (None, None, Some(parsed_yaml))
                                }
                            } else {
                                // Not a mapping, keep the parsed YAML (could be null for whitespace)
                                (None, None, Some(parsed_yaml))
                            }
                        }
                        Err(e) => {
                            // Calculate line number for the start of this block
                            let block_start_line = markdown[..abs_pos].lines().count() + 1;
                            return Err(crate::error::ParseError::YamlErrorWithLocation {
                                message: e.to_string(),
                                line: block_start_line,
                                block_index: blocks.len(),
                            });
                        }
                    }
                } else {
                    // Empty content
                    (None, None, None)
                };

                blocks.push(MetadataBlock {
                    start: abs_pos,
                    end: abs_closing_pos + closing_len, // After closing delimiter
                    yaml_value,
                    tag,
                    quill_ref,
                });

                // Check card count limit to prevent memory exhaustion
                if blocks.len() > crate::error::MAX_CARD_COUNT {
                    return Err(crate::error::ParseError::InputTooLarge {
                        size: blocks.len(),
                        max: crate::error::MAX_CARD_COUNT,
                    });
                }

                pos = abs_closing_pos + closing_len;
            } else if abs_pos == 0 {
                // Frontmatter started but not closed
                return Err(crate::error::ParseError::InvalidStructure(
                    "Frontmatter started but not closed with ---".to_string(),
                ));
            } else {
                // Not a valid metadata block, skip this position
                pos = abs_pos + 3;
            }
        } else {
            break;
        }
    }

    Ok(blocks)
}

/// Decompose markdown into frontmatter fields and body
fn decompose(markdown: &str) -> Result<ParsedDocument, crate::error::ParseError> {
    // Check input size limit
    if markdown.len() > crate::error::MAX_INPUT_SIZE {
        return Err(crate::error::ParseError::InputTooLarge {
            size: markdown.len(),
            max: crate::error::MAX_INPUT_SIZE,
        });
    }

    let mut fields = HashMap::new();

    // Find all metadata blocks
    let blocks = find_metadata_blocks(markdown)?;

    if blocks.is_empty() {
        // No metadata blocks, entire content is body
        fields.insert(
            BODY_FIELD.to_string(),
            QuillValue::from_json(serde_json::Value::String(markdown.to_string())),
        );
        return Ok(ParsedDocument::new(fields));
    }

    // Collect all card items into unified CARDS array
    let mut cards_array: Vec<serde_json::Value> = Vec::new();
    let mut global_frontmatter_index: Option<usize> = None;
    let mut quill_ref: Option<String> = None;

    // First pass: identify global frontmatter, quill directive, and validate
    for (idx, block) in blocks.iter().enumerate() {
        if idx == 0 {
            // Top-level frontmatter: can have QUILL or neither (not considered a card)
            if let Some(ref name) = block.quill_ref {
                quill_ref = Some(name.clone());
            }
            // If it has neither QUILL nor CARD, it's global frontmatter
            if block.tag.is_none() && block.quill_ref.is_none() {
                global_frontmatter_index = Some(idx);
            }
        } else {
            // Inline blocks (idx > 0): MUST have CARD, cannot have QUILL
            if block.quill_ref.is_some() {
                return Err(crate::error::ParseError::InvalidStructure("QUILL directive can only appear in the top-level frontmatter, not in inline blocks. Use CARD instead.".to_string()));
            }
            if block.tag.is_none() {
                // Inline block without CARD
                return Err(crate::error::ParseError::missing_card_directive());
            }
        }
    }

    // Parse global frontmatter if present
    if let Some(idx) = global_frontmatter_index {
        let block = &blocks[idx];

        // Get parsed JSON fields directly (already parsed in find_metadata_blocks)
        let json_fields: HashMap<String, serde_json::Value> = match &block.yaml_value {
            Some(serde_json::Value::Object(mapping)) => mapping
                .iter()
                .map(|(k, v)| (k.clone(), v.clone()))
                .collect(),
            Some(serde_json::Value::Null) => {
                // Null value (from whitespace-only YAML) - treat as empty mapping
                HashMap::new()
            }
            Some(_) => {
                // Non-mapping, non-null YAML (e.g., scalar, sequence) - this is an error for frontmatter
                return Err(crate::error::ParseError::InvalidStructure(
                    "Invalid YAML frontmatter: expected a mapping".to_string(),
                ));
            }
            None => HashMap::new(),
        };

        // Convert JSON values to QuillValue at boundary
        for (key, value) in json_fields {
            fields.insert(key, QuillValue::from_json(value));
        }
    }

    // Process blocks with quill directives
    for block in &blocks {
        if block.quill_ref.is_some() {
            // Quill directive blocks can have YAML content (becomes part of frontmatter)
            if let Some(ref json_val) = block.yaml_value {
                let json_fields: HashMap<String, serde_json::Value> = match json_val {
                    serde_json::Value::Object(mapping) => mapping
                        .iter()
                        .map(|(k, v)| (k.clone(), v.clone()))
                        .collect(),
                    serde_json::Value::Null => {
                        // Null value (from whitespace-only YAML) - treat as empty mapping
                        HashMap::new()
                    }
                    _ => {
                        return Err(crate::error::ParseError::InvalidStructure(
                            "Invalid YAML in quill block: expected a mapping".to_string(),
                        ));
                    }
                };

                // Check for conflicts with existing fields
                for key in json_fields.keys() {
                    if fields.contains_key(key) {
                        return Err(crate::error::ParseError::InvalidStructure(format!(
                            "Name collision: quill block field '{}' conflicts with existing field",
                            key
                        )));
                    }
                }

                // Convert JSON values to QuillValue at boundary
                for (key, value) in json_fields {
                    fields.insert(key, QuillValue::from_json(value));
                }
            }
        }
    }

    // Parse tagged blocks (CARD blocks)
    for (idx, block) in blocks.iter().enumerate() {
        if let Some(ref tag_name) = block.tag {
            // Get YAML metadata directly (already parsed in find_metadata_blocks)
            // Get JSON metadata directly (already parsed in find_metadata_blocks)
            let mut item_fields: serde_json::Map<String, serde_json::Value> =
                match &block.yaml_value {
                    Some(serde_json::Value::Object(mapping)) => mapping.clone(),
                    Some(serde_json::Value::Null) => {
                        // Null value (from whitespace-only YAML) - treat as empty mapping
                        serde_json::Map::new()
                    }
                    Some(_) => {
                        return Err(crate::error::ParseError::InvalidStructure(format!(
                            "Invalid YAML in card block '{}': expected a mapping",
                            tag_name
                        )));
                    }
                    None => serde_json::Map::new(),
                };

            // Extract body for this card block
            let body_start = block.end;
            let body_end = if idx + 1 < blocks.len() {
                blocks[idx + 1].start
            } else {
                markdown.len()
            };
            let body = &markdown[body_start..body_end];

            // Add body to item fields
            item_fields.insert(
                BODY_FIELD.to_string(),
                serde_json::Value::String(body.to_string()),
            );

            // Add CARD discriminator field
            item_fields.insert(
                "CARD".to_string(),
                serde_json::Value::String(tag_name.clone()),
            );

            // Add to CARDS array
            cards_array.push(serde_json::Value::Object(item_fields));
        }
    }

    // Extract global body
    // Body starts after global frontmatter or quill block (whichever comes first)
    // Body ends at the first card block or EOF
    let first_non_card_block_idx = blocks
        .iter()
        .position(|b| b.tag.is_none() && b.quill_ref.is_none())
        .or_else(|| blocks.iter().position(|b| b.quill_ref.is_some()));

    let (body_start, body_end) = if let Some(idx) = first_non_card_block_idx {
        // Body starts after the first non-card block (global frontmatter or quill)
        let start = blocks[idx].end;

        // Body ends at the first card block after this, or EOF
        let end = blocks
            .iter()
            .skip(idx + 1)
            .find(|b| b.tag.is_some())
            .map(|b| b.start)
            .unwrap_or(markdown.len());

        (start, end)
    } else {
        // No global frontmatter or quill block - body is everything before the first card block
        let end = blocks
            .iter()
            .find(|b| b.tag.is_some())
            .map(|b| b.start)
            .unwrap_or(0);

        (0, end)
    };

    let global_body = &markdown[body_start..body_end];

    fields.insert(
        BODY_FIELD.to_string(),
        QuillValue::from_json(serde_json::Value::String(global_body.to_string())),
    );

    // Always add CARDS array to fields (may be empty)
    fields.insert(
        "CARDS".to_string(),
        QuillValue::from_json(serde_json::Value::Array(cards_array)),
    );

    // Check field count limit to prevent memory exhaustion
    if fields.len() > crate::error::MAX_FIELD_COUNT {
        return Err(crate::error::ParseError::InputTooLarge {
            size: fields.len(),
            max: crate::error::MAX_FIELD_COUNT,
        });
    }

    let quill_tag = quill_ref.unwrap_or_else(|| "__default__".to_string());
    let quill_ref = QuillReference::from_str(&quill_tag).map_err(|e| {
        ParseError::InvalidStructure(format!("Invalid QUILL tag '{}': {}", quill_tag, e))
    })?;
    let parsed = ParsedDocument::with_quill_ref(fields, quill_ref);

    Ok(parsed)
}

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

    #[test]
    fn test_no_frontmatter() {
        let markdown = "# Hello World\n\nThis is a test.";
        let doc = decompose(markdown).unwrap();

        assert_eq!(doc.body(), Some(markdown));
        assert_eq!(doc.fields().len(), 1);
        // Verify default quill tag is set
        assert_eq!(doc.quill_reference().name, "__default__");
    }

    #[test]
    fn test_with_frontmatter() {
        let markdown = r#"---
title: Test Document
author: Test Author
---

# Hello World

This is the body."#;

        let doc = decompose(markdown).unwrap();

        assert_eq!(doc.body(), Some("\n# Hello World\n\nThis is the body."));
        assert_eq!(
            doc.get_field("title").unwrap().as_str().unwrap(),
            "Test Document"
        );
        assert_eq!(
            doc.get_field("author").unwrap().as_str().unwrap(),
            "Test Author"
        );
        assert_eq!(doc.fields().len(), 4); // title, author, body, CARDS
                                           // Verify default quill tag is set when no QUILL directive
        assert_eq!(doc.quill_reference().name, "__default__");
    }

    #[test]
    fn test_whitespace_frontmatter() {
        // Frontmatter with only whitespace should be treated as empty/valid
        // and not error out or be treated as null YAML
        let markdown = "---\n   \n---\n\n# Hello";
        let doc = decompose(markdown).unwrap();

        assert_eq!(doc.body(), Some("\n# Hello"));
        // Should have default fields (BODY + CARDS) but no others
        // (unless defaults are applied later, but decompose returns basics)
        assert!(doc.get_field("title").is_none());
        assert_eq!(doc.fields().len(), 2); // BODY, CARDS
    }

    #[test]
    fn test_complex_yaml_frontmatter() {
        let markdown = r#"---
title: Complex Document
tags:
  - test
  - yaml
metadata:
  version: 1.0
  nested:
    field: value
---

Content here."#;

        let doc = decompose(markdown).unwrap();

        assert_eq!(doc.body(), Some("\nContent here."));
        assert_eq!(
            doc.get_field("title").unwrap().as_str().unwrap(),
            "Complex Document"
        );

        let tags = doc.get_field("tags").unwrap().as_sequence().unwrap();
        assert_eq!(tags.len(), 2);
        assert_eq!(tags[0].as_str().unwrap(), "test");
        assert_eq!(tags[1].as_str().unwrap(), "yaml");
    }

    #[test]
    fn test_with_defaults_empty_document() {
        use std::collections::HashMap;

        let mut defaults = HashMap::new();
        defaults.insert(
            "status".to_string(),
            QuillValue::from_json(serde_json::json!("draft")),
        );
        defaults.insert(
            "version".to_string(),
            QuillValue::from_json(serde_json::json!(1)),
        );

        // Create an empty parsed document
        let doc = ParsedDocument::new(HashMap::new());
        let doc_with_defaults = doc.with_defaults(&defaults);

        // Check that defaults were applied
        assert_eq!(
            doc_with_defaults
                .get_field("status")
                .unwrap()
                .as_str()
                .unwrap(),
            "draft"
        );
        assert_eq!(
            doc_with_defaults
                .get_field("version")
                .unwrap()
                .as_number()
                .unwrap()
                .as_i64()
                .unwrap(),
            1
        );
    }

    #[test]
    fn test_with_defaults_preserves_existing_values() {
        use std::collections::HashMap;

        let mut defaults = HashMap::new();
        defaults.insert(
            "status".to_string(),
            QuillValue::from_json(serde_json::json!("draft")),
        );

        // Create document with existing status
        let mut fields = HashMap::new();
        fields.insert(
            "status".to_string(),
            QuillValue::from_json(serde_json::json!("published")),
        );
        let doc = ParsedDocument::new(fields);

        let doc_with_defaults = doc.with_defaults(&defaults);

        // Existing value should be preserved
        assert_eq!(
            doc_with_defaults
                .get_field("status")
                .unwrap()
                .as_str()
                .unwrap(),
            "published"
        );
    }

    #[test]
    fn test_with_defaults_partial_application() {
        use std::collections::HashMap;

        let mut defaults = HashMap::new();
        defaults.insert(
            "status".to_string(),
            QuillValue::from_json(serde_json::json!("draft")),
        );
        defaults.insert(
            "version".to_string(),
            QuillValue::from_json(serde_json::json!(1)),
        );

        // Create document with only one field
        let mut fields = HashMap::new();
        fields.insert(
            "status".to_string(),
            QuillValue::from_json(serde_json::json!("published")),
        );
        let doc = ParsedDocument::new(fields);

        let doc_with_defaults = doc.with_defaults(&defaults);

        // Existing field preserved, missing field gets default
        assert_eq!(
            doc_with_defaults
                .get_field("status")
                .unwrap()
                .as_str()
                .unwrap(),
            "published"
        );
        assert_eq!(
            doc_with_defaults
                .get_field("version")
                .unwrap()
                .as_number()
                .unwrap()
                .as_i64()
                .unwrap(),
            1
        );
    }

    #[test]
    fn test_with_defaults_no_defaults() {
        use std::collections::HashMap;

        let defaults = HashMap::new(); // Empty defaults map

        let doc = ParsedDocument::new(HashMap::new());
        let doc_with_defaults = doc.with_defaults(&defaults);

        // No defaults should be applied
        assert!(doc_with_defaults.fields().is_empty());
    }

    #[test]
    fn test_with_defaults_complex_types() {
        use std::collections::HashMap;

        let mut defaults = HashMap::new();
        defaults.insert(
            "tags".to_string(),
            QuillValue::from_json(serde_json::json!(["default", "tag"])),
        );

        let doc = ParsedDocument::new(HashMap::new());
        let doc_with_defaults = doc.with_defaults(&defaults);

        // Complex default value should be applied
        let tags = doc_with_defaults
            .get_field("tags")
            .unwrap()
            .as_sequence()
            .unwrap();
        assert_eq!(tags.len(), 2);
        assert_eq!(tags[0].as_str().unwrap(), "default");
        assert_eq!(tags[1].as_str().unwrap(), "tag");
    }

    #[test]
    fn test_with_coercion_singular_to_array() {
        use std::collections::HashMap;

        let schema = QuillValue::from_json(serde_json::json!({
            "$schema": "https://json-schema.org/draft/2019-09/schema",
            "type": "object",
            "properties": {
                "tags": {"type": "array"}
            }
        }));

        let mut fields = HashMap::new();
        fields.insert(
            "tags".to_string(),
            QuillValue::from_json(serde_json::json!("single-tag")),
        );
        let doc = ParsedDocument::new(fields);

        let coerced_doc = doc.with_coercion(&schema);

        let tags = coerced_doc.get_field("tags").unwrap();
        assert!(tags.as_array().is_some());
        let tags_array = tags.as_array().unwrap();
        assert_eq!(tags_array.len(), 1);
        assert_eq!(tags_array[0].as_str().unwrap(), "single-tag");
    }

    #[test]
    fn test_with_coercion_string_to_boolean() {
        use std::collections::HashMap;

        let schema = QuillValue::from_json(serde_json::json!({
            "$schema": "https://json-schema.org/draft/2019-09/schema",
            "type": "object",
            "properties": {
                "active": {"type": "boolean"}
            }
        }));

        let mut fields = HashMap::new();
        fields.insert(
            "active".to_string(),
            QuillValue::from_json(serde_json::json!("true")),
        );
        let doc = ParsedDocument::new(fields);

        let coerced_doc = doc.with_coercion(&schema);

        assert!(coerced_doc.get_field("active").unwrap().as_bool().unwrap());
    }

    #[test]
    fn test_with_coercion_string_to_number() {
        use std::collections::HashMap;

        let schema = QuillValue::from_json(serde_json::json!({
            "$schema": "https://json-schema.org/draft/2019-09/schema",
            "type": "object",
            "properties": {
                "count": {"type": "number"}
            }
        }));

        let mut fields = HashMap::new();
        fields.insert(
            "count".to_string(),
            QuillValue::from_json(serde_json::json!("42")),
        );
        let doc = ParsedDocument::new(fields);

        let coerced_doc = doc.with_coercion(&schema);

        assert_eq!(
            coerced_doc.get_field("count").unwrap().as_i64().unwrap(),
            42
        );
    }

    #[test]
    fn test_invalid_yaml() {
        let markdown = r#"---
title: [invalid yaml
author: missing close bracket
---

Content here."#;

        let result = decompose(markdown);
        assert!(result.is_err());
        // Error message now includes location context
        assert!(result.unwrap_err().to_string().contains("YAML error"));
    }

    #[test]
    fn test_unclosed_frontmatter() {
        let markdown = r#"---
title: Test
author: Test Author

Content without closing ---"#;

        let result = decompose(markdown);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not closed"));
    }

    // Extended metadata tests

    #[test]
    fn test_basic_tagged_block() {
        let markdown = r#"---
title: Main Document
---

Main body content.

---
CARD: items
name: Item 1
---

Body of item 1."#;

        let doc = decompose(markdown).unwrap();

        assert_eq!(doc.body(), Some("\nMain body content.\n\n"));
        assert_eq!(
            doc.get_field("title").unwrap().as_str().unwrap(),
            "Main Document"
        );

        // Cards are now in CARDS array with CARD discriminator
        let cards = doc.get_field("CARDS").unwrap().as_sequence().unwrap();
        assert_eq!(cards.len(), 1);

        let item = cards[0].as_object().unwrap();
        assert_eq!(item.get("CARD").unwrap().as_str().unwrap(), "items");
        assert_eq!(item.get("name").unwrap().as_str().unwrap(), "Item 1");
        assert_eq!(
            item.get(BODY_FIELD).unwrap().as_str().unwrap(),
            "\nBody of item 1."
        );
    }

    #[test]
    fn test_multiple_tagged_blocks() {
        let markdown = r#"---
CARD: items
name: Item 1
tags: [a, b]
---

First item body.

---
CARD: items
name: Item 2
tags: [c, d]
---

Second item body."#;

        let doc = decompose(markdown).unwrap();

        // Cards are in CARDS array
        let cards = doc.get_field("CARDS").unwrap().as_sequence().unwrap();
        assert_eq!(cards.len(), 2);

        let item1 = cards[0].as_object().unwrap();
        assert_eq!(item1.get("CARD").unwrap().as_str().unwrap(), "items");
        assert_eq!(item1.get("name").unwrap().as_str().unwrap(), "Item 1");

        let item2 = cards[1].as_object().unwrap();
        assert_eq!(item2.get("CARD").unwrap().as_str().unwrap(), "items");
        assert_eq!(item2.get("name").unwrap().as_str().unwrap(), "Item 2");
    }

    #[test]
    fn test_mixed_global_and_tagged() {
        let markdown = r#"---
title: Global
author: John Doe
---

Global body.

---
CARD: sections
title: Section 1
---

Section 1 content.

---
CARD: sections
title: Section 2
---

Section 2 content."#;

        let doc = decompose(markdown).unwrap();

        assert_eq!(doc.get_field("title").unwrap().as_str().unwrap(), "Global");
        assert_eq!(doc.body(), Some("\nGlobal body.\n\n"));

        // Cards are in unified CARDS array
        let cards = doc.get_field("CARDS").unwrap().as_sequence().unwrap();
        assert_eq!(cards.len(), 2);
        assert_eq!(
            cards[0]
                .as_object()
                .unwrap()
                .get("CARD")
                .unwrap()
                .as_str()
                .unwrap(),
            "sections"
        );
    }

    #[test]
    fn test_empty_tagged_metadata() {
        let markdown = r#"---
CARD: items
---

Body without metadata."#;

        let doc = decompose(markdown).unwrap();

        let cards = doc.get_field("CARDS").unwrap().as_sequence().unwrap();
        assert_eq!(cards.len(), 1);

        let item = cards[0].as_object().unwrap();
        assert_eq!(item.get("CARD").unwrap().as_str().unwrap(), "items");
        assert_eq!(
            item.get(BODY_FIELD).unwrap().as_str().unwrap(),
            "\nBody without metadata."
        );
    }

    #[test]
    fn test_tagged_block_without_body() {
        let markdown = r#"---
CARD: items
name: Item
---"#;

        let doc = decompose(markdown).unwrap();

        let cards = doc.get_field("CARDS").unwrap().as_sequence().unwrap();
        assert_eq!(cards.len(), 1);

        let item = cards[0].as_object().unwrap();
        assert_eq!(item.get("CARD").unwrap().as_str().unwrap(), "items");
        assert_eq!(item.get(BODY_FIELD).unwrap().as_str().unwrap(), "");
    }

    #[test]
    fn test_name_collision_global_and_tagged() {
        let markdown = r#"---
items: "global value"
---

Body

---
CARD: items
name: Item
---

Item body"#;

        let result = decompose(markdown);
        assert!(result.is_ok(), "Name collision should be allowed now");
    }

    #[test]
    fn test_card_name_collision_with_array_field() {
        // CARD type names CAN now conflict with frontmatter field names
        let markdown = r#"---
items:
  - name: Global Item 1
    value: 100
---

Global body

---
CARD: items
name: Scope Item 1
---

Scope item 1 body"#;

        let result = decompose(markdown);
        assert!(
            result.is_ok(),
            "Collision with array field should be allowed"
        );
    }

    #[test]
    fn test_empty_global_array_with_card() {
        // CARD type names CAN now conflict with frontmatter field names
        let markdown = r#"---
items: []
---

Global body

---
CARD: items
name: Item 1
---

Item 1 body"#;

        let result = decompose(markdown);
        assert!(
            result.is_ok(),
            "Collision with empty array field should be allowed"
        );
    }

    #[test]
    fn test_reserved_field_body_rejected() {
        let markdown = r#"---
CARD: section
BODY: Test
---"#;

        let result = decompose(markdown);
        assert!(result.is_err(), "BODY is a reserved field name");
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Reserved field name"));
    }

    #[test]
    fn test_reserved_field_cards_rejected() {
        let markdown = r#"---
title: Test
CARDS: []
---"#;

        let result = decompose(markdown);
        assert!(result.is_err(), "CARDS is a reserved field name");
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Reserved field name"));
    }

    #[test]
    fn test_delimiter_inside_fenced_code_block_backticks() {
        let markdown = r#"---
title: Test
---
Here is some code:

```yaml
---
fake: frontmatter
---
```

More content.
"#;

        let doc = decompose(markdown).unwrap();
        // The --- inside the code block should NOT be parsed as metadata
        assert!(doc.body().unwrap().contains("fake: frontmatter"));
        assert!(doc.get_field("fake").is_none());
    }

    #[test]
    fn test_tildes_are_not_fences() {
        // Per EXTENDED_MARKDOWN.md: tildes (~~~) are NOT treated as fences
        // So --- inside ~~~ WILL be parsed as a metadata block
        let markdown = r#"---
title: Test
---
Here is some code:

~~~yaml
---
CARD: code_example
fake: frontmatter
---
~~~

More content.
"#;

        let doc = decompose(markdown).unwrap();
        // The --- should be parsed as a CARD block since tildes aren't fences
        let cards = doc.get_field("CARDS").unwrap().as_sequence().unwrap();
        assert_eq!(cards.len(), 1);
        assert_eq!(
            cards[0].get("fake").unwrap().as_str().unwrap(),
            "frontmatter"
        );
    }

    #[test]
    fn test_four_backticks_are_not_fences() {
        // Per EXTENDED_MARKDOWN.md: only exactly 3 backticks are valid fences
        // 4+ backticks are NOT treated as fences
        let markdown = r#"---
title: Test
---
Here is some code:

````yaml
---
CARD: code_example
fake: frontmatter
---
````

More content.
"#;

        let doc = decompose(markdown).unwrap();
        // The --- should be parsed as a CARD block since 4 backticks aren't a fence
        let cards = doc.get_field("CARDS").unwrap().as_sequence().unwrap();
        assert_eq!(cards.len(), 1);
        assert_eq!(
            cards[0].get("fake").unwrap().as_str().unwrap(),
            "frontmatter"
        );
    }

    #[test]
    fn test_invalid_tag_syntax() {
        let markdown = r#"---
CARD: Invalid-Name
title: Test
---"#;

        let result = decompose(markdown);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Invalid card field name"));
    }

    #[test]
    fn test_multiple_global_frontmatter_blocks() {
        let markdown = r#"---
title: First
---

Body

---
author: Second
---

More body"#;

        let result = decompose(markdown);
        assert!(result.is_err());

        // Verify the error message contains CARD hint
        let err = result.unwrap_err();
        let err_str = err.to_string();
        assert!(
            err_str.contains("CARD"),
            "Error should mention CARD directive: {}",
            err_str
        );
        assert!(
            err_str.contains("missing"),
            "Error should indicate missing directive: {}",
            err_str
        );
    }

    #[test]
    fn test_adjacent_blocks_different_tags() {
        let markdown = r#"---
CARD: items
name: Item 1
---

Item 1 body

---
CARD: sections
title: Section 1
---

Section 1 body"#;

        let doc = decompose(markdown).unwrap();

        // All cards in unified CARDS array
        let cards = doc.get_field("CARDS").unwrap().as_sequence().unwrap();
        assert_eq!(cards.len(), 2);

        // First card is "items" type
        let item = cards[0].as_object().unwrap();
        assert_eq!(item.get("CARD").unwrap().as_str().unwrap(), "items");
        assert_eq!(item.get("name").unwrap().as_str().unwrap(), "Item 1");

        // Second card is "sections" type
        let section = cards[1].as_object().unwrap();
        assert_eq!(section.get("CARD").unwrap().as_str().unwrap(), "sections");
        assert_eq!(section.get("title").unwrap().as_str().unwrap(), "Section 1");
    }

    #[test]
    fn test_order_preservation() {
        let markdown = r#"---
CARD: items
id: 1
---

First

---
CARD: items
id: 2
---

Second

---
CARD: items
id: 3
---

Third"#;

        let doc = decompose(markdown).unwrap();

        let cards = doc.get_field("CARDS").unwrap().as_sequence().unwrap();
        assert_eq!(cards.len(), 3);

        for (i, card) in cards.iter().enumerate() {
            let mapping = card.as_object().unwrap();
            assert_eq!(mapping.get("CARD").unwrap().as_str().unwrap(), "items");
            let id = mapping.get("id").unwrap().as_i64().unwrap();
            assert_eq!(id, (i + 1) as i64);
        }
    }

    #[test]
    fn test_product_catalog_integration() {
        let markdown = r#"---
title: Product Catalog
author: John Doe
date: 2024-01-01
---

This is the main catalog description.

---
CARD: products
name: Widget A
price: 19.99
sku: WID-001
---

The **Widget A** is our most popular product.

---
CARD: products
name: Gadget B
price: 29.99
sku: GAD-002
---

The **Gadget B** is perfect for professionals.

---
CARD: reviews
product: Widget A
rating: 5
---

"Excellent product! Highly recommended."

---
CARD: reviews
product: Gadget B
rating: 4
---

"Very good, but a bit pricey.""#;

        let doc = decompose(markdown).unwrap();

        // Verify global fields
        assert_eq!(
            doc.get_field("title").unwrap().as_str().unwrap(),
            "Product Catalog"
        );
        assert_eq!(
            doc.get_field("author").unwrap().as_str().unwrap(),
            "John Doe"
        );
        assert_eq!(
            doc.get_field("date").unwrap().as_str().unwrap(),
            "2024-01-01"
        );

        // Verify global body
        assert!(doc.body().unwrap().contains("main catalog description"));

        // All cards in unified CARDS array
        let cards = doc.get_field("CARDS").unwrap().as_sequence().unwrap();
        assert_eq!(cards.len(), 4); // 2 products + 2 reviews

        // First 2 are products
        let product1 = cards[0].as_object().unwrap();
        assert_eq!(product1.get("CARD").unwrap().as_str().unwrap(), "products");
        assert_eq!(product1.get("name").unwrap().as_str().unwrap(), "Widget A");
        assert_eq!(product1.get("price").unwrap().as_f64().unwrap(), 19.99);

        let product2 = cards[1].as_object().unwrap();
        assert_eq!(product2.get("CARD").unwrap().as_str().unwrap(), "products");
        assert_eq!(product2.get("name").unwrap().as_str().unwrap(), "Gadget B");

        // Last 2 are reviews
        let review1 = cards[2].as_object().unwrap();
        assert_eq!(review1.get("CARD").unwrap().as_str().unwrap(), "reviews");
        assert_eq!(
            review1.get("product").unwrap().as_str().unwrap(),
            "Widget A"
        );
        assert_eq!(review1.get("rating").unwrap().as_i64().unwrap(), 5);

        // Total fields: title, author, date, body, CARDS = 5
        assert_eq!(doc.fields().len(), 5);
    }

    #[test]
    fn taro_quill_directive() {
        let markdown = r#"---
QUILL: usaf_memo
memo_for: [ORG/SYMBOL]
memo_from: [ORG/SYMBOL]
---

This is the memo body."#;

        let doc = decompose(markdown).unwrap();

        // Verify quill tag is set
        assert_eq!(doc.quill_reference().name, "usaf_memo");

        // Verify fields from quill block become frontmatter
        assert_eq!(
            doc.get_field("memo_for").unwrap().as_sequence().unwrap()[0]
                .as_str()
                .unwrap(),
            "ORG/SYMBOL"
        );

        // Verify body
        assert_eq!(doc.body(), Some("\nThis is the memo body."));
    }

    #[test]
    fn test_quill_with_card_blocks() {
        let markdown = r#"---
QUILL: document
title: Test Document
---

Main body.

---
CARD: sections
name: Section 1
---

Section 1 body."#;

        let doc = decompose(markdown).unwrap();

        // Verify quill tag
        assert_eq!(doc.quill_reference().name, "document");

        // Verify global field from quill block
        assert_eq!(
            doc.get_field("title").unwrap().as_str().unwrap(),
            "Test Document"
        );

        // Verify card blocks work via CARDS array
        let cards = doc.get_field("CARDS").unwrap().as_sequence().unwrap();
        assert_eq!(cards.len(), 1);
        assert_eq!(
            cards[0]
                .as_object()
                .unwrap()
                .get("CARD")
                .unwrap()
                .as_str()
                .unwrap(),
            "sections"
        );

        // Verify body
        assert_eq!(doc.body(), Some("\nMain body.\n\n"));
    }

    #[test]
    fn test_multiple_quill_directives_error() {
        let markdown = r#"---
QUILL: first
---

---
QUILL: second
---"#;

        let result = decompose(markdown);
        assert!(result.is_err());
        // QUILL in inline block is now an error (must appear in top-level frontmatter only)
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("top-level frontmatter"));
    }

    #[test]
    fn test_invalid_quill_ref() {
        let markdown = r#"---
QUILL: Invalid-Name
---"#;

        let result = decompose(markdown);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Invalid QUILL reference"));
    }

    #[test]
    fn test_quill_wrong_value_type() {
        let markdown = r#"---
QUILL: 123
---"#;

        let result = decompose(markdown);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("QUILL value must be a string"));
    }

    #[test]
    fn test_card_wrong_value_type() {
        let markdown = r#"---
CARD: 123
---"#;

        let result = decompose(markdown);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("CARD value must be a string"));
    }

    #[test]
    fn test_both_quill_and_card_error() {
        let markdown = r#"---
QUILL: test
CARD: items
---"#;

        let result = decompose(markdown);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Cannot specify both QUILL and CARD"));
    }

    #[test]
    fn test_blank_lines_in_frontmatter() {
        // New parsing standard: blank lines are allowed within YAML blocks
        let markdown = r#"---
title: Test Document
author: Test Author

description: This has a blank line above it
tags:
  - one
  - two
---

# Hello World

This is the body."#;

        let doc = decompose(markdown).unwrap();

        assert_eq!(doc.body(), Some("\n# Hello World\n\nThis is the body."));
        assert_eq!(
            doc.get_field("title").unwrap().as_str().unwrap(),
            "Test Document"
        );
        assert_eq!(
            doc.get_field("author").unwrap().as_str().unwrap(),
            "Test Author"
        );
        assert_eq!(
            doc.get_field("description").unwrap().as_str().unwrap(),
            "This has a blank line above it"
        );

        let tags = doc.get_field("tags").unwrap().as_sequence().unwrap();
        assert_eq!(tags.len(), 2);
    }

    #[test]
    fn test_blank_lines_in_scope_blocks() {
        // Blank lines should be allowed in CARD blocks too
        let markdown = r#"---
CARD: items
name: Item 1

price: 19.99

tags:
  - electronics
  - gadgets
---

Body of item 1."#;

        let doc = decompose(markdown).unwrap();

        // Cards are in CARDS array
        let cards = doc.get_field("CARDS").unwrap().as_sequence().unwrap();
        assert_eq!(cards.len(), 1);

        let item = cards[0].as_object().unwrap();
        assert_eq!(item.get("CARD").unwrap().as_str().unwrap(), "items");
        assert_eq!(item.get("name").unwrap().as_str().unwrap(), "Item 1");
        assert_eq!(item.get("price").unwrap().as_f64().unwrap(), 19.99);

        let tags = item.get("tags").unwrap().as_array().unwrap();
        assert_eq!(tags.len(), 2);
    }

    #[test]
    fn test_horizontal_rule_with_blank_lines_above_and_below() {
        // Horizontal rule: blank lines both above AND below the ---
        let markdown = r#"---
title: Test
---

First paragraph.

---

Second paragraph."#;

        let doc = decompose(markdown).unwrap();

        assert_eq!(doc.get_field("title").unwrap().as_str().unwrap(), "Test");

        // The body should contain the horizontal rule (---) as part of the content
        let body = doc.body().unwrap();
        assert!(body.contains("First paragraph."));
        assert!(body.contains("---"));
        assert!(body.contains("Second paragraph."));
    }

    #[test]
    fn test_horizontal_rule_not_preceded_by_blank() {
        // --- not preceded by blank line but followed by blank line is NOT a horizontal rule
        // It's also NOT a valid metadata block opening (since it's followed by blank)
        let markdown = r#"---
title: Test
---

First paragraph.
---

Second paragraph."#;

        let doc = decompose(markdown).unwrap();

        let body = doc.body().unwrap();
        // The second --- should be in the body as text (not a horizontal rule since no blank above)
        assert!(body.contains("---"));
    }

    #[test]
    fn test_multiple_blank_lines_in_yaml() {
        // Multiple blank lines should also be allowed
        let markdown = r#"---
title: Test


author: John Doe


version: 1.0
---

Body content."#;

        let doc = decompose(markdown).unwrap();

        assert_eq!(doc.get_field("title").unwrap().as_str().unwrap(), "Test");
        assert_eq!(
            doc.get_field("author").unwrap().as_str().unwrap(),
            "John Doe"
        );
        assert_eq!(doc.get_field("version").unwrap().as_f64().unwrap(), 1.0);
    }

    #[test]
    fn test_html_comment_interaction() {
        let markdown = r#"<!---
---> the rest of the page content

---
key: value
---
"#;
        let doc = decompose(markdown).unwrap();

        // The comment should be ignored (or at least not cause a parse error)
        // The frontmatter should be parsed
        let key = doc.get_field("key").and_then(|v| v.as_str());
        assert_eq!(key, Some("value"));
    }
}
#[cfg(test)]
mod demo_file_test {
    use super::*;

    #[test]
    fn test_extended_metadata_demo_file() {
        let markdown = include_str!("../../fixtures/resources/extended_metadata_demo.md");
        let doc = decompose(markdown).unwrap();

        // Verify global fields
        assert_eq!(
            doc.get_field("title").unwrap().as_str().unwrap(),
            "Extended Metadata Demo"
        );
        assert_eq!(
            doc.get_field("author").unwrap().as_str().unwrap(),
            "Quillmark Team"
        );
        // version is parsed as a number by YAML
        assert_eq!(doc.get_field("version").unwrap().as_f64().unwrap(), 1.0);

        // Verify body
        assert!(doc
            .body()
            .unwrap()
            .contains("extended YAML metadata standard"));

        // All cards are now in unified CARDS array
        let cards = doc.get_field("CARDS").unwrap().as_sequence().unwrap();
        assert_eq!(cards.len(), 5); // 3 features + 2 use_cases

        // Count features and use_cases cards
        let features_count = cards
            .iter()
            .filter(|c| {
                c.as_object()
                    .unwrap()
                    .get("CARD")
                    .unwrap()
                    .as_str()
                    .unwrap()
                    == "features"
            })
            .count();
        let use_cases_count = cards
            .iter()
            .filter(|c| {
                c.as_object()
                    .unwrap()
                    .get("CARD")
                    .unwrap()
                    .as_str()
                    .unwrap()
                    == "use_cases"
            })
            .count();
        assert_eq!(features_count, 3);
        assert_eq!(use_cases_count, 2);

        // Check first card is a feature
        let feature1 = cards[0].as_object().unwrap();
        assert_eq!(feature1.get("CARD").unwrap().as_str().unwrap(), "features");
        assert_eq!(
            feature1.get("name").unwrap().as_str().unwrap(),
            "Tag Directives"
        );
    }

    #[test]
    fn test_input_size_limit() {
        // Create markdown larger than MAX_INPUT_SIZE (10 MB)
        let size = crate::error::MAX_INPUT_SIZE + 1;
        let large_markdown = "a".repeat(size);

        let result = decompose(&large_markdown);
        assert!(result.is_err());

        let err_msg = result.unwrap_err().to_string();
        assert!(err_msg.contains("Input too large"));
    }

    #[test]
    fn test_yaml_size_limit() {
        // Create YAML block larger than MAX_YAML_SIZE (1 MB)
        let mut markdown = String::from("---\n");

        // Create a very large YAML field
        let size = crate::error::MAX_YAML_SIZE + 1;
        markdown.push_str("data: \"");
        markdown.push_str(&"x".repeat(size));
        markdown.push_str("\"\n---\n\nBody");

        let result = decompose(&markdown);
        assert!(result.is_err());

        let err_msg = result.unwrap_err().to_string();
        assert!(err_msg.contains("Input too large"));
    }

    #[test]
    fn test_input_within_size_limit() {
        // Create markdown just under the limit
        let size = 1000; // Much smaller than limit
        let markdown = format!("---\ntitle: Test\n---\n\n{}", "a".repeat(size));

        let result = decompose(&markdown);
        assert!(result.is_ok());
    }

    #[test]
    fn test_yaml_within_size_limit() {
        // Create YAML block well within the limit
        let markdown = "---\ntitle: Test\nauthor: John Doe\n---\n\nBody content";

        let result = decompose(markdown);
        assert!(result.is_ok());
    }

    #[test]
    fn test_yaml_depth_limit() {
        // Create deeply nested YAML that exceeds MAX_YAML_DEPTH (100 levels)
        // This tests serde-saphyr's Budget.max_depth enforcement
        let mut yaml_content = String::new();
        for i in 0..110 {
            yaml_content.push_str(&"  ".repeat(i));
            yaml_content.push_str(&format!("level{}: value\n", i));
        }

        let markdown = format!("---\n{}---\n\nBody", yaml_content);
        let result = decompose(&markdown);

        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        // serde-saphyr returns "budget exceeded" or similar for depth violations
        assert!(
            err_msg.to_lowercase().contains("budget")
                || err_msg.to_lowercase().contains("depth")
                || err_msg.contains("YAML"),
            "Expected depth/budget error, got: {}",
            err_msg
        );
    }

    #[test]
    fn test_yaml_depth_within_limit() {
        // Create reasonably nested YAML (should succeed)
        let markdown = r#"---
level1:
  level2:
    level3:
      level4:
        value: test
---

Body content"#;

        let result = decompose(markdown);
        assert!(result.is_ok());
    }

    // Tests for guillemet preservation in parsing (guillemets are NOT converted during parsing)
    // Guillemet conversion now happens in process_plate, not during parsing
    #[test]
    fn test_chevrons_preserved_in_body_no_frontmatter() {
        let markdown = "Use <<raw content>> here.";
        let doc = decompose(markdown).unwrap();

        // Body should preserve chevrons (conversion happens later in process_plate)
        assert_eq!(doc.body(), Some("Use <<raw content>> here."));
    }

    #[test]
    fn test_chevrons_preserved_in_body_with_frontmatter() {
        let markdown = r#"---
title: Test
---

Use <<raw content>> here."#;
        let doc = decompose(markdown).unwrap();

        // Body should preserve chevrons
        assert_eq!(doc.body(), Some("\nUse <<raw content>> here."));
    }

    #[test]
    fn test_chevrons_preserved_in_yaml_string() {
        let markdown = r#"---
title: Test <<with chevrons>>
---

Body content."#;
        let doc = decompose(markdown).unwrap();

        // YAML string values should preserve chevrons
        assert_eq!(
            doc.get_field("title").unwrap().as_str().unwrap(),
            "Test <<with chevrons>>"
        );
    }

    #[test]
    fn test_chevrons_preserved_in_yaml_array() {
        let markdown = r#"---
items:
  - "<<first>>"
  - "<<second>>"
---

Body."#;
        let doc = decompose(markdown).unwrap();

        let items = doc.get_field("items").unwrap().as_sequence().unwrap();
        assert_eq!(items[0].as_str().unwrap(), "<<first>>");
        assert_eq!(items[1].as_str().unwrap(), "<<second>>");
    }

    #[test]
    fn test_chevrons_preserved_in_yaml_nested() {
        let markdown = r#"---
metadata:
  description: "<<nested value>>"
---

Body."#;
        let doc = decompose(markdown).unwrap();

        let metadata = doc.get_field("metadata").unwrap().as_object().unwrap();
        assert_eq!(
            metadata.get("description").unwrap().as_str().unwrap(),
            "<<nested value>>"
        );
    }

    #[test]
    fn test_chevrons_preserved_in_code_blocks() {
        let markdown = r#"```
<<in code block>>
```

<<outside code block>>"#;
        let doc = decompose(markdown).unwrap();

        let body = doc.body().unwrap();
        // All chevrons should be preserved (no conversion during parsing)
        assert!(body.contains("<<in code block>>"));
        assert!(body.contains("<<outside code block>>"));
    }

    #[test]
    fn test_chevrons_preserved_in_inline_code() {
        let markdown = "`<<in inline code>>` and <<outside inline code>>";
        let doc = decompose(markdown).unwrap();

        let body = doc.body().unwrap();
        // All chevrons should be preserved
        assert!(body.contains("`<<in inline code>>`"));
        assert!(body.contains("<<outside inline code>>"));
    }

    #[test]
    fn test_chevrons_preserved_in_tagged_block_body() {
        let markdown = r#"---
title: Main
---

Main body.

---
CARD: items
name: Item 1
---

Use <<raw>> here."#;
        let doc = decompose(markdown).unwrap();

        let cards = doc.get_field("CARDS").unwrap().as_sequence().unwrap();
        let item = cards[0].as_object().unwrap();
        assert_eq!(item.get("CARD").unwrap().as_str().unwrap(), "items");
        let item_body = item.get(BODY_FIELD).unwrap().as_str().unwrap();
        // Tagged block body should preserve chevrons
        assert!(item_body.contains("<<raw>>"));
    }

    #[test]
    fn test_chevrons_preserved_in_tagged_block_yaml() {
        let markdown = r#"---
title: Main
---

Main body.

---
CARD: items
description: "<<tagged yaml>>"
---

Item body."#;
        let doc = decompose(markdown).unwrap();

        let cards = doc.get_field("CARDS").unwrap().as_sequence().unwrap();
        let item = cards[0].as_object().unwrap();
        assert_eq!(item.get("CARD").unwrap().as_str().unwrap(), "items");
        // Tagged block YAML should preserve chevrons
        assert_eq!(
            item.get("description").unwrap().as_str().unwrap(),
            "<<tagged yaml>>"
        );
    }

    #[test]
    fn test_yaml_numbers_not_affected() {
        // Numbers should not be affected
        let markdown = r#"---
count: 42
---

Body."#;
        let doc = decompose(markdown).unwrap();
        assert_eq!(doc.get_field("count").unwrap().as_i64().unwrap(), 42);
    }

    #[test]
    fn test_yaml_booleans_not_affected() {
        // Booleans should not be affected
        let markdown = r#"---
active: true
---

Body."#;
        let doc = decompose(markdown).unwrap();
        assert!(doc.get_field("active").unwrap().as_bool().unwrap());
    }

    #[test]
    fn test_multiline_chevrons_preserved() {
        // Multiline chevrons should be preserved as-is
        let markdown = "<<text\nacross lines>>";
        let doc = decompose(markdown).unwrap();

        let body = doc.body().unwrap();
        // Should contain the original chevrons
        assert!(body.contains("<<text"));
        assert!(body.contains("across lines>>"));
    }

    #[test]
    fn test_unmatched_chevrons_preserved() {
        let markdown = "<<unmatched";
        let doc = decompose(markdown).unwrap();

        let body = doc.body().unwrap();
        // Unmatched should remain as-is
        assert_eq!(body, "<<unmatched");
    }
}

// Additional robustness tests
#[cfg(test)]
mod robustness_tests {
    use super::*;

    // Edge cases for delimiter handling

    #[test]
    fn test_empty_document() {
        let doc = decompose("").unwrap();
        assert_eq!(doc.body(), Some(""));
        assert_eq!(doc.quill_reference().name, "__default__");
    }

    #[test]
    fn test_only_whitespace() {
        let doc = decompose("   \n\n   \t").unwrap();
        assert_eq!(doc.body(), Some("   \n\n   \t"));
    }

    #[test]
    fn test_only_dashes() {
        // Just "---" at document start without newline is not treated as frontmatter opener
        // (requires "---\n" to start a frontmatter block)
        let result = decompose("---");
        // This is NOT an error - "---" alone without newline is just body content
        assert!(result.is_ok());
        assert_eq!(result.unwrap().body(), Some("---"));
    }

    #[test]
    fn test_dashes_in_middle_of_line() {
        // --- not at start of line should not be treated as delimiter
        let markdown = "some text --- more text";
        let doc = decompose(markdown).unwrap();
        assert_eq!(doc.body(), Some("some text --- more text"));
    }

    #[test]
    fn test_four_dashes() {
        // ---- is not a valid delimiter
        let markdown = "----\ntitle: Test\n----\n\nBody";
        let doc = decompose(markdown).unwrap();
        // Should treat entire content as body
        assert!(doc.body().unwrap().contains("----"));
    }

    #[test]
    fn test_crlf_line_endings() {
        // Windows-style line endings
        let markdown = "---\r\ntitle: Test\r\n---\r\n\r\nBody content.";
        let doc = decompose(markdown).unwrap();
        assert_eq!(doc.get_field("title").unwrap().as_str().unwrap(), "Test");
        assert!(doc.body().unwrap().contains("Body content."));
    }

    #[test]
    fn test_mixed_line_endings() {
        // Mix of \n and \r\n
        let markdown = "---\ntitle: Test\r\n---\n\nBody.";
        let doc = decompose(markdown).unwrap();
        assert_eq!(doc.get_field("title").unwrap().as_str().unwrap(), "Test");
    }

    #[test]
    fn test_frontmatter_at_eof_no_trailing_newline() {
        // Frontmatter closed at EOF without trailing newline
        let markdown = "---\ntitle: Test\n---";
        let doc = decompose(markdown).unwrap();
        assert_eq!(doc.get_field("title").unwrap().as_str().unwrap(), "Test");
        assert_eq!(doc.body(), Some(""));
    }

    #[test]
    fn test_empty_frontmatter() {
        // Empty frontmatter block - requires content between delimiters
        // "---\n---" is not valid because --- followed by --- (blank line then ---)
        // is treated as horizontal rule logic, not empty frontmatter
        // A valid empty frontmatter would be "---\n \n---" (with whitespace content)
        let markdown = "---\n \n---\n\nBody content.";
        let doc = decompose(markdown).unwrap();
        assert!(doc.body().unwrap().contains("Body content."));
        // Should have body and CARDS fields
        assert_eq!(doc.fields().len(), 2);
    }

    #[test]
    fn test_whitespace_only_frontmatter() {
        // Frontmatter with only whitespace
        let markdown = "---\n   \n\n   \n---\n\nBody.";
        let doc = decompose(markdown).unwrap();
        assert!(doc.body().unwrap().contains("Body."));
    }

    // Unicode handling

    #[test]
    fn test_unicode_in_yaml_keys() {
        let markdown = "---\ntitre: Bonjour\nタイトル: こんにちは\n---\n\nBody.";
        let doc = decompose(markdown).unwrap();
        assert_eq!(doc.get_field("titre").unwrap().as_str().unwrap(), "Bonjour");
        assert_eq!(
            doc.get_field("タイトル").unwrap().as_str().unwrap(),
            "こんにちは"
        );
    }

    #[test]
    fn test_unicode_in_yaml_values() {
        let markdown = "---\ntitle: 你好世界 🎉\n---\n\nBody.";
        let doc = decompose(markdown).unwrap();
        assert_eq!(
            doc.get_field("title").unwrap().as_str().unwrap(),
            "你好世界 🎉"
        );
    }

    #[test]
    fn test_unicode_in_body() {
        let markdown = "---\ntitle: Test\n---\n\n日本語テキスト with emoji 🚀";
        let doc = decompose(markdown).unwrap();
        assert!(doc.body().unwrap().contains("日本語テキスト"));
        assert!(doc.body().unwrap().contains("🚀"));
    }

    // YAML edge cases

    #[test]
    fn test_yaml_multiline_string() {
        let markdown = r#"---
description: |
  This is a
  multiline string
  with preserved newlines.
---

Body."#;
        let doc = decompose(markdown).unwrap();
        let desc = doc.get_field("description").unwrap().as_str().unwrap();
        assert!(desc.contains("multiline string"));
        assert!(desc.contains('\n'));
    }

    #[test]
    fn test_yaml_folded_string() {
        let markdown = r#"---
description: >
  This is a folded
  string that becomes
  a single line.
---

Body."#;
        let doc = decompose(markdown).unwrap();
        let desc = doc.get_field("description").unwrap().as_str().unwrap();
        // Folded strings join lines with spaces
        assert!(desc.contains("folded"));
    }

    #[test]
    fn test_yaml_null_value() {
        let markdown = "---\noptional: null\n---\n\nBody.";
        let doc = decompose(markdown).unwrap();
        assert!(doc.get_field("optional").unwrap().is_null());
    }

    #[test]
    fn test_yaml_empty_string_value() {
        let markdown = "---\nempty: \"\"\n---\n\nBody.";
        let doc = decompose(markdown).unwrap();
        assert_eq!(doc.get_field("empty").unwrap().as_str().unwrap(), "");
    }

    #[test]
    fn test_yaml_special_characters_in_string() {
        let markdown = "---\nspecial: \"colon: here, and [brackets]\"\n---\n\nBody.";
        let doc = decompose(markdown).unwrap();
        assert_eq!(
            doc.get_field("special").unwrap().as_str().unwrap(),
            "colon: here, and [brackets]"
        );
    }

    #[test]
    fn test_yaml_nested_objects() {
        let markdown = r#"---
config:
  database:
    host: localhost
    port: 5432
  cache:
    enabled: true
---

Body."#;
        let doc = decompose(markdown).unwrap();
        let config = doc.get_field("config").unwrap().as_object().unwrap();
        let db = config.get("database").unwrap().as_object().unwrap();
        assert_eq!(db.get("host").unwrap().as_str().unwrap(), "localhost");
        assert_eq!(db.get("port").unwrap().as_i64().unwrap(), 5432);
    }

    // CARD block edge cases

    #[test]
    fn test_card_with_empty_body() {
        let markdown = r#"---
CARD: items
name: Item
---"#;
        let doc = decompose(markdown).unwrap();
        let cards = doc.get_field("CARDS").unwrap().as_sequence().unwrap();
        assert_eq!(cards.len(), 1);
        let item = cards[0].as_object().unwrap();
        assert_eq!(item.get("CARD").unwrap().as_str().unwrap(), "items");
        assert_eq!(item.get(BODY_FIELD).unwrap().as_str().unwrap(), "");
    }

    #[test]
    fn test_card_consecutive_blocks() {
        let markdown = r#"---
CARD: a
id: 1
---
---
CARD: a
id: 2
---"#;
        let doc = decompose(markdown).unwrap();
        let cards = doc.get_field("CARDS").unwrap().as_sequence().unwrap();
        assert_eq!(cards.len(), 2);
        assert_eq!(
            cards[0]
                .as_object()
                .unwrap()
                .get("CARD")
                .unwrap()
                .as_str()
                .unwrap(),
            "a"
        );
        assert_eq!(
            cards[1]
                .as_object()
                .unwrap()
                .get("CARD")
                .unwrap()
                .as_str()
                .unwrap(),
            "a"
        );
    }

    #[test]
    fn test_card_with_body_containing_dashes() {
        let markdown = r#"---
CARD: items
name: Item
---

Some text with --- dashes in it."#;
        let doc = decompose(markdown).unwrap();
        let cards = doc.get_field("CARDS").unwrap().as_sequence().unwrap();
        let item = cards[0].as_object().unwrap();
        assert_eq!(item.get("CARD").unwrap().as_str().unwrap(), "items");
        let body = item.get(BODY_FIELD).unwrap().as_str().unwrap();
        assert!(body.contains("--- dashes"));
    }

    // QUILL directive edge cases

    #[test]
    fn test_quill_with_underscore_prefix() {
        let markdown = "---\nQUILL: _internal\n---\n\nBody.";
        let doc = decompose(markdown).unwrap();
        assert_eq!(doc.quill_reference().name, "_internal");
    }

    #[test]
    fn test_quill_with_numbers() {
        let markdown = "---\nQUILL: form_8_v2\n---\n\nBody.";
        let doc = decompose(markdown).unwrap();
        assert_eq!(doc.quill_reference().name, "form_8_v2");
    }

    #[test]
    fn test_quill_with_additional_fields() {
        let markdown = r#"---
QUILL: my_quill
title: Document Title
author: John Doe
---

Body content."#;
        let doc = decompose(markdown).unwrap();
        assert_eq!(doc.quill_reference().name, "my_quill");
        assert_eq!(
            doc.get_field("title").unwrap().as_str().unwrap(),
            "Document Title"
        );
        assert_eq!(
            doc.get_field("author").unwrap().as_str().unwrap(),
            "John Doe"
        );
    }

    // Error handling

    #[test]
    fn test_invalid_scope_name_uppercase() {
        let markdown = "---\nCARD: ITEMS\n---\n\nBody.";
        let result = decompose(markdown);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Invalid card field name"));
    }

    #[test]
    fn test_invalid_scope_name_starts_with_number() {
        let markdown = "---\nCARD: 123items\n---\n\nBody.";
        let result = decompose(markdown);
        assert!(result.is_err());
    }

    #[test]
    fn test_invalid_scope_name_with_hyphen() {
        let markdown = "---\nCARD: my-items\n---\n\nBody.";
        let result = decompose(markdown);
        assert!(result.is_err());
    }

    #[test]
    fn test_invalid_quill_ref_uppercase() {
        let markdown = "---\nQUILL: MyQuill\n---\n\nBody.";
        let result = decompose(markdown);
        assert!(result.is_err());
    }

    #[test]
    fn test_yaml_syntax_error_missing_colon() {
        let markdown = "---\ntitle Test\n---\n\nBody.";
        let result = decompose(markdown);
        assert!(result.is_err());
    }

    #[test]
    fn test_yaml_syntax_error_bad_indentation() {
        let markdown = "---\nitems:\n- one\n - two\n---\n\nBody.";
        let result = decompose(markdown);
        // Bad indentation may or may not be an error depending on YAML parser
        // Just ensure it doesn't panic
        let _ = result;
    }

    // Body extraction edge cases

    #[test]
    fn test_body_with_leading_newlines() {
        let markdown = "---\ntitle: Test\n---\n\n\n\nBody with leading newlines.";
        let doc = decompose(markdown).unwrap();
        // Body should preserve leading newlines after frontmatter
        assert!(doc.body().unwrap().starts_with('\n'));
    }

    #[test]
    fn test_body_with_trailing_newlines() {
        let markdown = "---\ntitle: Test\n---\n\nBody.\n\n\n";
        let doc = decompose(markdown).unwrap();
        // Body should preserve trailing newlines
        assert!(doc.body().unwrap().ends_with('\n'));
    }

    #[test]
    fn test_no_body_after_frontmatter() {
        let markdown = "---\ntitle: Test\n---";
        let doc = decompose(markdown).unwrap();
        assert_eq!(doc.body(), Some(""));
    }

    // Tag name validation

    #[test]
    fn test_valid_tag_name_single_underscore() {
        assert!(is_valid_tag_name("_"));
    }

    #[test]
    fn test_valid_tag_name_underscore_prefix() {
        assert!(is_valid_tag_name("_private"));
    }

    #[test]
    fn test_valid_tag_name_with_numbers() {
        assert!(is_valid_tag_name("item1"));
        assert!(is_valid_tag_name("item_2"));
    }

    #[test]
    fn test_invalid_tag_name_empty() {
        assert!(!is_valid_tag_name(""));
    }

    #[test]
    fn test_invalid_tag_name_starts_with_number() {
        assert!(!is_valid_tag_name("1item"));
    }

    #[test]
    fn test_invalid_tag_name_uppercase() {
        assert!(!is_valid_tag_name("Items"));
        assert!(!is_valid_tag_name("ITEMS"));
    }

    #[test]
    fn test_invalid_tag_name_special_chars() {
        assert!(!is_valid_tag_name("my-items"));
        assert!(!is_valid_tag_name("my.items"));
        assert!(!is_valid_tag_name("my items"));
    }

    // Guillemet preprocessing in YAML

    #[test]
    fn test_guillemet_in_yaml_preserves_non_strings() {
        let markdown = r#"---
count: 42
price: 19.99
active: true
items:
  - first
  - 100
  - true
---

Body."#;
        let doc = decompose(markdown).unwrap();
        assert_eq!(doc.get_field("count").unwrap().as_i64().unwrap(), 42);
        assert_eq!(doc.get_field("price").unwrap().as_f64().unwrap(), 19.99);
        assert!(doc.get_field("active").unwrap().as_bool().unwrap());
    }

    #[test]
    fn test_guillemet_double_conversion_prevention() {
        // Ensure «» in input doesn't get double-processed
        let markdown = "---\ntitle: Already «converted»\n---\n\nBody.";
        let doc = decompose(markdown).unwrap();
        // Should remain as-is (not double-escaped)
        assert_eq!(
            doc.get_field("title").unwrap().as_str().unwrap(),
            "Already «converted»"
        );
    }

    #[test]
    fn test_allowed_card_field_collision() {
        let markdown = r#"---
my_card: "some global value"
---

---
CARD: my_card
title: "My Card"
---
Body
"#;
        // This should SUCCEED according to new PARSE.md
        let doc = decompose(markdown).unwrap();

        // Verify global field exists
        assert_eq!(
            doc.get_field("my_card").unwrap().as_str().unwrap(),
            "some global value"
        );

        // Verify Card exists in CARDS array
        let cards = doc.get_field("CARDS").unwrap().as_array().unwrap();
        assert!(!cards.is_empty());
        let card = cards
            .iter()
            .find(|v| v.get("CARD").and_then(|c| c.as_str()) == Some("my_card"))
            .expect("Card not found");
        assert_eq!(card.get("title").unwrap().as_str().unwrap(), "My Card");
    }

    #[test]
    fn test_yaml_custom_tags_in_frontmatter() {
        // User-defined YAML tags like !fill should be accepted and ignored
        let markdown = r#"---
memo_from: !fill 2d lt example
regular_field: normal value
---

Body content."#;
        let doc = decompose(markdown).unwrap();

        // The tag !fill should be ignored, value parsed as string "2d lt example"
        assert_eq!(
            doc.get_field("memo_from").unwrap().as_str().unwrap(),
            "2d lt example"
        );
        // Regular fields should still work
        assert_eq!(
            doc.get_field("regular_field").unwrap().as_str().unwrap(),
            "normal value"
        );
        assert_eq!(doc.body(), Some("\nBody content."));
    }

    /// Test the exact example from EXTENDED_MARKDOWN.md (lines 92-127)
    #[test]
    fn test_spec_example() {
        let markdown = r#"---
title: My Document
QUILL: blog_post
---
Main document body.

***

More content after horizontal rule.

---
CARD: section
heading: Introduction
---
Introduction content.

---
CARD: section
heading: Conclusion
---
Conclusion content.
"#;

        let doc = decompose(markdown).unwrap();

        // Verify global fields
        assert_eq!(
            doc.get_field("title").unwrap().as_str().unwrap(),
            "My Document"
        );
        assert_eq!(doc.quill_reference().name, "blog_post");

        // Verify body contains horizontal rule (*** preserved)
        let body = doc.body().unwrap();
        assert!(body.contains("Main document body."));
        assert!(body.contains("***"));
        assert!(body.contains("More content after horizontal rule."));

        // Verify CARDS array
        let cards = doc.get_field("CARDS").unwrap().as_array().unwrap();
        assert_eq!(cards.len(), 2);

        // First card
        let card1 = cards[0].as_object().unwrap();
        assert_eq!(card1.get("CARD").unwrap().as_str().unwrap(), "section");
        assert_eq!(
            card1.get("heading").unwrap().as_str().unwrap(),
            "Introduction"
        );
        assert_eq!(
            card1.get("BODY").unwrap().as_str().unwrap(),
            "Introduction content.\n\n"
        );

        // Second card
        let card2 = cards[1].as_object().unwrap();
        assert_eq!(card2.get("CARD").unwrap().as_str().unwrap(), "section");
        assert_eq!(
            card2.get("heading").unwrap().as_str().unwrap(),
            "Conclusion"
        );
        assert_eq!(
            card2.get("BODY").unwrap().as_str().unwrap(),
            "Conclusion content.\n"
        );
    }
}