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
//! Quill template bundle types and implementations.

use std::collections::HashMap;
use std::error::Error as StdError;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::value::QuillValue;

/// Semantic constants for field schema keys used in parsing and JSON Schema generation.
/// Using constants provides IDE support (find references, autocomplete) and ensures
/// consistency between parsing and output.
pub mod field_key {
    /// Short label for the field
    pub const TITLE: &str = "title";
    /// Field type (string, number, boolean, array, etc.)
    pub const TYPE: &str = "type";
    /// Detailed field description
    pub const DESCRIPTION: &str = "description";
    /// Default value for the field
    pub const DEFAULT: &str = "default";
    /// Example values for the field
    pub const EXAMPLES: &str = "examples";
    /// UI-specific metadata
    pub const UI: &str = "ui";
    /// Whether the field is required
    pub const REQUIRED: &str = "required";
    /// Enum values for string fields
    pub const ENUM: &str = "enum";
    /// Date format specifier (JSON Schema)
    pub const FORMAT: &str = "format";
}

/// Semantic constants for UI schema keys
pub mod ui_key {
    /// Group name for field organization
    pub const GROUP: &str = "group";
    /// Display order within the UI
    pub const ORDER: &str = "order";
    /// Whether the field or specific component is hide-body (no body editor)
    pub const HIDE_BODY: &str = "hide_body";
    /// Conditional visibility rules: field → accepted values
    pub const VISIBLE_WHEN: &str = "visible_when";
}

/// UI-specific metadata for field rendering
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UiFieldSchema {
    /// Group name for organizing fields (e.g., "Personal Info", "Preferences")
    pub group: Option<String>,
    /// Order of the field in the UI (automatically generated based on field position in Quill.yaml)
    pub order: Option<i32>,
    /// Conditional visibility: map of sibling field name → accepted values.
    /// The field is visible when ALL conditions match (AND across keys, OR within each key's values).
    /// Example: `visible_when: { format: [standard, separate_page] }` means show this field
    /// only when the sibling `format` field has value "standard" or "separate_page".
    pub visible_when: Option<HashMap<String, Vec<String>>>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UiContainerSchema {
    /// Whether to hide the body editor for this element (metadata only)
    pub hide_body: Option<bool>,
}

/// Schema definition for a card type (composable content blocks)
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CardSchema {
    /// Card type name (e.g., "indorsements")
    pub name: String,
    /// Short label for the card type
    pub title: Option<String>,
    /// Detailed description of this card type
    pub description: Option<String>,
    /// List of fields in the card
    pub fields: HashMap<String, FieldSchema>,
    /// UI layout hints
    pub ui: Option<UiContainerSchema>,
}

/// Field type hint enum for type-safe field type definitions
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FieldType {
    /// String type
    #[serde(alias = "str")]
    String,
    /// Numeric type
    Number,
    /// Boolean type
    Boolean,
    /// Array type
    Array,
    /// Dictionary/object type
    Object,
    /// Date type (formatted as string with date format)
    Date,
    /// DateTime type (formatted as string with date-time format)
    DateTime,
    /// Markdown type (string with markdown content, contentMediaType: text/markdown)
    Markdown,
}

impl FieldType {
    /// Parse a FieldType from a string
    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "string" | "str" => Some(FieldType::String),
            "number" => Some(FieldType::Number),
            "boolean" => Some(FieldType::Boolean),
            "array" => Some(FieldType::Array),
            "object" | "dict" => Some(FieldType::Object),
            "date" => Some(FieldType::Date),
            "datetime" => Some(FieldType::DateTime),
            "markdown" => Some(FieldType::Markdown),
            _ => None,
        }
    }

    /// Get the canonical string representation for this type
    pub fn as_str(&self) -> &'static str {
        match self {
            FieldType::String => "string",
            FieldType::Number => "number",
            FieldType::Boolean => "boolean",
            FieldType::Array => "array",
            FieldType::Object => "dict",
            FieldType::Date => "date",
            FieldType::DateTime => "datetime",
            FieldType::Markdown => "markdown",
        }
    }
}

/// Schema definition for a template field
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FieldSchema {
    pub name: String,
    /// Short label for the field (used in JSON Schema title)
    pub title: Option<String>,
    /// Field type (required)
    pub r#type: FieldType,
    /// Detailed description of the field (used in JSON Schema description)
    pub description: Option<String>,
    /// Default value for the field
    pub default: Option<QuillValue>,
    /// Example values for the field
    pub examples: Option<QuillValue>,
    /// UI layout hints
    pub ui: Option<UiFieldSchema>,
    /// Whether this field is required (fields are optional by default)
    pub required: bool,
    /// Enum values for string fields (restricts valid values)
    pub enum_values: Option<Vec<String>>,
    /// Properties for dict/object types (nested field schemas)
    pub properties: Option<HashMap<String, Box<FieldSchema>>>,
    /// Item schema for array types
    pub items: Option<Box<FieldSchema>>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct FieldSchemaDef {
    pub title: Option<String>,
    pub r#type: FieldType,
    pub description: Option<String>,
    pub default: Option<QuillValue>,
    pub examples: Option<QuillValue>,
    pub ui: Option<UiFieldSchema>,
    #[serde(default)]
    pub required: bool,
    #[serde(rename = "enum")]
    pub enum_values: Option<Vec<String>>,
    // Nested schema support
    // Nested schema support
    pub properties: Option<serde_json::Map<String, serde_json::Value>>,
    pub items: Option<serde_json::Value>,
}

impl FieldSchema {
    /// Create a new FieldSchema with default values
    pub fn new(name: String, r#type: FieldType, description: Option<String>) -> Self {
        Self {
            name,
            title: None,
            r#type,
            description,
            default: None,
            examples: None,
            ui: None,
            required: false,
            enum_values: None,
            properties: None,
            items: None,
        }
    }

    /// Parse a FieldSchema from a QuillValue
    pub fn from_quill_value(key: String, value: &QuillValue) -> Result<Self, String> {
        let def: FieldSchemaDef = serde_json::from_value(value.clone().into_json())
            .map_err(|e| format!("Failed to parse field schema: {}", e))?;

        Ok(Self {
            name: key,
            title: def.title,
            r#type: def.r#type,
            description: def.description,
            default: def.default,
            examples: def.examples,
            ui: def.ui,
            required: def.required,
            enum_values: def.enum_values,
            properties: if let Some(props) = def.properties {
                let mut p = HashMap::new();
                for (key, value) in props {
                    p.insert(
                        key.clone(),
                        Box::new(FieldSchema::from_quill_value(
                            key,
                            &QuillValue::from_json(value),
                        )?),
                    );
                }
                Some(p)
            } else {
                None
            },
            items: if let Some(item_def) = def.items {
                Some(Box::new(FieldSchema::from_quill_value(
                    "items".to_string(),
                    &QuillValue::from_json(item_def),
                )?))
            } else {
                None
            },
        })
    }
}

/// A node in the file tree structure
#[derive(Debug, Clone)]
pub enum FileTreeNode {
    /// A file with its contents
    File {
        /// The file contents as bytes or UTF-8 string
        contents: Vec<u8>,
    },
    /// A directory containing other files and directories
    Directory {
        /// The files and subdirectories in this directory
        files: HashMap<String, FileTreeNode>,
    },
}

impl FileTreeNode {
    /// Get a file or directory node by path
    pub fn get_node<P: AsRef<Path>>(&self, path: P) -> Option<&FileTreeNode> {
        let path = path.as_ref();

        // Handle root path
        if path == Path::new("") {
            return Some(self);
        }

        // Split path into components
        let components: Vec<_> = path
            .components()
            .filter_map(|c| {
                if let std::path::Component::Normal(s) = c {
                    s.to_str()
                } else {
                    None
                }
            })
            .collect();

        if components.is_empty() {
            return Some(self);
        }

        // Navigate through the tree
        let mut current_node = self;
        for component in components {
            match current_node {
                FileTreeNode::Directory { files } => {
                    current_node = files.get(component)?;
                }
                FileTreeNode::File { .. } => {
                    return None; // Can't traverse into a file
                }
            }
        }

        Some(current_node)
    }

    /// Get file contents by path
    pub fn get_file<P: AsRef<Path>>(&self, path: P) -> Option<&[u8]> {
        match self.get_node(path)? {
            FileTreeNode::File { contents } => Some(contents.as_slice()),
            FileTreeNode::Directory { .. } => None,
        }
    }

    /// Check if a file exists at the given path
    pub fn file_exists<P: AsRef<Path>>(&self, path: P) -> bool {
        matches!(self.get_node(path), Some(FileTreeNode::File { .. }))
    }

    /// Check if a directory exists at the given path
    pub fn dir_exists<P: AsRef<Path>>(&self, path: P) -> bool {
        matches!(self.get_node(path), Some(FileTreeNode::Directory { .. }))
    }

    /// List all files in a directory (non-recursive)
    pub fn list_files<P: AsRef<Path>>(&self, dir_path: P) -> Vec<String> {
        match self.get_node(dir_path) {
            Some(FileTreeNode::Directory { files }) => files
                .iter()
                .filter_map(|(name, node)| {
                    if matches!(node, FileTreeNode::File { .. }) {
                        Some(name.clone())
                    } else {
                        None
                    }
                })
                .collect(),
            _ => Vec::new(),
        }
    }

    /// List all subdirectories in a directory (non-recursive)
    pub fn list_subdirectories<P: AsRef<Path>>(&self, dir_path: P) -> Vec<String> {
        match self.get_node(dir_path) {
            Some(FileTreeNode::Directory { files }) => files
                .iter()
                .filter_map(|(name, node)| {
                    if matches!(node, FileTreeNode::Directory { .. }) {
                        Some(name.clone())
                    } else {
                        None
                    }
                })
                .collect(),
            _ => Vec::new(),
        }
    }

    /// Insert a file or directory at the given path
    pub fn insert<P: AsRef<Path>>(
        &mut self,
        path: P,
        node: FileTreeNode,
    ) -> Result<(), Box<dyn StdError + Send + Sync>> {
        let path = path.as_ref();

        // Split path into components
        let components: Vec<_> = path
            .components()
            .filter_map(|c| {
                if let std::path::Component::Normal(s) = c {
                    s.to_str().map(|s| s.to_string())
                } else {
                    None
                }
            })
            .collect();

        if components.is_empty() {
            return Err("Cannot insert at root path".into());
        }

        // Navigate to parent directory, creating directories as needed
        let mut current_node = self;
        for component in &components[..components.len() - 1] {
            match current_node {
                FileTreeNode::Directory { files } => {
                    current_node =
                        files
                            .entry(component.clone())
                            .or_insert_with(|| FileTreeNode::Directory {
                                files: HashMap::new(),
                            });
                }
                FileTreeNode::File { .. } => {
                    return Err("Cannot traverse into a file".into());
                }
            }
        }

        // Insert the new node
        let filename = &components[components.len() - 1];
        match current_node {
            FileTreeNode::Directory { files } => {
                files.insert(filename.clone(), node);
                Ok(())
            }
            FileTreeNode::File { .. } => Err("Cannot insert into a file".into()),
        }
    }

    /// Parse a tree structure from JSON value
    fn from_json_value(value: &serde_json::Value) -> Result<Self, Box<dyn StdError + Send + Sync>> {
        if let Some(contents_str) = value.get("contents").and_then(|v| v.as_str()) {
            // It's a file with string contents
            Ok(FileTreeNode::File {
                contents: contents_str.as_bytes().to_vec(),
            })
        } else if let Some(bytes_array) = value.get("contents").and_then(|v| v.as_array()) {
            // It's a file with byte array contents
            let contents: Vec<u8> = bytes_array
                .iter()
                .filter_map(|v| v.as_u64().and_then(|n| u8::try_from(n).ok()))
                .collect();
            Ok(FileTreeNode::File { contents })
        } else if let Some(obj) = value.as_object() {
            // It's a directory (either empty or with nested files)
            let mut files = HashMap::new();
            for (name, child_value) in obj {
                files.insert(name.clone(), Self::from_json_value(child_value)?);
            }
            // Empty directories are valid
            Ok(FileTreeNode::Directory { files })
        } else {
            Err(format!("Invalid file tree node: {:?}", value).into())
        }
    }

    pub fn print_tree(&self) -> String {
        self.print_tree_recursive("", "", true)
    }

    fn print_tree_recursive(&self, name: &str, prefix: &str, is_last: bool) -> String {
        let mut result = String::new();

        // Choose the appropriate tree characters
        let connector = if is_last { "└── " } else { "├── " };
        let extension = if is_last { "    " } else { "│   " };

        match self {
            FileTreeNode::File { .. } => {
                result.push_str(&format!("{}{}{}\n", prefix, connector, name));
            }
            FileTreeNode::Directory { files } => {
                // Add trailing slash for directories like `tree` does
                result.push_str(&format!("{}{}{}/\n", prefix, connector, name));

                let child_prefix = format!("{}{}", prefix, extension);
                let count = files.len();

                for (i, (child_name, node)) in files.iter().enumerate() {
                    let is_last_child = i == count - 1;
                    result.push_str(&node.print_tree_recursive(
                        child_name,
                        &child_prefix,
                        is_last_child,
                    ));
                }
            }
        }

        result
    }
}

/// Simple gitignore-style pattern matcher for .quillignore
#[derive(Debug, Clone)]
pub struct QuillIgnore {
    patterns: Vec<String>,
}

impl QuillIgnore {
    /// Create a new QuillIgnore from pattern strings
    pub fn new(patterns: Vec<String>) -> Self {
        Self { patterns }
    }

    /// Parse .quillignore content into patterns
    pub fn from_content(content: &str) -> Self {
        let patterns = content
            .lines()
            .map(|line| line.trim())
            .filter(|line| !line.is_empty() && !line.starts_with('#'))
            .map(|line| line.to_string())
            .collect();
        Self::new(patterns)
    }

    /// Check if a path should be ignored
    pub fn is_ignored<P: AsRef<Path>>(&self, path: P) -> bool {
        let path = path.as_ref();
        let path_str = path.to_string_lossy();

        for pattern in &self.patterns {
            if self.matches_pattern(pattern, &path_str) {
                return true;
            }
        }
        false
    }

    /// Simple pattern matching (supports * wildcard and directory patterns)
    fn matches_pattern(&self, pattern: &str, path: &str) -> bool {
        // Handle directory patterns
        if let Some(pattern_prefix) = pattern.strip_suffix('/') {
            return path.starts_with(pattern_prefix)
                && (path.len() == pattern_prefix.len()
                    || path.chars().nth(pattern_prefix.len()) == Some('/'));
        }

        // Handle exact matches
        if !pattern.contains('*') {
            return path == pattern || path.ends_with(&format!("/{}", pattern));
        }

        // Simple wildcard matching
        if pattern == "*" {
            return true;
        }

        // Handle patterns with wildcards
        let pattern_parts: Vec<&str> = pattern.split('*').collect();
        if pattern_parts.len() == 2 {
            let (prefix, suffix) = (pattern_parts[0], pattern_parts[1]);
            if prefix.is_empty() {
                return path.ends_with(suffix);
            } else if suffix.is_empty() {
                return path.starts_with(prefix);
            } else {
                return path.starts_with(prefix) && path.ends_with(suffix);
            }
        }

        false
    }
}

/// A quill template bundle.
#[derive(Debug, Clone)]
pub struct Quill {
    /// Quill-specific metadata
    pub metadata: HashMap<String, QuillValue>,
    /// Name of the quill
    pub name: String,
    /// Backend identifier (e.g., "typst")
    pub backend: String,
    /// Plate template content (optional)
    pub plate: Option<String>,
    /// Markdown template content (optional)
    pub example: Option<String>,
    /// Field JSON schema (single source of truth for schema and defaults)
    pub schema: QuillValue,
    /// Cached default values extracted from schema (for performance)
    pub defaults: HashMap<String, QuillValue>,
    /// Cached example values extracted from schema (for performance)
    pub examples: HashMap<String, Vec<QuillValue>>,
    /// In-memory file system (tree structure)
    pub files: FileTreeNode,
}

/// Top-level configuration for a Quillmark project
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct QuillConfig {
    /// The root document schema
    pub document: CardSchema,
    /// Backend to use for rendering (e.g., "typst", "html")
    pub backend: String,
    /// Version of the Quillmark spec
    pub version: String,
    /// Author of the project
    pub author: String,
    /// Example data file for preview
    pub example_file: Option<String>,
    /// Plate file (template)
    pub plate_file: Option<String>,
    /// Card definitions (reusable sub-schemas)
    pub cards: HashMap<String, CardSchema>,
    /// Additional unstructured metadata
    #[serde(flatten)]
    pub metadata: HashMap<String, QuillValue>,
    /// Typst specific configuration
    #[serde(default)]
    pub typst_config: HashMap<String, QuillValue>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct CardSchemaDef {
    pub title: Option<String>,
    pub description: Option<String>,
    pub fields: Option<serde_json::Map<String, serde_json::Value>>,
    pub ui: Option<UiContainerSchema>,
}

impl QuillConfig {
    /// Parse fields from a JSON Value map, assigning ui.order based on key_order.
    ///
    /// This helper ensures consistent field ordering logic for both top-level
    /// fields and card fields.
    ///
    /// # Arguments
    /// * `fields_map` - The JSON map containing field definitions
    /// * `key_order` - Vector of field names in their definition order
    /// * `context` - Context string for error messages (e.g., "field" or "card 'indorsement' field")
    fn parse_fields_with_order(
        fields_map: &serde_json::Map<String, serde_json::Value>,
        key_order: &[String],
        context: &str,
    ) -> HashMap<String, FieldSchema> {
        let mut fields = HashMap::new();
        let mut fallback_counter = 0;

        for (field_name, field_value) in fields_map {
            // Determine order from key_order, or use fallback counter
            let order = if let Some(idx) = key_order.iter().position(|k| k == field_name) {
                idx as i32
            } else {
                let o = key_order.len() as i32 + fallback_counter;
                fallback_counter += 1;
                o
            };

            let quill_value = QuillValue::from_json(field_value.clone());
            match FieldSchema::from_quill_value(field_name.clone(), &quill_value) {
                Ok(mut schema) => {
                    // Always set ui.order based on position
                    if schema.ui.is_none() {
                        schema.ui = Some(UiFieldSchema {
                            group: None,
                            order: Some(order),
                            visible_when: None,
                        });
                    } else if let Some(ui) = &mut schema.ui {
                        // Only set if not already set
                        if ui.order.is_none() {
                            ui.order = Some(order);
                        }
                    }

                    fields.insert(field_name.clone(), schema);
                }
                Err(e) => {
                    eprintln!(
                        "Warning: Failed to parse {} '{}': {}",
                        context, field_name, e
                    );
                }
            }
        }

        fields
    }

    /// Parse QuillConfig from YAML content
    pub fn from_yaml(yaml_content: &str) -> Result<Self, Box<dyn StdError + Send + Sync>> {
        // Parse YAML into serde_json::Value via serde_saphyr
        // Note: serde_json with "preserve_order" feature is required for this to work as expected
        let quill_yaml_val: serde_json::Value = serde_saphyr::from_str(yaml_content)
            .map_err(|e| format!("Failed to parse Quill.yaml: {}", e))?;

        // Extract [Quill] section (required)
        let quill_section = quill_yaml_val
            .get("Quill")
            .ok_or("Missing required 'Quill' section in Quill.yaml")?;

        // Extract required fields
        let name = quill_section
            .get("name")
            .and_then(|v| v.as_str())
            .ok_or("Missing required 'name' field in 'Quill' section")?
            .to_string();

        let backend = quill_section
            .get("backend")
            .and_then(|v| v.as_str())
            .ok_or("Missing required 'backend' field in 'Quill' section")?
            .to_string();

        let description = quill_section
            .get("description")
            .and_then(|v| v.as_str())
            .ok_or("Missing required 'description' field in 'Quill' section")?;

        if description.trim().is_empty() {
            return Err("'description' field in 'Quill' section cannot be empty".into());
        }
        let description = description.to_string();

        // Extract optional fields (now version is required)
        let version_val = quill_section
            .get("version")
            .ok_or("Missing required 'version' field in 'Quill' section")?;

        // Handle version as string or number (YAML might parse 1.0 as number)
        let version = if let Some(s) = version_val.as_str() {
            s.to_string()
        } else if let Some(n) = version_val.as_f64() {
            n.to_string()
        } else {
            return Err("Invalid 'version' field format".into());
        };

        // Validate version format (semver: MAJOR.MINOR.PATCH or MAJOR.MINOR)
        use std::str::FromStr;
        crate::version::Version::from_str(&version)
            .map_err(|e| format!("Invalid version '{}': {}", version, e))?;

        let author = quill_section
            .get("author")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string())
            .unwrap_or_else(|| "Unknown".to_string()); // Default author

        let example_file = quill_section
            .get("example_file")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

        let plate_file = quill_section
            .get("plate_file")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

        let ui_section: Option<UiContainerSchema> = quill_section
            .get("ui")
            .cloned()
            .and_then(|v| serde_json::from_value(v).ok());

        // Extract additional metadata from [Quill] section (excluding standard fields)
        let mut metadata = HashMap::new();
        if let Some(table) = quill_section.as_object() {
            for (key, value) in table {
                // Skip standard fields that are stored in dedicated struct fields
                if key != "name"
                    && key != "backend"
                    && key != "description"
                    && key != "version"
                    && key != "author"
                    && key != "example_file"
                    && key != "plate_file"
                    && key != "ui"
                {
                    metadata.insert(key.clone(), QuillValue::from_json(value.clone()));
                }
            }
        }

        // Extract [typst] section (optional)
        let mut typst_config = HashMap::new();
        if let Some(typst_val) = quill_yaml_val.get("typst") {
            if let Some(table) = typst_val.as_object() {
                for (key, value) in table {
                    typst_config.insert(key.clone(), QuillValue::from_json(value.clone()));
                }
            }
        }

        // Extract [fields] section (optional) using shared helper
        let fields = if let Some(fields_val) = quill_yaml_val.get("fields") {
            if let Some(fields_map) = fields_val.as_object() {
                // With preserve_order feature, keys iterator respects insertion order
                let field_order: Vec<String> = fields_map.keys().cloned().collect();
                Self::parse_fields_with_order(fields_map, &field_order, "field schema")
            } else {
                HashMap::new()
            }
        } else {
            HashMap::new()
        };

        // Extract [cards] section (optional)
        let mut cards: HashMap<String, CardSchema> = HashMap::new();
        if let Some(cards_val) = quill_yaml_val.get("cards") {
            let cards_table = cards_val
                .as_object()
                .ok_or("'cards' section must be an object")?;

            for (card_name, card_value) in cards_table {
                // Parse card basic info using serde
                let card_def: CardSchemaDef = serde_json::from_value(card_value.clone())
                    .map_err(|e| format!("Failed to parse card '{}': {}", card_name, e))?;

                // Parse card fields
                let card_fields = if let Some(card_fields_table) =
                    card_value.get("fields").and_then(|v| v.as_object())
                {
                    let card_field_order: Vec<String> = card_fields_table.keys().cloned().collect();

                    Self::parse_fields_with_order(
                        card_fields_table,
                        &card_field_order,
                        &format!("card '{}' field", card_name),
                    )
                } else if let Some(_toml_fields) = &card_def.fields {
                    HashMap::new()
                } else {
                    HashMap::new()
                };

                let card_schema = CardSchema {
                    name: card_name.clone(),
                    title: card_def.title,
                    description: card_def.description,
                    fields: card_fields,
                    ui: card_def.ui,
                };

                cards.insert(card_name.clone(), card_schema);
            }
        }

        // Create document schema from root fields
        let document = CardSchema {
            name: name.clone(),
            title: Some(name),
            description: Some(description),
            fields,
            ui: ui_section,
        };

        Ok(QuillConfig {
            document,
            backend,
            version,
            author,
            example_file,
            plate_file,
            cards,
            metadata,
            typst_config,
        })
    }
}

impl Quill {
    /// Create a Quill from a directory path
    pub fn from_path<P: AsRef<std::path::Path>>(
        path: P,
    ) -> Result<Self, Box<dyn StdError + Send + Sync>> {
        use std::fs;

        let path = path.as_ref();

        // Load .quillignore if it exists
        let quillignore_path = path.join(".quillignore");
        let ignore = if quillignore_path.exists() {
            let ignore_content = fs::read_to_string(&quillignore_path)
                .map_err(|e| format!("Failed to read .quillignore: {}", e))?;
            QuillIgnore::from_content(&ignore_content)
        } else {
            // Default ignore patterns
            QuillIgnore::new(vec![
                ".git/".to_string(),
                ".gitignore".to_string(),
                ".quillignore".to_string(),
                "target/".to_string(),
                "node_modules/".to_string(),
            ])
        };

        // Load all files into a tree structure
        let root = Self::load_directory_as_tree(path, path, &ignore)?;

        // Create Quill from the file tree
        Self::from_tree(root)
    }

    /// Create a Quill from a tree structure
    ///
    /// This is the authoritative method for creating a Quill from an in-memory file tree.
    ///
    /// # Arguments
    ///
    /// * `root` - The root node of the file tree
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Quill.yaml is not found in the file tree
    /// - Quill.yaml is not valid UTF-8 or YAML
    /// - The plate file specified in Quill.yaml is not found or not valid UTF-8
    /// - Validation fails
    pub fn from_tree(root: FileTreeNode) -> Result<Self, Box<dyn StdError + Send + Sync>> {
        // Read Quill.yaml
        let quill_yaml_bytes = root
            .get_file("Quill.yaml")
            .ok_or("Quill.yaml not found in file tree")?;

        let quill_yaml_content = String::from_utf8(quill_yaml_bytes.to_vec())
            .map_err(|e| format!("Quill.yaml is not valid UTF-8: {}", e))?;

        // Parse YAML into QuillConfig
        let config = QuillConfig::from_yaml(&quill_yaml_content)?;

        // Construct Quill from QuillConfig
        Self::from_config(config, root)
    }

    /// Create a Quill from a QuillConfig and file tree
    ///
    /// This method constructs a Quill from a parsed QuillConfig and validates
    /// all file references.
    ///
    /// # Arguments
    ///
    /// * `config` - The parsed QuillConfig
    /// * `root` - The root node of the file tree
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The plate file specified in config is not found or not valid UTF-8
    /// - The example file specified in config is not found or not valid UTF-8
    /// - Schema generation fails
    fn from_config(
        config: QuillConfig,
        root: FileTreeNode,
    ) -> Result<Self, Box<dyn StdError + Send + Sync>> {
        // Build metadata from config
        let mut metadata = config.metadata.clone();

        // Add backend to metadata
        metadata.insert(
            "backend".to_string(),
            QuillValue::from_json(serde_json::Value::String(config.backend.clone())),
        );

        metadata.insert(
            "description".to_string(),
            QuillValue::from_json(serde_json::Value::String(
                config.document.description.clone().unwrap_or_default(),
            )),
        );

        // Add author
        metadata.insert(
            "author".to_string(),
            QuillValue::from_json(serde_json::Value::String(config.author.clone())),
        );

        // Add version
        metadata.insert(
            "version".to_string(),
            QuillValue::from_json(serde_json::Value::String(config.version.clone())),
        );

        // Add typst config to metadata with typst_ prefix
        for (key, value) in &config.typst_config {
            metadata.insert(format!("typst_{}", key), value.clone());
        }

        // Build JSON schema from field and card schemas
        // Build JSON schema from field and card schemas
        let schema = crate::schema::build_schema(&config.document, &config.cards)
            .map_err(|e| format!("Failed to build JSON schema from field schemas: {}", e))?;

        // Read the plate content from plate file (if specified)
        let plate_content: Option<String> = if let Some(ref plate_file_name) = config.plate_file {
            let plate_bytes = root.get_file(plate_file_name).ok_or_else(|| {
                format!("Plate file '{}' not found in file tree", plate_file_name)
            })?;

            let content = String::from_utf8(plate_bytes.to_vec()).map_err(|e| {
                format!("Plate file '{}' is not valid UTF-8: {}", plate_file_name, e)
            })?;
            Some(content)
        } else {
            // No plate file specified
            None
        };

        // Read the markdown example content if specified
        // Read the markdown example content if specified, or check for default "example.md"
        let example_content = if let Some(ref example_file_name) = config.example_file {
            root.get_file(example_file_name).and_then(|bytes| {
                String::from_utf8(bytes.to_vec())
                    .map_err(|e| {
                        eprintln!(
                            "Warning: Example file '{}' is not valid UTF-8: {}",
                            example_file_name, e
                        );
                        e
                    })
                    .ok()
            })
        } else if root.file_exists("example.md") {
            // Smart default: use example.md if it exists
            root.get_file("example.md").and_then(|bytes| {
                String::from_utf8(bytes.to_vec())
                    .map_err(|e| {
                        eprintln!(
                            "Warning: Default example file 'example.md' is not valid UTF-8: {}",
                            e
                        );
                        e
                    })
                    .ok()
            })
        } else {
            None
        };

        // Extract and cache defaults and examples from schema for performance
        let defaults = crate::schema::extract_defaults_from_schema(&schema);
        let examples = crate::schema::extract_examples_from_schema(&schema);

        let quill = Quill {
            metadata,
            name: config.document.name,
            backend: config.backend,
            plate: plate_content,
            example: example_content,
            schema,
            defaults,
            examples,
            files: root,
        };

        Ok(quill)
    }

    /// Create a Quill from a JSON representation
    ///
    /// Parses a JSON string into an in-memory file tree and validates it. The
    /// precise JSON contract is documented in `designs/QUILL.md`.
    /// The JSON format MUST have a root object with a `files` key. The optional
    /// `metadata` key provides additional metadata that overrides defaults.
    pub fn from_json(json_str: &str) -> Result<Self, Box<dyn StdError + Send + Sync>> {
        use serde_json::Value as JsonValue;

        let json: JsonValue =
            serde_json::from_str(json_str).map_err(|e| format!("Failed to parse JSON: {}", e))?;

        let obj = json.as_object().ok_or("Root must be an object")?;

        // Extract files (required)
        let files_obj = obj
            .get("files")
            .and_then(|v| v.as_object())
            .ok_or("Missing or invalid 'files' key")?;

        // Parse file tree
        let mut root_files = HashMap::new();
        for (key, value) in files_obj {
            root_files.insert(key.clone(), FileTreeNode::from_json_value(value)?);
        }

        let root = FileTreeNode::Directory { files: root_files };

        // Create Quill from tree
        Self::from_tree(root)
    }

    /// Recursively load all files from a directory into a tree structure
    fn load_directory_as_tree(
        current_dir: &Path,
        base_dir: &Path,
        ignore: &QuillIgnore,
    ) -> Result<FileTreeNode, Box<dyn StdError + Send + Sync>> {
        use std::fs;

        if !current_dir.exists() {
            return Ok(FileTreeNode::Directory {
                files: HashMap::new(),
            });
        }

        let mut files = HashMap::new();

        for entry in fs::read_dir(current_dir)? {
            let entry = entry?;
            let path = entry.path();
            let relative_path = path
                .strip_prefix(base_dir)
                .map_err(|e| format!("Failed to get relative path: {}", e))?
                .to_path_buf();

            // Check if this path should be ignored
            if ignore.is_ignored(&relative_path) {
                continue;
            }

            // Get the filename
            let filename = path
                .file_name()
                .and_then(|n| n.to_str())
                .ok_or_else(|| format!("Invalid filename: {}", path.display()))?
                .to_string();

            if path.is_file() {
                let contents = fs::read(&path)
                    .map_err(|e| format!("Failed to read file '{}': {}", path.display(), e))?;

                files.insert(filename, FileTreeNode::File { contents });
            } else if path.is_dir() {
                // Recursively process subdirectory
                let subdir_tree = Self::load_directory_as_tree(&path, base_dir, ignore)?;
                files.insert(filename, subdir_tree);
            }
        }

        Ok(FileTreeNode::Directory { files })
    }

    /// Get the list of typst packages to download, if specified in Quill.yaml
    pub fn typst_packages(&self) -> Vec<String> {
        self.metadata
            .get("typst_packages")
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str().map(|s| s.to_string()))
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Get default values from the cached schema defaults
    ///
    /// Returns a reference to the pre-computed defaults HashMap that was extracted
    /// during Quill construction. This is more efficient than re-parsing the schema.
    ///
    /// This is used by `ParsedDocument::with_defaults()` to apply default values
    /// to missing fields.
    pub fn extract_defaults(&self) -> &HashMap<String, QuillValue> {
        &self.defaults
    }

    /// Get example values from the cached schema examples
    ///
    /// Returns a reference to the pre-computed examples HashMap that was extracted
    /// during Quill construction. This is more efficient than re-parsing the schema.
    pub fn extract_examples(&self) -> &HashMap<String, Vec<QuillValue>> {
        &self.examples
    }

    /// Get file contents by path (relative to quill root)
    pub fn get_file<P: AsRef<Path>>(&self, path: P) -> Option<&[u8]> {
        self.files.get_file(path)
    }

    /// Check if a file exists in memory
    pub fn file_exists<P: AsRef<Path>>(&self, path: P) -> bool {
        self.files.file_exists(path)
    }

    /// Check if a directory exists in memory
    pub fn dir_exists<P: AsRef<Path>>(&self, path: P) -> bool {
        self.files.dir_exists(path)
    }

    /// List files in a directory (non-recursive, returns file names only)
    pub fn list_files<P: AsRef<Path>>(&self, path: P) -> Vec<String> {
        self.files.list_files(path)
    }

    /// List subdirectories in a directory (non-recursive, returns directory names only)
    pub fn list_subdirectories<P: AsRef<Path>>(&self, path: P) -> Vec<String> {
        self.files.list_subdirectories(path)
    }

    /// List all files in a directory (returns paths relative to quill root)
    pub fn list_directory<P: AsRef<Path>>(&self, dir_path: P) -> Vec<PathBuf> {
        let dir_path = dir_path.as_ref();
        let filenames = self.files.list_files(dir_path);

        // Convert filenames to full paths
        filenames
            .iter()
            .map(|name| {
                if dir_path == Path::new("") {
                    PathBuf::from(name)
                } else {
                    dir_path.join(name)
                }
            })
            .collect()
    }

    /// List all directories in a directory (returns paths relative to quill root)
    pub fn list_directories<P: AsRef<Path>>(&self, dir_path: P) -> Vec<PathBuf> {
        let dir_path = dir_path.as_ref();
        let subdirs = self.files.list_subdirectories(dir_path);

        // Convert subdirectory names to full paths
        subdirs
            .iter()
            .map(|name| {
                if dir_path == Path::new("") {
                    PathBuf::from(name)
                } else {
                    dir_path.join(name)
                }
            })
            .collect()
    }

    /// Get all files matching a pattern (supports glob-style wildcards)
    pub fn find_files<P: AsRef<Path>>(&self, pattern: P) -> Vec<PathBuf> {
        let pattern_str = pattern.as_ref().to_string_lossy();
        let mut matches = Vec::new();

        // Compile the glob pattern
        let glob_pattern = match glob::Pattern::new(&pattern_str) {
            Ok(pat) => pat,
            Err(_) => return matches, // Invalid pattern returns empty results
        };

        // Recursively search the tree for matching files
        Self::find_files_recursive(&self.files, Path::new(""), &glob_pattern, &mut matches);

        matches.sort();
        matches
    }

    /// Helper method to recursively search for files matching a pattern
    fn find_files_recursive(
        node: &FileTreeNode,
        current_path: &Path,
        pattern: &glob::Pattern,
        matches: &mut Vec<PathBuf>,
    ) {
        match node {
            FileTreeNode::File { .. } => {
                let path_str = current_path.to_string_lossy();
                if pattern.matches(&path_str) {
                    matches.push(current_path.to_path_buf());
                }
            }
            FileTreeNode::Directory { files } => {
                for (name, child_node) in files {
                    let child_path = if current_path == Path::new("") {
                        PathBuf::from(name)
                    } else {
                        current_path.join(name)
                    };
                    Self::find_files_recursive(child_node, &child_path, pattern, matches);
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn test_quillignore_parsing() {
        let ignore_content = r#"
# This is a comment
*.tmp
target/
node_modules/
.git/
"#;
        let ignore = QuillIgnore::from_content(ignore_content);
        assert_eq!(ignore.patterns.len(), 4);
        assert!(ignore.patterns.contains(&"*.tmp".to_string()));
        assert!(ignore.patterns.contains(&"target/".to_string()));
    }

    #[test]
    fn test_quillignore_matching() {
        let ignore = QuillIgnore::new(vec![
            "*.tmp".to_string(),
            "target/".to_string(),
            "node_modules/".to_string(),
            ".git/".to_string(),
        ]);

        // Test file patterns
        assert!(ignore.is_ignored("test.tmp"));
        assert!(ignore.is_ignored("path/to/file.tmp"));
        assert!(!ignore.is_ignored("test.txt"));

        // Test directory patterns
        assert!(ignore.is_ignored("target"));
        assert!(ignore.is_ignored("target/debug"));
        assert!(ignore.is_ignored("target/debug/deps"));
        assert!(!ignore.is_ignored("src/target.rs"));

        assert!(ignore.is_ignored("node_modules"));
        assert!(ignore.is_ignored("node_modules/package"));
        assert!(!ignore.is_ignored("my_node_modules"));
    }

    #[test]
    fn test_in_memory_file_system() {
        let temp_dir = TempDir::new().unwrap();
        let quill_dir = temp_dir.path();

        // Create test files
        fs::write(
            quill_dir.join("Quill.yaml"),
            "Quill:\n  name: \"test\"\n  version: \"1.0\"\n  backend: \"typst\"\n  plate_file: \"plate.typ\"\n  description: \"Test quill\"",
        )
        .unwrap();
        fs::write(quill_dir.join("plate.typ"), "test plate").unwrap();

        let assets_dir = quill_dir.join("assets");
        fs::create_dir_all(&assets_dir).unwrap();
        fs::write(assets_dir.join("test.txt"), "asset content").unwrap();

        let packages_dir = quill_dir.join("packages");
        fs::create_dir_all(&packages_dir).unwrap();
        fs::write(packages_dir.join("package.typ"), "package content").unwrap();

        // Load quill
        let quill = Quill::from_path(quill_dir).unwrap();

        // Test file access
        assert!(quill.file_exists("plate.typ"));
        assert!(quill.file_exists("assets/test.txt"));
        assert!(quill.file_exists("packages/package.typ"));
        assert!(!quill.file_exists("nonexistent.txt"));

        // Test file content
        let asset_content = quill.get_file("assets/test.txt").unwrap();
        assert_eq!(asset_content, b"asset content");

        // Test directory listing
        let asset_files = quill.list_directory("assets");
        assert_eq!(asset_files.len(), 1);
        assert!(asset_files.contains(&PathBuf::from("assets/test.txt")));
    }

    #[test]
    fn test_quillignore_integration() {
        let temp_dir = TempDir::new().unwrap();
        let quill_dir = temp_dir.path();

        // Create .quillignore
        fs::write(quill_dir.join(".quillignore"), "*.tmp\ntarget/\n").unwrap();

        // Create test files
        fs::write(
            quill_dir.join("Quill.yaml"),
            "Quill:\n  name: \"test\"\n  version: \"1.0\"\n  backend: \"typst\"\n  plate_file: \"plate.typ\"\n  description: \"Test quill\"",
        )
        .unwrap();
        fs::write(quill_dir.join("plate.typ"), "test template").unwrap();
        fs::write(quill_dir.join("should_ignore.tmp"), "ignored").unwrap();

        let target_dir = quill_dir.join("target");
        fs::create_dir_all(&target_dir).unwrap();
        fs::write(target_dir.join("debug.txt"), "also ignored").unwrap();

        // Load quill
        let quill = Quill::from_path(quill_dir).unwrap();

        // Test that ignored files are not loaded
        assert!(quill.file_exists("plate.typ"));
        assert!(!quill.file_exists("should_ignore.tmp"));
        assert!(!quill.file_exists("target/debug.txt"));
    }

    #[test]
    fn test_find_files_pattern() {
        let temp_dir = TempDir::new().unwrap();
        let quill_dir = temp_dir.path();

        // Create test directory structure
        fs::write(
            quill_dir.join("Quill.yaml"),
            "Quill:\n  name: \"test\"\n  version: \"1.0\"\n  backend: \"typst\"\n  plate_file: \"plate.typ\"\n  description: \"Test quill\"",
        )
        .unwrap();
        fs::write(quill_dir.join("plate.typ"), "template").unwrap();

        let assets_dir = quill_dir.join("assets");
        fs::create_dir_all(&assets_dir).unwrap();
        fs::write(assets_dir.join("image.png"), "png data").unwrap();
        fs::write(assets_dir.join("data.json"), "json data").unwrap();

        let fonts_dir = assets_dir.join("fonts");
        fs::create_dir_all(&fonts_dir).unwrap();
        fs::write(fonts_dir.join("font.ttf"), "font data").unwrap();

        // Load quill
        let quill = Quill::from_path(quill_dir).unwrap();

        // Test pattern matching
        let all_assets = quill.find_files("assets/*");
        assert!(all_assets.len() >= 3); // At least image.png, data.json, fonts/font.ttf

        let typ_files = quill.find_files("*.typ");
        assert_eq!(typ_files.len(), 1);
        assert!(typ_files.contains(&PathBuf::from("plate.typ")));
    }

    #[test]
    fn test_new_standardized_yaml_format() {
        let temp_dir = TempDir::new().unwrap();
        let quill_dir = temp_dir.path();

        // Create test files using new standardized format
        let yaml_content = r#"
Quill:
  name: my-custom-quill
  version: "1.0"
  backend: typst
  plate_file: custom_plate.typ
  description: Test quill with new format
  author: Test Author
"#;
        fs::write(quill_dir.join("Quill.yaml"), yaml_content).unwrap();
        fs::write(
            quill_dir.join("custom_plate.typ"),
            "= Custom Template\n\nThis is a custom template.",
        )
        .unwrap();

        // Load quill
        let quill = Quill::from_path(quill_dir).unwrap();

        // Test that name comes from YAML, not directory
        assert_eq!(quill.name, "my-custom-quill");

        // Test that backend is in metadata
        assert!(quill.metadata.contains_key("backend"));
        if let Some(backend_val) = quill.metadata.get("backend") {
            if let Some(backend_str) = backend_val.as_str() {
                assert_eq!(backend_str, "typst");
            } else {
                panic!("Backend value is not a string");
            }
        }

        // Test that other fields are in metadata including version
        assert!(quill.metadata.contains_key("description"));
        assert!(quill.metadata.contains_key("author"));
        assert!(quill.metadata.contains_key("version")); // version should now be included
        if let Some(version_val) = quill.metadata.get("version") {
            if let Some(version_str) = version_val.as_str() {
                assert_eq!(version_str, "1.0");
            }
        }

        // Test that plate template content is loaded correctly
        assert!(quill.plate.unwrap().contains("Custom Template"));
    }

    #[test]
    fn test_typst_packages_parsing() {
        let temp_dir = TempDir::new().unwrap();
        let quill_dir = temp_dir.path();

        let yaml_content = r#"
Quill:
  name: "test-quill"
  version: "1.0"
  backend: "typst"
  plate_file: "plate.typ"
  description: "Test quill for packages"

typst:
  packages:
    - "@preview/bubble:0.2.2"
    - "@preview/example:1.0.0"
"#;

        fs::write(quill_dir.join("Quill.yaml"), yaml_content).unwrap();
        fs::write(quill_dir.join("plate.typ"), "test").unwrap();

        let quill = Quill::from_path(quill_dir).unwrap();
        let packages = quill.typst_packages();

        assert_eq!(packages.len(), 2);
        assert_eq!(packages[0], "@preview/bubble:0.2.2");
        assert_eq!(packages[1], "@preview/example:1.0.0");
    }

    #[test]
    fn test_template_loading() {
        let temp_dir = TempDir::new().unwrap();
        let quill_dir = temp_dir.path();

        // Create test files with example specified
        let yaml_content = r#"Quill:
  name: "test-with-template"
  version: "1.0"
  backend: "typst"
  plate_file: "plate.typ"
  example_file: "example.md"
  description: "Test quill with template"
"#;
        fs::write(quill_dir.join("Quill.yaml"), yaml_content).unwrap();
        fs::write(quill_dir.join("plate.typ"), "plate content").unwrap();
        fs::write(
            quill_dir.join("example.md"),
            "---\ntitle: Test\n---\n\nThis is a test template.",
        )
        .unwrap();

        // Load quill
        let quill = Quill::from_path(quill_dir).unwrap();

        // Test that example content is loaded and includes some the text
        assert!(quill.example.is_some());
        let example = quill.example.unwrap();
        assert!(example.contains("title: Test"));
        assert!(example.contains("This is a test template"));

        // Test that plate template is still loaded
        assert_eq!(quill.plate.unwrap(), "plate content");
    }

    #[test]
    fn test_template_smart_default() {
        let temp_dir = TempDir::new().unwrap();
        let quill_dir = temp_dir.path();

        // Create test files without example specified
        let yaml_content = r#"Quill:
  name: "test-smart-default"
  version: "1.0"
  backend: "typst"
  plate_file: "plate.typ"
  description: "Test quill with smart default"
"#;
        fs::write(quill_dir.join("Quill.yaml"), yaml_content).unwrap();
        fs::write(quill_dir.join("plate.typ"), "plate content").unwrap();
        // Create example.md which should be picked up automatically
        fs::write(
            quill_dir.join("example.md"),
            "---\ntitle: Smart Default\n---\n\nPicked up automatically.",
        )
        .unwrap();

        // Load quill
        let quill = Quill::from_path(quill_dir).unwrap();

        // Test that example content is loaded
        assert!(quill.example.is_some());
        let example = quill.example.unwrap();
        assert!(example.contains("title: Smart Default"));
        assert!(example.contains("Picked up automatically"));
    }

    #[test]
    fn test_template_optional() {
        let temp_dir = TempDir::new().unwrap();
        let quill_dir = temp_dir.path();

        // Create test files without example specified
        let yaml_content = r#"Quill:
  name: "test-without-template"
  version: "1.0"
  backend: "typst"
  plate_file: "plate.typ"
  description: "Test quill without template"
"#;
        fs::write(quill_dir.join("Quill.yaml"), yaml_content).unwrap();
        fs::write(quill_dir.join("plate.typ"), "plate content").unwrap();

        // Load quill
        let quill = Quill::from_path(quill_dir).unwrap();

        // Test that example fields are None
        assert_eq!(quill.example, None);

        // Test that plate template is still loaded
        assert_eq!(quill.plate.unwrap(), "plate content");
    }

    #[test]
    fn test_from_tree() {
        // Create a simple in-memory file tree
        let mut root_files = HashMap::new();

        // Add Quill.yaml
        let quill_yaml = r#"Quill:
  name: "test-from-tree"
  version: "1.0"
  backend: "typst"
  plate_file: "plate.typ"
  description: "A test quill from tree"
"#;
        root_files.insert(
            "Quill.yaml".to_string(),
            FileTreeNode::File {
                contents: quill_yaml.as_bytes().to_vec(),
            },
        );

        // Add plate file
        let plate_content = "= Test Template\n\nThis is a test.";
        root_files.insert(
            "plate.typ".to_string(),
            FileTreeNode::File {
                contents: plate_content.as_bytes().to_vec(),
            },
        );

        let root = FileTreeNode::Directory { files: root_files };

        // Create Quill from tree
        let quill = Quill::from_tree(root).unwrap();

        // Validate the quill
        assert_eq!(quill.name, "test-from-tree");
        assert_eq!(quill.plate.unwrap(), plate_content);
        assert!(quill.metadata.contains_key("backend"));
        assert!(quill.metadata.contains_key("description"));
    }

    #[test]
    fn test_from_tree_with_template() {
        let mut root_files = HashMap::new();

        // Add Quill.yaml with example specified
        // Add Quill.yaml with example specified
        let quill_yaml = r#"
Quill:
  name: test-tree-template
  version: "1.0"
  backend: typst
  plate_file: plate.typ
  example_file: template.md
  description: Test tree with template
"#;
        root_files.insert(
            "Quill.yaml".to_string(),
            FileTreeNode::File {
                contents: quill_yaml.as_bytes().to_vec(),
            },
        );

        // Add plate file
        root_files.insert(
            "plate.typ".to_string(),
            FileTreeNode::File {
                contents: b"plate content".to_vec(),
            },
        );

        // Add template file
        let template_content = "# {{ title }}\n\n{{ body }}";
        root_files.insert(
            "template.md".to_string(),
            FileTreeNode::File {
                contents: template_content.as_bytes().to_vec(),
            },
        );

        let root = FileTreeNode::Directory { files: root_files };

        // Create Quill from tree
        let quill = Quill::from_tree(root).unwrap();

        // Validate template is loaded
        assert_eq!(quill.example, Some(template_content.to_string()));
    }

    #[test]
    fn test_from_json() {
        // Create JSON representation of a Quill using new format
        let json_str = r#"{
            "metadata": {
                "name": "test_from_json"
            },
            "files": {
                "Quill.yaml": {
                    "contents": "Quill:\n  name: test_from_json\n  version: \"1.0\"\n  backend: typst\n  plate_file: plate.typ\n  description: Test quill from JSON\n"
                },
                "plate.typ": {
                    "contents": "= Test Plate\n\nThis is test content."
                }
            }
        }"#;

        // Create Quill from JSON
        let quill = Quill::from_json(json_str).unwrap();

        // Validate the quill
        assert_eq!(quill.name, "test_from_json");
        assert!(quill.plate.unwrap().contains("Test Plate"));
        assert!(quill.metadata.contains_key("backend"));
    }

    #[test]
    fn test_from_json_with_byte_array() {
        // Create JSON with byte array representation using new format
        let json_str = r#"{
            "files": {
                "Quill.yaml": {
                    "contents": "Quill:\n  name: test\n  version: \"1.0\"\n  backend: typst\n  plate_file: plate.typ\n  description: Test quill\n"
                },
                "plate.typ": {
                    "contents": "test plate"
                }
            }
        }"#;

        // Create Quill from JSON
        let quill = Quill::from_json(json_str).unwrap();

        // Validate the quill was created
        assert_eq!(quill.name, "test");
        assert_eq!(quill.plate.unwrap(), "test plate");
    }

    #[test]
    fn test_from_json_missing_files() {
        // JSON without files field should fail
        let json_str = r#"{
            "metadata": {
                "name": "test"
            }
        }"#;

        let result = Quill::from_json(json_str);
        assert!(result.is_err());
        // Should fail because there's no 'files' key
        assert!(result.unwrap_err().to_string().contains("files"));
    }

    #[test]
    fn test_from_json_tree_structure() {
        // Test the new tree structure format
        let json_str = r#"{
            "files": {
                "Quill.yaml": {
                    "contents": "Quill:\n  name: test_tree_json\n  version: \"1.0\"\n  backend: typst\n  plate_file: plate.typ\n  description: Test tree JSON\n"
                },
                "plate.typ": {
                    "contents": "= Test Plate\n\nTree structure content."
                }
            }
        }"#;

        let quill = Quill::from_json(json_str).unwrap();

        assert_eq!(quill.name, "test_tree_json");
        assert!(quill.plate.unwrap().contains("Tree structure content"));
        assert!(quill.metadata.contains_key("backend"));
    }

    #[test]
    fn test_from_json_nested_tree_structure() {
        // Test nested directories in tree structure
        let json_str = r#"{
            "files": {
                "Quill.yaml": {
                    "contents": "Quill:\n  name: nested_test\n  version: \"1.0\"\n  backend: typst\n  plate_file: plate.typ\n  description: Nested test\n"
                },
                "plate.typ": {
                    "contents": "plate"
                },
                "src": {
                    "main.rs": {
                        "contents": "fn main() {}"
                    },
                    "lib.rs": {
                        "contents": "// lib"
                    }
                }
            }
        }"#;

        let quill = Quill::from_json(json_str).unwrap();

        assert_eq!(quill.name, "nested_test");
        // Verify nested files are accessible
        assert!(quill.file_exists("src/main.rs"));
        assert!(quill.file_exists("src/lib.rs"));

        let main_rs = quill.get_file("src/main.rs").unwrap();
        assert_eq!(main_rs, b"fn main() {}");
    }

    #[test]
    fn test_from_tree_structure_direct() {
        // Test using from_tree_structure directly
        let mut root_files = HashMap::new();

        root_files.insert(
            "Quill.yaml".to_string(),
            FileTreeNode::File {
                contents:
                    b"Quill:\n  name: direct_tree\n  version: \"1.0\"\n  backend: typst\n  plate_file: plate.typ\n  description: Direct tree test\n"
                        .to_vec(),
            },
        );

        root_files.insert(
            "plate.typ".to_string(),
            FileTreeNode::File {
                contents: b"plate content".to_vec(),
            },
        );

        // Add a nested directory
        let mut src_files = HashMap::new();
        src_files.insert(
            "main.rs".to_string(),
            FileTreeNode::File {
                contents: b"fn main() {}".to_vec(),
            },
        );

        root_files.insert(
            "src".to_string(),
            FileTreeNode::Directory { files: src_files },
        );

        let root = FileTreeNode::Directory { files: root_files };

        let quill = Quill::from_tree(root).unwrap();

        assert_eq!(quill.name, "direct_tree");
        assert!(quill.file_exists("src/main.rs"));
        assert!(quill.file_exists("plate.typ"));
    }

    #[test]
    fn test_from_json_with_metadata_override() {
        // Test that metadata key overrides name from Quill.yaml
        let json_str = r#"{
            "metadata": {
                "name": "override_name"
            },
            "files": {
                "Quill.yaml": {
                    "contents": "Quill:\n  name: toml_name\n  version: \"1.0\"\n  backend: typst\n  plate_file: plate.typ\n  description: TOML name test\n"
                },
                "plate.typ": {
                    "contents": "= plate"
                }
            }
        }"#;

        let quill = Quill::from_json(json_str).unwrap();
        // Metadata name should be used as default, but Quill.yaml takes precedence
        // when from_tree is called
        assert_eq!(quill.name, "toml_name");
    }

    #[test]
    fn test_from_json_empty_directory() {
        // Test that empty directories are supported
        let json_str = r#"{
            "files": {
                "Quill.yaml": {
                    "contents": "Quill:\n  name: empty_dir_test\n  version: \"1.0\"\n  backend: typst\n  plate_file: plate.typ\n  description: Empty directory test\n"
                },
                "plate.typ": {
                    "contents": "plate"
                },
                "empty_dir": {}
            }
        }"#;

        let quill = Quill::from_json(json_str).unwrap();
        assert_eq!(quill.name, "empty_dir_test");
        assert!(quill.dir_exists("empty_dir"));
        assert!(!quill.file_exists("empty_dir"));
    }

    #[test]
    fn test_dir_exists_and_list_apis() {
        let mut root_files = HashMap::new();

        // Add Quill.yaml
        root_files.insert(
            "Quill.yaml".to_string(),
            FileTreeNode::File {
                contents: b"Quill:\n  name: test\n  version: \"1.0\"\n  backend: typst\n  plate_file: plate.typ\n  description: Test quill\n"
                    .to_vec(),
            },
        );

        // Add plate file
        root_files.insert(
            "plate.typ".to_string(),
            FileTreeNode::File {
                contents: b"plate content".to_vec(),
            },
        );

        // Add assets directory with files
        let mut assets_files = HashMap::new();
        assets_files.insert(
            "logo.png".to_string(),
            FileTreeNode::File {
                contents: vec![137, 80, 78, 71],
            },
        );
        assets_files.insert(
            "icon.svg".to_string(),
            FileTreeNode::File {
                contents: b"<svg></svg>".to_vec(),
            },
        );

        // Add subdirectory in assets
        let mut fonts_files = HashMap::new();
        fonts_files.insert(
            "font.ttf".to_string(),
            FileTreeNode::File {
                contents: b"font data".to_vec(),
            },
        );
        assets_files.insert(
            "fonts".to_string(),
            FileTreeNode::Directory { files: fonts_files },
        );

        root_files.insert(
            "assets".to_string(),
            FileTreeNode::Directory {
                files: assets_files,
            },
        );

        // Add empty directory
        root_files.insert(
            "empty".to_string(),
            FileTreeNode::Directory {
                files: HashMap::new(),
            },
        );

        let root = FileTreeNode::Directory { files: root_files };
        let quill = Quill::from_tree(root).unwrap();

        // Test dir_exists
        assert!(quill.dir_exists("assets"));
        assert!(quill.dir_exists("assets/fonts"));
        assert!(quill.dir_exists("empty"));
        assert!(!quill.dir_exists("nonexistent"));
        assert!(!quill.dir_exists("plate.typ")); // file, not directory

        // Test file_exists
        assert!(quill.file_exists("plate.typ"));
        assert!(quill.file_exists("assets/logo.png"));
        assert!(quill.file_exists("assets/fonts/font.ttf"));
        assert!(!quill.file_exists("assets")); // directory, not file

        // Test list_files
        let root_files_list = quill.list_files("");
        assert_eq!(root_files_list.len(), 2); // Quill.yaml and plate.typ
        assert!(root_files_list.contains(&"Quill.yaml".to_string()));
        assert!(root_files_list.contains(&"plate.typ".to_string()));

        let assets_files_list = quill.list_files("assets");
        assert_eq!(assets_files_list.len(), 2); // logo.png and icon.svg
        assert!(assets_files_list.contains(&"logo.png".to_string()));
        assert!(assets_files_list.contains(&"icon.svg".to_string()));

        // Test list_subdirectories
        let root_subdirs = quill.list_subdirectories("");
        assert_eq!(root_subdirs.len(), 2); // assets and empty
        assert!(root_subdirs.contains(&"assets".to_string()));
        assert!(root_subdirs.contains(&"empty".to_string()));

        let assets_subdirs = quill.list_subdirectories("assets");
        assert_eq!(assets_subdirs.len(), 1); // fonts
        assert!(assets_subdirs.contains(&"fonts".to_string()));

        let empty_subdirs = quill.list_subdirectories("empty");
        assert_eq!(empty_subdirs.len(), 0);
    }

    #[test]
    fn test_field_schemas_parsing() {
        let mut root_files = HashMap::new();

        // Add Quill.yaml with field schemas
        let quill_yaml = r#"Quill:
  name: "taro"
  version: "1.0"
  backend: "typst"
  plate_file: "plate.typ"
  example_file: "taro.md"
  description: "Test template for field schemas"

fields:
  author:
    type: "string"
    description: "Author of document"
  ice_cream:
    type: "string"
    description: "favorite ice cream flavor"
  title:
    type: "string"
    description: "title of document"
"#;
        root_files.insert(
            "Quill.yaml".to_string(),
            FileTreeNode::File {
                contents: quill_yaml.as_bytes().to_vec(),
            },
        );

        // Add plate file
        let plate_content = "= Test Template\n\nThis is a test.";
        root_files.insert(
            "plate.typ".to_string(),
            FileTreeNode::File {
                contents: plate_content.as_bytes().to_vec(),
            },
        );

        // Add template file
        root_files.insert(
            "taro.md".to_string(),
            FileTreeNode::File {
                contents: b"# Template".to_vec(),
            },
        );

        let root = FileTreeNode::Directory { files: root_files };

        // Create Quill from tree
        let quill = Quill::from_tree(root).unwrap();

        // Validate field schemas were parsed (author, ice_cream, title, BODY)
        assert_eq!(quill.schema["properties"].as_object().unwrap().len(), 4);
        assert!(quill.schema["properties"]
            .as_object()
            .unwrap()
            .contains_key("author"));
        assert!(quill.schema["properties"]
            .as_object()
            .unwrap()
            .contains_key("ice_cream"));
        assert!(quill.schema["properties"]
            .as_object()
            .unwrap()
            .contains_key("title"));
        assert!(quill.schema["properties"]
            .as_object()
            .unwrap()
            .contains_key("BODY"));

        // Verify author field schema
        let author_schema = quill.schema["properties"]["author"].as_object().unwrap();
        assert_eq!(author_schema["description"], "Author of document");

        // Verify ice_cream field schema (no required field, should default to false)
        let ice_cream_schema = quill.schema["properties"]["ice_cream"].as_object().unwrap();
        assert_eq!(ice_cream_schema["description"], "favorite ice cream flavor");

        // Verify title field schema
        let title_schema = quill.schema["properties"]["title"].as_object().unwrap();
        assert_eq!(title_schema["description"], "title of document");
    }

    #[test]
    fn test_field_schema_struct() {
        // Test creating FieldSchema with minimal fields
        let schema1 = FieldSchema::new(
            "test_name".to_string(),
            FieldType::String,
            Some("Test description".to_string()),
        );
        assert_eq!(schema1.description, Some("Test description".to_string()));
        assert_eq!(schema1.r#type, FieldType::String);
        assert_eq!(schema1.examples, None);
        assert_eq!(schema1.default, None);

        // Test parsing FieldSchema from YAML with all fields
        let yaml_str = r#"
description: "Full field schema"
type: "string"
examples:
  - "Example value"
default: "Default value"
"#;
        let quill_value = QuillValue::from_yaml_str(yaml_str).unwrap();
        let schema2 = FieldSchema::from_quill_value("test_name".to_string(), &quill_value).unwrap();
        assert_eq!(schema2.name, "test_name");
        assert_eq!(schema2.description, Some("Full field schema".to_string()));
        assert_eq!(schema2.r#type, FieldType::String);
        assert_eq!(
            schema2
                .examples
                .as_ref()
                .and_then(|v| v.as_array())
                .and_then(|arr| arr.first())
                .and_then(|v| v.as_str()),
            Some("Example value")
        );
        assert_eq!(
            schema2.default.as_ref().and_then(|v| v.as_str()),
            Some("Default value")
        );
    }

    #[test]
    fn test_quill_without_plate_file() {
        // Test creating a Quill without specifying a plate file
        let mut root_files = HashMap::new();

        // Add Quill.yaml without plate field
        let quill_yaml = r#"Quill:
  name: "test-no-plate"
  version: "1.0"
  backend: "typst"
  description: "Test quill without plate file"
"#;
        root_files.insert(
            "Quill.yaml".to_string(),
            FileTreeNode::File {
                contents: quill_yaml.as_bytes().to_vec(),
            },
        );

        let root = FileTreeNode::Directory { files: root_files };

        // Create Quill from tree
        let quill = Quill::from_tree(root).unwrap();

        // Validate that plate is null (will use auto plate)
        assert!(quill.plate.clone().is_none());
        assert_eq!(quill.name, "test-no-plate");
    }

    #[test]
    fn test_quill_config_from_yaml() {
        // Test parsing QuillConfig from YAML content
        let yaml_content = r#"
Quill:
  name: test_config
  version: "1.0"
  backend: typst
  description: Test configuration parsing
  author: Test Author
  plate_file: plate.typ
  example_file: example.md

typst:
  packages: 
    - "@preview/bubble:0.2.2"

fields:
  title:
    description: Document title
    type: string
  author:
    type: string
    description: Document author
"#;

        let config = QuillConfig::from_yaml(yaml_content).unwrap();

        // Verify required fields
        assert_eq!(config.document.name, "test_config");
        assert_eq!(config.backend, "typst");
        assert_eq!(
            config.document.description,
            Some("Test configuration parsing".to_string())
        );

        // Verify optional fields
        assert_eq!(config.version, "1.0");
        assert_eq!(config.author, "Test Author");
        assert_eq!(config.plate_file, Some("plate.typ".to_string()));
        assert_eq!(config.example_file, Some("example.md".to_string()));

        // Verify typst config
        assert!(config.typst_config.contains_key("packages"));

        // Verify field schemas
        assert_eq!(config.document.fields.len(), 2);
        assert!(config.document.fields.contains_key("title"));
        assert!(config.document.fields.contains_key("author"));

        let title_field = &config.document.fields["title"];
        assert_eq!(title_field.description, Some("Document title".to_string()));
        assert_eq!(title_field.r#type, FieldType::String);
    }

    #[test]
    fn test_quill_config_missing_required_fields() {
        // Test that missing required fields result in error
        let yaml_missing_name = r#"
Quill:
  backend: typst
  description: Missing name
"#;
        let result = QuillConfig::from_yaml(yaml_missing_name);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Missing required 'name'"));

        let yaml_missing_backend = r#"
Quill:
  name: test
  description: Missing backend
"#;
        let result = QuillConfig::from_yaml(yaml_missing_backend);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Missing required 'backend'"));

        let yaml_missing_description = r#"
Quill:
  name: test
  version: "1.0"
  backend: typst
"#;
        let result = QuillConfig::from_yaml(yaml_missing_description);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Missing required 'description'"));
    }

    #[test]
    fn test_quill_config_empty_description() {
        // Test that empty description results in error
        let yaml_empty_description = r#"
Quill:
  name: test
  version: "1.0"
  backend: typst
  description: "   "
"#;
        let result = QuillConfig::from_yaml(yaml_empty_description);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("description' field in 'Quill' section cannot be empty"));
    }

    #[test]
    fn test_quill_config_missing_quill_section() {
        // Test that missing [Quill] section results in error
        let yaml_no_section = r#"
fields:
  title:
    description: Title
"#;
        let result = QuillConfig::from_yaml(yaml_no_section);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Missing required 'Quill' section"));
    }

    #[test]
    fn test_quill_from_config_metadata() {
        // Test that QuillConfig metadata flows through to Quill
        let mut root_files = HashMap::new();

        let quill_yaml = r#"
Quill:
  name: metadata-test
  version: "1.0"
  backend: typst
  description: Test metadata flow
  author: Test Author
  custom_field: custom_value

typst:
  packages: 
    - "@preview/bubble:0.2.2"
"#;
        root_files.insert(
            "Quill.yaml".to_string(),
            FileTreeNode::File {
                contents: quill_yaml.as_bytes().to_vec(),
            },
        );

        let root = FileTreeNode::Directory { files: root_files };
        let quill = Quill::from_tree(root).unwrap();

        // Verify metadata includes backend and description
        assert!(quill.metadata.contains_key("backend"));
        assert!(quill.metadata.contains_key("description"));
        assert!(quill.metadata.contains_key("author"));

        // Verify custom field is in metadata
        assert!(quill.metadata.contains_key("custom_field"));
        assert_eq!(
            quill.metadata.get("custom_field").unwrap().as_str(),
            Some("custom_value")
        );

        // Verify typst config with typst_ prefix
        assert!(quill.metadata.contains_key("typst_packages"));
    }

    #[test]
    fn test_extract_defaults_method() {
        // Test the extract_defaults method on Quill
        let mut root_files = HashMap::new();

        let quill_yaml = r#"
Quill:
  name: metadata-test-yaml
  version: "1.0"
  backend: typst
  description: Test metadata flow
  author: Test Author
  custom_field: custom_value

typst:
  packages: 
    - "@preview/bubble:0.2.2"

fields:
  author:
    type: string
    default: Anonymous
  status:
    type: string
    default: draft
  title:
    type: string
"#;
        root_files.insert(
            "Quill.yaml".to_string(),
            FileTreeNode::File {
                contents: quill_yaml.as_bytes().to_vec(),
            },
        );

        let root = FileTreeNode::Directory { files: root_files };
        let quill = Quill::from_tree(root).unwrap();

        // Extract defaults
        let defaults = quill.extract_defaults();

        // Verify only fields with defaults are returned
        assert_eq!(defaults.len(), 2);
        assert!(!defaults.contains_key("title")); // no default
        assert!(defaults.contains_key("author"));
        assert!(defaults.contains_key("status"));

        // Verify default values
        assert_eq!(defaults.get("author").unwrap().as_str(), Some("Anonymous"));
        assert_eq!(defaults.get("status").unwrap().as_str(), Some("draft"));
    }

    #[test]
    fn test_field_order_preservation() {
        let yaml_content = r#"
Quill:
  name: order-test
  version: "1.0"
  backend: typst
  description: Test field order

fields:
  first:
    type: string
    description: First field
  second:
    type: string
    description: Second field
  third:
    type: string
    description: Third field
    ui:
      group: Test Group
  fourth:
    type: string
    description: Fourth field
"#;

        let config = QuillConfig::from_yaml(yaml_content).unwrap();

        // Check that fields have correct order based on TOML position
        // Order is automatically generated based on field position

        let first = config.document.fields.get("first").unwrap();
        assert_eq!(first.ui.as_ref().unwrap().order, Some(0));

        let second = config.document.fields.get("second").unwrap();
        assert_eq!(second.ui.as_ref().unwrap().order, Some(1));

        let third = config.document.fields.get("third").unwrap();
        assert_eq!(third.ui.as_ref().unwrap().order, Some(2));
        assert_eq!(
            third.ui.as_ref().unwrap().group,
            Some("Test Group".to_string())
        );

        let fourth = config.document.fields.get("fourth").unwrap();
        assert_eq!(fourth.ui.as_ref().unwrap().order, Some(3));
    }

    #[test]
    fn test_quill_with_all_ui_properties() {
        let yaml_content = r#"
Quill:
  name: full-ui-test
  version: "1.0"
  backend: typst
  description: Test all UI properties

fields:
  author:
    description: The full name of the document author
    type: str
    ui:
      group: Author Info
"#;

        let config = QuillConfig::from_yaml(yaml_content).unwrap();

        let author_field = &config.document.fields["author"];
        let ui = author_field.ui.as_ref().unwrap();
        assert_eq!(ui.group, Some("Author Info".to_string()));
        assert_eq!(ui.order, Some(0)); // First field should have order 0
    }
    #[test]
    fn test_field_schema_with_title_and_description() {
        // Test parsing field with new schema format (title + description, no tooltip)
        let yaml = r#"
title: "Field Title"
description: "Detailed field description"
type: "string"
examples:
  - "Example value"
ui:
  group: "Test Group"
"#;
        let quill_value = QuillValue::from_yaml_str(yaml).unwrap();
        let schema = FieldSchema::from_quill_value("test_field".to_string(), &quill_value).unwrap();

        assert_eq!(schema.title, Some("Field Title".to_string()));
        assert_eq!(
            schema.description,
            Some("Detailed field description".to_string())
        );

        assert_eq!(
            schema
                .examples
                .as_ref()
                .and_then(|v| v.as_array())
                .and_then(|arr| arr.first())
                .and_then(|v| v.as_str()),
            Some("Example value")
        );

        let ui = schema.ui.as_ref().unwrap();
        assert_eq!(ui.group, Some("Test Group".to_string()));
    }

    #[test]
    fn test_parse_card_field_type() {
        // Test that FieldSchema no longer supports type = "card" (cards are in CardSchema now)
        let yaml = r#"
type: "string"
title: "Simple Field"
description: "A simple string field"
"#;
        let quill_value = QuillValue::from_yaml_str(yaml).unwrap();
        let schema =
            FieldSchema::from_quill_value("simple_field".to_string(), &quill_value).unwrap();

        assert_eq!(schema.name, "simple_field");
        assert_eq!(schema.r#type, FieldType::String);
        assert_eq!(schema.title, Some("Simple Field".to_string()));
        assert_eq!(
            schema.description,
            Some("A simple string field".to_string())
        );
    }

    #[test]
    fn test_parse_card_with_fields_in_yaml() {
        // Test parsing [cards] section with [cards.X.fields.Y] syntax
        let yaml_content = r#"
Quill:
  name: cards-fields-test
  version: "1.0"
  backend: typst
  description: Test [cards.X.fields.Y] syntax

cards:
  endorsements:
    title: Endorsements
    description: Chain of endorsements
    fields:
      name:
        type: string
        title: Endorser Name
        description: Name of the endorsing official
        required: true
      org:
        type: string
        title: Organization
        description: Endorser's organization
        default: Unknown
"#;

        let config = QuillConfig::from_yaml(yaml_content).unwrap();

        // Verify the card was parsed into config.cards
        assert!(config.cards.contains_key("endorsements"));
        let card = config.cards.get("endorsements").unwrap();

        assert_eq!(card.name, "endorsements");
        assert_eq!(card.title, Some("Endorsements".to_string()));
        assert_eq!(card.description, Some("Chain of endorsements".to_string()));

        // Verify card fields
        assert_eq!(card.fields.len(), 2);

        let name_field = card.fields.get("name").unwrap();
        assert_eq!(name_field.r#type, FieldType::String);
        assert_eq!(name_field.title, Some("Endorser Name".to_string()));
        assert!(name_field.required);

        let org_field = card.fields.get("org").unwrap();
        assert_eq!(org_field.r#type, FieldType::String);
        assert!(org_field.default.is_some());
        assert_eq!(
            org_field.default.as_ref().unwrap().as_str(),
            Some("Unknown")
        );
    }

    #[test]
    fn test_field_schema_rejects_unknown_keys() {
        // Test that unknown keys like "invalid_key" are rejected (strict mode)
        let yaml = r#"
type: "string"
description: "A string field"
invalid_key:
  sub_field:
    type: "string"
    description: "Nested field"
"#;
        let quill_value = QuillValue::from_yaml_str(yaml).unwrap();

        let result = FieldSchema::from_quill_value("author".to_string(), &quill_value);

        // The parsing should fail due to deny_unknown_fields
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.contains("unknown field `invalid_key`"),
            "Error was: {}",
            err
        );
    }

    #[test]
    fn test_quill_config_with_cards_section() {
        let yaml_content = r#"
Quill:
  name: cards-test
  version: "1.0"
  backend: typst
  description: Test [cards] section

fields:
  regular:
    description: Regular field
    type: string

cards:
  indorsements:
    title: Routing Indorsements
    description: Chain of endorsements
    fields:
      name:
        title: Name
        type: string
        description: Name field
"#;

        let config = QuillConfig::from_yaml(yaml_content).unwrap();

        // Check regular field
        assert!(config.document.fields.contains_key("regular"));
        let regular = config.document.fields.get("regular").unwrap();
        assert_eq!(regular.r#type, FieldType::String);

        // Check card is in config.cards (not config.document.fields)
        assert!(config.cards.contains_key("indorsements"));
        let card = config.cards.get("indorsements").unwrap();
        assert_eq!(card.title, Some("Routing Indorsements".to_string()));
        assert_eq!(card.description, Some("Chain of endorsements".to_string()));
        assert!(card.fields.contains_key("name"));
    }

    #[test]
    fn test_quill_config_cards_empty_fields() {
        // Test that cards with no fields section are valid
        let yaml_content = r#"
Quill:
  name: cards-empty-fields-test
  version: "1.0"
  backend: typst
  description: Test cards without fields

cards:
  myscope:
    description: My scope
"#;

        let config = QuillConfig::from_yaml(yaml_content).unwrap();
        let card = config.cards.get("myscope").unwrap();
        assert_eq!(card.name, "myscope");
        assert_eq!(card.description, Some("My scope".to_string()));
        assert!(card.fields.is_empty());
    }

    #[test]
    fn test_quill_config_allows_card_collision() {
        // Test that scope name colliding with field name is ALLOWED
        let yaml_content = r#"
Quill:
  name: collision-test
  version: "1.0"
  backend: typst
  description: Test collision

fields:
  conflict:
    description: Field
    type: string

cards:
  conflict:
    description: Card
"#;

        let result = QuillConfig::from_yaml(yaml_content);
        if let Err(e) = &result {
            panic!(
                "Card name collision should be allowed, but got error: {}",
                e
            );
        }
        assert!(result.is_ok());

        let config = result.unwrap();
        assert!(config.document.fields.contains_key("conflict"));
        assert!(config.cards.contains_key("conflict"));
    }

    #[test]
    fn test_quill_config_ordering_with_cards() {
        // Test that fields have proper UI ordering (cards no longer have card-level ordering)
        let yaml_content = r#"
Quill:
  name: ordering-test
  version: "1.0"
  backend: typst
  description: Test ordering

fields:
  first:
    type: string
    description: First
  zero:
    type: string
    description: Zero

cards:
  second:
    description: Second
    fields:
      card_field:
        type: string
        description: A card field
"#;

        let config = QuillConfig::from_yaml(yaml_content).unwrap();

        let first = config.document.fields.get("first").unwrap();
        let zero = config.document.fields.get("zero").unwrap();
        let second = config.cards.get("second").unwrap();

        // Check field ordering
        let ord_first = first.ui.as_ref().unwrap().order.unwrap();
        let ord_zero = zero.ui.as_ref().unwrap().order.unwrap();

        // Within fields, "first" is before "zero"
        assert!(ord_first < ord_zero);
        assert_eq!(ord_first, 0);
        assert_eq!(ord_zero, 1);

        // Card fields should also have ordering
        let card_field = second.fields.get("card_field").unwrap();
        let ord_card_field = card_field.ui.as_ref().unwrap().order.unwrap();
        assert_eq!(ord_card_field, 0); // First (and only) field in this card
    }
    #[test]
    fn test_card_field_order_preservation() {
        // Test that card fields preserve definition order (not alphabetical)
        // defined: z_first, then a_second
        // alphabetical: a_second, then z_first
        let yaml_content = r#"
Quill:
  name: card-order-test
  version: "1.0"
  backend: typst
  description: Test card field order

cards:
  mycard:
    description: Test card
    fields:
      z_first:
        type: string
        description: Defined first
      a_second:
        type: string
        description: Defined second
"#;

        let config = QuillConfig::from_yaml(yaml_content).unwrap();
        let card = config.cards.get("mycard").unwrap();

        let z_first = card.fields.get("z_first").unwrap();
        let a_second = card.fields.get("a_second").unwrap();

        // Check orders
        let z_order = z_first.ui.as_ref().unwrap().order.unwrap();
        let a_order = a_second.ui.as_ref().unwrap().order.unwrap();

        // If strict file order is preserved:
        // z_first should be 0, a_second should be 1
        assert_eq!(z_order, 0, "z_first should be 0 (defined first)");
        assert_eq!(a_order, 1, "a_second should be 1 (defined second)");
    }
    #[test]
    fn test_nested_schema_parsing() {
        let yaml_content = r#"
Quill:
  name: nested-test
  version: "1.0"
  backend: typst
  description: Test nested elements

fields:
  my_list:
    type: array
    description: List of objects
    items:
      type: object
      properties:
        sub_a:
          type: string
          description: Subfield A
        sub_b:
          type: number
          description: Subfield B
  my_obj:
    type: object
    description: Single object
    properties:
      child:
        type: boolean
        description: Child field
"#;

        let config = QuillConfig::from_yaml(yaml_content).unwrap();

        // Check array with items
        let list_field = config.document.fields.get("my_list").unwrap();
        assert_eq!(list_field.r#type, FieldType::Array);
        assert!(list_field.items.is_some());

        let items_schema = list_field.items.as_ref().unwrap();
        assert_eq!(items_schema.r#type, FieldType::Object);
        assert!(items_schema.properties.is_some());

        let props = items_schema.properties.as_ref().unwrap();
        assert!(props.contains_key("sub_a"));
        assert!(props.contains_key("sub_b"));
        assert_eq!(props["sub_a"].r#type, FieldType::String);
        assert_eq!(props["sub_b"].r#type, FieldType::Number);

        // Check object with properties
        let obj_field = config.document.fields.get("my_obj").unwrap();
        assert_eq!(obj_field.r#type, FieldType::Object);
        assert!(obj_field.properties.is_some());

        let obj_props = obj_field.properties.as_ref().unwrap();
        assert!(obj_props.contains_key("child"));
        assert_eq!(obj_props["child"].r#type, FieldType::Boolean);
    }
}