nucleation 0.7.0

A high-performance Minecraft schematic parser and utility library
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
//! The core `Schematic` opaque, wrapping [`crate::UniversalSchematic`], plus the
//! `BlockState` opaque. Port of `ffi/schematic.rs`.
//!
//! Omitted from port (obsolete by construction — destructors and error transport are
//! generated): `schematic_free`, `blockstate_free`, `free_file_map`, `free_entity_array`.
//! `schematic_new` is covered by [`ffi::Schematic::create`] (the old fn hard-coded the
//! name "Default"; pass any name here).

use crate::bridge::shared::ffi::NucleationError;

/// Validate a `&DiplomatStr` (raw UTF-8 bytes) into `&str`.
fn utf8(bytes: &[u8]) -> Result<&str, NucleationError> {
    std::str::from_utf8(bytes).map_err(|_| NucleationError::InvalidArgument)
}

fn b64(bytes: &[u8]) -> String {
    use base64::Engine as _;
    base64::engine::general_purpose::STANDARD.encode(bytes)
}

fn parse_excluded_blocks(json: &str) -> Result<Vec<crate::BlockState>, NucleationError> {
    if json.is_empty() {
        return Ok(Vec::new());
    }
    let strings: Vec<String> = serde_json::from_str(json).map_err(|_| NucleationError::Parse)?;
    strings
        .iter()
        .map(|block| {
            crate::UniversalSchematic::parse_block_string(block)
                .map(|(state, _)| state)
                .map_err(|_| NucleationError::Parse)
        })
        .collect()
}

/// Parse optional world-export options JSON (empty string ⇒ defaults).
fn parse_world_options(
    json: &str,
) -> Result<Option<crate::formats::world::WorldExportOptions>, NucleationError> {
    if json.is_empty() {
        return Ok(None);
    }
    serde_json::from_str(json)
        .map(Some)
        .map_err(|_| NucleationError::Parse)
}

/// One block as JSON, shaped like the old `CBlock` (properties as serialized pairs).
fn block_json(
    pos: &crate::block_position::BlockPosition,
    block: &crate::BlockState,
) -> serde_json::Value {
    serde_json::json!({
        "x": pos.x,
        "y": pos.y,
        "z": pos.z,
        "name": block.name.as_str(),
        "properties": serde_json::to_value(&block.properties).unwrap_or(serde_json::Value::Null),
    })
}

#[diplomat::bridge]
pub mod ffi {
    use super::super::shared::ffi::{BlockPos, Dimensions, NucleationError};
    use super::{b64, block_json, parse_excluded_blocks, parse_world_options, utf8};
    use crate::formats::{litematic, manager::get_manager, mcstructure};
    use crate::universal_schematic::ChunkLoadingStrategy;
    use diplomat_runtime::DiplomatWrite;
    use std::collections::HashMap;
    use std::fmt::Write;

    #[diplomat::opaque_mut]
    pub struct Schematic(pub(crate) crate::UniversalSchematic);

    impl Schematic {
        /// Create a new, empty schematic with the given name.
        pub fn create(name: &DiplomatStr) -> Box<Schematic> {
            Box::new(Schematic(crate::UniversalSchematic::new(
                String::from_utf8_lossy(name).into_owned(),
            )))
        }

        /// Return an independent deep copy. Subsequent block, region, entity,
        /// metadata, or transform changes do not affect the original.
        pub fn deep_clone(&self) -> Box<Schematic> {
            Box::new(Schematic(self.0.clone()))
        }

        /// The allocated dimensions (width, height, length) of the schematic's
        /// bounding box.
        pub fn dimensions(&self) -> Dimensions {
            let (x, y, z) = self.0.get_dimensions();
            Dimensions { x, y, z }
        }

        /// Returns `true` if a block was placed (out-of-range coordinates extend the
        /// schematic rather than erroring, matching `UniversalSchematic::set_block`).
        pub fn set_block(
            &mut self,
            x: i32,
            y: i32,
            z: i32,
            block_name: &DiplomatStr,
        ) -> Result<bool, NucleationError> {
            let name =
                std::str::from_utf8(block_name).map_err(|_| NucleationError::InvalidArgument)?;
            self.0
                .try_set_block_str(x, y, z, name)
                .map_err(|_| NucleationError::InvalidArgument)
        }

        /// The name of the block at a position. `NotFound` if the position is
        /// outside every region.
        pub fn get_block_name(
            &self,
            x: i32,
            y: i32,
            z: i32,
            out: &mut DiplomatWrite,
        ) -> Result<(), NucleationError> {
            match self.0.get_block(x, y, z) {
                Some(state) => {
                    let _ = write!(out, "{}", state.name);
                    Ok(())
                }
                None => Err(NucleationError::NotFound),
            }
        }

        /// Save the schematic to a file, picking the format from the file
        /// extension (`.litematic`, `.schem`, `.schematic`, `.mcstructure`,
        /// `.nbt`, `.nusn`; unknown extensions write Litematic). For an
        /// explicit format or version, use `save_to_file_with_format`.
        /// Not available in JS: the WASM build has no filesystem — use
        /// `save_as_b64` there.
        #[diplomat::attr(js, disable)]
        pub fn save_to_file(&self, path: &DiplomatStr) -> Result<(), NucleationError> {
            let path = std::str::from_utf8(path).map_err(|_| NucleationError::InvalidArgument)?;
            let manager = get_manager();
            let manager = manager.lock().map_err(|_| NucleationError::Lock)?;
            let bytes = manager
                .write_auto_with_settings(path, &self.0, None, None)
                .map_err(|_| NucleationError::Serialize)?;
            std::fs::write(path, bytes).map_err(|_| NucleationError::Io)?;
            Ok(())
        }

        /// Convenience alias for `save_to_file`, matching the established
        /// Python API (`schematic.save("build.schem")`).
        #[diplomat::attr(js, disable)]
        pub fn save(&self, path: &DiplomatStr) -> Result<(), NucleationError> {
            self.save_to_file(path)
        }

        /// Load a schematic from a file, auto-detecting the format from the
        /// contents (any supported format, whatever the extension says).
        /// Not available in JS: the WASM build has no filesystem — read the
        /// bytes yourself and use `from_data`.
        #[diplomat::attr(js, disable)]
        pub fn load_from_file(path: &DiplomatStr) -> Result<Box<Schematic>, NucleationError> {
            let path = std::str::from_utf8(path).map_err(|_| NucleationError::InvalidArgument)?;
            let bytes = std::fs::read(path).map_err(|_| NucleationError::Io)?;
            Self::from_data(&bytes)
        }

        /// Convenience alias for `load_from_file`, matching the established
        /// Python API (`Schematic.open("build.schem")`).
        #[diplomat::attr(js, disable)]
        pub fn open(path: &DiplomatStr) -> Result<Box<Schematic>, NucleationError> {
            Self::load_from_file(path)
        }

        // --- Data I/O (old fns populated an existing schematic; these construct) ---

        /// Build a schematic from raw byte data, auto-detecting the format.
        /// Supports Litematic, Sponge Schematic, and McStructure (Bedrock) formats.
        /// `Parse` if a format was detected but failed to parse, `InvalidArgument` if
        /// no format was recognized.
        pub fn from_data(data: &[u8]) -> Result<Box<Schematic>, NucleationError> {
            let manager = get_manager();
            let manager = manager.lock().map_err(|_| NucleationError::Lock)?;
            match manager.read(data) {
                Ok(res) => Ok(Box::new(Schematic(res))),
                Err(_) => {
                    if manager.detect_format(data).is_some() {
                        Err(NucleationError::Parse)
                    } else {
                        Err(NucleationError::InvalidArgument)
                    }
                }
            }
        }

        /// Build a schematic from Litematic data.
        pub fn from_litematic(data: &[u8]) -> Result<Box<Schematic>, NucleationError> {
            litematic::from_litematic(data)
                .map(|s| Box::new(Schematic(s)))
                .map_err(|_| NucleationError::Parse)
        }

        /// The schematic as Litematic bytes, base64-encoded.
        pub fn to_litematic_b64(&self, out: &mut DiplomatWrite) -> Result<(), NucleationError> {
            let data = litematic::to_litematic(&self.0).map_err(|_| NucleationError::Serialize)?;
            let _ = write!(out, "{}", b64(&data));
            Ok(())
        }

        /// Build a schematic from classic `.schematic` data.
        pub fn from_schematic(data: &[u8]) -> Result<Box<Schematic>, NucleationError> {
            crate::formats::schematic::from_schematic(data)
                .map(|s| Box::new(Schematic(s)))
                .map_err(|_| NucleationError::Parse)
        }

        /// The schematic as classic `.schematic` bytes, base64-encoded.
        pub fn to_schematic_b64(&self, out: &mut DiplomatWrite) -> Result<(), NucleationError> {
            let data = crate::formats::schematic::to_schematic(&self.0)
                .map_err(|_| NucleationError::Serialize)?;
            let _ = write!(out, "{}", b64(&data));
            Ok(())
        }

        /// Build a schematic from snapshot (fast binary) data.
        pub fn from_snapshot(data: &[u8]) -> Result<Box<Schematic>, NucleationError> {
            crate::formats::snapshot::from_snapshot(data)
                .map(|s| Box::new(Schematic(s)))
                .map_err(|_| NucleationError::Parse)
        }

        /// The schematic as snapshot (fast binary) bytes, base64-encoded.
        pub fn to_snapshot_b64(&self, out: &mut DiplomatWrite) -> Result<(), NucleationError> {
            let data = crate::formats::snapshot::to_snapshot(&self.0)
                .map_err(|_| NucleationError::Serialize)?;
            let _ = write!(out, "{}", b64(&data));
            Ok(())
        }

        /// Build a schematic from McStructure (Bedrock) data.
        pub fn from_mcstructure(data: &[u8]) -> Result<Box<Schematic>, NucleationError> {
            mcstructure::from_mcstructure(data)
                .map(|s| Box::new(Schematic(s)))
                .map_err(|_| NucleationError::Parse)
        }

        /// The schematic as McStructure (Bedrock) bytes, base64-encoded.
        pub fn to_mcstructure_b64(&self, out: &mut DiplomatWrite) -> Result<(), NucleationError> {
            let data =
                mcstructure::to_mcstructure(&self.0).map_err(|_| NucleationError::Serialize)?;
            let _ = write!(out, "{}", b64(&data));
            Ok(())
        }

        // --- MCA / World Import/Export ---

        /// Import from a single MCA region file.
        pub fn from_mca(data: &[u8]) -> Result<Box<Schematic>, NucleationError> {
            crate::formats::world::from_mca(data)
                .map(|s| Box::new(Schematic(s)))
                .map_err(|_| NucleationError::Parse)
        }

        /// Import from MCA with coordinate bounds.
        pub fn from_mca_bounded(
            data: &[u8],
            min_x: i32,
            min_y: i32,
            min_z: i32,
            max_x: i32,
            max_y: i32,
            max_z: i32,
        ) -> Result<Box<Schematic>, NucleationError> {
            crate::formats::world::from_mca_bounded(data, min_x, min_y, min_z, max_x, max_y, max_z)
                .map(|s| Box::new(Schematic(s)))
                .map_err(|_| NucleationError::Parse)
        }

        /// Import from a zipped world folder.
        pub fn from_world_zip(data: &[u8]) -> Result<Box<Schematic>, NucleationError> {
            crate::formats::world::from_world_zip(data)
                .map(|s| Box::new(Schematic(s)))
                .map_err(|_| NucleationError::Parse)
        }

        /// Import from zipped world with coordinate bounds.
        pub fn from_world_zip_bounded(
            data: &[u8],
            min_x: i32,
            min_y: i32,
            min_z: i32,
            max_x: i32,
            max_y: i32,
            max_z: i32,
        ) -> Result<Box<Schematic>, NucleationError> {
            crate::formats::world::from_world_zip_bounded(
                data, min_x, min_y, min_z, max_x, max_y, max_z,
            )
            .map(|s| Box::new(Schematic(s)))
            .map_err(|_| NucleationError::Parse)
        }

        /// Import from a Minecraft world directory path.
        #[cfg(not(target_arch = "wasm32"))]
        pub fn from_world_directory(path: &DiplomatStr) -> Result<Box<Schematic>, NucleationError> {
            let path = utf8(path)?;
            crate::formats::world::from_world_directory(std::path::Path::new(path))
                .map(|s| Box::new(Schematic(s)))
                .map_err(|_| NucleationError::Parse)
        }

        /// Import from world directory with coordinate bounds.
        #[cfg(not(target_arch = "wasm32"))]
        pub fn from_world_directory_bounded(
            path: &DiplomatStr,
            min_x: i32,
            min_y: i32,
            min_z: i32,
            max_x: i32,
            max_y: i32,
            max_z: i32,
        ) -> Result<Box<Schematic>, NucleationError> {
            let path = utf8(path)?;
            crate::formats::world::from_world_directory_bounded(
                std::path::Path::new(path),
                min_x,
                min_y,
                min_z,
                max_x,
                max_y,
                max_z,
            )
            .map(|s| Box::new(Schematic(s)))
            .map_err(|_| NucleationError::Parse)
        }

        /// Export the schematic as a Minecraft world: a JSON array of
        /// `{"path": <relative file path>, "data_b64": <base64 bytes>}` entries
        /// (the old `CFileMap`). `options_json` may be empty for defaults.
        pub fn to_world_json(
            &self,
            options_json: &DiplomatStr,
            out: &mut DiplomatWrite,
        ) -> Result<(), NucleationError> {
            let options = parse_world_options(utf8(options_json)?)?;
            let files = crate::formats::world::to_world(&self.0, options)
                .map_err(|_| NucleationError::Serialize)?;
            let items: Vec<serde_json::Value> = files
                .into_iter()
                .map(|(path, data)| serde_json::json!({ "path": path, "data_b64": b64(&data) }))
                .collect();
            let json = serde_json::to_string(&items).map_err(|_| NucleationError::Serialize)?;
            let _ = write!(out, "{}", json);
            Ok(())
        }

        /// Export and write world files to a directory. `options_json` may be empty.
        #[cfg(not(target_arch = "wasm32"))]
        pub fn save_world(
            &self,
            directory: &DiplomatStr,
            options_json: &DiplomatStr,
        ) -> Result<(), NucleationError> {
            let dir = utf8(directory)?;
            let options = parse_world_options(utf8(options_json)?)?;
            crate::formats::world::save_world(&self.0, std::path::Path::new(dir), options)
                .map_err(|_| NucleationError::Io)
        }

        /// Export the schematic as a zipped Minecraft world, base64-encoded.
        /// `options_json` may be empty for defaults.
        pub fn to_world_zip_b64(
            &self,
            options_json: &DiplomatStr,
            out: &mut DiplomatWrite,
        ) -> Result<(), NucleationError> {
            let options = parse_world_options(utf8(options_json)?)?;
            let bytes = crate::formats::world::to_world_zip(&self.0, options)
                .map_err(|_| NucleationError::Serialize)?;
            let _ = write!(out, "{}", b64(&bytes));
            Ok(())
        }

        // --- Block Manipulation ---

        /// Set a block with properties given as a JSON object of string→string
        /// (the old `CProperty` array).
        pub fn set_block_with_properties(
            &mut self,
            x: i32,
            y: i32,
            z: i32,
            block_name: &DiplomatStr,
            properties_json: &DiplomatStr,
        ) -> Result<(), NucleationError> {
            let name = utf8(block_name)?;
            let props_str = utf8(properties_json)?;
            let props: Vec<(smol_str::SmolStr, smol_str::SmolStr)> = if props_str.is_empty() {
                Vec::new()
            } else {
                let map: serde_json::Map<String, serde_json::Value> =
                    serde_json::from_str(props_str).map_err(|_| NucleationError::Parse)?;
                let mut props = Vec::with_capacity(map.len());
                for (k, v) in map {
                    let v = v.as_str().ok_or(NucleationError::InvalidArgument)?;
                    props.push((k.into(), v.into()));
                }
                props
            };
            let block_state = crate::BlockState {
                name: name.into(),
                properties: props,
            };
            self.0.set_block(x, y, z, &block_state);
            Ok(())
        }

        /// Set a block from a full block string, e.g.
        /// `minecraft:chest[facing=north]{Items:[...]}`.
        pub fn set_block_from_string(
            &mut self,
            x: i32,
            y: i32,
            z: i32,
            block_string: &DiplomatStr,
        ) -> Result<(), NucleationError> {
            let block_str = utf8(block_string)?;
            self.0
                .set_block_from_string(x, y, z, block_str)
                .map(|_| ())
                .map_err(|_| NucleationError::Parse)
        }

        /// Pre-resolve a plain block name to a palette index for use with `place`.
        /// Pair them in hot loops with many unique block names to skip the per-call
        /// name → palette lookup.
        pub fn prepare_block(&mut self, block_name: &DiplomatStr) -> Result<i32, NucleationError> {
            let name = utf8(block_name)?;
            Ok(self.0.default_region.get_or_insert_palette_by_name(name) as i32)
        }

        /// Place a block by pre-resolved palette index (from `prepare_block`).
        pub fn place(
            &mut self,
            x: i32,
            y: i32,
            z: i32,
            palette_index: i32,
        ) -> Result<(), NucleationError> {
            if palette_index < 0 {
                return Err(NucleationError::InvalidArgument);
            }
            let region = &mut self.0.default_region;
            if (palette_index as usize) >= region.palette.len() {
                return Err(NucleationError::InvalidArgument);
            }
            if !region.is_in_region(x, y, z) {
                region.expand_to_fit(x, y, z);
            }
            region.set_block_at_index_unchecked(palette_index as usize, x, y, z);
            Ok(())
        }

        /// Batch-set blocks at multiple positions to the same block (name, block
        /// string with properties, or block string with NBT). `positions` is flat
        /// `[x0,y0,z0, x1,y1,z1, ...]` (length must be a multiple of 3).
        /// Returns the number of blocks set.
        pub fn set_blocks(
            &mut self,
            positions: &[i32],
            block_name: &DiplomatStr,
        ) -> Result<i32, NucleationError> {
            let block_name_str = utf8(block_name)?;
            if positions.len() % 3 != 0 {
                return Err(NucleationError::InvalidArgument);
            }
            let count = positions.len() / 3;
            if count == 0 {
                return Ok(0);
            }
            let count_i32 = i32::try_from(count).map_err(|_| NucleationError::InvalidArgument)?;
            let s = &mut self.0;

            let (mut min_x, mut min_y, mut min_z) = (positions[0], positions[1], positions[2]);
            let (mut max_x, mut max_y, mut max_z) = (min_x, min_y, min_z);
            for i in 1..count {
                let (x, y, z) = (positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
                min_x = min_x.min(x);
                min_y = min_y.min(y);
                min_z = min_z.min(z);
                max_x = max_x.max(x);
                max_y = max_y.max(y);
                max_z = max_z.max(z);
            }

            // Validate before mutating any position. The shared setter caches the
            // parsed result after the first placement, while keeping replacement,
            // jukebox-state, and block-entity behavior identical to set_block.
            crate::UniversalSchematic::parse_block_string(block_name_str)
                .map_err(|_| NucleationError::InvalidArgument)?;
            s.default_region
                .ensure_bounds((min_x, min_y, min_z), (max_x, max_y, max_z));
            for position in positions.chunks_exact(3) {
                s.set_block_from_string(position[0], position[1], position[2], block_name_str)
                    .map_err(|_| NucleationError::InvalidArgument)?;
            }
            Ok(count_i32)
        }

        /// Batch-get block names at multiple positions. `positions` is flat
        /// `[x0,y0,z0, ...]` (length must be a multiple of 3). Writes a JSON array,
        /// one entry per position: the block name string, or `null` for
        /// empty/out-of-bounds positions.
        pub fn get_blocks_json(
            &self,
            positions: &[i32],
            out: &mut DiplomatWrite,
        ) -> Result<(), NucleationError> {
            if positions.len() % 3 != 0 {
                return Err(NucleationError::InvalidArgument);
            }
            let count = positions.len() / 3;
            let region = &self.0.default_region;
            let mut results: Vec<Option<&str>> = Vec::with_capacity(count);
            for i in 0..count {
                let (x, y, z) = (positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
                let name = if region.is_in_region(x, y, z) {
                    region.get_block_name(x, y, z)
                } else {
                    self.0.get_block(x, y, z).map(|bs| bs.name.as_str())
                };
                results.push(name);
            }
            let json = serde_json::to_string(&results).map_err(|_| NucleationError::Serialize)?;
            let _ = write!(out, "{}", json);
            Ok(())
        }

        /// Stamp a merged source box into the default region. Excluded blocks
        /// are skipped, preserving destination content. Empty string or `[]`
        /// means no exclusions.
        #[allow(clippy::too_many_arguments)]
        pub fn stamp_box(
            &mut self,
            source: &Schematic,
            min_x: i32,
            min_y: i32,
            min_z: i32,
            max_x: i32,
            max_y: i32,
            max_z: i32,
            target_x: i32,
            target_y: i32,
            target_z: i32,
            excluded_blocks_json: &DiplomatStr,
        ) -> Result<(), NucleationError> {
            let excluded = parse_excluded_blocks(utf8(excluded_blocks_json)?)?;
            let bounds = crate::BoundingBox::new((min_x, min_y, min_z), (max_x, max_y, max_z));
            self.0
                .stamp_box(
                    &source.0,
                    &bounds,
                    (target_x, target_y, target_z),
                    &excluded,
                )
                .map_err(|_| NucleationError::InvalidArgument)
        }

        /// Stamp one explicitly named source region into the default region.
        /// The region's minimum corner is mapped to the target position.
        pub fn stamp_region(
            &mut self,
            source: &Schematic,
            source_region_name: &DiplomatStr,
            target_x: i32,
            target_y: i32,
            target_z: i32,
            excluded_blocks_json: &DiplomatStr,
        ) -> Result<(), NucleationError> {
            let region_name = utf8(source_region_name)?;
            if !source.0.has_region(region_name) {
                return Err(NucleationError::NotFound);
            }
            let excluded = parse_excluded_blocks(utf8(excluded_blocks_json)?)?;
            self.0
                .stamp_region(
                    &source.0,
                    region_name,
                    (target_x, target_y, target_z),
                    &excluded,
                )
                .map_err(|_| NucleationError::InvalidArgument)
        }

        /// Compatibility alias for `stamp_box`.
        #[allow(clippy::too_many_arguments)]
        pub fn copy_region(
            &mut self,
            source: &Schematic,
            min_x: i32,
            min_y: i32,
            min_z: i32,
            max_x: i32,
            max_y: i32,
            max_z: i32,
            target_x: i32,
            target_y: i32,
            target_z: i32,
            excluded_blocks_json: &DiplomatStr,
        ) -> Result<(), NucleationError> {
            self.stamp_box(
                source,
                min_x,
                min_y,
                min_z,
                max_x,
                max_y,
                max_z,
                target_x,
                target_y,
                target_z,
                excluded_blocks_json,
            )
        }

        // --- Block & Entity Accessors ---

        /// The full block state at a position. `NotFound` if the position is
        /// outside every region.
        pub fn get_block(
            &self,
            x: i32,
            y: i32,
            z: i32,
        ) -> Result<Box<BlockState>, NucleationError> {
            self.0
                .get_block(x, y, z)
                .cloned()
                .map(BlockState)
                .map(Box::new)
                .ok_or(NucleationError::NotFound)
        }

        /// The block at a position with its properties, as a `BlockState`.
        /// Kept as an explicit alias for callers migrating from the older API.
        pub fn get_block_with_properties(
            &self,
            x: i32,
            y: i32,
            z: i32,
        ) -> Result<Box<BlockState>, NucleationError> {
            self.get_block(x, y, z)
        }

        /// The full block state at a position in one specific region. This
        /// avoids composite lookup ambiguity when regions overlap.
        pub fn get_block_in_region(
            &self,
            region_name: &DiplomatStr,
            x: i32,
            y: i32,
            z: i32,
        ) -> Result<Box<BlockState>, NucleationError> {
            let name = utf8(region_name)?;
            self.0
                .get_block_from_region(name, x, y, z)
                .cloned()
                .map(BlockState)
                .map(Box::new)
                .ok_or(NucleationError::NotFound)
        }

        /// The block string at a position in one specific region.
        pub fn get_block_string_in_region(
            &self,
            region_name: &DiplomatStr,
            x: i32,
            y: i32,
            z: i32,
            out: &mut DiplomatWrite,
        ) -> Result<(), NucleationError> {
            let block = self
                .0
                .get_block_string_in_region(utf8(region_name)?, x, y, z)
                .ok_or(NucleationError::NotFound)?;
            let _ = write!(out, "{}", block);
            Ok(())
        }

        /// The full block string (name, properties, NBT) at a position.
        pub fn get_block_string(
            &self,
            x: i32,
            y: i32,
            z: i32,
            out: &mut DiplomatWrite,
        ) -> Result<(), NucleationError> {
            match self.0.get_block(x, y, z) {
                Some(bs) => {
                    let _ = write!(out, "{}", bs);
                    Ok(())
                }
                None => Err(NucleationError::NotFound),
            }
        }

        /// The block entity at a position as JSON
        /// `{"id": ..., "position": [x,y,z], "nbt": {...}}` (the old `CBlockEntity`).
        pub fn get_block_entity_json(
            &self,
            x: i32,
            y: i32,
            z: i32,
            out: &mut DiplomatWrite,
        ) -> Result<(), NucleationError> {
            let pos = crate::block_position::BlockPosition { x, y, z };
            match self.0.get_block_entity_owned(pos) {
                Some(be) => {
                    let json = serde_json::json!({
                        "id": be.id,
                        "position": [x, y, z],
                        "nbt": serde_json::to_value(&be.nbt).unwrap_or(serde_json::Value::Null),
                    });
                    let _ = write!(out, "{}", json);
                    Ok(())
                }
                None => Err(NucleationError::NotFound),
            }
        }

        /// The block entity at a position in one specific region as JSON.
        pub fn get_block_entity_json_in_region(
            &self,
            region_name: &DiplomatStr,
            x: i32,
            y: i32,
            z: i32,
            out: &mut DiplomatWrite,
        ) -> Result<(), NucleationError> {
            let entity = self
                .0
                .get_block_entity_in_region(utf8(region_name)?, x, y, z)
                .ok_or(NucleationError::NotFound)?;
            let json = serde_json::json!({
                "id": entity.id,
                "position": [x, y, z],
                "nbt": serde_json::to_value(&entity.nbt).unwrap_or(serde_json::Value::Null),
            });
            let _ = write!(out, "{}", json);
            Ok(())
        }

        /// Every block entity as a JSON array of
        /// `{"id": ..., "position": [x,y,z], "nbt": {...}}`.
        pub fn get_all_block_entities_json(&self, out: &mut DiplomatWrite) {
            let items: Vec<serde_json::Value> = self
                .0
                .get_block_entities_as_list()
                .into_iter()
                .map(|be| {
                    serde_json::json!({
                        "id": be.id,
                        "position": [be.position.0, be.position.1, be.position.2],
                        "nbt": serde_json::to_value(&be.nbt).unwrap_or(serde_json::Value::Null),
                    })
                })
                .collect();
            let json = serde_json::to_string(&items).unwrap_or_else(|_| "[]".to_string());
            let _ = write!(out, "{}", json);
        }

        /// The number of mobile entities (not block entities).
        pub fn entity_count(&self) -> u32 {
            self.0.default_region.entities.len() as u32
        }

        /// Every mobile entity as a JSON array of
        /// `{"id": ..., "position": [x,y,z], "nbt": {...}}` (the old `CEntityArray`).
        pub fn get_entities_json(&self, out: &mut DiplomatWrite) {
            let items: Vec<serde_json::Value> = self
                .0
                .default_region
                .entities
                .iter()
                .map(|entity| {
                    serde_json::json!({
                        "id": entity.id,
                        "position": [entity.position.0, entity.position.1, entity.position.2],
                        "nbt": serde_json::to_value(&entity.nbt).unwrap_or(serde_json::Value::Null),
                    })
                })
                .collect();
            let json = serde_json::to_string(&items).unwrap_or_else(|_| "[]".to_string());
            let _ = write!(out, "{}", json);
        }

        /// Add a mobile entity. `nbt_json` is a JSON object (may be empty).
        pub fn add_entity(
            &mut self,
            id: &DiplomatStr,
            x: f64,
            y: f64,
            z: f64,
            nbt_json: &DiplomatStr,
        ) -> Result<(), NucleationError> {
            let id_str = utf8(id)?.to_string();
            let json = utf8(nbt_json)?;
            let mut entity = crate::entity::Entity::new(id_str, (x, y, z));
            if !json.is_empty() {
                if let Ok(nbt_map) = serde_json::from_str(json) {
                    entity.nbt = nbt_map;
                }
            }
            self.0.add_entity(entity);
            Ok(())
        }

        /// Add an armor stand without hand-authoring entity NBT.
        ///
        /// `armor_material` accepts `diamond`, `netherite`, `iron`, etc.; an
        /// empty string creates an unarmored stand. `yaw` uses Minecraft degrees.
        pub fn add_armor_stand(
            &mut self,
            x: f64,
            y: f64,
            z: f64,
            yaw: f32,
            armor_material: &DiplomatStr,
        ) -> Result<(), NucleationError> {
            let material = utf8(armor_material)?;
            let equipment = if material.is_empty() {
                crate::ArmorStandEquipment::default()
            } else {
                crate::ArmorStandEquipment::full_set(material)
            };
            self.0
                .add_entity(crate::Entity::armor_stand((x, y, z), yaw, equipment));
            Ok(())
        }

        /// Remove a mobile entity by index.
        pub fn remove_entity(&mut self, index: u32) -> Result<(), NucleationError> {
            self.0
                .remove_entity(index as usize)
                .map(|_| ())
                .ok_or(NucleationError::NotFound)
        }

        // --- Data-version conversion (datafixers) ---

        /// The canonical in-memory data version (the forward-conversion target).
        pub fn canonical_data_version() -> i32 {
            crate::dataconverter::CANONICAL_DATA_VERSION
        }

        /// Convert block/item/entity data between Minecraft data versions. Forward
        /// (`target >= source`) is lossless; reverse is lossy. Writes a JSON loss
        /// report (`[]` when lossless).
        pub fn convert_to_data_version(
            &mut self,
            target_data_version: i32,
            source_data_version: i32,
            out: &mut DiplomatWrite,
        ) {
            let json = if target_data_version == source_data_version {
                "[]".to_string()
            } else if target_data_version > source_data_version {
                crate::dataconverter::convert_schematic(
                    &mut self.0,
                    source_data_version,
                    target_data_version,
                );
                "[]".to_string()
            } else {
                crate::dataconverter::convert_schematic_reverse(
                    &mut self.0,
                    source_data_version,
                    target_data_version,
                )
                .to_json()
            };
            let _ = write!(out, "{}", json);
        }

        /// Convert to `target_data_version` using the schematic's captured source
        /// version (else `mc_version`, else canonical) as origin, updating metadata
        /// to the target. Writes a JSON loss report (`[]` when lossless).
        pub fn convert_to_version(&mut self, target_data_version: i32, out: &mut DiplomatWrite) {
            let json = self
                .0
                .convert_to_data_version(target_data_version)
                .to_json();
            let _ = write!(out, "{}", json);
        }

        /// The Minecraft data version of the file this schematic was loaded from, or
        /// `-1` if none was captured (versionless / freshly built).
        pub fn source_data_version(&self) -> i32 {
            self.0.metadata.source_data_version.unwrap_or(-1)
        }

        /// Override the source data version for formats that carry no Java data
        /// version, so the converter knows what to convert *from*.
        pub fn set_source_data_version(&mut self, version: i32) {
            self.0.metadata.source_data_version = Some(version);
        }

        /// Serialize a `.litematic` targeting a specific Minecraft data version. A
        /// COPY is converted and the matching Version header written; the schematic
        /// is left unchanged. Writes JSON
        /// `{"data_b64": <base64 .litematic>, "loss": <loss report>}`.
        pub fn to_litematic_for_version_json(
            &self,
            target_data_version: i32,
            out: &mut DiplomatWrite,
        ) -> Result<(), NucleationError> {
            let (data, report) =
                litematic::to_litematic_for_data_version(&self.0, target_data_version)
                    .map_err(|_| NucleationError::Serialize)?;
            let loss: serde_json::Value = serde_json::from_str(&report.to_json())
                .unwrap_or(serde_json::Value::Array(Vec::new()));
            let json = serde_json::json!({ "data_b64": b64(&data), "loss": loss });
            let _ = write!(out, "{}", json);
            Ok(())
        }

        // --- Faithful (SNBT) block-entity / entity access ---

        /// The block entity's NBT as a typed SNBT string. Round-trips losslessly.
        pub fn get_block_entity_snbt(
            &self,
            x: i32,
            y: i32,
            z: i32,
            out: &mut DiplomatWrite,
        ) -> Result<(), NucleationError> {
            let pos = crate::block_position::BlockPosition { x, y, z };
            match self.0.get_block_entity(pos) {
                Some(be) => {
                    let snbt = quartz_nbt::NbtTag::Compound(be.nbt.to_quartz_nbt()).to_snbt();
                    let _ = write!(out, "{}", snbt);
                    Ok(())
                }
                None => Err(NucleationError::NotFound),
            }
        }

        /// Set (or replace) a block entity at a position from a typed SNBT string.
        pub fn set_block_entity(
            &mut self,
            x: i32,
            y: i32,
            z: i32,
            id: &DiplomatStr,
            snbt: &DiplomatStr,
        ) -> Result<(), NucleationError> {
            let id_str = utf8(id)?.to_string();
            let snbt_str = utf8(snbt)?;
            let compound = quartz_nbt::snbt::parse(snbt_str).map_err(|_| NucleationError::Parse)?;
            let nbt = crate::nbt::NbtMap::from_quartz_nbt(&compound);
            let mut be = crate::block_entity::BlockEntity::new(id_str, (x, y, z));
            be.set_nbt(nbt);
            self.0
                .set_block_entity(crate::block_position::BlockPosition { x, y, z }, be);
            Ok(())
        }

        /// Remove the block entity at a position. `NotFound` if none was there.
        pub fn remove_block_entity(
            &mut self,
            x: i32,
            y: i32,
            z: i32,
        ) -> Result<(), NucleationError> {
            self.0
                .remove_block_entity((x, y, z))
                .map(|_| ())
                .ok_or(NucleationError::NotFound)
        }

        /// Every block entity as a JSON array of `{id, position: [x,y,z], snbt}`.
        /// The `snbt` is the inner data only (no `Id`/`Pos`).
        pub fn get_all_block_entities_snbt_json(&self, out: &mut DiplomatWrite) {
            let items: Vec<serde_json::Value> = self
                .0
                .get_block_entities_as_list()
                .into_iter()
                .map(|be| {
                    let snbt = quartz_nbt::NbtTag::Compound(be.nbt.to_quartz_nbt()).to_snbt();
                    serde_json::json!({
                        "id": be.id,
                        "position": [be.position.0, be.position.1, be.position.2],
                        "snbt": snbt,
                    })
                })
                .collect();
            let json = serde_json::to_string(&items).unwrap_or_else(|_| "[]".to_string());
            let _ = write!(out, "{}", json);
        }

        /// Every mobile entity as a JSON array of typed SNBT strings (full compound
        /// incl. `id`/`Pos`).
        pub fn get_entities_snbt_json(&self, out: &mut DiplomatWrite) {
            let snbts: Vec<String> = self
                .0
                .get_entities_as_list()
                .iter()
                .map(|entity| entity.to_nbt().to_snbt())
                .collect();
            let json = serde_json::to_string(&snbts).unwrap_or_else(|_| "[]".to_string());
            let _ = write!(out, "{}", json);
        }

        /// Add a mobile entity from a full SNBT entity compound (must contain `id`
        /// and `Pos`).
        pub fn add_entity_from_snbt(&mut self, snbt: &DiplomatStr) -> Result<(), NucleationError> {
            let snbt_str = utf8(snbt)?;
            let compound = quartz_nbt::snbt::parse(snbt_str).map_err(|_| NucleationError::Parse)?;
            let entity =
                crate::entity::Entity::from_nbt(&compound).map_err(|_| NucleationError::Parse)?;
            self.0.add_entity(entity);
            Ok(())
        }

        /// Every non-air block as a JSON array of
        /// `{"x", "y", "z", "name", "properties"}` (the old `CBlockArray`).
        pub fn get_all_blocks_json(&self, out: &mut DiplomatWrite) {
            let items: Vec<serde_json::Value> = self
                .0
                .iter_blocks()
                .map(|(pos, block)| block_json(&pos, block))
                .collect();
            let json = serde_json::to_string(&items).unwrap_or_else(|_| "[]".to_string());
            let _ = write!(out, "{}", json);
        }

        /// All blocks within a sub-region (chunk) of the schematic, as the same
        /// JSON array shape as `get_all_blocks_json`.
        #[allow(clippy::too_many_arguments)]
        pub fn get_chunk_blocks_json(
            &self,
            offset_x: i32,
            offset_y: i32,
            offset_z: i32,
            width: i32,
            height: i32,
            length: i32,
            out: &mut DiplomatWrite,
        ) {
            let items: Vec<serde_json::Value> = self
                .0
                .iter_blocks()
                .filter(|(pos, _)| {
                    pos.x >= offset_x
                        && pos.x < offset_x + width
                        && pos.y >= offset_y
                        && pos.y < offset_y + height
                        && pos.z >= offset_z
                        && pos.z < offset_z + length
                })
                .map(|(pos, block)| block_json(&pos, block))
                .collect();
            let json = serde_json::to_string(&items).unwrap_or_else(|_| "[]".to_string());
            let _ = write!(out, "{}", json);
        }

        // --- Chunking ---

        /// Split the schematic into chunks (default bottom-up strategy). Writes a
        /// JSON array of `{"chunk_x", "chunk_y", "chunk_z", "blocks": [...]}` where
        /// blocks have the `get_all_blocks_json` shape (the old `CChunkArray`).
        pub fn get_chunks_json(
            &self,
            chunk_width: i32,
            chunk_height: i32,
            chunk_length: i32,
            out: &mut DiplomatWrite,
        ) {
            self.get_chunks_with_strategy_json(
                chunk_width,
                chunk_height,
                chunk_length,
                b"",
                0.0,
                0.0,
                0.0,
                out,
            )
        }

        /// Split the schematic into chunks with a loading strategy: one of
        /// `distance_to_camera`, `top_down`, `bottom_up`, `center_outward`,
        /// `random` (anything else falls back to `bottom_up`). Camera coordinates
        /// are only used by `distance_to_camera`. Same JSON shape as
        /// `get_chunks_json`.
        #[allow(clippy::too_many_arguments)]
        pub fn get_chunks_with_strategy_json(
            &self,
            chunk_width: i32,
            chunk_height: i32,
            chunk_length: i32,
            strategy: &DiplomatStr,
            camera_x: f32,
            camera_y: f32,
            camera_z: f32,
            out: &mut DiplomatWrite,
        ) {
            let strategy_str = std::str::from_utf8(strategy).unwrap_or("");
            let strategy_enum = match strategy_str {
                "distance_to_camera" => {
                    ChunkLoadingStrategy::DistanceToCamera(camera_x, camera_y, camera_z)
                }
                "top_down" => ChunkLoadingStrategy::TopDown,
                "bottom_up" => ChunkLoadingStrategy::BottomUp,
                "center_outward" => ChunkLoadingStrategy::CenterOutward,
                "random" => ChunkLoadingStrategy::Random,
                _ => ChunkLoadingStrategy::BottomUp,
            };
            let chunks: Vec<serde_json::Value> = self
                .0
                .iter_chunks(chunk_width, chunk_height, chunk_length, Some(strategy_enum))
                .map(|chunk| {
                    let blocks: Vec<serde_json::Value> = chunk
                        .positions
                        .into_iter()
                        .filter_map(|pos| self.0.get_block(pos.x, pos.y, pos.z).map(|b| (pos, b)))
                        .map(|(pos, block)| block_json(&pos, block))
                        .collect();
                    serde_json::json!({
                        "chunk_x": chunk.chunk_x,
                        "chunk_y": chunk.chunk_y,
                        "chunk_z": chunk.chunk_z,
                        "blocks": blocks,
                    })
                })
                .collect();
            let json = serde_json::to_string(&chunks).unwrap_or_else(|_| "[]".to_string());
            let _ = write!(out, "{}", json);
        }

        // --- Metadata & Info ---

        /// The total number of non-air blocks in the schematic.
        pub fn block_count(&self) -> i32 {
            self.0.total_blocks()
        }

        /// The total volume of the schematic's bounding box.
        pub fn volume(&self) -> i32 {
            self.0.total_volume()
        }

        /// The names of all regions, as a JSON array of strings.
        pub fn region_names_json(&self, out: &mut DiplomatWrite) {
            let names = self.0.get_region_names();
            let json = serde_json::to_string(&names).unwrap_or_else(|_| "[]".to_string());
            let _ = write!(out, "{}", json);
        }

        // --- Debugging & Utility ---

        /// Basic debug info about the schematic (name + region count).
        pub fn debug_info(&self, out: &mut DiplomatWrite) {
            let _ = write!(
                out,
                "Schematic name: {}, Regions: {}",
                self.0.metadata.name.as_deref().unwrap_or("Unnamed"),
                self.0.other_regions.len() + 1 // +1 for the main region
            );
        }

        /// A formatted schematic layout string (old `schematic_print`).
        pub fn print_string(&self, out: &mut DiplomatWrite) {
            let _ = write!(out, "{}", crate::format_schematic(&self.0));
        }

        /// A formatted schematic layout string (old `schematic_print_schematic`;
        /// same output as `print_string`).
        pub fn print_schematic_string(&self, out: &mut DiplomatWrite) {
            let _ = write!(out, "{}", crate::format_schematic(&self.0));
        }

        /// A detailed debug string, including a visual layout (old `debug_schematic`).
        pub fn debug_string(&self, out: &mut DiplomatWrite) {
            let _ = write!(
                out,
                "Schematic name: {}, Regions: {}\n{}",
                self.0.metadata.name.as_deref().unwrap_or("Unnamed"),
                self.0.other_regions.len() + 1,
                crate::format_schematic(&self.0)
            );
        }

        /// A detailed debug string with a JSON layout (old `debug_json_schematic`).
        pub fn debug_json_string(&self, out: &mut DiplomatWrite) {
            let _ = write!(
                out,
                "Schematic name: {}, Regions: {}\n{}",
                self.0.metadata.name.as_deref().unwrap_or("Unnamed"),
                self.0.other_regions.len() + 1,
                crate::format_json_schematic(&self.0)
            );
        }

        // --- Metadata Accessors ---

        /// The schematic name. `NotFound` if not set.
        pub fn name(&self, out: &mut DiplomatWrite) -> Result<(), NucleationError> {
            match &self.0.metadata.name {
                Some(name) => {
                    let _ = write!(out, "{}", name);
                    Ok(())
                }
                None => Err(NucleationError::NotFound),
            }
        }

        /// Set the schematic name.
        pub fn set_name(&mut self, name: &DiplomatStr) -> Result<(), NucleationError> {
            self.0.metadata.name = Some(utf8(name)?.to_string());
            Ok(())
        }

        /// The schematic author. `NotFound` if not set.
        pub fn author(&self, out: &mut DiplomatWrite) -> Result<(), NucleationError> {
            match &self.0.metadata.author {
                Some(author) => {
                    let _ = write!(out, "{}", author);
                    Ok(())
                }
                None => Err(NucleationError::NotFound),
            }
        }

        /// Set the schematic author.
        pub fn set_author(&mut self, author: &DiplomatStr) -> Result<(), NucleationError> {
            self.0.metadata.author = Some(utf8(author)?.to_string());
            Ok(())
        }

        /// The schematic description. `NotFound` if not set.
        pub fn description(&self, out: &mut DiplomatWrite) -> Result<(), NucleationError> {
            match &self.0.metadata.description {
                Some(desc) => {
                    let _ = write!(out, "{}", desc);
                    Ok(())
                }
                None => Err(NucleationError::NotFound),
            }
        }

        /// Set the schematic description.
        pub fn set_description(
            &mut self,
            description: &DiplomatStr,
        ) -> Result<(), NucleationError> {
            self.0.metadata.description = Some(utf8(description)?.to_string());
            Ok(())
        }

        /// The creation timestamp (milliseconds since epoch), or `-1` if not set.
        pub fn created(&self) -> i64 {
            self.0.metadata.created.map(|v| v as i64).unwrap_or(-1)
        }

        /// Set the creation timestamp (milliseconds since epoch).
        pub fn set_created(&mut self, created: u64) {
            self.0.metadata.created = Some(created);
        }

        /// The modification timestamp (milliseconds since epoch), or `-1` if not set.
        pub fn modified(&self) -> i64 {
            self.0.metadata.modified.map(|v| v as i64).unwrap_or(-1)
        }

        /// Set the modification timestamp (milliseconds since epoch).
        pub fn set_modified(&mut self, modified: u64) {
            self.0.metadata.modified = Some(modified);
        }

        /// The Litematic format version, or `-1` if not set.
        pub fn lm_version(&self) -> i32 {
            self.0.metadata.lm_version.unwrap_or(-1)
        }

        /// Set the Litematic format version.
        pub fn set_lm_version(&mut self, version: i32) {
            self.0.metadata.lm_version = Some(version);
        }

        /// The Minecraft data version, or `-1` if not set.
        pub fn mc_version(&self) -> i32 {
            self.0.metadata.mc_version.unwrap_or(-1)
        }

        /// Set the Minecraft data version.
        pub fn set_mc_version(&mut self, version: i32) {
            self.0.metadata.mc_version = Some(version);
        }

        /// The WorldEdit version, or `-1` if not set.
        pub fn we_version(&self) -> i32 {
            self.0.metadata.we_version.unwrap_or(-1)
        }

        /// Set the WorldEdit version.
        pub fn set_we_version(&mut self, version: i32) {
            self.0.metadata.we_version = Some(version);
        }

        // --- Transformations ---

        /// Mirror the default region along the X axis (in place). Block
        /// orientations, block entities, and entities are mirrored too.
        pub fn flip_x(&mut self) {
            self.0.flip_x();
        }

        /// Mirror the default region along the Y axis (in place).
        pub fn flip_y(&mut self) {
            self.0.flip_y();
        }

        /// Mirror the default region along the Z axis (in place).
        pub fn flip_z(&mut self) {
            self.0.flip_z();
        }

        /// Rotate the default region about the X axis. +90° maps south (+Z)
        /// to down (-Y). Only multiples of 90 are accepted; invalid angles
        /// return `InvalidArgument` without changing the schematic. Negative
        /// values wrap.
        pub fn rotate_x(&mut self, degrees: i32) -> Result<(), NucleationError> {
            self.0
                .rotate_x(degrees)
                .map_err(|_| NucleationError::InvalidArgument)
        }

        /// Rotate the default region clockwise about the Y axis when viewed
        /// from above. +90° maps east (+X) to south (+Z).
        pub fn rotate_y(&mut self, degrees: i32) -> Result<(), NucleationError> {
            self.0
                .rotate_y(degrees)
                .map_err(|_| NucleationError::InvalidArgument)
        }

        /// Rotate the default region about the Z axis. +90° maps up (+Y) to
        /// west (-X).
        pub fn rotate_z(&mut self, degrees: i32) -> Result<(), NucleationError> {
            self.0
                .rotate_z(degrees)
                .map_err(|_| NucleationError::InvalidArgument)
        }

        /// Move the default region and all attached block entities/entities.
        pub fn translate(&mut self, dx: i32, dy: i32, dz: i32) -> Result<(), NucleationError> {
            self.0
                .translate(dx, dy, dz)
                .map_err(|_| NucleationError::InvalidArgument)
        }

        /// Mirror a named region along the X axis.
        pub fn flip_region_x(&mut self, region_name: &DiplomatStr) -> Result<(), NucleationError> {
            let name = utf8(region_name)?;
            if !self.0.has_region(name) {
                return Err(NucleationError::NotFound);
            }
            self.0
                .flip_region_x(name)
                .map_err(|_| NucleationError::InvalidArgument)
        }

        /// Mirror a named region along the Y axis.
        pub fn flip_region_y(&mut self, region_name: &DiplomatStr) -> Result<(), NucleationError> {
            let name = utf8(region_name)?;
            if !self.0.has_region(name) {
                return Err(NucleationError::NotFound);
            }
            self.0
                .flip_region_y(name)
                .map_err(|_| NucleationError::InvalidArgument)
        }

        /// Mirror a named region along the Z axis.
        pub fn flip_region_z(&mut self, region_name: &DiplomatStr) -> Result<(), NucleationError> {
            let name = utf8(region_name)?;
            if !self.0.has_region(name) {
                return Err(NucleationError::NotFound);
            }
            self.0
                .flip_region_z(name)
                .map_err(|_| NucleationError::InvalidArgument)
        }

        /// Rotate a named region about the X axis by a multiple of 90 degrees.
        pub fn rotate_region_x(
            &mut self,
            region_name: &DiplomatStr,
            degrees: i32,
        ) -> Result<(), NucleationError> {
            let name = utf8(region_name)?;
            if !self.0.has_region(name) {
                return Err(NucleationError::NotFound);
            }
            self.0
                .rotate_region_x(name, degrees)
                .map_err(|_| NucleationError::InvalidArgument)
        }

        /// Rotate a named region clockwise about the Y axis by a multiple of
        /// 90 degrees.
        pub fn rotate_region_y(
            &mut self,
            region_name: &DiplomatStr,
            degrees: i32,
        ) -> Result<(), NucleationError> {
            let name = utf8(region_name)?;
            if !self.0.has_region(name) {
                return Err(NucleationError::NotFound);
            }
            self.0
                .rotate_region_y(name, degrees)
                .map_err(|_| NucleationError::InvalidArgument)
        }

        /// Rotate a named region about the Z axis by a multiple of 90 degrees.
        pub fn rotate_region_z(
            &mut self,
            region_name: &DiplomatStr,
            degrees: i32,
        ) -> Result<(), NucleationError> {
            let name = utf8(region_name)?;
            if !self.0.has_region(name) {
                return Err(NucleationError::NotFound);
            }
            self.0
                .rotate_region_z(name, degrees)
                .map_err(|_| NucleationError::InvalidArgument)
        }

        /// Move one named region without affecting its siblings.
        pub fn translate_region(
            &mut self,
            region_name: &DiplomatStr,
            dx: i32,
            dy: i32,
            dz: i32,
        ) -> Result<(), NucleationError> {
            let name = utf8(region_name)?;
            if !self.0.has_region(name) {
                return Err(NucleationError::NotFound);
            }
            self.0
                .translate_region(name, dx, dy, dz)
                .map_err(|_| NucleationError::InvalidArgument)
        }

        /// Rotate every region as one rigid schematic around the shared bounds.
        pub fn rotate_schematic_x(&mut self, degrees: i32) -> Result<(), NucleationError> {
            self.0
                .rotate_schematic_x(degrees)
                .map_err(|_| NucleationError::InvalidArgument)
        }

        /// Rotate every region as one rigid schematic around the shared bounds.
        pub fn rotate_schematic_y(&mut self, degrees: i32) -> Result<(), NucleationError> {
            self.0
                .rotate_schematic_y(degrees)
                .map_err(|_| NucleationError::InvalidArgument)
        }

        /// Rotate every region as one rigid schematic around the shared bounds.
        pub fn rotate_schematic_z(&mut self, degrees: i32) -> Result<(), NucleationError> {
            self.0
                .rotate_schematic_z(degrees)
                .map_err(|_| NucleationError::InvalidArgument)
        }

        /// Mirror every region across the shared schematic X bounds.
        pub fn flip_schematic_x(&mut self) -> Result<(), NucleationError> {
            self.0
                .flip_schematic_x()
                .map_err(|_| NucleationError::InvalidArgument)
        }

        /// Mirror every region across the shared schematic Y bounds.
        pub fn flip_schematic_y(&mut self) -> Result<(), NucleationError> {
            self.0
                .flip_schematic_y()
                .map_err(|_| NucleationError::InvalidArgument)
        }

        /// Mirror every region across the shared schematic Z bounds.
        pub fn flip_schematic_z(&mut self) -> Result<(), NucleationError> {
            self.0
                .flip_schematic_z()
                .map_err(|_| NucleationError::InvalidArgument)
        }

        /// Move every region by the same delta, preserving their relative layout.
        pub fn translate_schematic(
            &mut self,
            dx: i32,
            dy: i32,
            dz: i32,
        ) -> Result<(), NucleationError> {
            self.0
                .translate_schematic(dx, dy, dz)
                .map_err(|_| NucleationError::InvalidArgument)
        }

        // --- Building ---

        /// Fill a cuboid with a block.
        #[allow(clippy::too_many_arguments)]
        pub fn fill_cuboid(
            &mut self,
            min_x: i32,
            min_y: i32,
            min_z: i32,
            max_x: i32,
            max_y: i32,
            max_z: i32,
            block_name: &DiplomatStr,
        ) -> Result<(), NucleationError> {
            let name = utf8(block_name)?.to_string();
            let block = crate::BlockState::new(name);
            let shape = crate::building::ShapeEnum::Cuboid(crate::building::Cuboid::new(
                (min_x, min_y, min_z),
                (max_x, max_y, max_z),
            ));
            let brush = crate::building::SolidBrush::new(block);
            let mut tool = crate::building::BuildingTool::new(&mut self.0);
            tool.fill(&shape, &brush);
            Ok(())
        }

        /// Fill a sphere with a block.
        pub fn fill_sphere(
            &mut self,
            cx: f32,
            cy: f32,
            cz: f32,
            radius: f32,
            block_name: &DiplomatStr,
        ) -> Result<(), NucleationError> {
            let name = utf8(block_name)?.to_string();
            let block = crate::BlockState::new(name);
            let shape = crate::building::ShapeEnum::Sphere(crate::building::Sphere::new(
                (cx as i32, cy as i32, cz as i32),
                radius as f64,
            ));
            let brush = crate::building::SolidBrush::new(block);
            let mut tool = crate::building::BuildingTool::new(&mut self.0);
            tool.fill(&shape, &brush);
            Ok(())
        }

        // --- Format management ---

        /// Serialize to a named format, base64-encoded. `version` and `settings`
        /// may be empty strings for defaults.
        pub fn save_as_b64(
            &self,
            format: &DiplomatStr,
            version: &DiplomatStr,
            settings: &DiplomatStr,
            out: &mut DiplomatWrite,
        ) -> Result<(), NucleationError> {
            let fmt = utf8(format)?;
            let ver = utf8(version)?;
            let ver = if ver.is_empty() { None } else { Some(ver) };
            let settings_str = utf8(settings)?;
            let settings_str = if settings_str.is_empty() {
                None
            } else {
                Some(settings_str)
            };
            let manager = get_manager();
            let manager = manager.lock().map_err(|_| NucleationError::Lock)?;
            let data = manager
                .write_with_settings(fmt, &self.0, ver, settings_str)
                .map_err(|_| NucleationError::Serialize)?;
            let _ = write!(out, "{}", b64(&data));
            Ok(())
        }

        /// Save to a file. If `format` is empty, the format is auto-detected from
        /// the file extension; `version` may be empty for the default.
        /// Not available in JS (no filesystem in WASM) — use `save_as_b64`.
        #[diplomat::attr(js, disable)]
        pub fn save_to_file_with_format(
            &self,
            path: &DiplomatStr,
            format: &DiplomatStr,
            version: &DiplomatStr,
        ) -> Result<(), NucleationError> {
            let path = utf8(path)?;
            let fmt = utf8(format)?;
            let ver = utf8(version)?;
            let ver = if ver.is_empty() { None } else { Some(ver) };
            let manager = get_manager();
            let manager = manager.lock().map_err(|_| NucleationError::Lock)?;
            let bytes = if fmt.is_empty() {
                manager.write_auto_with_settings(path, &self.0, ver, None)
            } else {
                manager.write_with_settings(fmt, &self.0, ver, None)
            }
            .map_err(|_| NucleationError::Serialize)?;
            std::fs::write(path, &bytes).map_err(|_| NucleationError::Io)
        }

        /// Serialize as a Sponge schematic targeting a specific format version,
        /// base64-encoded.
        pub fn to_schematic_version_b64(
            &self,
            version: &DiplomatStr,
            out: &mut DiplomatWrite,
        ) -> Result<(), NucleationError> {
            let ver = utf8(version)?;
            let manager = get_manager();
            let manager = manager.lock().map_err(|_| NucleationError::Lock)?;
            let data = manager
                .write("sponge", &self.0, Some(ver))
                .map_err(|_| NucleationError::Serialize)?;
            let _ = write!(out, "{}", b64(&data));
            Ok(())
        }

        /// The available Sponge schematic exporter versions, as a JSON array of
        /// strings.
        pub fn available_schematic_versions_json(
            out: &mut DiplomatWrite,
        ) -> Result<(), NucleationError> {
            let manager = get_manager();
            let manager = manager.lock().map_err(|_| NucleationError::Lock)?;
            let versions = manager.get_exporter_versions("sponge").unwrap_or_default();
            let json = serde_json::to_string(&versions).map_err(|_| NucleationError::Serialize)?;
            let _ = write!(out, "{}", json);
            Ok(())
        }

        // --- More block setters ---

        /// Set a block with NBT data given as a JSON object of string→string
        /// (may be empty).
        pub fn set_block_with_nbt(
            &mut self,
            x: i32,
            y: i32,
            z: i32,
            block_name: &DiplomatStr,
            nbt_json: &DiplomatStr,
        ) -> Result<(), NucleationError> {
            let name = utf8(block_name)?;
            let json = utf8(nbt_json)?;
            let nbt: HashMap<String, String> = if json.is_empty() {
                HashMap::new()
            } else {
                serde_json::from_str(json).unwrap_or_default()
            };
            self.0
                .set_block_with_nbt(x, y, z, name, nbt)
                .map(|_| ())
                .map_err(|_| NucleationError::Parse)
        }

        /// Set a block (by name) in a named region.
        pub fn set_block_in_region(
            &mut self,
            region_name: &DiplomatStr,
            x: i32,
            y: i32,
            z: i32,
            block_name: &DiplomatStr,
        ) -> Result<(), NucleationError> {
            let region = utf8(region_name)?;
            let block = utf8(block_name)?;
            self.0
                .try_set_block_in_region_str(region, x, y, z, block)
                .and_then(|placed| {
                    placed
                        .then_some(())
                        .ok_or_else(|| "Block placement failed".to_string())
                })
                .map_err(|_| NucleationError::InvalidArgument)
        }

        // --- Palette / bounding box / info ---

        /// Whether a default or named schematic region exists.
        pub fn has_region(&self, region_name: &DiplomatStr) -> Result<bool, NucleationError> {
            Ok(self.0.has_region(utf8(region_name)?))
        }

        /// Create an empty named region. Its first block anchors its bounds.
        pub fn create_region(&mut self, region_name: &DiplomatStr) -> Result<(), NucleationError> {
            self.0
                .create_schematic_region(utf8(region_name)?)
                .map_err(|_| NucleationError::InvalidArgument)
        }

        /// Remove a named region. The default region cannot be removed.
        pub fn remove_region(&mut self, region_name: &DiplomatStr) -> Result<(), NucleationError> {
            let name = utf8(region_name)?;
            if !self.0.has_region(name) {
                return Err(NucleationError::NotFound);
            }
            self.0
                .remove_schematic_region(name)
                .map(|_| ())
                .map_err(|_| NucleationError::InvalidArgument)
        }

        /// Rename a named region. The default region cannot be renamed.
        pub fn rename_region(
            &mut self,
            old_name: &DiplomatStr,
            new_name: &DiplomatStr,
        ) -> Result<(), NucleationError> {
            let old = utf8(old_name)?;
            let new = utf8(new_name)?;
            if !self.0.has_region(old) {
                return Err(NucleationError::NotFound);
            }
            self.0
                .rename_schematic_region(old, new)
                .map_err(|_| NucleationError::InvalidArgument)
        }

        /// The schematic bounding box as a JSON array
        /// `[min_x, min_y, min_z, max_x, max_y, max_z]`.
        pub fn bounding_box_json(&self, out: &mut DiplomatWrite) {
            let bbox = self.0.get_bounding_box();
            let _ = write!(
                out,
                "[{},{},{},{},{},{}]",
                bbox.min.0, bbox.min.1, bbox.min.2, bbox.max.0, bbox.max.1, bbox.max.2
            );
        }

        /// A named region's bounding box as a JSON array
        /// `[min_x, min_y, min_z, max_x, max_y, max_z]`. `"default"`/`"Default"`
        /// address the default region.
        pub fn region_bounding_box_json(
            &self,
            region_name: &DiplomatStr,
            out: &mut DiplomatWrite,
        ) -> Result<(), NucleationError> {
            let name = utf8(region_name)?;
            let region = self
                .0
                .get_region(name)
                .or_else(|| {
                    (name == "default" || name == "Default").then_some(&self.0.default_region)
                })
                .ok_or(NucleationError::NotFound)?;
            // The tight content bounds (min/max of placed non-air blocks), not
            // the internal storage box — which over-allocates by up to 64 blocks
            // per axis and would otherwise leak allocation padding into the
            // reported bounds. Empty regions fall back to their (degenerate)
            // origin box.
            let bbox = region
                .get_tight_bounds()
                .unwrap_or_else(|| region.get_bounding_box());
            let _ = write!(
                out,
                "[{},{},{},{},{},{}]",
                bbox.min.0, bbox.min.1, bbox.min.2, bbox.max.0, bbox.max.1, bbox.max.2
            );
            Ok(())
        }

        /// The merged-region palette block names, as a JSON array of strings.
        pub fn palette_json(&self, out: &mut DiplomatWrite) {
            let merged = self.0.get_merged_region();
            let names: Vec<&str> = merged.palette.iter().map(|bs| bs.name.as_str()).collect();
            let json = serde_json::to_string(&names).unwrap_or_else(|_| "[]".to_string());
            let _ = write!(out, "{}", json);
        }

        /// The tight (content) dimensions.
        pub fn tight_dimensions(&self) -> Dimensions {
            let (x, y, z) = self.0.get_tight_dimensions();
            Dimensions { x, y, z }
        }

        /// The allocated dimensions (same as `dimensions`; named for parity with
        /// the old `schematic_get_allocated_dimensions`).
        pub fn allocated_dimensions(&self) -> Dimensions {
            let (x, y, z) = self.0.get_dimensions();
            Dimensions { x, y, z }
        }

        /// Every sign in the schematic, as a JSON array of
        /// `{"pos": [x,y,z], "text": [...]}`.
        pub fn extract_signs_json(&self, out: &mut DiplomatWrite) {
            let signs = crate::insign::extract_signs(&self.0);
            // SignInput doesn't derive Serialize, manually build JSON.
            let json_array: Vec<String> = signs
                .iter()
                .map(|sign| {
                    format!(
                        "{{\"pos\":[{},{},{}],\"text\":{}}}",
                        sign.pos[0],
                        sign.pos[1],
                        sign.pos[2],
                        serde_json::to_string(&sign.text).unwrap_or_default()
                    )
                })
                .collect();
            let _ = write!(out, "[{}]", json_array.join(","));
        }

        /// Compile the schematic's insign annotations to JSON.
        pub fn compile_insign_json(&self, out: &mut DiplomatWrite) -> Result<(), NucleationError> {
            let data = crate::insign::compile_schematic_insign(&self.0)
                .map_err(|_| NucleationError::Parse)?;
            let json = serde_json::to_string(&data).map_err(|_| NucleationError::Serialize)?;
            let _ = write!(out, "{}", json);
            Ok(())
        }

        /// Every region's palette, as a JSON object mapping region name → array of
        /// block names (the default region under `"default"`).
        pub fn all_palettes_json(&self, out: &mut DiplomatWrite) {
            let mut palettes: HashMap<String, Vec<String>> = HashMap::new();
            let default_blocks: Vec<String> = self
                .0
                .default_region
                .palette
                .iter()
                .map(|bs| bs.name.to_string())
                .collect();
            palettes.insert("default".to_string(), default_blocks);
            for (name, region) in &self.0.other_regions {
                let blocks: Vec<String> = region
                    .palette
                    .iter()
                    .map(|bs| bs.name.to_string())
                    .collect();
                palettes.insert(name.clone(), blocks);
            }
            let json = serde_json::to_string(&palettes).unwrap_or_else(|_| "{}".to_string());
            let _ = write!(out, "{}", json);
        }

        /// The default region's palette block names, as a JSON array of strings.
        pub fn default_region_palette_json(&self, out: &mut DiplomatWrite) {
            let names: Vec<&str> = self
                .0
                .default_region
                .palette
                .iter()
                .map(|bs| bs.name.as_str())
                .collect();
            let json = serde_json::to_string(&names).unwrap_or_else(|_| "[]".to_string());
            let _ = write!(out, "{}", json);
        }

        /// A named region's palette block names, as a JSON array of strings.
        /// `"default"`/`"Default"` address the default region.
        pub fn region_palette_json(
            &self,
            region_name: &DiplomatStr,
            out: &mut DiplomatWrite,
        ) -> Result<(), NucleationError> {
            let name = utf8(region_name)?;
            let region = self
                .0
                .get_region(name)
                .or_else(|| {
                    (name == "default" || name == "Default").then_some(&self.0.default_region)
                })
                .ok_or(NucleationError::NotFound)?;
            let names: Vec<&str> = region.palette.iter().map(|bs| bs.name.as_str()).collect();
            let json = serde_json::to_string(&names).unwrap_or_else(|_| "[]".to_string());
            let _ = write!(out, "{}", json);
            Ok(())
        }

        /// The minimum corner of the tight (content) bounds. `NotFound` when the
        /// schematic has no content.
        pub fn tight_bounds_min(&self) -> Result<BlockPos, NucleationError> {
            self.0
                .get_tight_bounds()
                .map(|bbox| BlockPos {
                    x: bbox.min.0,
                    y: bbox.min.1,
                    z: bbox.min.2,
                })
                .ok_or(NucleationError::NotFound)
        }

        /// The maximum corner of the tight (content) bounds. `NotFound` when the
        /// schematic has no content.
        pub fn tight_bounds_max(&self) -> Result<BlockPos, NucleationError> {
            self.0
                .get_tight_bounds()
                .map(|bbox| BlockPos {
                    x: bbox.max.0,
                    y: bbox.max.1,
                    z: bbox.max.2,
                })
                .ok_or(NucleationError::NotFound)
        }
    }

    /// A block state: a block name plus its properties. Port of the old
    /// `BlockStateWrapper` / `blockstate_*` fns.
    #[diplomat::opaque]
    pub struct BlockState(pub(crate) crate::BlockState);

    impl BlockState {
        /// Create a block state with the given name and no properties.
        pub fn create(name: &DiplomatStr) -> Box<BlockState> {
            Box::new(BlockState(crate::BlockState::new(
                String::from_utf8_lossy(name).into_owned(),
            )))
        }

        /// A copy of this block state with `key=value` set; the original is
        /// unchanged.
        pub fn with_property(
            &self,
            key: &DiplomatStr,
            value: &DiplomatStr,
        ) -> Result<Box<BlockState>, NucleationError> {
            let key = utf8(key)?;
            let value = utf8(value)?;
            Ok(Box::new(BlockState(
                self.0.clone().with_property(key, value),
            )))
        }

        /// The block name (e.g. `minecraft:stone`).
        pub fn name(&self, out: &mut DiplomatWrite) {
            let _ = write!(out, "{}", self.0.name);
        }

        /// The properties as a JSON object of string→string (the old
        /// `CPropertyArray`).
        pub fn properties_json(&self, out: &mut DiplomatWrite) {
            let mut map = serde_json::Map::new();
            for (k, v) in &self.0.properties {
                map.insert(k.to_string(), serde_json::Value::String(v.to_string()));
            }
            let json = serde_json::to_string(&serde_json::Value::Object(map))
                .unwrap_or_else(|_| "{}".to_string());
            let _ = write!(out, "{}", json);
        }
    }
}

#[cfg(test)]
mod file_convenience_alias_tests {
    use super::ffi::Schematic;

    #[test]
    fn open_and_save_round_trip_a_file() {
        let path = std::env::temp_dir().join(format!(
            "nucleation-python-open-save-{}.schem",
            std::process::id()
        ));
        let path_bytes = path.to_string_lossy();

        let mut schematic = Schematic::create(b"open-save-regression");
        schematic
            .set_block(0, 0, 0, b"minecraft:stone")
            .expect("place block");
        schematic.save(path_bytes.as_bytes()).expect("save alias");

        let loaded = Schematic::open(path_bytes.as_bytes()).expect("open alias");
        let dimensions = loaded.dimensions();
        assert_eq!((dimensions.x, dimensions.y, dimensions.z), (1, 1, 1));

        std::fs::remove_file(path).expect("remove test file");
    }
}