dreamwell-engine 1.0.0

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

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

// =============================================================================
// §0  SCHEMA VERSION
// =============================================================================

/// Current schema version string.
pub const SCHEMA_VERSION: &str = "dreamwell_waymark_v1.0.0";

fn default_schema_version() -> String {
    SCHEMA_VERSION.to_string()
}

// =============================================================================
// §1  ROOT — DreamwellPackV1
// =============================================================================

/// Dreamwell Waymark v1.0.0 — Unified Engine Configuration Schema.
/// Single source of truth for all configurable engine parameters.
/// Backward compatible with existing pack.json format.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DreamwellPackV1 {
    // === Pack Identity ===
    /// Unique pack identifier (kebab_case). Required, must be non-empty.
    pub id: String,

    /// Human-readable pack title.
    pub title: String,

    /// Semantic version string (e.g. "1.0.0").
    #[serde(default)]
    pub version: String,

    /// Pack description.
    #[serde(default)]
    pub description: String,

    /// Schema version. Defaults to "dreamwell_waymark_v1.0.0".
    #[serde(default = "default_schema_version")]
    pub schema_version: String,

    /// Optional tags for categorization and search.
    #[serde(default)]
    pub tags: Vec<String>,

    /// Optional world ID this pack targets (e.g. "world:braxxis:v1").
    #[serde(default)]
    pub world_id: Option<String>,

    /// Optional theme identifier (e.g. "SURVIVAL", "FANTASY").
    #[serde(default)]
    pub theme: Option<String>,

    // === Entry Point ===
    /// Scenario enum variant or identifier.
    #[serde(default)]
    pub scenario: Option<String>,

    /// Path to the Waymark scenario script (relative to pack root).
    #[serde(default)]
    pub scenario_script: Option<String>,

    /// Starting map identifier.
    #[serde(default)]
    pub starting_map: Option<String>,

    // === Grid & Spatial ===
    /// Grid dimensions for map generation.
    #[serde(default)]
    pub grid: GridConfig,

    /// Spatial engine parameters (cell size, FOV, pathfinding).
    #[serde(default)]
    pub spatial: SpatialConfig,

    // === Display ===
    /// Client display configuration.
    #[serde(default)]
    pub display: DisplayConfig,

    // === Features ===
    /// Feature flags controlling which engine subsystems are active.
    #[serde(default)]
    pub features: FeatureFlags,

    // === Equipment ===
    /// Ordered list of equipment slot names.
    #[serde(default)]
    pub equip_slots: Vec<String>,

    // === Simulation ===
    /// Core simulation tick and entity limits.
    #[serde(default)]
    pub simulation: SimulationConfig,

    // === Combat ===
    /// Combat formula parameters.
    #[serde(default)]
    pub combat: CombatConfig,

    // === Economy ===
    /// Economy and trade parameters.
    #[serde(default)]
    pub economy: EconomyConfig,

    // === Progression ===
    /// Leveling, XP, and reputation parameters.
    #[serde(default)]
    pub progression: ProgressionConfig,

    // === AI & Agents ===
    /// Agent cognition and inference parameters.
    #[serde(default)]
    pub agents: AgentConfig,

    // === Tiles & Visual ===
    /// Tile ID mappings, movement costs, and collision rules.
    #[serde(default)]
    pub tiles: TileConfig,

    // === Canon Event ===
    /// Canon event pipeline parameters.
    #[serde(default)]
    pub canon: CanonConfig,

    // === Waymark Scripting ===
    /// Waymark scripting engine limits.
    #[serde(default)]
    pub scripting: ScriptingConfig,

    // === Content ===
    /// Paths to content data files (items, enemies, abilities, etc.).
    #[serde(default)]
    pub content: ContentConfig,

    // === Map Eviction ===
    /// Map eviction and caching parameters.
    #[serde(default)]
    pub eviction: EvictionConfig,

    // === Props ===
    /// Prop definitions for this pack.
    #[serde(default)]
    pub props: Vec<PropDefinition>,

    // === Generators ===
    /// Map generator configurations (pack-specific, arbitrary structure).
    #[serde(default)]
    pub generators: serde_json::Value,

    // === Connection Props ===
    /// Mapping of connection types to prop IDs.
    #[serde(default)]
    pub connection_type_props: HashMap<String, String>,

    // === Boon Triggers ===
    /// Boon trigger definitions (pack-specific, arbitrary structure).
    #[serde(default)]
    pub boon_triggers: Vec<serde_json::Value>,

    // === Companion Services ===
    /// Whether this pack uses companion (AI) services.
    #[serde(default)]
    pub uses_companion_services: bool,

    // === Scenario Config (arbitrary, pack-specific) ===
    /// Pack-specific scenario configuration. Arbitrary JSON.
    #[serde(default)]
    pub scenario_config: serde_json::Value,

    // === Encumbrance (legacy field from existing packs) ===
    /// Optional encumbrance configuration (pack-specific).
    #[serde(default)]
    pub encumbrance: Option<serde_json::Value>,

    // === AI Brains (legacy field from existing packs) ===
    /// AI brain definitions for NPCs/creatures.
    #[serde(default)]
    pub ai_brains: HashMap<String, serde_json::Value>,

    // === Rules (legacy field from existing packs) ===
    /// Pack-specific game rules (arbitrary structure).
    #[serde(default)]
    pub rules: Option<serde_json::Value>,

    // === Identity (legacy field from existing packs) ===
    /// Identity system configuration (pack-specific).
    #[serde(default)]
    pub identity: Option<serde_json::Value>,

    // === Boot Sequence (legacy field from existing packs) ===
    /// Boot sequence display configuration (pack-specific).
    #[serde(default)]
    pub boot_sequence: Option<serde_json::Value>,

    // === Topology (v1.0.0) ===
    /// 9-layer topology configuration. Defines the cosmic-to-point hierarchy
    /// for this content pack. If omitted, seed creates a minimal 1-of-each.
    #[serde(default)]
    pub topology: TopologyConfig,

    // === Chronoshift (v1.0.0) ===
    /// Chronoshift (timeline fork/replay) parameters.
    #[serde(default)]
    pub chronoshift: ChronoshiftConfig,

    // === Forensics (v1.0.0) ===
    /// Forensics and proof lane parameters.
    #[serde(default)]
    pub forensics: ForensicsConfig,

    // === Physics (v1.0.0) ===
    /// Physics environment parameters for pack-driven worlds.
    #[serde(default)]
    pub physics: PhysicsConfig,

    // === GPU Pipeline (v1.0.0) ===
    /// Meshlet LOD configuration for GPU-driven rendering.
    #[serde(default)]
    pub meshlet_lod: Option<MeshletLodConfig>,

    /// Meshlet emission configuration for DreamMatter.
    #[serde(default)]
    pub meshlet_emission: Option<MeshletEmissionConfig>,

    /// Observer configuration for Quantum Culling.
    #[serde(default)]
    pub observer_config: Option<WaymarkObserverConfig>,

    /// Promotion targets for DreamMatter → server authority.
    #[serde(default)]
    pub promotion_targets: Vec<WaymarkPromotionTarget>,
    /// Default avatar physics/locomotion configuration.
    #[serde(default)]
    pub avatar_defaults: Option<AvatarDefaults>,
}

/// Default avatar configuration for a content pack.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AvatarDefaults {
    #[serde(default = "default_avatar_radius")]
    pub radius: f32,
    #[serde(default = "default_avatar_height")]
    pub height: f32,
    #[serde(default = "default_avatar_step_height")]
    pub step_height: f32,
    #[serde(default = "default_avatar_slope_limit")]
    pub slope_limit_degrees: f32,
    #[serde(default = "default_avatar_mass")]
    pub mass: f32,
    #[serde(default = "default_avatar_input_scheme")]
    pub input_scheme: String,
}

fn default_avatar_radius() -> f32 {
    0.3
}
fn default_avatar_height() -> f32 {
    1.8
}
fn default_avatar_step_height() -> f32 {
    0.35
}
fn default_avatar_slope_limit() -> f32 {
    45.0
}
fn default_avatar_mass() -> f32 {
    70.0
}
fn default_avatar_input_scheme() -> String {
    "ThirdPerson".into()
}

impl Default for AvatarDefaults {
    fn default() -> Self {
        Self {
            radius: default_avatar_radius(),
            height: default_avatar_height(),
            step_height: default_avatar_step_height(),
            slope_limit_degrees: default_avatar_slope_limit(),
            mass: default_avatar_mass(),
            input_scheme: default_avatar_input_scheme(),
        }
    }
}

// =============================================================================
// §2  GRID CONFIG
// =============================================================================

/// Grid dimensions for map generation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GridConfig {
    /// Grid width in tiles. Default: 80.
    #[serde(default = "default_grid_width")]
    pub width: u32,

    /// Grid height in tiles. Default: 50.
    #[serde(default = "default_grid_height")]
    pub height: u32,

    /// Chunk edge size in tiles. Default: 32. Must be a power of two.
    #[serde(default = "default_chunk_size")]
    pub chunk_size: u32,
}

fn default_grid_width() -> u32 {
    80
}
fn default_grid_height() -> u32 {
    50
}
fn default_chunk_size() -> u32 {
    32
}

impl Default for GridConfig {
    fn default() -> Self {
        Self {
            width: default_grid_width(),
            height: default_grid_height(),
            chunk_size: default_chunk_size(),
        }
    }
}

// =============================================================================
// §3  SPATIAL CONFIG
// =============================================================================

/// Spatial engine parameters: cell sizing, field-of-view, pathfinding, AOI.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpatialConfig {
    /// Cell size in world units. Default: 128.
    #[serde(default = "default_cell_size")]
    pub cell_size: i32,

    /// Default field-of-view radius in tiles. Default: 8.
    #[serde(default = "default_fov_default_radius")]
    pub fov_default_radius: i32,

    /// Maximum allowed FOV radius. Default: 24.
    #[serde(default = "default_fov_max_radius")]
    pub fov_max_radius: i32,

    /// Maximum A* pathfinding iterations before aborting. Default: 512.
    #[serde(default = "default_max_pathfind_steps")]
    pub max_pathfind_steps: u32,

    /// AOI neighbor depth. 1 = 3x3 grid of cells. Default: 1.
    #[serde(default = "default_aoi_neighbor_depth")]
    pub aoi_neighbor_depth: u32,

    /// Whether entity-tile collision is enabled. Default: true.
    #[serde(default = "default_true")]
    pub collision_enabled: bool,
}

fn default_cell_size() -> i32 {
    128
}
fn default_fov_default_radius() -> i32 {
    8
}
fn default_fov_max_radius() -> i32 {
    24
}
fn default_max_pathfind_steps() -> u32 {
    512
}
fn default_aoi_neighbor_depth() -> u32 {
    1
}
fn default_true() -> bool {
    true
}

impl Default for SpatialConfig {
    fn default() -> Self {
        Self {
            cell_size: default_cell_size(),
            fov_default_radius: default_fov_default_radius(),
            fov_max_radius: default_fov_max_radius(),
            max_pathfind_steps: default_max_pathfind_steps(),
            aoi_neighbor_depth: default_aoi_neighbor_depth(),
            collision_enabled: true,
        }
    }
}

// =============================================================================
// §4  DISPLAY CONFIG
// =============================================================================

/// Client-side display configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DisplayConfig {
    /// Display name for the mana resource. Default: "Mana".
    #[serde(default = "default_mana_name")]
    pub mana_name: String,

    /// Subtitle shown on the title screen or HUD.
    #[serde(default)]
    pub subtitle: Option<String>,

    /// Whether to show the minimap. Default: true.
    #[serde(default = "default_true")]
    pub show_minimap: bool,

    /// Whether to show tile coordinates in the HUD. Default: false.
    #[serde(default)]
    pub show_coordinates: bool,

    /// Visual theme identifier (e.g. "dark", "light", "terminal").
    #[serde(default)]
    pub theme: Option<String>,
}

fn default_mana_name() -> String {
    "Mana".to_string()
}

impl Default for DisplayConfig {
    fn default() -> Self {
        Self {
            mana_name: default_mana_name(),
            subtitle: None,
            show_minimap: true,
            show_coordinates: false,
            theme: None,
        }
    }
}

// =============================================================================
// §5  FEATURE FLAGS
// =============================================================================

/// Feature flags controlling which engine subsystems are active for this pack.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FeatureFlags {
    /// Enable content plan system. Default: false.
    #[serde(default)]
    pub content_plan: bool,

    /// Enable boon trigger system. Default: false.
    #[serde(default)]
    pub boons: bool,

    /// Enable shrine interactables. Default: false.
    #[serde(default)]
    pub shrines: bool,

    /// Enable container/inventory on props. Default: false.
    #[serde(default)]
    pub containers: bool,

    /// Enable carry-weight encumbrance. Default: false.
    #[serde(default)]
    pub encumbrance: bool,

    /// Enable player-versus-player combat. Default: false.
    #[serde(default)]
    pub pvp: bool,

    /// Enable dynasty/lineage system. Default: false.
    #[serde(default)]
    pub dynasties: bool,

    /// Enable crafting system. Default: false.
    #[serde(default)]
    pub crafting: bool,

    /// Enable market/auction house. Default: false.
    #[serde(default)]
    pub market: bool,

    /// Enable instanced areas. Default: false.
    #[serde(default)]
    pub instances: bool,

    /// Enable crime/reputation system. Default: false.
    #[serde(default)]
    pub crime_system: bool,

    /// Enable dynamic weather. Default: false.
    #[serde(default)]
    pub weather: bool,

    /// Enable day/night cycle. Default: false.
    #[serde(default)]
    pub day_night_cycle: bool,

    /// Enable fog of war. Default: false.
    #[serde(default)]
    pub fog_of_war: bool,

    /// Enable chronoshift (timeline fork/replay). Default: false.
    #[serde(default)]
    pub chronoshift_enabled: bool,

    /// Enable proof lane (forensics). Default: false.
    #[serde(default)]
    pub proof_lane_enabled: bool,

    /// Enable dungeon ambient soundtrack. Default: true.
    #[serde(default = "default_true")]
    pub dungeon_ambient: bool,

    /// Enable line-of-sight computation. Default: true.
    #[serde(default = "default_true")]
    pub line_of_sight: bool,

    /// Enable tile collisions. Default: true.
    #[serde(default = "default_true")]
    pub collisions: bool,

    /// Enable identity system (Embersteel-style reprints). Default: false.
    #[serde(default)]
    pub identity_system: bool,

    /// Enable death-reprint mechanic. Default: false.
    #[serde(default)]
    pub death_reprint: bool,
}

impl Default for FeatureFlags {
    fn default() -> Self {
        Self {
            content_plan: false,
            boons: false,
            shrines: false,
            containers: false,
            encumbrance: false,
            pvp: false,
            dynasties: false,
            crafting: false,
            market: false,
            instances: false,
            crime_system: false,
            weather: false,
            day_night_cycle: false,
            fog_of_war: false,
            chronoshift_enabled: false,
            proof_lane_enabled: false,
            dungeon_ambient: true,
            line_of_sight: true,
            collisions: true,
            identity_system: false,
            death_reprint: false,
        }
    }
}

// =============================================================================
// §6  SIMULATION CONFIG
// =============================================================================

/// Core simulation tick rate and entity limits.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SimulationConfig {
    /// Milliseconds per simulation tick. Default: 100.
    #[serde(default = "default_tick_rate_ms")]
    pub tick_rate_ms: u32,

    /// Number of ticks that constitute one in-game day. Default: 365.
    #[serde(default = "default_ticks_per_day")]
    pub ticks_per_day: u32,

    /// Time dilation multiplier. 1.0 = real time. Default: 1.0.
    #[serde(default = "default_time_dilation")]
    pub time_dilation: f64,

    /// Maximum entities allowed in a single area. Default: 256.
    #[serde(default = "default_max_entities_per_area")]
    pub max_entities_per_area: u32,

    /// Maximum canon events emitted per tick. Default: 1024.
    #[serde(default = "default_max_events_per_tick")]
    pub max_events_per_tick: u32,

    /// Deterministic seed for RNG. 0 = use ctx.rng (server-provided). Default: 0.
    #[serde(default)]
    pub deterministic_seed: u64,
}

fn default_tick_rate_ms() -> u32 {
    100
}
fn default_ticks_per_day() -> u32 {
    365
}
fn default_time_dilation() -> f64 {
    1.0
}
fn default_max_entities_per_area() -> u32 {
    256
}
fn default_max_events_per_tick() -> u32 {
    1024
}

impl Default for SimulationConfig {
    fn default() -> Self {
        Self {
            tick_rate_ms: default_tick_rate_ms(),
            ticks_per_day: default_ticks_per_day(),
            time_dilation: default_time_dilation(),
            max_entities_per_area: default_max_entities_per_area(),
            max_events_per_tick: default_max_events_per_tick(),
            deterministic_seed: 0,
        }
    }
}

// =============================================================================
// §7  COMBAT CONFIG
// =============================================================================

/// Combat formula parameters.
///
/// Note: `crit_multiplier` is for display/client reference only. The
/// authoritative server uses fixed-point arithmetic for all combat math.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CombatConfig {
    /// Base hit chance percentage. Default: 80.
    #[serde(default = "default_base_hit_chance")]
    pub base_hit_chance: u32,

    /// Critical hit damage multiplier (display/client only). Default: 2.0.
    #[serde(default = "default_crit_multiplier")]
    pub crit_multiplier: f64,

    /// Base dodge chance percentage. Default: 10.
    #[serde(default = "default_dodge_base")]
    pub dodge_base: u32,

    /// Base parry chance percentage. Default: 5.
    #[serde(default = "default_parry_base")]
    pub parry_base: u32,

    /// HP percentage threshold below which NPCs attempt to flee. Default: 20.
    #[serde(default = "default_flee_threshold_hp_pct")]
    pub flee_threshold_hp_pct: u32,

    /// Maximum simultaneous threat targets per actor. Default: 8.
    #[serde(default = "default_max_threat_targets")]
    pub max_threat_targets: u32,

    /// Ticks before a duel request expires. Default: 100.
    #[serde(default = "default_duel_timeout_ticks")]
    pub duel_timeout_ticks: u32,

    /// HP percentage restored on revive. Default: 25.
    #[serde(default = "default_revive_hp_pct")]
    pub revive_hp_pct: u32,

    /// Maximum status effect stacks per effect type. Default: 5.
    #[serde(default = "default_status_max_stacks")]
    pub status_max_stacks: u32,

    /// Available damage type identifiers.
    #[serde(default = "default_damage_types")]
    pub damage_types: Vec<String>,

    /// Maximum resistance percentage cap. Default: 75.
    #[serde(default = "default_resistance_cap")]
    pub resistance_cap: u32,
}

fn default_base_hit_chance() -> u32 {
    80
}
fn default_crit_multiplier() -> f64 {
    2.0
}
fn default_dodge_base() -> u32 {
    10
}
fn default_parry_base() -> u32 {
    5
}
fn default_flee_threshold_hp_pct() -> u32 {
    20
}
fn default_max_threat_targets() -> u32 {
    8
}
fn default_duel_timeout_ticks() -> u32 {
    100
}
fn default_revive_hp_pct() -> u32 {
    25
}
fn default_status_max_stacks() -> u32 {
    5
}
fn default_damage_types() -> Vec<String> {
    vec![
        "physical".to_string(),
        "fire".to_string(),
        "ice".to_string(),
        "lightning".to_string(),
        "arcane".to_string(),
        "poison".to_string(),
        "holy".to_string(),
        "shadow".to_string(),
    ]
}
fn default_resistance_cap() -> u32 {
    75
}

impl Default for CombatConfig {
    fn default() -> Self {
        Self {
            base_hit_chance: default_base_hit_chance(),
            crit_multiplier: default_crit_multiplier(),
            dodge_base: default_dodge_base(),
            parry_base: default_parry_base(),
            flee_threshold_hp_pct: default_flee_threshold_hp_pct(),
            max_threat_targets: default_max_threat_targets(),
            duel_timeout_ticks: default_duel_timeout_ticks(),
            revive_hp_pct: default_revive_hp_pct(),
            status_max_stacks: default_status_max_stacks(),
            damage_types: default_damage_types(),
            resistance_cap: default_resistance_cap(),
        }
    }
}

// =============================================================================
// §8  ECONOMY CONFIG
// =============================================================================

/// Economy and trade parameters.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EconomyConfig {
    /// Starting gold for new characters. Default: 100.
    #[serde(default = "default_starting_gold")]
    pub starting_gold: u64,

    /// Trade tax percentage applied to direct trades. Default: 5.
    #[serde(default = "default_trade_tax_pct")]
    pub trade_tax_pct: u32,

    /// Market listing fee percentage. Default: 10.
    #[serde(default = "default_market_fee_pct")]
    pub market_fee_pct: u32,

    /// Maximum active market listings per player. Default: 20.
    #[serde(default = "default_max_listings_per_player")]
    pub max_listings_per_player: u32,

    /// Currency type identifiers (e.g. "gold", "silver", "embercore").
    #[serde(default = "default_currency_types")]
    pub currency_types: Vec<String>,

    /// Base crafting failure chance percentage. Default: 10.
    #[serde(default = "default_crafting_fail_chance_base")]
    pub crafting_fail_chance_base: u32,
}

fn default_starting_gold() -> u64 {
    100
}
fn default_trade_tax_pct() -> u32 {
    5
}
fn default_market_fee_pct() -> u32 {
    10
}
fn default_max_listings_per_player() -> u32 {
    20
}
fn default_currency_types() -> Vec<String> {
    vec!["gold".to_string()]
}
fn default_crafting_fail_chance_base() -> u32 {
    10
}

impl Default for EconomyConfig {
    fn default() -> Self {
        Self {
            starting_gold: default_starting_gold(),
            trade_tax_pct: default_trade_tax_pct(),
            market_fee_pct: default_market_fee_pct(),
            max_listings_per_player: default_max_listings_per_player(),
            currency_types: default_currency_types(),
            crafting_fail_chance_base: default_crafting_fail_chance_base(),
        }
    }
}

// =============================================================================
// §9  PROGRESSION CONFIG
// =============================================================================

/// Leveling, XP curve, and reputation parameters.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProgressionConfig {
    /// Maximum character level. Default: 100.
    #[serde(default = "default_max_level")]
    pub max_level: u32,

    /// Exponential XP curve base. XP(n) = base_xp * xp_curve_base^(n-1). Default: 1.5.
    #[serde(default = "default_xp_curve_base")]
    pub xp_curve_base: f64,

    /// Base XP required for level 2. Default: 100.
    #[serde(default = "default_base_xp")]
    pub base_xp: u64,

    /// HP bonus gained per level. Default: 10.
    #[serde(default = "default_level_hp_bonus")]
    pub level_hp_bonus: u32,

    /// Stat points gained per level. Default: 2.
    #[serde(default = "default_level_stat_bonus")]
    pub level_stat_bonus: u32,

    /// Minimum reputation value. Default: -1000.
    #[serde(default = "default_reputation_min")]
    pub reputation_min: i64,

    /// Maximum reputation value. Default: 1000.
    #[serde(default = "default_reputation_max")]
    pub reputation_max: i64,
}

fn default_max_level() -> u32 {
    100
}
fn default_xp_curve_base() -> f64 {
    1.5
}
fn default_base_xp() -> u64 {
    100
}
fn default_level_hp_bonus() -> u32 {
    10
}
fn default_level_stat_bonus() -> u32 {
    2
}
fn default_reputation_min() -> i64 {
    -1000
}
fn default_reputation_max() -> i64 {
    1000
}

impl Default for ProgressionConfig {
    fn default() -> Self {
        Self {
            max_level: default_max_level(),
            xp_curve_base: default_xp_curve_base(),
            base_xp: default_base_xp(),
            level_hp_bonus: default_level_hp_bonus(),
            level_stat_bonus: default_level_stat_bonus(),
            reputation_min: default_reputation_min(),
            reputation_max: default_reputation_max(),
        }
    }
}

// =============================================================================
// §10  AGENT CONFIG
// =============================================================================

/// Agent cognition, perception, and inference parameters.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentConfig {
    /// Maximum cognition actions per agent per tick. Default: 3.
    #[serde(default = "default_cognition_budget_per_tick")]
    pub cognition_budget_per_tick: u32,

    /// Perception range in tiles. Default: 10.
    #[serde(default = "default_perception_range")]
    pub perception_range: u32,

    /// Maximum memory entries per agent. Default: 32.
    #[serde(default = "default_memory_capacity")]
    pub memory_capacity: u32,

    /// Default reasoning tier (0 = reactive, 1 = deliberative, 2 = planning). Default: 1.
    #[serde(default = "default_reasoning_tier")]
    pub reasoning_tier_default: u32,

    /// Default motor tier (0 = static, 1 = mobile, 2 = acrobatic). Default: 1.
    #[serde(default = "default_motor_tier")]
    pub motor_tier_default: u32,

    /// Maximum concurrently active agents. Default: 64.
    #[serde(default = "default_max_concurrent_agents")]
    pub max_concurrent_agents: u32,

    /// Inference request timeout in milliseconds. Default: 5000.
    #[serde(default = "default_inference_timeout_ms")]
    pub inference_timeout_ms: u32,

    /// Maximum tokens per inference response. Default: 512.
    #[serde(default = "default_inference_max_tokens")]
    pub inference_max_tokens: u32,
}

fn default_cognition_budget_per_tick() -> u32 {
    3
}
fn default_perception_range() -> u32 {
    10
}
fn default_memory_capacity() -> u32 {
    32
}
fn default_reasoning_tier() -> u32 {
    1
}
fn default_motor_tier() -> u32 {
    1
}
fn default_max_concurrent_agents() -> u32 {
    64
}
fn default_inference_timeout_ms() -> u32 {
    5000
}
fn default_inference_max_tokens() -> u32 {
    512
}

impl Default for AgentConfig {
    fn default() -> Self {
        Self {
            cognition_budget_per_tick: default_cognition_budget_per_tick(),
            perception_range: default_perception_range(),
            memory_capacity: default_memory_capacity(),
            reasoning_tier_default: default_reasoning_tier(),
            motor_tier_default: default_motor_tier(),
            max_concurrent_agents: default_max_concurrent_agents(),
            inference_timeout_ms: default_inference_timeout_ms(),
            inference_max_tokens: default_inference_max_tokens(),
        }
    }
}

// =============================================================================
// §11  TILE CONFIG
// =============================================================================

/// Individual tile type definition: glyph, movement cost, blocking rules.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TileTypeDef {
    /// Tile ID (u16).
    pub glyph: u16,

    /// Optional display character for rendering.
    #[serde(default)]
    pub display_char: Option<char>,

    /// Movement cost for pathfinding. 999 = impassable.
    #[serde(default = "default_move_cost_1")]
    pub move_cost: u32,

    /// Whether this tile blocks entity movement.
    #[serde(default)]
    pub blocks_move: bool,

    /// Whether this tile blocks line of sight.
    #[serde(default)]
    pub blocks_sight: bool,
}

fn default_move_cost_1() -> u32 {
    1
}

/// Tile ID (u16) mappings, movement costs, and collision rules.
///
/// Defaults match the constants in `tile.rs`:
/// - Ground layer: `.` `,` `:` `` ` `` `~` `=` `b` `;` `'`
/// - Structure layer: `#` `|` `_` `I` `*` `^` `v`
/// - Object layer: `o` `C` `c` `S` `B` `!` `$` `K` `?`
/// - Effect layer: `x` `%`
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TileConfig {
    // -- Ground layer --
    /// Ground tile: b'.' — open floor. Cost 1, passable, transparent.
    #[serde(default = "default_tile_ground")]
    pub ground: TileTypeDef,

    /// Dirt tile: b',' — soft earth. Cost 1, passable, transparent.
    #[serde(default = "default_tile_dirt")]
    pub dirt: TileTypeDef,

    /// Sand tile: b':' — loose sand. Cost 2, passable, transparent.
    #[serde(default = "default_tile_sand")]
    pub sand: TileTypeDef,

    /// Mud tile: b'`' — wet ground. Cost 2, passable, transparent.
    #[serde(default = "default_tile_mud")]
    pub mud: TileTypeDef,

    /// Liquid tile: b'~' — shallow water. Cost 3, passable, transparent.
    #[serde(default = "default_tile_liquid")]
    pub liquid: TileTypeDef,

    /// Deep water tile: b'=' — impassable water. Cost 999, blocks move, transparent.
    #[serde(default = "default_tile_deep_water")]
    pub deep_water: TileTypeDef,

    /// Rocky ground tile: b'b' — rough terrain. Cost 2, passable, transparent.
    #[serde(default = "default_tile_rocky_ground")]
    pub rocky_ground: TileTypeDef,

    /// Grass tile: b';' — grass. Cost 2, passable, transparent.
    #[serde(default = "default_tile_grass")]
    pub grass: TileTypeDef,

    /// Debris tile: b'\'' — rubble. Cost 2, passable, transparent.
    #[serde(default = "default_tile_debris")]
    pub debris: TileTypeDef,

    // -- Structure layer --
    /// Wall tile: b'#' — solid wall. Cost 999, blocks move, blocks sight.
    #[serde(default = "default_tile_wall")]
    pub wall: TileTypeDef,

    /// Vertical wall tile: b'|' — vertical wall segment. Cost 999, blocks move, blocks sight.
    #[serde(default = "default_tile_wall_vert")]
    pub wall_vert: TileTypeDef,

    /// Horizontal wall tile: b'_' — horizontal wall segment. Cost 999, blocks move, blocks sight.
    #[serde(default = "default_tile_wall_horiz")]
    pub wall_horiz: TileTypeDef,

    /// Closed door tile: b'I' — closed door. Cost 999, blocks move, blocks sight.
    #[serde(default = "default_tile_door_closed")]
    pub door_closed: TileTypeDef,

    /// Open door tile: b'*' — open door. Cost 1, passable, transparent.
    #[serde(default = "default_tile_door_open")]
    pub door_open: TileTypeDef,

    /// Stairs up tile: b'^' — ascending stairs. Cost 1, passable, transparent.
    #[serde(default = "default_tile_stairs_up")]
    pub stairs_up: TileTypeDef,

    /// Stairs down tile: b'v' — descending stairs. Cost 1, passable, transparent.
    #[serde(default = "default_tile_stairs_down")]
    pub stairs_down: TileTypeDef,

    /// Bridge tile: b'=' — walkable bridge. Cost 1, passable, transparent.
    #[serde(default = "default_tile_bridge")]
    pub bridge: TileTypeDef,

    // -- Object layer --
    /// Boulder tile: b'o' — large rock. Cost 999, blocks move, blocks sight.
    #[serde(default = "default_tile_boulder")]
    pub boulder: TileTypeDef,

    /// Chest tile: b'C' — closed chest. Cost 999, blocks move, transparent.
    #[serde(default = "default_tile_chest")]
    pub chest: TileTypeDef,

    /// Crate tile: b'c' — wooden crate. Cost 999, blocks move, transparent.
    #[serde(default = "default_tile_crate")]
    pub crate_obj: TileTypeDef,

    /// Shrine tile: b'S' — interactive shrine. Cost 1, passable, transparent.
    #[serde(default = "default_tile_shrine")]
    pub shrine: TileTypeDef,

    /// Bed tile: b'B' — bed. Cost 999, blocks move, transparent.
    #[serde(default = "default_tile_bed")]
    pub bed: TileTypeDef,

    /// Consumable tile: b'!' — pickup item. Cost 1, passable, transparent.
    #[serde(default = "default_tile_consumable")]
    pub consumable: TileTypeDef,

    /// Currency tile: b'$' — gold drop. Cost 1, passable, transparent.
    #[serde(default = "default_tile_currency")]
    pub currency: TileTypeDef,

    /// Key item tile: b'K' — quest item pickup. Cost 1, passable, transparent.
    #[serde(default = "default_tile_key_item")]
    pub key_item: TileTypeDef,

    /// Unknown object tile: b'?' — unidentified. Cost 999, blocks move, transparent.
    #[serde(default = "default_tile_unknown_obj")]
    pub unknown_obj: TileTypeDef,

    // -- Effect layer --
    /// Hazard tile: b'x' — environmental hazard. Cost 2, passable, transparent.
    #[serde(default = "default_tile_hazard")]
    pub hazard: TileTypeDef,

    /// Smoke tile: b'%' — obscuring smoke. Cost 2, passable, blocks sight.
    #[serde(default = "default_tile_smoke")]
    pub smoke: TileTypeDef,

    /// Additional custom tile definitions. Key = tile name, value = definition.
    #[serde(default)]
    pub custom: HashMap<String, TileTypeDef>,
}

// -- Ground layer defaults --
fn default_tile_ground() -> TileTypeDef {
    TileTypeDef {
        glyph: b'.' as u16,
        display_char: None,
        move_cost: 1,
        blocks_move: false,
        blocks_sight: false,
    }
}
fn default_tile_dirt() -> TileTypeDef {
    TileTypeDef {
        glyph: b',' as u16,
        display_char: None,
        move_cost: 1,
        blocks_move: false,
        blocks_sight: false,
    }
}
fn default_tile_sand() -> TileTypeDef {
    TileTypeDef {
        glyph: b':' as u16,
        display_char: None,
        move_cost: 2,
        blocks_move: false,
        blocks_sight: false,
    }
}
fn default_tile_mud() -> TileTypeDef {
    TileTypeDef {
        glyph: b'`' as u16,
        display_char: None,
        move_cost: 2,
        blocks_move: false,
        blocks_sight: false,
    }
}
fn default_tile_liquid() -> TileTypeDef {
    TileTypeDef {
        glyph: b'~' as u16,
        display_char: None,
        move_cost: 3,
        blocks_move: false,
        blocks_sight: false,
    }
}
fn default_tile_deep_water() -> TileTypeDef {
    TileTypeDef {
        glyph: b'=' as u16,
        display_char: None,
        move_cost: 999,
        blocks_move: true,
        blocks_sight: false,
    }
}
fn default_tile_rocky_ground() -> TileTypeDef {
    TileTypeDef {
        glyph: b'b' as u16,
        display_char: None,
        move_cost: 2,
        blocks_move: false,
        blocks_sight: false,
    }
}
fn default_tile_grass() -> TileTypeDef {
    TileTypeDef {
        glyph: b';' as u16,
        display_char: None,
        move_cost: 2,
        blocks_move: false,
        blocks_sight: false,
    }
}
fn default_tile_debris() -> TileTypeDef {
    TileTypeDef {
        glyph: b'\'' as u16,
        display_char: None,
        move_cost: 2,
        blocks_move: false,
        blocks_sight: false,
    }
}
// -- Structure layer defaults --
fn default_tile_wall() -> TileTypeDef {
    TileTypeDef {
        glyph: b'#' as u16,
        display_char: None,
        move_cost: 999,
        blocks_move: true,
        blocks_sight: true,
    }
}
fn default_tile_wall_vert() -> TileTypeDef {
    TileTypeDef {
        glyph: b'|' as u16,
        display_char: None,
        move_cost: 999,
        blocks_move: true,
        blocks_sight: true,
    }
}
fn default_tile_wall_horiz() -> TileTypeDef {
    TileTypeDef {
        glyph: b'_' as u16,
        display_char: None,
        move_cost: 999,
        blocks_move: true,
        blocks_sight: true,
    }
}
fn default_tile_door_closed() -> TileTypeDef {
    TileTypeDef {
        glyph: b'I' as u16,
        display_char: None,
        move_cost: 999,
        blocks_move: true,
        blocks_sight: true,
    }
}
fn default_tile_door_open() -> TileTypeDef {
    TileTypeDef {
        glyph: b'*' as u16,
        display_char: None,
        move_cost: 1,
        blocks_move: false,
        blocks_sight: false,
    }
}
fn default_tile_stairs_up() -> TileTypeDef {
    TileTypeDef {
        glyph: b'^' as u16,
        display_char: None,
        move_cost: 1,
        blocks_move: false,
        blocks_sight: false,
    }
}
fn default_tile_stairs_down() -> TileTypeDef {
    TileTypeDef {
        glyph: b'v' as u16,
        display_char: None,
        move_cost: 1,
        blocks_move: false,
        blocks_sight: false,
    }
}
fn default_tile_bridge() -> TileTypeDef {
    TileTypeDef {
        glyph: b'=' as u16,
        display_char: None,
        move_cost: 1,
        blocks_move: false,
        blocks_sight: false,
    }
}
// -- Object layer defaults --
fn default_tile_boulder() -> TileTypeDef {
    TileTypeDef {
        glyph: b'o' as u16,
        display_char: None,
        move_cost: 999,
        blocks_move: true,
        blocks_sight: true,
    }
}
fn default_tile_chest() -> TileTypeDef {
    TileTypeDef {
        glyph: b'C' as u16,
        display_char: None,
        move_cost: 999,
        blocks_move: true,
        blocks_sight: false,
    }
}
fn default_tile_crate() -> TileTypeDef {
    TileTypeDef {
        glyph: b'c' as u16,
        display_char: None,
        move_cost: 999,
        blocks_move: true,
        blocks_sight: false,
    }
}
fn default_tile_shrine() -> TileTypeDef {
    TileTypeDef {
        glyph: b'S' as u16,
        display_char: None,
        move_cost: 1,
        blocks_move: false,
        blocks_sight: false,
    }
}
fn default_tile_bed() -> TileTypeDef {
    TileTypeDef {
        glyph: b'B' as u16,
        display_char: None,
        move_cost: 999,
        blocks_move: true,
        blocks_sight: false,
    }
}
fn default_tile_consumable() -> TileTypeDef {
    TileTypeDef {
        glyph: b'!' as u16,
        display_char: None,
        move_cost: 1,
        blocks_move: false,
        blocks_sight: false,
    }
}
fn default_tile_currency() -> TileTypeDef {
    TileTypeDef {
        glyph: b'$' as u16,
        display_char: None,
        move_cost: 1,
        blocks_move: false,
        blocks_sight: false,
    }
}
fn default_tile_key_item() -> TileTypeDef {
    TileTypeDef {
        glyph: b'K' as u16,
        display_char: None,
        move_cost: 1,
        blocks_move: false,
        blocks_sight: false,
    }
}
fn default_tile_unknown_obj() -> TileTypeDef {
    TileTypeDef {
        glyph: b'?' as u16,
        display_char: None,
        move_cost: 999,
        blocks_move: true,
        blocks_sight: false,
    }
}
// -- Effect layer defaults --
fn default_tile_hazard() -> TileTypeDef {
    TileTypeDef {
        glyph: b'x' as u16,
        display_char: None,
        move_cost: 2,
        blocks_move: false,
        blocks_sight: false,
    }
}
fn default_tile_smoke() -> TileTypeDef {
    TileTypeDef {
        glyph: b'%' as u16,
        display_char: None,
        move_cost: 2,
        blocks_move: false,
        blocks_sight: true,
    }
}

impl Default for TileConfig {
    fn default() -> Self {
        Self {
            ground: default_tile_ground(),
            dirt: default_tile_dirt(),
            sand: default_tile_sand(),
            mud: default_tile_mud(),
            liquid: default_tile_liquid(),
            deep_water: default_tile_deep_water(),
            rocky_ground: default_tile_rocky_ground(),
            grass: default_tile_grass(),
            debris: default_tile_debris(),
            wall: default_tile_wall(),
            wall_vert: default_tile_wall_vert(),
            wall_horiz: default_tile_wall_horiz(),
            door_closed: default_tile_door_closed(),
            door_open: default_tile_door_open(),
            stairs_up: default_tile_stairs_up(),
            stairs_down: default_tile_stairs_down(),
            bridge: default_tile_bridge(),
            boulder: default_tile_boulder(),
            chest: default_tile_chest(),
            crate_obj: default_tile_crate(),
            shrine: default_tile_shrine(),
            bed: default_tile_bed(),
            consumable: default_tile_consumable(),
            currency: default_tile_currency(),
            key_item: default_tile_key_item(),
            unknown_obj: default_tile_unknown_obj(),
            hazard: default_tile_hazard(),
            smoke: default_tile_smoke(),
            custom: HashMap::new(),
        }
    }
}

// =============================================================================
// §12  CANON CONFIG
// =============================================================================

/// Canon event pipeline parameters.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CanonConfig {
    /// Ticks between block hash checkpoints. Default: 100.
    #[serde(default = "default_block_hash_interval")]
    pub block_hash_interval: u64,

    /// Ticks between tick-level hash accumulation. Default: 10.
    #[serde(default = "default_tick_hash_interval")]
    pub tick_hash_interval: u64,

    /// Maximum BFS traversal depth for graph queries. Default: 10.
    #[serde(default = "default_max_traversal_depth")]
    pub max_traversal_depth: u32,

    /// Default scope token budget. Default: 100.
    #[serde(default = "default_scope_budget")]
    pub scope_budget_default: u32,

    /// Tokens refilled per tick. Default: 5.
    #[serde(default = "default_token_refill_per_tick")]
    pub token_refill_per_tick: u32,

    /// Maximum token cap. Default: 50.
    #[serde(default = "default_max_tokens")]
    pub max_tokens: u32,

    /// Maximum trigger chain depth (prevents infinite loops). Default: 3.
    #[serde(default = "default_max_trigger_depth")]
    pub max_trigger_depth: u32,

    /// Maximum triggers fired per single canon event. Default: 5.
    #[serde(default = "default_max_triggers_per_event")]
    pub max_triggers_per_event: u32,

    /// Maximum total triggers fired per tick across all events. Default: 50.
    #[serde(default = "default_max_triggers_per_tick")]
    pub max_triggers_per_tick: u32,
}

fn default_block_hash_interval() -> u64 {
    100
}
fn default_tick_hash_interval() -> u64 {
    10
}
fn default_max_traversal_depth() -> u32 {
    10
}
fn default_scope_budget() -> u32 {
    100
}
fn default_token_refill_per_tick() -> u32 {
    5
}
fn default_max_tokens() -> u32 {
    50
}
fn default_max_trigger_depth() -> u32 {
    3
}
fn default_max_triggers_per_event() -> u32 {
    5
}
fn default_max_triggers_per_tick() -> u32 {
    50
}

impl Default for CanonConfig {
    fn default() -> Self {
        Self {
            block_hash_interval: default_block_hash_interval(),
            tick_hash_interval: default_tick_hash_interval(),
            max_traversal_depth: default_max_traversal_depth(),
            scope_budget_default: default_scope_budget(),
            token_refill_per_tick: default_token_refill_per_tick(),
            max_tokens: default_max_tokens(),
            max_trigger_depth: default_max_trigger_depth(),
            max_triggers_per_event: default_max_triggers_per_event(),
            max_triggers_per_tick: default_max_triggers_per_tick(),
        }
    }
}

// =============================================================================
// §13  SCRIPTING CONFIG
// =============================================================================

/// Waymark scripting engine limits.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScriptingConfig {
    /// Maximum rune (trigger) definitions. Default: 256.
    #[serde(default = "default_max_runes")]
    pub max_runes: u32,

    /// Maximum omen (scheduled event) definitions. Default: 128.
    #[serde(default = "default_max_omens")]
    pub max_omens: u32,

    /// Maximum chapter definitions. Default: 64.
    #[serde(default = "default_max_chapters")]
    pub max_chapters: u32,

    /// Maximum dialogue definitions. Default: 64.
    #[serde(default = "default_max_dialogues")]
    pub max_dialogues: u32,

    /// Maximum vision (cutscene) definitions. Default: 32.
    #[serde(default = "default_max_visions")]
    pub max_visions: u32,

    /// Maximum gate (condition) definitions. Default: 64.
    #[serde(default = "default_max_gates")]
    pub max_gates: u32,

    /// Capacity of the fire-once set (prevents re-triggering). Default: 512.
    #[serde(default = "default_fire_once_capacity")]
    pub fire_once_capacity: u32,

    /// Whether meta-persistence (cross-session state) is enabled. Default: true.
    #[serde(default = "default_true")]
    pub meta_persistence_enabled: bool,

    /// Whether hot-reload of scripts is enabled (false in production). Default: false.
    #[serde(default)]
    pub hot_reload_enabled: bool,
}

fn default_max_runes() -> u32 {
    256
}
fn default_max_omens() -> u32 {
    128
}
fn default_max_chapters() -> u32 {
    64
}
fn default_max_dialogues() -> u32 {
    64
}
fn default_max_visions() -> u32 {
    32
}
fn default_max_gates() -> u32 {
    64
}
fn default_fire_once_capacity() -> u32 {
    512
}

impl Default for ScriptingConfig {
    fn default() -> Self {
        Self {
            max_runes: default_max_runes(),
            max_omens: default_max_omens(),
            max_chapters: default_max_chapters(),
            max_dialogues: default_max_dialogues(),
            max_visions: default_max_visions(),
            max_gates: default_max_gates(),
            fire_once_capacity: default_fire_once_capacity(),
            meta_persistence_enabled: true,
            hot_reload_enabled: false,
        }
    }
}

// =============================================================================
// §14  CONTENT CONFIG
// =============================================================================

/// Paths to content data files. All paths are relative to the pack root.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ContentConfig {
    /// Path to items definition file (e.g. "content/items.json").
    #[serde(default)]
    pub items_path: Option<String>,

    /// Path to enemies definition file (e.g. "content/enemies.json").
    #[serde(default)]
    pub enemies_path: Option<String>,

    /// Path to abilities definition file (e.g. "content/abilities.json").
    #[serde(default)]
    pub abilities_path: Option<String>,

    /// Path to loot tables definition file (e.g. "content/loot_tables.json").
    #[serde(default)]
    pub loot_tables_path: Option<String>,

    /// Path to economy/shops definition file (e.g. "content/economy.json").
    #[serde(default)]
    pub economy_path: Option<String>,

    /// Path to dialogue definition file (e.g. "content/dialogue.json").
    #[serde(default)]
    pub dialogue_path: Option<String>,

    /// Path to balance tuning file (e.g. "content/balance.json").
    #[serde(default)]
    pub balance_path: Option<String>,

    /// Path to stats/attributes definition file (e.g. "content/stats.json").
    #[serde(default)]
    pub stats_path: Option<String>,

    /// Path to scenario text/strings file (e.g. "content/scenario_text.json").
    #[serde(default)]
    pub scenario_text_path: Option<String>,

    /// Path to lore entries file (e.g. "content/lore.json").
    #[serde(default)]
    pub lore_path: Option<String>,

    /// Path to crafting recipes file (e.g. "content/crafting.json").
    #[serde(default)]
    pub crafting_path: Option<String>,

    /// Path to quest definitions file (e.g. "content/quests.json").
    #[serde(default)]
    pub quests_path: Option<String>,

    /// Path to factions definitions file (e.g. "content/factions.json").
    #[serde(default)]
    pub factions_path: Option<String>,

    /// Path to map templates directory (e.g. "maps/templates").
    #[serde(default)]
    pub maps_path: Option<String>,

    /// Path to texture pack file (e.g. "textures/pack.json").
    #[serde(default)]
    pub textures_path: Option<String>,
}

// =============================================================================
// §15  EVICTION CONFIG
// =============================================================================

/// Map eviction and caching parameters.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EvictionConfig {
    /// Maximum number of cached maps before eviction. Default: 20.
    #[serde(default = "default_max_cached")]
    pub max_cached: u32,

    /// Map IDs that are never evicted.
    #[serde(default)]
    pub keep_ids: Vec<String>,

    /// Map tags that are never evicted.
    #[serde(default)]
    pub keep_tags: Vec<String>,
}

fn default_max_cached() -> u32 {
    20
}

impl Default for EvictionConfig {
    fn default() -> Self {
        Self {
            max_cached: default_max_cached(),
            keep_ids: Vec::new(),
            keep_tags: Vec::new(),
        }
    }
}

// =============================================================================
// §16  PROP DEFINITION
// =============================================================================

/// A single state entry for a multi-state prop.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PropStateDef {
    /// Glyph displayed in this state.
    #[serde(default)]
    pub glyph: Option<String>,

    /// Whether the prop blocks movement in this state.
    #[serde(default)]
    pub blocking: Option<bool>,

    /// Whether entities can walk through in this state.
    #[serde(default)]
    pub walkthrough: Option<bool>,

    /// Description shown in this state.
    #[serde(default)]
    pub description: Option<String>,

    /// State to transition to on primary interact.
    #[serde(default)]
    pub on_interact: Option<String>,

    /// State to transition to on secondary interact.
    #[serde(default)]
    pub on_secondary_interact: Option<String>,

    /// Bump messages shown in this state.
    #[serde(default)]
    pub bump_messages: Vec<String>,
}

/// Prop definition. Props are interactive or decorative objects placed on maps.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PropDefinition {
    /// Unique prop identifier within the pack.
    pub id: String,

    /// Human-readable prop name.
    pub name: String,

    /// Prop description shown on examine.
    #[serde(default)]
    pub description: String,

    /// Extended look description.
    #[serde(default)]
    pub look_description: Option<String>,

    /// Display glyph (single character string or Unicode).
    #[serde(default)]
    pub glyph: Option<String>,

    /// Whether the prop blocks entity movement. Default: false.
    #[serde(default)]
    pub blocking: bool,

    /// Whether entities can walk through (overrides blocking for pathing). Default: false.
    #[serde(default)]
    pub walkthrough: bool,

    /// Whether the prop can be targeted by abilities. Default: false.
    #[serde(default)]
    pub targetable: bool,

    /// Whether the prop responds to interact actions. Default: false.
    #[serde(default)]
    pub interactive: bool,

    /// Whether the prop has multiple states. Default: false.
    #[serde(default)]
    pub has_secondary_state: bool,

    /// Default state name for multi-state props.
    #[serde(default)]
    pub default_state: Option<String>,

    /// Foley sound stub identifier.
    #[serde(default)]
    pub foley_stub_id: Option<String>,

    /// Messages shown when an entity bumps into this prop.
    #[serde(default)]
    pub bump_messages: Vec<String>,

    /// Whether this prop has an inventory. Default: false.
    #[serde(default)]
    pub has_inventory: bool,

    /// Maximum items this container can hold.
    #[serde(default)]
    pub container_capacity: Option<u32>,

    /// Loot table identifier for container drops.
    #[serde(default)]
    pub loot_table: Option<String>,

    /// State definitions for multi-state props. Key = state name.
    #[serde(default)]
    pub states: HashMap<String, PropStateDef>,
}

// =============================================================================
// §17  CHRONOBREAK CONFIG
// =============================================================================

/// Chronobreak (timeline fork and replay) parameters.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChronoshiftConfig {
    /// Whether chronoshift is enabled for this pack. Default: false.
    #[serde(default)]
    pub enabled: bool,

    /// Maximum checkpoint history depth. Default: 10.
    #[serde(default = "default_max_checkpoint_depth")]
    pub max_checkpoint_depth: u32,

    /// Replay speed multiplier. 1.0 = real time. Default: 1.0.
    #[serde(default = "default_replay_speed_multiplier")]
    pub replay_speed_multiplier: f64,

    /// Auto-checkpoint interval in ticks. 0 = disabled. Default: 0.
    #[serde(default)]
    pub auto_checkpoint_interval_ticks: u64,

    /// Maximum concurrent timeline forks. Default: 4.
    #[serde(default = "default_max_fork_count")]
    pub max_fork_count: u32,

    /// Maximum compute budget percentage allocated to forks. Default: 25.
    #[serde(default = "default_fork_compute_cap_pct")]
    pub fork_compute_cap_pct: u32,
}

fn default_max_checkpoint_depth() -> u32 {
    10
}
fn default_replay_speed_multiplier() -> f64 {
    1.0
}
fn default_max_fork_count() -> u32 {
    4
}
fn default_fork_compute_cap_pct() -> u32 {
    25
}

impl Default for ChronoshiftConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            max_checkpoint_depth: default_max_checkpoint_depth(),
            replay_speed_multiplier: default_replay_speed_multiplier(),
            auto_checkpoint_interval_ticks: 0,
            max_fork_count: default_max_fork_count(),
            fork_compute_cap_pct: default_fork_compute_cap_pct(),
        }
    }
}

// =============================================================================
// §18  FORENSICS CONFIG
// =============================================================================

/// Forensics and proof lane parameters.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ForensicsConfig {
    /// Whether the proof lane is enabled. Default: false.
    #[serde(default)]
    pub proof_lane_enabled: bool,

    /// Whether BLAKE3 domain separation is used for hashing. Default: true.
    #[serde(default = "default_true")]
    pub blake3_domain_separation: bool,

    /// Whether Merkle state root computation is enabled. Default: false.
    #[serde(default)]
    pub merkle_state_root_enabled: bool,

    /// Whether Ed25519 signing of canon events is enabled. Default: false.
    #[serde(default)]
    pub ed25519_signing_enabled: bool,

    /// Whether public audit tables are exposed. Default: false.
    #[serde(default)]
    pub public_audit_tables: bool,
}

impl Default for ForensicsConfig {
    fn default() -> Self {
        Self {
            proof_lane_enabled: false,
            blake3_domain_separation: true,
            merkle_state_root_enabled: false,
            ed25519_signing_enabled: false,
            public_audit_tables: false,
        }
    }
}

// =============================================================================
// §19a  PHYSICS CONFIG
// =============================================================================

/// Physics environment parameters for pack-driven worlds.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PhysicsConfig {
    /// Planetary gravity acceleration. Default: 9.81.
    #[serde(default = "default_gravity_planetary")]
    pub gravity_planetary: f32,

    /// Local gravity override (if set, overrides planetary at region level).
    #[serde(default)]
    pub gravity_local: Option<f32>,

    /// Atmospheric density multiplier. Default: 1.0.
    #[serde(default = "default_atmosphere_density")]
    pub atmosphere_density: f32,

    /// Ambient temperature in Celsius. Default: 20.0.
    #[serde(default = "default_temperature_ambient")]
    pub temperature_ambient: f32,

    /// Emitter preset IDs to pre-load.
    #[serde(default)]
    pub emitter_presets: Vec<String>,

    /// Force field configurations.
    #[serde(default)]
    pub force_fields: Vec<ForceFieldConfig>,

    /// Collision plane configurations.
    #[serde(default)]
    pub collision_planes: Vec<CollisionPlaneConfig>,
}

/// Force field configuration for pack-driven physics.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ForceFieldConfig {
    /// Force field kind identifier.
    pub kind: String,

    /// Position in world space.
    #[serde(default)]
    pub position: [f32; 3],

    /// Field strength. Default: 9.81.
    #[serde(default = "default_ff_strength")]
    pub strength: f32,

    /// Field radius. Default: 100.0.
    #[serde(default = "default_ff_radius")]
    pub radius: f32,
}

/// Collision plane configuration for pack-driven physics.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CollisionPlaneConfig {
    /// Plane normal vector. Default: [0, 1, 0] (up).
    #[serde(default = "default_plane_normal")]
    pub normal: [f32; 3],

    /// Plane offset from origin. Default: 0.0.
    #[serde(default)]
    pub offset: f32,

    /// Coefficient of restitution (bounciness). Default: 0.5.
    #[serde(default = "default_restitution")]
    pub restitution: f32,
}

fn default_gravity_planetary() -> f32 {
    9.81
}
fn default_atmosphere_density() -> f32 {
    1.0
}
fn default_temperature_ambient() -> f32 {
    20.0
}
fn default_ff_strength() -> f32 {
    9.81
}
fn default_ff_radius() -> f32 {
    100.0
}
fn default_plane_normal() -> [f32; 3] {
    [0.0, 1.0, 0.0]
}
fn default_restitution() -> f32 {
    0.5
}

impl Default for PhysicsConfig {
    fn default() -> Self {
        Self {
            gravity_planetary: default_gravity_planetary(),
            gravity_local: None,
            atmosphere_density: default_atmosphere_density(),
            temperature_ambient: default_temperature_ambient(),
            emitter_presets: Vec::new(),
            force_fields: Vec::new(),
            collision_planes: Vec::new(),
        }
    }
}

// =============================================================================
// §18b  GPU PIPELINE CONFIG (v1.0.0)
// =============================================================================

/// Meshlet LOD configuration for GPU-driven rendering.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MeshletLodConfig {
    /// Maximum meshlets per object. Default: 1024.
    #[serde(default = "default_max_meshlets_per_object")]
    pub max_meshlets_per_object: u32,
    /// LOD distance thresholds (world units).
    #[serde(default)]
    pub lod_distances: Vec<f32>,
    /// Maximum vertices per meshlet. Default: 64.
    #[serde(default = "default_max_vertices_per_meshlet")]
    pub max_vertices_per_meshlet: u32,
    /// Maximum triangles per meshlet. Default: 126.
    #[serde(default = "default_max_triangles_per_meshlet")]
    pub max_triangles_per_meshlet: u32,
}

fn default_max_meshlets_per_object() -> u32 {
    1024
}
fn default_max_vertices_per_meshlet() -> u32 {
    64
}
fn default_max_triangles_per_meshlet() -> u32 {
    126
}

impl Default for MeshletLodConfig {
    fn default() -> Self {
        Self {
            max_meshlets_per_object: default_max_meshlets_per_object(),
            lod_distances: vec![50.0, 100.0, 200.0],
            max_vertices_per_meshlet: default_max_vertices_per_meshlet(),
            max_triangles_per_meshlet: default_max_triangles_per_meshlet(),
        }
    }
}

/// Meshlet emission configuration for DreamMatter integration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MeshletEmissionConfig {
    /// Maximum particles per emitter. Default: 1024.
    #[serde(default = "default_max_particles_per_emitter")]
    pub max_particles_per_emitter: u32,
    /// Default particle lifetime in seconds.
    #[serde(default = "default_particle_lifetime")]
    pub default_lifetime: f32,
    /// Default emission rate (particles/sec).
    #[serde(default = "default_emission_rate")]
    pub default_emission_rate: f32,
}

fn default_max_particles_per_emitter() -> u32 {
    1024
}
fn default_particle_lifetime() -> f32 {
    2.0
}
fn default_emission_rate() -> f32 {
    100.0
}

impl Default for MeshletEmissionConfig {
    fn default() -> Self {
        Self {
            max_particles_per_emitter: default_max_particles_per_emitter(),
            default_lifetime: default_particle_lifetime(),
            default_emission_rate: default_emission_rate(),
        }
    }
}

/// Observer configuration for Quantum Culling.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WaymarkObserverConfig {
    /// Default FOV radius in cells. Default: 10.
    #[serde(default = "default_fov_radius")]
    pub default_fov_radius: i32,
    /// Default topology layer for the observer. Default: "area".
    #[serde(default = "default_observer_layer")]
    pub default_layer: String,
}

fn default_fov_radius() -> i32 {
    10
}
fn default_observer_layer() -> String {
    "area".into()
}

impl Default for WaymarkObserverConfig {
    fn default() -> Self {
        Self {
            default_fov_radius: default_fov_radius(),
            default_layer: default_observer_layer(),
        }
    }
}

/// Promotion target for DreamMatter → server authority handoff.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WaymarkPromotionTarget {
    /// Kind identifier for the promotion event.
    pub kind: String,
    /// Entity type to create on promotion.
    pub entity_type: String,
    /// Minimum age before promotion (seconds).
    #[serde(default)]
    pub min_age: f32,
}

/// Mesh source config for FBX/GLTF/primitive references in packs.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MeshSourceConfig {
    /// Built-in primitive type (e.g., "Cube", "Sphere"). Mutually exclusive with paths.
    #[serde(default)]
    pub primitive_type: Option<String>,
    /// Path to FBX binary file (relative to pack root).
    #[serde(default)]
    pub fbx_path: Option<String>,
    /// Path to GLTF file (relative to pack root).
    #[serde(default)]
    pub gltf_path: Option<String>,
    /// Topology layers this mesh is active on.
    #[serde(default)]
    pub active_layers: Vec<u32>,
}

// =============================================================================
// §19  TOPOLOGY CONFIG
// =============================================================================

/// 9-layer topology configuration for the Dreamwell spatial hierarchy.
///
/// Layers (0-9): Universe → Galaxy → Sector → World → Realm → Region →
/// Area → Location → Room → Point.
///
/// If omitted, the seed pipeline creates a minimal 1-of-each hierarchy.
/// Each layer entry defines the initial topology entities to create.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TopologyConfig {
    /// Universe name. Defaults to pack title.
    #[serde(default)]
    pub universe_name: Option<String>,

    /// Galaxy definitions. If empty, one galaxy is auto-created.
    #[serde(default)]
    pub galaxies: Vec<GalaxyDef>,

    /// Sector definitions. If empty, one sector per galaxy is auto-created.
    #[serde(default)]
    pub sectors: Vec<SectorDef>,

    /// World definitions. If empty, one world is created from pack identity.
    #[serde(default)]
    pub worlds: Vec<WorldDef>,

    /// Realm definitions per world. If empty, one realm per world.
    #[serde(default)]
    pub realms: Vec<RealmDef>,

    /// Region definitions per realm. If empty, one region per realm.
    #[serde(default)]
    pub regions: Vec<RegionDef>,

    /// Area definitions per region. If empty, one area per region.
    #[serde(default)]
    pub areas: Vec<AreaDef>,

    /// Location definitions per area.
    #[serde(default)]
    pub locations: Vec<LocationDef>,

    /// Point definitions (POI/AOI spawn markers).
    #[serde(default)]
    pub points: Vec<PointDef>,
}

/// Galaxy definition for topology seeding.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GalaxyDef {
    pub id: String,
    pub name: String,
    #[serde(default)]
    pub kind: String,
}

/// Sector definition for topology seeding.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SectorDef {
    pub id: String,
    pub galaxy_id: String,
    pub name: String,
    #[serde(default)]
    pub governing_entity_id: String,
}

/// World definition for topology seeding.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorldDef {
    pub id: String,
    #[serde(default)]
    pub sector_id: String,
    pub name: String,
    #[serde(default)]
    pub theme: String,
}

/// Realm definition for topology seeding.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RealmDef {
    pub id: String,
    pub world_id: String,
    pub name: String,
}

/// Region definition for topology seeding.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegionDef {
    pub id: String,
    pub realm_id: String,
    pub name: String,
    #[serde(default = "default_pressure")]
    pub pressure_security: i32,
    #[serde(default = "default_pressure")]
    pub pressure_scarcity: i32,
    #[serde(default = "default_pressure")]
    pub pressure_unrest: i32,
    #[serde(default = "default_pressure")]
    pub pressure_anomaly: i32,
}

fn default_pressure() -> i32 {
    25
}

/// Area definition for topology seeding.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AreaDef {
    pub id: String,
    pub region_id: String,
    pub name: String,
    #[serde(default)]
    pub kind: String,
    #[serde(default = "default_danger")]
    pub danger_rating: i32,
}

fn default_danger() -> i32 {
    1
}

/// Location definition for topology seeding.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LocationDef {
    pub id: String,
    pub area_id: String,
    pub name: String,
    #[serde(default)]
    pub kind: String,
    #[serde(default)]
    pub x: i32,
    #[serde(default)]
    pub y: i32,
}

/// Point definition (POI/AOI markers) for topology seeding.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PointDef {
    pub id: String,
    #[serde(default)]
    pub location_id: String,
    #[serde(default)]
    pub room_id: String,
    #[serde(default)]
    pub x: i32,
    #[serde(default)]
    pub y: i32,
    #[serde(default)]
    pub kind: String,
    #[serde(default)]
    pub label: String,
    #[serde(default)]
    pub trigger_id: String,
    #[serde(default)]
    pub template_id: String,
}

// =============================================================================
// §20  DEFAULT IMPLEMENTATION — DreamwellPackV1
// =============================================================================

impl Default for DreamwellPackV1 {
    fn default() -> Self {
        Self {
            id: String::new(),
            title: String::new(),
            version: String::new(),
            description: String::new(),
            schema_version: default_schema_version(),
            tags: Vec::new(),
            world_id: None,
            theme: None,
            scenario: None,
            scenario_script: None,
            starting_map: None,
            grid: GridConfig::default(),
            spatial: SpatialConfig::default(),
            display: DisplayConfig::default(),
            features: FeatureFlags::default(),
            equip_slots: Vec::new(),
            simulation: SimulationConfig::default(),
            combat: CombatConfig::default(),
            economy: EconomyConfig::default(),
            progression: ProgressionConfig::default(),
            agents: AgentConfig::default(),
            tiles: TileConfig::default(),
            canon: CanonConfig::default(),
            scripting: ScriptingConfig::default(),
            content: ContentConfig::default(),
            eviction: EvictionConfig::default(),
            props: Vec::new(),
            generators: serde_json::Value::Null,
            connection_type_props: HashMap::new(),
            boon_triggers: Vec::new(),
            uses_companion_services: false,
            scenario_config: serde_json::Value::Null,
            encumbrance: None,
            ai_brains: HashMap::new(),
            rules: None,
            identity: None,
            boot_sequence: None,
            topology: TopologyConfig::default(),
            chronoshift: ChronoshiftConfig::default(),
            forensics: ForensicsConfig::default(),
            physics: PhysicsConfig::default(),
            meshlet_lod: None,
            meshlet_emission: None,
            observer_config: None,
            promotion_targets: Vec::new(),
            avatar_defaults: None,
        }
    }
}

// =============================================================================
// §20  METHODS — Parsing, Serialization, Validation, Migration
// =============================================================================

impl DreamwellPackV1 {
    /// Parse a JSON string into a DreamwellPackV1.
    ///
    /// Accepts both v1.0.0 format and legacy pack.json format. Missing fields
    /// receive their default values via serde defaults.
    pub fn from_json(json: &str) -> Result<Self, String> {
        serde_json::from_str::<Self>(json).map_err(|e| format!("pack_parse_error: {}", e))
    }

    /// Serialize this pack to a pretty-printed JSON string.
    pub fn to_json(&self) -> String {
        serde_json::to_string_pretty(self).unwrap_or_else(|e| format!("{{\"error\": \"{}\"}}", e))
    }

    /// Validate the pack configuration. Returns a list of validation errors.
    /// An empty list means the pack is valid.
    pub fn validate(&self) -> Vec<String> {
        let mut errors = Vec::new();

        // -- Identity --
        if self.id.is_empty() {
            errors.push("id_required: pack id must be non-empty".to_string());
        } else if self.id.len() > 128 {
            errors.push(format!("id_too_long: {} chars (max 128)", self.id.len()));
        } else if !self
            .id
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
        {
            errors.push("id_invalid_chars: pack id must contain only [a-zA-Z0-9_-]".to_string());
        }

        if self.title.is_empty() {
            errors.push("title_required: pack title must be non-empty".to_string());
        } else if self.title.len() > 256 {
            errors.push(format!("title_too_long: {} chars (max 256)", self.title.len()));
        }

        if self.description.len() > 4096 {
            errors.push(format!(
                "description_too_long: {} chars (max 4096)",
                self.description.len()
            ));
        }

        // -- Grid --
        if self.grid.width == 0 {
            errors.push("grid_width_zero: width must be > 0".to_string());
        }
        if self.grid.height == 0 {
            errors.push("grid_height_zero: height must be > 0".to_string());
        }
        if self.grid.width > 4096 {
            errors.push(format!("grid_width_too_large: {} (max 4096)", self.grid.width));
        }
        if self.grid.height > 4096 {
            errors.push(format!("grid_height_too_large: {} (max 4096)", self.grid.height));
        }
        if self.grid.chunk_size == 0 || !self.grid.chunk_size.is_power_of_two() {
            errors.push(format!(
                "grid_chunk_size_invalid: {} (must be a non-zero power of two)",
                self.grid.chunk_size
            ));
        }

        // -- Spatial --
        if self.spatial.cell_size <= 0 {
            errors.push(format!(
                "spatial_cell_size_invalid: {} (must be > 0)",
                self.spatial.cell_size
            ));
        }
        if self.spatial.fov_default_radius < 0 {
            errors.push(format!(
                "spatial_fov_default_radius_negative: {}",
                self.spatial.fov_default_radius
            ));
        }
        if self.spatial.fov_max_radius < self.spatial.fov_default_radius {
            errors.push(format!(
                "spatial_fov_max_radius_less_than_default: max={} default={}",
                self.spatial.fov_max_radius, self.spatial.fov_default_radius
            ));
        }
        if self.spatial.max_pathfind_steps == 0 {
            errors.push("spatial_max_pathfind_steps_zero".to_string());
        }

        // -- Simulation --
        if self.simulation.tick_rate_ms == 0 {
            errors.push("simulation_tick_rate_ms_zero".to_string());
        }
        if self.simulation.ticks_per_day == 0 {
            errors.push("simulation_ticks_per_day_zero".to_string());
        }
        if self.simulation.time_dilation <= 0.0 {
            errors.push(format!(
                "simulation_time_dilation_invalid: {} (must be > 0.0)",
                self.simulation.time_dilation
            ));
        }
        if self.simulation.max_entities_per_area == 0 {
            errors.push("simulation_max_entities_per_area_zero".to_string());
        }
        if self.simulation.max_events_per_tick == 0 {
            errors.push("simulation_max_events_per_tick_zero".to_string());
        }

        // -- Combat --
        if self.combat.base_hit_chance > 100 {
            errors.push(format!(
                "combat_base_hit_chance_out_of_range: {} (max 100)",
                self.combat.base_hit_chance
            ));
        }
        if self.combat.crit_multiplier < 1.0 {
            errors.push(format!(
                "combat_crit_multiplier_too_low: {} (min 1.0)",
                self.combat.crit_multiplier
            ));
        }
        if self.combat.dodge_base > 100 {
            errors.push(format!(
                "combat_dodge_base_out_of_range: {} (max 100)",
                self.combat.dodge_base
            ));
        }
        if self.combat.parry_base > 100 {
            errors.push(format!(
                "combat_parry_base_out_of_range: {} (max 100)",
                self.combat.parry_base
            ));
        }
        if self.combat.flee_threshold_hp_pct > 100 {
            errors.push(format!(
                "combat_flee_threshold_hp_pct_out_of_range: {} (max 100)",
                self.combat.flee_threshold_hp_pct
            ));
        }
        if self.combat.revive_hp_pct > 100 {
            errors.push(format!(
                "combat_revive_hp_pct_out_of_range: {} (max 100)",
                self.combat.revive_hp_pct
            ));
        }
        if self.combat.resistance_cap > 100 {
            errors.push(format!(
                "combat_resistance_cap_out_of_range: {} (max 100)",
                self.combat.resistance_cap
            ));
        }

        // -- Economy --
        if self.economy.trade_tax_pct > 100 {
            errors.push(format!(
                "economy_trade_tax_pct_out_of_range: {} (max 100)",
                self.economy.trade_tax_pct
            ));
        }
        if self.economy.market_fee_pct > 100 {
            errors.push(format!(
                "economy_market_fee_pct_out_of_range: {} (max 100)",
                self.economy.market_fee_pct
            ));
        }
        if self.economy.crafting_fail_chance_base > 100 {
            errors.push(format!(
                "economy_crafting_fail_chance_base_out_of_range: {} (max 100)",
                self.economy.crafting_fail_chance_base
            ));
        }

        // -- Progression --
        if self.progression.max_level == 0 {
            errors.push("progression_max_level_zero".to_string());
        }
        if self.progression.xp_curve_base <= 0.0 {
            errors.push(format!(
                "progression_xp_curve_base_invalid: {} (must be > 0.0)",
                self.progression.xp_curve_base
            ));
        }
        if self.progression.reputation_min > self.progression.reputation_max {
            errors.push(format!(
                "progression_reputation_range_inverted: min={} max={}",
                self.progression.reputation_min, self.progression.reputation_max
            ));
        }

        // -- Agents --
        if self.agents.cognition_budget_per_tick == 0 {
            errors.push("agents_cognition_budget_per_tick_zero".to_string());
        }
        if self.agents.perception_range == 0 {
            errors.push("agents_perception_range_zero".to_string());
        }
        if self.agents.memory_capacity == 0 {
            errors.push("agents_memory_capacity_zero".to_string());
        }
        if self.agents.inference_timeout_ms == 0 {
            errors.push("agents_inference_timeout_ms_zero".to_string());
        }
        if self.agents.inference_max_tokens == 0 {
            errors.push("agents_inference_max_tokens_zero".to_string());
        }

        // -- Canon --
        if self.canon.block_hash_interval == 0 {
            errors.push("canon_block_hash_interval_zero".to_string());
        }
        if self.canon.tick_hash_interval == 0 {
            errors.push("canon_tick_hash_interval_zero".to_string());
        }
        if self.canon.max_traversal_depth == 0 {
            errors.push("canon_max_traversal_depth_zero".to_string());
        }

        // -- Scripting --
        if self.scripting.max_runes == 0 {
            errors.push("scripting_max_runes_zero".to_string());
        }
        if self.scripting.fire_once_capacity == 0 {
            errors.push("scripting_fire_once_capacity_zero".to_string());
        }

        // -- Chronobreak --
        if self.chronoshift.enabled {
            if self.chronoshift.max_checkpoint_depth == 0 {
                errors.push("chronoshift_max_checkpoint_depth_zero".to_string());
            }
            if self.chronoshift.replay_speed_multiplier <= 0.0 {
                errors.push(format!(
                    "chronoshift_replay_speed_multiplier_invalid: {} (must be > 0.0)",
                    self.chronoshift.replay_speed_multiplier
                ));
            }
            if self.chronoshift.max_fork_count == 0 {
                errors.push("chronoshift_max_fork_count_zero".to_string());
            }
            if self.chronoshift.fork_compute_cap_pct > 100 {
                errors.push(format!(
                    "chronoshift_fork_compute_cap_pct_out_of_range: {} (max 100)",
                    self.chronoshift.fork_compute_cap_pct
                ));
            }
        }

        // -- Props --
        let mut prop_ids = std::collections::HashSet::new();
        for (i, prop) in self.props.iter().enumerate() {
            if prop.id.is_empty() {
                errors.push(format!("prop[{}]_id_required", i));
            } else if !prop_ids.insert(&prop.id) {
                errors.push(format!("prop_id_duplicate: \"{}\"", prop.id));
            }
            if prop.name.is_empty() {
                errors.push(format!("prop[{}]_name_required (id: \"{}\")", i, prop.id));
            }
            if prop.has_secondary_state && prop.states.is_empty() {
                errors.push(format!("prop_has_secondary_state_but_no_states: \"{}\"", prop.id));
            }
            if let Some(ref default_state) = prop.default_state {
                if prop.has_secondary_state && !prop.states.contains_key(default_state) {
                    errors.push(format!(
                        "prop_default_state_not_found: \"{}\" state \"{}\"",
                        prop.id, default_state
                    ));
                }
            }
            if prop.has_inventory && (prop.container_capacity.is_none() || prop.container_capacity == Some(0)) {
                errors.push(format!("prop_has_inventory_but_no_capacity: \"{}\"", prop.id));
            }
        }

        errors
    }

    /// Detect whether a JSON value is in the legacy pack.json format
    /// (pre-v1.0.0, no `schema_version` field).
    pub fn is_legacy_format(json: &serde_json::Value) -> bool {
        if let Some(obj) = json.as_object() {
            // Legacy format: has "id" but no "schema_version" field.
            obj.contains_key("id") && !obj.contains_key("schema_version")
        } else {
            false
        }
    }

    /// Migrate a legacy pack.json value into the v1.0.0 schema.
    ///
    /// Legacy fields are mapped directly since the v1.0.0 struct is a superset
    /// of the legacy format. The `schema_version` field is injected and the
    /// result is deserialized through the normal path.
    pub fn migrate_legacy(json: &serde_json::Value) -> Result<Self, String> {
        let obj = json
            .as_object()
            .ok_or_else(|| "migrate_legacy_error: expected JSON object".to_string())?;

        let mut migrated = obj.clone();

        // Inject schema version.
        migrated.insert(
            "schema_version".to_string(),
            serde_json::Value::String(SCHEMA_VERSION.to_string()),
        );

        let json_str =
            serde_json::to_string(&migrated).map_err(|e| format!("migrate_legacy_serialize_error: {}", e))?;

        Self::from_json(&json_str)
    }
}

// =============================================================================
// §21  TESTS
// =============================================================================

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

    #[test]
    fn default_pack_has_schema_version() {
        let pack = DreamwellPackV1::default();
        assert_eq!(pack.schema_version, SCHEMA_VERSION);
    }

    #[test]
    fn default_pack_validation_requires_id_and_title() {
        let pack = DreamwellPackV1::default();
        let errors = pack.validate();
        assert!(errors.iter().any(|e| e.contains("id_required")));
        assert!(errors.iter().any(|e| e.contains("title_required")));
    }

    #[test]
    fn minimal_valid_pack() {
        let json = r#"{"id": "test_pack", "title": "Test Pack"}"#;
        let pack = DreamwellPackV1::from_json(json).unwrap();
        assert_eq!(pack.id, "test_pack");
        assert_eq!(pack.title, "Test Pack");
        assert_eq!(pack.schema_version, SCHEMA_VERSION);
        assert_eq!(pack.grid.width, 80);
        assert_eq!(pack.grid.height, 50);
        assert_eq!(pack.grid.chunk_size, 32);
        assert_eq!(pack.spatial.cell_size, 128);
        assert_eq!(pack.combat.base_hit_chance, 80);
        assert_eq!(pack.economy.starting_gold, 100);
        assert!(pack.validate().is_empty());
    }

    #[test]
    fn roundtrip_serialization() {
        let json = r#"{"id": "roundtrip", "title": "Roundtrip Test"}"#;
        let pack = DreamwellPackV1::from_json(json).unwrap();
        let serialized = pack.to_json();
        let reparsed = DreamwellPackV1::from_json(&serialized).unwrap();
        assert_eq!(reparsed.id, "roundtrip");
        assert_eq!(reparsed.grid.width, 80);
        assert_eq!(reparsed.combat.crit_multiplier, 2.0);
    }

    #[test]
    fn legacy_format_detection() {
        let legacy: serde_json::Value =
            serde_json::from_str(r#"{"id": "arena", "title": "Training Arena", "grid": {"width": 32, "height": 16}}"#)
                .unwrap();
        assert!(DreamwellPackV1::is_legacy_format(&legacy));

        let v1: serde_json::Value = serde_json::from_str(
            r#"{"id": "arena", "title": "Training Arena", "schema_version": "dreamwell_waymark_v1.0.0"}"#,
        )
        .unwrap();
        assert!(!DreamwellPackV1::is_legacy_format(&v1));
    }

    #[test]
    fn legacy_migration() {
        let legacy: serde_json::Value = serde_json::from_str(
            r#"{
                "id": "arena",
                "title": "Training Arena",
                "version": "0.1.0",
                "grid": {"width": 32, "height": 16},
                "features": {"content_plan": false, "boons": false}
            }"#,
        )
        .unwrap();

        let pack = DreamwellPackV1::migrate_legacy(&legacy).unwrap();
        assert_eq!(pack.id, "arena");
        assert_eq!(pack.schema_version, SCHEMA_VERSION);
        assert_eq!(pack.grid.width, 32);
        assert_eq!(pack.grid.height, 16);
        assert!(!pack.features.content_plan);
        assert!(!pack.features.boons);
        // Defaults applied for missing fields.
        assert_eq!(pack.combat.base_hit_chance, 80);
        assert_eq!(pack.spatial.cell_size, 128);
    }

    #[test]
    fn legacy_ayora_pack_loads() {
        let json = r#"{
            "id": "ayora",
            "title": "Ayora: The Barracks",
            "scenario_script": "scenario/main.wm",
            "uses_companion_services": true,
            "scenario_config": {
                "companion_ids": ["kael", "ryn", "senna"],
                "boss_npc_id": "grimsby"
            },
            "version": "0.1.0",
            "grid": {"width": 120, "height": 80},
            "display": {"mana_name": "Grace"},
            "features": {"content_plan": false, "boons": false, "shrines": false},
            "equip_slots": ["Head", "Body", "Hands", "Feet", "Weapon", "Offhand"],
            "boon_triggers": [{"id": "pool_room_5", "type": "RoomEntry"}],
            "props": [
                {
                    "id": "weapon_rack",
                    "name": "Weapon Rack",
                    "glyph": "\u2551",
                    "description": "A training weapon rests in the rack.",
                    "blocking": true,
                    "targetable": true,
                    "interactive": false,
                    "bump_messages": ["The rack is bolted to the wall."]
                }
            ]
        }"#;

        let pack = DreamwellPackV1::from_json(json).unwrap();
        assert_eq!(pack.id, "ayora");
        assert_eq!(pack.grid.width, 120);
        assert_eq!(pack.grid.height, 80);
        assert_eq!(pack.display.mana_name, "Grace");
        assert!(pack.uses_companion_services);
        assert_eq!(pack.equip_slots.len(), 6);
        assert_eq!(pack.props.len(), 1);
        assert_eq!(pack.props[0].id, "weapon_rack");
        assert!(pack.validate().is_empty());
    }

    #[test]
    fn legacy_embersteel_pack_loads() {
        let json = r#"{
            "id": "embersteel",
            "title": "Operation: Embersteel",
            "description": "Restore an abandoned research outpost.",
            "world_id": "world:braxxis:v1",
            "theme": "SURVIVAL",
            "version": "1.0.0",
            "tags": ["ascii", "roguelike", "survival"],
            "ai_brains": {
                "passive_roamer": {"base_brain": "state_machine", "profile": "passive_roamer"}
            },
            "starting_map": "olympus_9",
            "scenario_script": "scenario/main.wm",
            "grid": {"width": 80, "height": 55},
            "features": {"containers": true, "line_of_sight": true, "collisions": true, "identity_system": true},
            "rules": {"tick_rate_hz": 20, "determinism": "STRICT"},
            "identity": {"format": "{glyph}#{suffix}"},
            "boot_sequence": {"lines": ["[INFO] Signal Received"]},
            "generators": {
                "olympus_9": {"generator_type": "template", "template": "olympus_9"}
            },
            "props": [
                {"id": "printer", "name": "Bioprinter", "glyph": "P", "description": "Still warm.", "blocking": true, "targetable": true, "interactive": true}
            ]
        }"#;

        let pack = DreamwellPackV1::from_json(json).unwrap();
        assert_eq!(pack.id, "embersteel");
        assert_eq!(pack.world_id, Some("world:braxxis:v1".to_string()));
        assert_eq!(pack.theme, Some("SURVIVAL".to_string()));
        assert!(pack.features.containers);
        assert!(pack.features.identity_system);
        assert!(pack.features.line_of_sight);
        assert_eq!(pack.ai_brains.len(), 1);
        assert!(pack.rules.is_some());
        assert!(pack.identity.is_some());
        assert!(pack.boot_sequence.is_some());
        assert!(pack.validate().is_empty());
    }

    #[test]
    fn tile_defaults_match_tile_rs() {
        let tiles = TileConfig::default();
        assert_eq!(tiles.ground.glyph, b'.' as u16);
        assert_eq!(tiles.dirt.glyph, b',' as u16);
        assert_eq!(tiles.sand.glyph, b':' as u16);
        assert_eq!(tiles.mud.glyph, b'`' as u16);
        assert_eq!(tiles.liquid.glyph, b'~' as u16);
        assert_eq!(tiles.deep_water.glyph, b'=' as u16);
        assert_eq!(tiles.rocky_ground.glyph, b'b' as u16);
        assert_eq!(tiles.grass.glyph, b';' as u16);
        assert_eq!(tiles.debris.glyph, b'\'' as u16);
        assert_eq!(tiles.wall.glyph, b'#' as u16);
        assert_eq!(tiles.wall_vert.glyph, b'|' as u16);
        assert_eq!(tiles.wall_horiz.glyph, b'_' as u16);
        assert_eq!(tiles.door_closed.glyph, b'I' as u16);
        assert_eq!(tiles.door_open.glyph, b'*' as u16);
        assert_eq!(tiles.stairs_up.glyph, b'^' as u16);
        assert_eq!(tiles.stairs_down.glyph, b'v' as u16);
        assert_eq!(tiles.boulder.glyph, b'o' as u16);
        assert_eq!(tiles.chest.glyph, b'C' as u16);
        assert_eq!(tiles.shrine.glyph, b'S' as u16);
        assert_eq!(tiles.hazard.glyph, b'x' as u16);
        assert_eq!(tiles.smoke.glyph, b'%' as u16);

        // Movement costs match tile.rs move_cost()
        assert_eq!(tiles.ground.move_cost, 1);
        assert_eq!(tiles.sand.move_cost, 2);
        assert_eq!(tiles.liquid.move_cost, 3);
        assert_eq!(tiles.wall.move_cost, 999);

        // Blocking rules match tile.rs blocks_move()
        assert!(tiles.wall.blocks_move);
        assert!(tiles.door_closed.blocks_move);
        assert!(tiles.deep_water.blocks_move);
        assert!(tiles.boulder.blocks_move);
        assert!(!tiles.ground.blocks_move);
        assert!(!tiles.liquid.blocks_move);

        // Sight blocking matches tile.rs blocks_sight()
        assert!(tiles.wall.blocks_sight);
        assert!(tiles.door_closed.blocks_sight);
        assert!(tiles.boulder.blocks_sight);
        assert!(tiles.smoke.blocks_sight);
        assert!(!tiles.ground.blocks_sight);
        assert!(!tiles.deep_water.blocks_sight);
    }

    #[test]
    fn prop_validation_catches_duplicates() {
        let json = r#"{
            "id": "test",
            "title": "Test",
            "props": [
                {"id": "p1", "name": "Prop One"},
                {"id": "p1", "name": "Prop One Dupe"}
            ]
        }"#;
        let pack = DreamwellPackV1::from_json(json).unwrap();
        let errors = pack.validate();
        assert!(errors.iter().any(|e| e.contains("prop_id_duplicate")));
    }

    #[test]
    fn prop_validation_catches_state_mismatch() {
        let json = r#"{
            "id": "test",
            "title": "Test",
            "props": [
                {
                    "id": "broken",
                    "name": "Broken Prop",
                    "has_secondary_state": true,
                    "default_state": "missing_state"
                }
            ]
        }"#;
        let pack = DreamwellPackV1::from_json(json).unwrap();
        let errors = pack.validate();
        assert!(errors.iter().any(|e| e.contains("has_secondary_state_but_no_states")));
        assert!(errors.iter().any(|e| e.contains("default_state_not_found")));
    }

    #[test]
    fn combat_range_validation() {
        let json = r#"{
            "id": "test",
            "title": "Test",
            "combat": {"base_hit_chance": 150, "dodge_base": 101, "resistance_cap": 200}
        }"#;
        let pack = DreamwellPackV1::from_json(json).unwrap();
        let errors = pack.validate();
        assert!(errors.iter().any(|e| e.contains("base_hit_chance_out_of_range")));
        assert!(errors.iter().any(|e| e.contains("dodge_base_out_of_range")));
        assert!(errors.iter().any(|e| e.contains("resistance_cap_out_of_range")));
    }

    #[test]
    fn v1_full_config_loads() {
        let json = r#"{
            "id": "full",
            "title": "Full Config",
            "schema_version": "dreamwell_waymark_v1.0.0",
            "simulation": {"tick_rate_ms": 50, "ticks_per_day": 720, "time_dilation": 2.0},
            "combat": {"base_hit_chance": 75, "crit_multiplier": 2.5, "damage_types": ["physical", "fire"]},
            "economy": {"starting_gold": 500, "currency_types": ["gold", "silver"]},
            "progression": {"max_level": 50, "xp_curve_base": 1.8},
            "agents": {"cognition_budget_per_tick": 5, "max_concurrent_agents": 128},
            "canon": {"block_hash_interval": 200, "max_trigger_depth": 5},
            "scripting": {"max_runes": 512, "hot_reload_enabled": true},
            "chronoshift": {"enabled": true, "max_fork_count": 8},
            "forensics": {"proof_lane_enabled": true, "blake3_domain_separation": true}
        }"#;
        let pack = DreamwellPackV1::from_json(json).unwrap();
        assert_eq!(pack.simulation.tick_rate_ms, 50);
        assert_eq!(pack.simulation.ticks_per_day, 720);
        assert_eq!(pack.combat.base_hit_chance, 75);
        assert_eq!(pack.combat.damage_types.len(), 2);
        assert_eq!(pack.economy.starting_gold, 500);
        assert_eq!(pack.economy.currency_types.len(), 2);
        assert_eq!(pack.progression.max_level, 50);
        assert_eq!(pack.agents.max_concurrent_agents, 128);
        assert_eq!(pack.canon.block_hash_interval, 200);
        assert_eq!(pack.scripting.max_runes, 512);
        assert!(pack.scripting.hot_reload_enabled);
        assert!(pack.chronoshift.enabled);
        assert_eq!(pack.chronoshift.max_fork_count, 8);
        assert!(pack.forensics.proof_lane_enabled);
        assert!(pack.validate().is_empty());
    }

    #[test]
    fn cartographers_toolkit_with_encumbrance_loads() {
        let json = r#"{
            "id": "cartographers_toolkit",
            "title": "The Cartographer's Toolkit",
            "version": "0.1.0",
            "grid": {"width": 120, "height": 80},
            "features": {"content_plan": false, "encumbrance": true, "containers": true},
            "encumbrance": {
                "capacity_stat": "strength",
                "capacity_multiplier": 1000,
                "tiers": [
                    {"id": "burdened", "threshold": 0.75, "speed_modifier": 0.5},
                    {"id": "overloaded", "threshold": 1.0, "speed_modifier": 0.0}
                ]
            },
            "equip_slots": ["Head", "Body", "Weapon", "Ring1", "Ring2"],
            "generators": {
                "cartographers_toolkit": {
                    "player_spawn": [60, 5],
                    "player_stats": {"hp": 25, "atk": 4, "def": 2, "mana": 20}
                }
            }
        }"#;
        let pack = DreamwellPackV1::from_json(json).unwrap();
        assert_eq!(pack.id, "cartographers_toolkit");
        assert!(pack.features.encumbrance);
        assert!(pack.features.containers);
        assert!(pack.encumbrance.is_some());
        assert_eq!(pack.equip_slots.len(), 5);
        assert!(pack.validate().is_empty());
    }

    #[test]
    fn radiant_forest_with_ai_brains_loads() {
        let json = r#"{
            "id": "radiant_forest",
            "title": "The Radiant Forest",
            "ai_brains": {"wisp_brain": {"base_brain": "state_machine"}},
            "starting_map": "compound",
            "scenario_script": "scenario/main.wm",
            "version": "0.1.0",
            "grid": {"width": 80, "height": 55},
            "features": {"containers": true}
        }"#;
        let pack = DreamwellPackV1::from_json(json).unwrap();
        assert_eq!(pack.id, "radiant_forest");
        assert_eq!(pack.starting_map, Some("compound".to_string()));
        assert_eq!(pack.ai_brains.len(), 1);
        assert!(pack.ai_brains.contains_key("wisp_brain"));
        assert!(pack.validate().is_empty());
    }
}