nucleation 0.3.19

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
use crate::block_entity::BlockEntity;
use crate::entity::Entity;
use crate::formats::error::Result;
use crate::BlockState;
use flate2::read::{GzDecoder, ZlibDecoder};
use flate2::write::ZlibEncoder;
use flate2::Compression;
use quartz_nbt::io::Flavor;
use quartz_nbt::{NbtCompound, NbtList, NbtTag};
use std::io::{Cursor, Read, Seek, SeekFrom, Write};

// ─── Data Structures ────────────────────────────────────────────────────────

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum CompressionType {
    Gzip = 1,
    Zlib = 2,
    Uncompressed = 3,
    Lz4 = 4,
}

impl CompressionType {
    pub fn from_byte(b: u8) -> Result<Self> {
        match b {
            1 => Ok(CompressionType::Gzip),
            2 => Ok(CompressionType::Zlib),
            3 => Ok(CompressionType::Uncompressed),
            4 => Err("LZ4 compression (type 4) is not supported".into()),
            _ => Err(format!("Unknown compression type: {}", b).into()),
        }
    }
}

#[derive(Debug, Clone)]
pub struct ChunkSection {
    pub y: i8,
    pub palette: Vec<BlockState>,
    /// 4096 entries (16x16x16), each is an index into `palette`.
    pub block_states: Vec<u16>,
    /// Raw per-section biome NBT compound (1.18+ `biomes` tag: palette list of
    /// biome ids plus optional packed `data` array), preserved verbatim for
    /// lossless round-trips. `None` means "no biome data" — the writer falls
    /// back to a single-entry plains palette.
    pub biomes: Option<NbtCompound>,
}

#[derive(Debug, Clone)]
pub struct ChunkData {
    pub x: i32,
    pub z: i32,
    pub data_version: i32,
    pub status: String,
    pub sections: Vec<ChunkSection>,
    pub block_entities: Vec<BlockEntity>,
    pub entities: Vec<Entity>,
    /// Minimum section Y (e.g. -4 for overworld 1.18+)
    pub y_pos: i32,
}

#[derive(Debug, Clone)]
pub struct McaFile {
    pub chunks: Vec<Option<ChunkData>>,
    pub region_x: i32,
    pub region_z: i32,
}

// ─── Detection ──────────────────────────────────────────────────────────────

/// Check if data looks like an MCA region file.
///
/// A valid region is sector-aligned, has two 4 KiB header tables, and every
/// populated location entry points to a complete chunk record whose length and
/// compression byte fit inside its allocated sectors. Checking only the first
/// four bytes of a location entry produces false positives for large text files
/// such as GameTest SNBT.
pub fn is_mca(data: &[u8]) -> bool {
    const SECTOR_BYTES: usize = 4096;
    const HEADER_BYTES: usize = 2 * SECTOR_BYTES;

    if data.len() < HEADER_BYTES || !data.len().is_multiple_of(SECTOR_BYTES) {
        return false;
    }
    // Reject zip files (PK\x03\x04 magic) — these are handled by WorldZipFormat.
    if data.starts_with(&[0x50, 0x4B, 0x03, 0x04]) {
        return false;
    }

    let mut found_chunk = false;
    for i in 0..1024 {
        let offset = i * 4;
        let sector_offset = ((data[offset] as usize) << 16)
            | ((data[offset + 1] as usize) << 8)
            | data[offset + 2] as usize;
        let sector_count = data[offset + 3] as usize;

        if sector_offset == 0 && sector_count == 0 {
            continue;
        }
        if sector_offset < 2 || sector_count == 0 {
            return false;
        }

        let Some(byte_offset) = sector_offset.checked_mul(SECTOR_BYTES) else {
            return false;
        };
        let Some(allocated_bytes) = sector_count.checked_mul(SECTOR_BYTES) else {
            return false;
        };
        let Some(allocated_end) = byte_offset.checked_add(allocated_bytes) else {
            return false;
        };
        if byte_offset + 5 > data.len() || allocated_end > data.len() {
            return false;
        }

        let chunk_len = u32::from_be_bytes([
            data[byte_offset],
            data[byte_offset + 1],
            data[byte_offset + 2],
            data[byte_offset + 3],
        ]) as usize;
        let Some(record_len) = chunk_len.checked_add(4) else {
            return false;
        };
        let Some(chunk_end) = byte_offset.checked_add(record_len) else {
            return false;
        };
        if chunk_len <= 1 || record_len > allocated_bytes || chunk_end > data.len() {
            return false;
        }
        if !matches!(data[byte_offset + 4], 1..=4) {
            return false;
        }
        found_chunk = true;
    }
    found_chunk
}

// ─── Read Path ──────────────────────────────────────────────────────────────

impl McaFile {
    /// Parse an MCA region file from raw bytes.
    pub fn from_bytes(data: &[u8], region_x: i32, region_z: i32) -> Result<Self> {
        if data.len() < 8192 {
            return Err("MCA file too small (< 8192 bytes)".into());
        }

        let mut chunks = Vec::with_capacity(1024);
        for _ in 0..1024 {
            chunks.push(None);
        }

        // Parse location table (first 4096 bytes)
        for i in 0..1024u32 {
            let offset = (i as usize) * 4;
            let loc_offset = ((data[offset] as u32) << 16)
                | ((data[offset + 1] as u32) << 8)
                | (data[offset + 2] as u32);
            let sector_count = data[offset + 3] as u32;

            if loc_offset < 2 || sector_count == 0 {
                continue;
            }

            let byte_offset = (loc_offset as usize) * 4096;
            if byte_offset + 5 > data.len() {
                continue;
            }

            // Read chunk header: 4-byte length + 1-byte compression type
            let chunk_len = ((data[byte_offset] as u32) << 24)
                | ((data[byte_offset + 1] as u32) << 16)
                | ((data[byte_offset + 2] as u32) << 8)
                | (data[byte_offset + 3] as u32);

            if chunk_len <= 1 {
                continue;
            }

            let compression_byte = data[byte_offset + 4];
            let compression = CompressionType::from_byte(compression_byte)?;

            let compressed_start = byte_offset + 5;
            let compressed_len = (chunk_len as usize) - 1;
            if compressed_start + compressed_len > data.len() {
                continue;
            }

            let compressed_data = &data[compressed_start..compressed_start + compressed_len];

            // Decompress
            let decompressed = decompress_chunk(compressed_data, compression)?;

            // Parse NBT
            let (nbt, _) =
                quartz_nbt::io::read_nbt(&mut Cursor::new(&decompressed), Flavor::Uncompressed)?;

            // Parse chunk data
            let chunk_x = (region_x * 32) + ((i % 32) as i32);
            let chunk_z = (region_z * 32) + ((i / 32) as i32);

            match parse_chunk_nbt(&nbt, chunk_x, chunk_z) {
                Ok(chunk) => {
                    chunks[i as usize] = Some(chunk);
                }
                Err(_e) => {
                    // Skip malformed chunks
                    continue;
                }
            }
        }

        Ok(McaFile {
            chunks,
            region_x,
            region_z,
        })
    }

    /// Parse an MCA file without known region coordinates (inferred from chunk data).
    pub fn from_bytes_auto(data: &[u8]) -> Result<Self> {
        // First pass: find any chunk to determine region coordinates
        let mut region_x = 0i32;
        let mut region_z = 0i32;
        let mut found = false;

        if data.len() < 8192 {
            return Err("MCA file too small (< 8192 bytes)".into());
        }

        for i in 0..1024u32 {
            let offset = (i as usize) * 4;
            let loc_offset = ((data[offset] as u32) << 16)
                | ((data[offset + 1] as u32) << 8)
                | (data[offset + 2] as u32);
            let sector_count = data[offset + 3] as u32;

            if loc_offset < 2 || sector_count == 0 {
                continue;
            }

            let byte_offset = (loc_offset as usize) * 4096;
            if byte_offset + 5 > data.len() {
                continue;
            }

            let chunk_len = ((data[byte_offset] as u32) << 24)
                | ((data[byte_offset + 1] as u32) << 16)
                | ((data[byte_offset + 2] as u32) << 8)
                | (data[byte_offset + 3] as u32);

            if chunk_len <= 1 {
                continue;
            }

            let compression_byte = data[byte_offset + 4];
            let compression = match CompressionType::from_byte(compression_byte) {
                Ok(c) => c,
                Err(_) => continue,
            };

            let compressed_start = byte_offset + 5;
            let compressed_len = (chunk_len as usize) - 1;
            if compressed_start + compressed_len > data.len() {
                continue;
            }

            let compressed_data = &data[compressed_start..compressed_start + compressed_len];
            let decompressed = match decompress_chunk(compressed_data, compression) {
                Ok(d) => d,
                Err(_) => continue,
            };

            let (nbt, _) = match quartz_nbt::io::read_nbt(
                &mut Cursor::new(&decompressed),
                Flavor::Uncompressed,
            ) {
                Ok(r) => r,
                Err(_) => continue,
            };

            // Try to get xPos/zPos from chunk NBT
            if let (Ok(cx), Ok(cz)) = (nbt.get::<_, i32>("xPos"), nbt.get::<_, i32>("zPos")) {
                region_x = floor_div(cx, 32);
                region_z = floor_div(cz, 32);
                found = true;
                break;
            }
        }

        if !found {
            // Default to 0,0 if we can't determine
            region_x = 0;
            region_z = 0;
        }

        Self::from_bytes(data, region_x, region_z)
    }
}

fn decompress_chunk(data: &[u8], compression: CompressionType) -> Result<Vec<u8>> {
    let mut decompressed = Vec::new();
    match compression {
        CompressionType::Zlib => {
            let mut decoder = ZlibDecoder::new(data);
            decoder.read_to_end(&mut decompressed)?;
        }
        CompressionType::Gzip => {
            let mut decoder = GzDecoder::new(data);
            decoder.read_to_end(&mut decompressed)?;
        }
        CompressionType::Uncompressed => {
            decompressed = data.to_vec();
        }
        CompressionType::Lz4 => {
            return Err("LZ4 compression is not supported".into());
        }
    }
    Ok(decompressed)
}

fn parse_chunk_nbt(nbt: &NbtCompound, chunk_x: i32, chunk_z: i32) -> Result<ChunkData> {
    let data_version = nbt.get::<_, i32>("DataVersion").unwrap_or(3700);

    // Status can be at root level or under "Status"
    let status = nbt
        .get::<_, &str>("Status")
        .map(|s| s.to_string())
        .unwrap_or_else(|_| "minecraft:full".to_string());

    let x_pos = nbt.get::<_, i32>("xPos").unwrap_or(chunk_x);
    let z_pos = nbt.get::<_, i32>("zPos").unwrap_or(chunk_z);
    let y_pos = nbt.get::<_, i32>("yPos").unwrap_or(-4);

    // Parse sections
    let mut sections = Vec::new();
    if let Ok(section_list) = nbt.get::<_, &NbtList>("sections") {
        for section_tag in section_list.iter() {
            if let NbtTag::Compound(section_nbt) = section_tag {
                if let Ok(section) = parse_section(section_nbt) {
                    sections.push(section);
                }
            }
        }
    }

    // Parse block entities
    let mut block_entities = Vec::new();
    if let Ok(be_list) = nbt.get::<_, &NbtList>("block_entities") {
        for be_tag in be_list.iter() {
            if let NbtTag::Compound(be_nbt) = be_tag {
                if let Ok(be) = parse_block_entity(be_nbt) {
                    block_entities.push(be);
                }
            }
        }
    }

    // Parse entities (1.17+ stores in separate files, but some chunks still have them)
    let mut entities = Vec::new();
    if let Ok(entity_list) = nbt.get::<_, &NbtList>("Entities") {
        for entity_tag in entity_list.iter() {
            if let NbtTag::Compound(entity_nbt) = entity_tag {
                if let Ok(entity) = Entity::from_nbt(entity_nbt) {
                    entities.push(entity);
                }
            }
        }
    }

    Ok(ChunkData {
        x: x_pos,
        z: z_pos,
        data_version,
        status,
        sections,
        block_entities,
        entities,
        y_pos,
    })
}

fn parse_section(section_nbt: &NbtCompound) -> Result<ChunkSection> {
    let y = section_nbt.get::<_, i8>("Y")?;

    // Parse block_states compound
    let block_states_compound = match section_nbt.get::<_, &NbtCompound>("block_states") {
        Ok(bs) => bs,
        Err(_) => {
            // No block_states = all air section
            return Ok(ChunkSection {
                y,
                palette: vec![BlockState::new("minecraft:air".to_string())],
                block_states: vec![0; 4096],
                biomes: section_nbt.get::<_, &NbtCompound>("biomes").ok().cloned(),
            });
        }
    };

    // Parse palette
    let palette = match block_states_compound.get::<_, &NbtList>("palette") {
        Ok(palette_list) => {
            let mut palette = Vec::new();
            for tag in palette_list.iter() {
                if let NbtTag::Compound(compound) = tag {
                    palette.push(BlockState::from_nbt(compound)?);
                }
            }
            palette
        }
        Err(_) => {
            vec![BlockState::new("minecraft:air".to_string())]
        }
    };

    // Parse packed block state data
    let block_states = if palette.len() <= 1 {
        // Single-entry palette, all blocks are index 0 (no data array needed)
        vec![0u16; 4096]
    } else {
        match block_states_compound.get::<_, &[i64]>("data") {
            Ok(packed_data) => unpack_block_states(packed_data, palette.len()),
            Err(_) => vec![0u16; 4096],
        }
    };

    Ok(ChunkSection {
        y,
        palette,
        block_states,
        biomes: section_nbt.get::<_, &NbtCompound>("biomes").ok().cloned(),
    })
}

/// Build a `biomes` compound holding a single-entry palette of `biome` —
/// i.e. the whole 16x16x16 section is that one biome (no `data` array needed).
pub fn single_biome_compound(biome: &str) -> NbtCompound {
    let mut biomes = NbtCompound::new();
    let biome_palette = vec![NbtTag::String(biome.to_string())];
    biomes.insert("palette", NbtTag::List(NbtList::from(biome_palette)));
    biomes
}

/// Unpack block states from Minecraft's chunk format.
/// CRITICAL: Entries do NOT span across long boundaries (unlike Litematic).
/// Each i64 holds floor(64/bits_per_entry) entries, minimum 4 bits per entry.
pub fn unpack_block_states(packed: &[i64], palette_size: usize) -> Vec<u16> {
    let bits_per_entry = std::cmp::max(
        (palette_size as f64).log2().ceil() as u32,
        4, // Minecraft minimum is 4 bits per entry for chunk sections
    );

    let entries_per_long = 64 / bits_per_entry;
    let mask = (1u64 << bits_per_entry) - 1;

    let mut result = Vec::with_capacity(4096);

    for &long_val in packed {
        let long_unsigned = long_val as u64;
        for j in 0..entries_per_long {
            if result.len() >= 4096 {
                break;
            }
            let index = (long_unsigned >> (j * bits_per_entry)) & mask;
            result.push(index as u16);
        }
    }

    // Pad with 0 if we somehow have fewer than 4096
    result.resize(4096, 0);
    result
}

/// Pack block states into Minecraft's chunk format.
/// Entries do NOT span across long boundaries.
pub fn pack_block_states(indices: &[u16], palette_size: usize) -> Vec<i64> {
    if palette_size <= 1 {
        return Vec::new();
    }

    let bits_per_entry = std::cmp::max((palette_size as f64).log2().ceil() as u32, 4);

    let entries_per_long = 64 / bits_per_entry;
    let num_longs = 4096_usize.div_ceil(entries_per_long as usize);
    let mask = (1u64 << bits_per_entry) - 1;

    let mut packed = vec![0i64; num_longs];

    for (i, &index) in indices.iter().enumerate().take(4096) {
        let long_index = i / entries_per_long as usize;
        let bit_offset = (i % entries_per_long as usize) as u32 * bits_per_entry;
        let value = (index as u64) & mask;
        packed[long_index] |= (value << bit_offset) as i64;
    }

    packed
}

fn parse_block_entity(nbt: &NbtCompound) -> Result<BlockEntity> {
    let id = nbt
        .get::<_, &str>("id")
        .map(|s| s.to_string())
        .unwrap_or_default();

    let x = nbt.get::<_, i32>("x").unwrap_or(0);
    let y = nbt.get::<_, i32>("y").unwrap_or(0);
    let z = nbt.get::<_, i32>("z").unwrap_or(0);

    let mut block_entity = BlockEntity::new(id, (x, y, z));

    // Copy all NBT fields except x, y, z, id (those are handled separately)
    for (key, value) in nbt.inner() {
        match key.as_str() {
            "x" | "y" | "z" | "id" => continue,
            _ => {
                block_entity
                    .nbt_mut()
                    .insert(key.clone(), crate::utils::NbtValue::from_quartz_nbt(value));
            }
        }
    }

    Ok(block_entity)
}

// ─── Entity Region Files (1.17+) ────────────────────────────────────────────

/// Data from a single chunk in an entity region file.
/// Since 1.17+, entities are stored in separate `entities/r.x.z.mca` files.
#[derive(Debug, Clone)]
pub struct EntityChunkData {
    pub chunk_x: i32,
    pub chunk_z: i32,
    pub entities: Vec<Entity>,
}

/// Parse entity chunks from an MCA file (entities/r.x.z.mca format).
/// Uses the same binary MCA format but chunk NBT structure is:
/// { DataVersion: int, Position: int[2], Entities: list<compound> }
pub fn parse_entity_mca(data: &[u8], region_x: i32, region_z: i32) -> Result<Vec<EntityChunkData>> {
    if data.len() < 8192 {
        return Err("Entity MCA file too small (< 8192 bytes)".into());
    }

    let mut result = Vec::new();

    for i in 0..1024u32 {
        let offset = (i as usize) * 4;
        let loc_offset = ((data[offset] as u32) << 16)
            | ((data[offset + 1] as u32) << 8)
            | (data[offset + 2] as u32);
        let sector_count = data[offset + 3] as u32;

        if loc_offset < 2 || sector_count == 0 {
            continue;
        }

        let byte_offset = (loc_offset as usize) * 4096;
        if byte_offset + 5 > data.len() {
            continue;
        }

        let chunk_len = ((data[byte_offset] as u32) << 24)
            | ((data[byte_offset + 1] as u32) << 16)
            | ((data[byte_offset + 2] as u32) << 8)
            | (data[byte_offset + 3] as u32);

        if chunk_len <= 1 {
            continue;
        }

        let compression_byte = data[byte_offset + 4];
        let compression = match CompressionType::from_byte(compression_byte) {
            Ok(c) => c,
            Err(_) => continue,
        };

        let compressed_start = byte_offset + 5;
        let compressed_len = (chunk_len as usize) - 1;
        if compressed_start + compressed_len > data.len() {
            continue;
        }

        let compressed_data = &data[compressed_start..compressed_start + compressed_len];
        let decompressed = match decompress_chunk(compressed_data, compression) {
            Ok(d) => d,
            Err(_) => continue,
        };

        let (nbt, _) =
            match quartz_nbt::io::read_nbt(&mut Cursor::new(&decompressed), Flavor::Uncompressed) {
                Ok(r) => r,
                Err(_) => continue,
            };

        // Entity chunk NBT: Position is int array [chunkX, chunkZ]
        let (chunk_x, chunk_z) = if let Ok(pos) = nbt.get::<_, &[i32]>("Position") {
            if pos.len() >= 2 {
                (pos[0], pos[1])
            } else {
                let cx = (region_x * 32) + ((i % 32) as i32);
                let cz = (region_z * 32) + ((i / 32) as i32);
                (cx, cz)
            }
        } else {
            let cx = (region_x * 32) + ((i % 32) as i32);
            let cz = (region_z * 32) + ((i / 32) as i32);
            (cx, cz)
        };

        let mut entities = Vec::new();
        if let Ok(entity_list) = nbt.get::<_, &NbtList>("Entities") {
            for entity_tag in entity_list.iter() {
                if let NbtTag::Compound(entity_nbt) = entity_tag {
                    if let Ok(entity) = Entity::from_nbt(entity_nbt) {
                        entities.push(entity);
                    }
                }
            }
        }

        if !entities.is_empty() {
            result.push(EntityChunkData {
                chunk_x,
                chunk_z,
                entities,
            });
        }
    }

    Ok(result)
}

/// Build entity chunk NBT for writing to entity region files.
fn build_entity_chunk_nbt(chunk: &EntityChunkData, data_version: i32) -> NbtCompound {
    let mut root = NbtCompound::new();

    root.insert("DataVersion", NbtTag::Int(data_version));
    root.insert(
        "Position",
        NbtTag::IntArray(vec![chunk.chunk_x, chunk.chunk_z]),
    );

    let entity_tags: Vec<NbtTag> = chunk.entities.iter().map(|e| e.to_nbt()).collect();
    root.insert("Entities", NbtTag::List(NbtList::from(entity_tags)));

    root
}

/// Write entity chunks to an MCA file (entities/r.x.z.mca format).
pub fn write_entity_mca(
    chunks: &[EntityChunkData],
    _region_x: i32,
    _region_z: i32,
    data_version: i32,
) -> Result<Vec<u8>> {
    let mut chunk_data_parts: Vec<(u32, Vec<u8>)> = Vec::new();

    for chunk in chunks {
        let local_x = floor_mod(chunk.chunk_x, 32) as u32;
        let local_z = floor_mod(chunk.chunk_z, 32) as u32;
        let index = local_x + local_z * 32;

        let nbt = build_entity_chunk_nbt(chunk, data_version);
        let mut nbt_bytes = Vec::new();
        quartz_nbt::io::write_nbt(&mut nbt_bytes, None, &nbt, Flavor::Uncompressed)?;

        let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
        encoder.write_all(&nbt_bytes)?;
        let compressed = encoder.finish()?;

        chunk_data_parts.push((index, compressed));
    }

    // Sort by index for deterministic output
    chunk_data_parts.sort_by_key(|(idx, _)| *idx);

    // Build MCA file (same format as block region files)
    let mut location_table = vec![0u8; 4096];
    let timestamp_table = vec![0u8; 4096];
    let mut data_sectors = Vec::new();

    let mut current_sector: u32 = 2;

    for (index, compressed) in &chunk_data_parts {
        let chunk_payload_len = compressed.len() as u32 + 1;
        let total_len = 4 + chunk_payload_len;
        let sector_count = (total_len as usize).div_ceil(4096);

        let loc_offset = *index as usize * 4;
        location_table[loc_offset] = ((current_sector >> 16) & 0xFF) as u8;
        location_table[loc_offset + 1] = ((current_sector >> 8) & 0xFF) as u8;
        location_table[loc_offset + 2] = (current_sector & 0xFF) as u8;
        location_table[loc_offset + 3] = sector_count as u8;

        let mut chunk_sector = Vec::new();
        chunk_sector.push(((chunk_payload_len >> 24) & 0xFF) as u8);
        chunk_sector.push(((chunk_payload_len >> 16) & 0xFF) as u8);
        chunk_sector.push(((chunk_payload_len >> 8) & 0xFF) as u8);
        chunk_sector.push((chunk_payload_len & 0xFF) as u8);
        chunk_sector.push(2); // zlib
        chunk_sector.extend_from_slice(compressed);

        let padded_len = sector_count * 4096;
        chunk_sector.resize(padded_len, 0);

        data_sectors.extend_from_slice(&chunk_sector);
        current_sector += sector_count as u32;
    }

    let mut result = Vec::new();
    result.extend_from_slice(&location_table);
    result.extend_from_slice(&timestamp_table);
    result.extend_from_slice(&data_sectors);

    Ok(result)
}

// ─── Write Path ─────────────────────────────────────────────────────────────

impl McaFile {
    /// Write the MCA file to bytes.
    pub fn to_bytes(&self) -> Result<Vec<u8>> {
        let mut chunk_data_parts: Vec<(u32, Vec<u8>)> = Vec::new(); // (index, compressed_nbt)

        for (i, chunk_opt) in self.chunks.iter().enumerate() {
            if let Some(chunk) = chunk_opt {
                let nbt = build_chunk_nbt(chunk);
                let mut nbt_bytes = Vec::new();
                quartz_nbt::io::write_nbt(&mut nbt_bytes, None, &nbt, Flavor::Uncompressed)?;

                // Compress with zlib
                let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
                encoder.write_all(&nbt_bytes)?;
                let compressed = encoder.finish()?;

                chunk_data_parts.push((i as u32, compressed));
            }
        }

        // Build the file: 8KiB header + chunk sectors
        let mut location_table = vec![0u8; 4096];
        let timestamp_table = vec![0u8; 4096];
        let mut data_sectors = Vec::new();

        let mut current_sector: u32 = 2; // First two sectors are headers

        for (index, compressed) in &chunk_data_parts {
            // Chunk header: 4-byte length (including compression byte) + 1-byte compression type
            let chunk_payload_len = compressed.len() as u32 + 1; // +1 for compression byte
            let total_len = 4 + chunk_payload_len; // 4-byte length prefix + payload

            let sector_count = (total_len as usize).div_ceil(4096);

            // Write location table entry
            let loc_offset = *index as usize * 4;
            location_table[loc_offset] = ((current_sector >> 16) & 0xFF) as u8;
            location_table[loc_offset + 1] = ((current_sector >> 8) & 0xFF) as u8;
            location_table[loc_offset + 2] = (current_sector & 0xFF) as u8;
            location_table[loc_offset + 3] = sector_count as u8;

            // Build chunk sector data
            let mut chunk_sector = Vec::new();
            // 4-byte length (big-endian)
            chunk_sector.push(((chunk_payload_len >> 24) & 0xFF) as u8);
            chunk_sector.push(((chunk_payload_len >> 16) & 0xFF) as u8);
            chunk_sector.push(((chunk_payload_len >> 8) & 0xFF) as u8);
            chunk_sector.push((chunk_payload_len & 0xFF) as u8);
            // Compression type (2 = zlib)
            chunk_sector.push(2);
            // Compressed data
            chunk_sector.extend_from_slice(compressed);

            // Pad to 4KiB boundary
            let padded_len = sector_count * 4096;
            chunk_sector.resize(padded_len, 0);

            data_sectors.extend_from_slice(&chunk_sector);
            current_sector += sector_count as u32;
        }

        // Assemble the file
        let mut result = Vec::new();
        result.extend_from_slice(&location_table);
        result.extend_from_slice(&timestamp_table);
        result.extend_from_slice(&data_sectors);

        Ok(result)
    }
}

fn build_chunk_nbt(chunk: &ChunkData) -> NbtCompound {
    let mut root = NbtCompound::new();

    root.insert("DataVersion", NbtTag::Int(chunk.data_version));
    root.insert("xPos", NbtTag::Int(chunk.x));
    root.insert("yPos", NbtTag::Int(chunk.y_pos));
    root.insert("zPos", NbtTag::Int(chunk.z));
    root.insert("Status", NbtTag::String(chunk.status.clone()));

    // Build sections
    let mut section_list = Vec::new();
    for section in &chunk.sections {
        section_list.push(NbtTag::Compound(build_section_nbt(section)));
    }
    root.insert("sections", NbtTag::List(NbtList::from(section_list)));

    // Block entities
    let mut be_list = Vec::new();
    for be in &chunk.block_entities {
        let mut be_nbt = be.to_nbt();
        be_nbt.insert("x", NbtTag::Int(be.position.0));
        be_nbt.insert("y", NbtTag::Int(be.position.1));
        be_nbt.insert("z", NbtTag::Int(be.position.2));
        be_nbt.insert("id", NbtTag::String(be.id.clone()));
        be_list.push(NbtTag::Compound(be_nbt));
    }
    root.insert("block_entities", NbtTag::List(NbtList::from(be_list)));

    // Heightmaps (required by MC 1.18+ for status "minecraft:full")
    root.insert("Heightmaps", NbtTag::Compound(compute_heightmaps(chunk)));

    // isLightOn = 0: tell Minecraft to recalculate lighting on load
    root.insert("isLightOn", NbtTag::Byte(0));

    root
}

fn compute_heightmaps(chunk: &ChunkData) -> NbtCompound {
    let world_min_y = chunk.y_pos * 16;
    let mut motion_blocking = vec![0i32; 256];
    let mut world_surface = vec![0i32; 256];

    // Sort sections by Y descending so we scan from top down
    let mut sorted_sections: Vec<&ChunkSection> = chunk.sections.iter().collect();
    sorted_sections.sort_by(|a, b| b.y.cmp(&a.y));

    for lz in 0..16usize {
        for lx in 0..16usize {
            let col_idx = lz * 16 + lx;

            'outer: for section in &sorted_sections {
                let section_base_y = (section.y as i32) * 16;
                for ly in (0..16i32).rev() {
                    let block_idx = (ly * 256 + lz as i32 * 16 + lx as i32) as usize;
                    let palette_idx = section.block_states[block_idx] as usize;
                    if palette_idx >= section.palette.len() {
                        continue;
                    }
                    let name = &section.palette[palette_idx].name;
                    if !matches!(
                        name.as_str(),
                        "minecraft:air" | "minecraft:cave_air" | "minecraft:void_air"
                    ) {
                        let world_y = section_base_y + ly;
                        let hm_value = world_y - world_min_y + 1;
                        motion_blocking[col_idx] = hm_value;
                        world_surface[col_idx] = hm_value;
                        break 'outer;
                    }
                }
            }
        }
    }

    let mut heightmaps = NbtCompound::new();
    heightmaps.insert(
        "MOTION_BLOCKING",
        NbtTag::LongArray(pack_heightmap(&motion_blocking)),
    );
    heightmaps.insert(
        "WORLD_SURFACE",
        NbtTag::LongArray(pack_heightmap(&world_surface)),
    );
    heightmaps
}

/// Pack 256 heightmap values into a long array (9 bits per entry, entries don't span longs).
fn pack_heightmap(values: &[i32]) -> Vec<i64> {
    let bits_per_entry: usize = 9;
    let entries_per_long = 64 / bits_per_entry; // 7
    let num_longs = 256_usize.div_ceil(entries_per_long); // 37
    let mask = (1u64 << bits_per_entry) - 1;

    let mut packed = vec![0i64; num_longs];

    for (i, &value) in values.iter().enumerate().take(256) {
        let long_index = i / entries_per_long;
        let bit_offset = (i % entries_per_long) * bits_per_entry;
        let v = (value as u64) & mask;
        packed[long_index] |= (v << bit_offset) as i64;
    }

    packed
}

fn build_section_nbt(section: &ChunkSection) -> NbtCompound {
    let mut section_nbt = NbtCompound::new();
    section_nbt.insert("Y", NbtTag::Byte(section.y));

    // Block states
    let mut block_states_compound = NbtCompound::new();

    // Palette
    let palette_nbt: Vec<NbtTag> = section.palette.iter().map(|bs| bs.to_nbt()).collect();
    block_states_compound.insert("palette", NbtTag::List(NbtList::from(palette_nbt)));

    // Packed data (only if palette has more than 1 entry)
    if section.palette.len() > 1 {
        let packed = pack_block_states(&section.block_states, section.palette.len());
        block_states_compound.insert("data", NbtTag::LongArray(packed));
    }

    section_nbt.insert("block_states", NbtTag::Compound(block_states_compound));

    // Biomes (required for MC to accept chunks): preserve any parsed biome
    // data verbatim; otherwise fall back to a single-entry plains palette.
    let biomes = match &section.biomes {
        Some(b) => b.clone(),
        None => single_biome_compound("minecraft:plains"),
    };
    section_nbt.insert("biomes", NbtTag::Compound(biomes));

    section_nbt
}

// ─── Lazy Read Path ─────────────────────────────────────────────────────────

/// Lazily reads chunks from an MCA region file. Parses only the 4 KiB
/// location header up front; each chunk payload is seeked, decompressed,
/// and NBT-parsed on demand. Peak memory ≈ one decompressed chunk.
pub struct RegionReader<R: Read + Seek> {
    reader: R,
    region_x: i32,
    region_z: i32,
    /// (local index 0..1024, absolute byte offset) for present chunks.
    locations: Vec<(u32, u64)>,
}

impl<R: Read + Seek> RegionReader<R> {
    pub fn new(mut reader: R, region_x: i32, region_z: i32) -> Result<Self> {
        let mut header = [0u8; 4096];
        reader
            .read_exact(&mut header)
            .map_err(|_| "MCA file too small (< 4096 byte header)")?;
        let mut locations = Vec::new();
        for i in 0..1024u32 {
            let o = (i as usize) * 4;
            let loc =
                ((header[o] as u32) << 16) | ((header[o + 1] as u32) << 8) | (header[o + 2] as u32);
            let sector_count = header[o + 3];
            if loc >= 2 && sector_count > 0 {
                locations.push((i, (loc as u64) * 4096));
            }
        }
        Ok(Self {
            reader,
            region_x,
            region_z,
            locations,
        })
    }

    /// Like `new`, but infers region coordinates from the first parseable
    /// chunk's xPos/zPos (mirrors `McaFile::from_bytes_auto`).
    pub fn new_auto(reader: R) -> Result<Self> {
        let mut rr = Self::new(reader, 0, 0)?;
        let indices: Vec<u32> = rr.locations.iter().map(|(i, _)| *i).collect();
        for i in indices {
            if let Ok(Some(nbt)) = rr.read_chunk_nbt_at(i) {
                if let (Ok(cx), Ok(cz)) = (nbt.get::<_, i32>("xPos"), nbt.get::<_, i32>("zPos")) {
                    rr.region_x = floor_div(cx, 32);
                    rr.region_z = floor_div(cz, 32);
                    return Ok(rr);
                }
            }
        }
        Err("Could not determine region coordinates from MCA data".into())
    }

    pub fn region_position(&self) -> (i32, i32) {
        (self.region_x, self.region_z)
    }

    /// Chunk coordinates present in the location table (may include chunks
    /// that later fail to parse).
    pub fn chunk_positions(&self) -> Vec<(i32, i32)> {
        self.locations
            .iter()
            .map(|(i, _)| {
                (
                    self.region_x * 32 + (*i % 32) as i32,
                    self.region_z * 32 + (*i / 32) as i32,
                )
            })
            .collect()
    }

    /// Read and parse one chunk by absolute chunk coordinates.
    /// Ok(None) if the chunk is absent from this region.
    pub fn read_chunk(&mut self, cx: i32, cz: i32) -> Result<Option<ChunkData>> {
        let local_x = cx - self.region_x * 32;
        let local_z = cz - self.region_z * 32;
        if !(0..32).contains(&local_x) || !(0..32).contains(&local_z) {
            return Ok(None);
        }
        let index = (local_z * 32 + local_x) as u32;
        debug_assert!(index < 1024, "local chunk index out of range");
        match self.read_chunk_nbt_at(index)? {
            None => Ok(None),
            Some(nbt) => Ok(Some(parse_chunk_nbt(&nbt, cx, cz)?)),
        }
    }

    /// Seek to a chunk payload, decompress, and parse the raw NBT.
    fn read_chunk_nbt_at(&mut self, index: u32) -> Result<Option<quartz_nbt::NbtCompound>> {
        let offset = match self.locations.iter().find(|(i, _)| *i == index) {
            Some((_, off)) => *off,
            None => return Ok(None),
        };
        self.reader.seek(SeekFrom::Start(offset))?;
        let mut head = [0u8; 5];
        self.reader.read_exact(&mut head)?;
        let chunk_len = u32::from_be_bytes([head[0], head[1], head[2], head[3]]);
        if chunk_len <= 1 {
            return Ok(None);
        }
        let compression = CompressionType::from_byte(head[4])?;
        let mut compressed = vec![0u8; (chunk_len as usize) - 1];
        self.reader.read_exact(&mut compressed)?;
        let decompressed = decompress_chunk(&compressed, compression)?;
        let (nbt, _) =
            quartz_nbt::io::read_nbt(&mut Cursor::new(&decompressed), Flavor::Uncompressed)?;
        Ok(Some(nbt))
    }
}

// ─── Utility ────────────────────────────────────────────────────────────────

/// Floor division that handles negative numbers correctly.
/// Rust's integer division truncates toward zero, but we need toward negative infinity.
pub fn floor_div(a: i32, b: i32) -> i32 {
    let d = a / b;
    let r = a % b;
    if (r != 0) && ((r ^ b) < 0) {
        d - 1
    } else {
        d
    }
}

/// Floor modulo that handles negative numbers correctly.
pub fn floor_mod(a: i32, b: i32) -> i32 {
    ((a % b) + b) % b
}

// ─── Tests ──────────────────────────────────────────────────────────────────

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

    // ─── Floor division / modulo ────────────────────────────────────────────

    #[test]
    fn test_floor_div() {
        assert_eq!(floor_div(7, 32), 0);
        assert_eq!(floor_div(32, 32), 1);
        assert_eq!(floor_div(-1, 32), -1);
        assert_eq!(floor_div(-32, 32), -1);
        assert_eq!(floor_div(-33, 32), -2);
        assert_eq!(floor_div(0, 32), 0);
    }

    #[test]
    fn test_floor_mod() {
        assert_eq!(floor_mod(0, 32), 0);
        assert_eq!(floor_mod(1, 32), 1);
        assert_eq!(floor_mod(31, 32), 31);
        assert_eq!(floor_mod(32, 32), 0);
        assert_eq!(floor_mod(-1, 32), 31);
        assert_eq!(floor_mod(-32, 32), 0);
    }

    // ─── Chunk index formula: spec says (x & 31) + (z & 31) * 32 ───────────

    #[test]
    fn test_chunk_index_formula() {
        // Spec: headerIndex = (x & 31) + (z & 31) * 32
        // Chunk (0, 0) in region → index 0
        assert_eq!((0u32 & 31) + (0u32 & 31) * 32, 0);
        // Chunk (1, 0) → index 1
        assert_eq!((1u32 & 31) + (0u32 & 31) * 32, 1);
        // Chunk (0, 1) → index 32
        assert_eq!((0u32 & 31) + (1u32 & 31) * 32, 32);
        // Chunk (31, 31) → index 1023
        assert_eq!((31u32 & 31) + (31u32 & 31) * 32, 1023);
        // Chunk (5, 10) → index 325
        assert_eq!((5u32 & 31) + (10u32 & 31) * 32, 325);

        // Verify our read path mapping matches: i % 32 = x, i / 32 = z
        for i in 0..1024u32 {
            let x = i % 32;
            let z = i / 32;
            assert_eq!((x & 31) + (z & 31) * 32, i);
        }
    }

    // ─── Block state packing: spec says entries don't span longs ────────────

    #[test]
    fn test_pack_unpack_roundtrip() {
        let mut indices = vec![0u16; 4096];
        indices[0] = 1;
        indices[1] = 2;
        indices[15] = 3;
        indices[256] = 4;
        indices[4095] = 5;

        let palette_size = 6;
        let packed = pack_block_states(&indices, palette_size);
        let unpacked = unpack_block_states(&packed, palette_size);

        assert_eq!(indices, unpacked);
    }

    #[test]
    fn test_pack_unpack_4bit_minimum() {
        // Spec: minimum 4 bits per entry even for small palettes (2-16 entries)
        // Palette of 3 entries: ceil(log2(3)) = 2, but minimum is 4
        let mut indices = vec![0u16; 4096];
        indices[0] = 2;
        indices[100] = 1;

        let palette_size = 3;
        let packed = pack_block_states(&indices, palette_size);

        // With 4 bits per entry, 16 entries per long, need 256 longs
        assert_eq!(packed.len(), 256);

        let unpacked = unpack_block_states(&packed, palette_size);
        assert_eq!(indices, unpacked);
    }

    #[test]
    fn test_pack_unpack_exact_4bit_palette() {
        // Exactly 16 entries: needs exactly 4 bits, 16 entries per long, 256 longs
        let mut indices = vec![0u16; 4096];
        for i in 0..4096 {
            indices[i] = (i % 16) as u16;
        }

        let palette_size = 16;
        let packed = pack_block_states(&indices, palette_size);
        assert_eq!(packed.len(), 256); // 4096 / 16 entries_per_long
        let unpacked = unpack_block_states(&packed, palette_size);
        assert_eq!(indices, unpacked);
    }

    #[test]
    fn test_pack_unpack_5bit() {
        // 17-32 entries: needs 5 bits, floor(64/5)=12 entries per long
        let mut indices = vec![0u16; 4096];
        for i in 0..4096 {
            indices[i] = (i % 32) as u16;
        }

        let palette_size = 32;
        let packed = pack_block_states(&indices, palette_size);
        // 5 bits per entry, 12 entries per long, ceil(4096/12)=342 longs
        assert_eq!(packed.len(), 342);
        let unpacked = unpack_block_states(&packed, palette_size);
        assert_eq!(indices, unpacked);
    }

    #[test]
    fn test_pack_unpack_6bit() {
        // 33-64 entries: needs 6 bits, floor(64/6)=10 entries per long
        let mut indices = vec![0u16; 4096];
        for i in 0..4096 {
            indices[i] = (i % 64) as u16;
        }

        let palette_size = 64;
        let packed = pack_block_states(&indices, palette_size);
        // 6 bits, 10 entries/long, ceil(4096/10) = 410
        assert_eq!(packed.len(), 410);
        let unpacked = unpack_block_states(&packed, palette_size);
        assert_eq!(indices, unpacked);
    }

    #[test]
    fn test_pack_unpack_8bit() {
        // 129-256 entries: needs 8 bits, floor(64/8)=8 entries per long
        let mut indices = vec![0u16; 4096];
        for i in 0..4096 {
            indices[i] = (i % 256) as u16;
        }

        let palette_size = 256;
        let packed = pack_block_states(&indices, palette_size);
        assert_eq!(packed.len(), 512); // 4096 / 8
        let unpacked = unpack_block_states(&packed, palette_size);
        assert_eq!(indices, unpacked);
    }

    #[test]
    fn test_pack_unpack_12bit_max() {
        // Max palette 4096 entries: 12 bits, floor(64/12)=5 entries per long
        let mut indices = vec![0u16; 4096];
        for i in 0..4096 {
            indices[i] = i as u16;
        }

        let palette_size = 4096;
        let packed = pack_block_states(&indices, palette_size);
        // 12 bits, 5 entries/long, ceil(4096/5) = 820
        assert_eq!(packed.len(), 820);
        let unpacked = unpack_block_states(&packed, palette_size);
        assert_eq!(indices, unpacked);
    }

    #[test]
    fn test_entries_dont_span_long_boundaries() {
        // Key spec invariant: entries do NOT span across i64 boundaries.
        // With 5 bits per entry, 12 fit in a long (60 bits used, 4 bits padding).
        // If entries DID span, 64/5 = 12.8, so 12 full + 1 partial would span.
        let palette_size = 32; // 5 bits
        let entries_per_long = 64 / 5; // 12
        assert_eq!(entries_per_long, 12);
        let wasted_bits = 64 - entries_per_long * 5; // 4 padding bits
        assert_eq!(wasted_bits, 4);

        // Set entry at boundary: index 11 is last in first long, index 12 is first in second
        let mut indices = vec![0u16; 4096];
        indices[11] = 31; // max for 5-bit
        indices[12] = 31;

        let packed = pack_block_states(&indices, palette_size);

        // Verify first long: entry 11 at bits 55..59, leaving bits 60..63 as padding
        let first_long = packed[0] as u64;
        let entry_11 = (first_long >> (11 * 5)) & 0x1F;
        assert_eq!(entry_11, 31);
        // Bits 60..63 should be zero (padding)
        let padding_bits = first_long >> 60;
        assert_eq!(padding_bits, 0);

        // Second long: entry 12 at bits 0..4
        let second_long = packed[1] as u64;
        let entry_12 = second_long & 0x1F;
        assert_eq!(entry_12, 31);

        let unpacked = unpack_block_states(&packed, palette_size);
        assert_eq!(indices, unpacked);
    }

    #[test]
    fn test_single_palette_no_data() {
        // Spec: single-block sections omit the data field
        let packed = pack_block_states(&[0u16; 4096], 1);
        assert!(packed.is_empty());
    }

    // ─── MCA header / detection ─────────────────────────────────────────────

    #[test]
    fn test_is_mca_detection() {
        // Empty data
        assert!(!is_mca(&[]));
        // Too small (must be >= 8192 bytes per spec: two 4KiB tables)
        assert!(!is_mca(&[0; 100]));
        assert!(!is_mca(&[0; 8191]));
        // Valid header but all-zero location entries = no chunks
        assert!(!is_mca(&[0; 8192]));

        // Valid: one location entry at offset 2 with a complete chunk record.
        let mut data = vec![0u8; 8192 + 4096];
        // Location entry 0: 3-byte BE offset = 2, 1-byte sector count = 1.
        data[0] = 0;
        data[1] = 0;
        data[2] = 2;
        data[3] = 1;
        // Chunk record: BE length includes one compression byte plus payload.
        data[8192..8196].copy_from_slice(&2u32.to_be_bytes());
        data[8196] = CompressionType::Zlib as u8;
        data[8197] = 0;
        assert!(is_mca(&data));
    }

    #[test]
    fn test_is_mca_rejects_offset_less_than_2() {
        // Offset < 2 is invalid (sectors 0-1 are the headers)
        let mut data = vec![0u8; 8192 + 4096];
        // offset=1 means pointing into timestamp table — invalid
        data[0] = 0;
        data[1] = 0;
        data[2] = 1;
        data[3] = 1;
        assert!(!is_mca(&data));
    }

    // ─── MCA binary layout ──────────────────────────────────────────────────

    #[test]
    fn test_mca_header_layout() {
        // Spec: bytes 0x00-0x0FFF = location table, 0x1000-0x1FFF = timestamp table
        let mca = make_single_chunk_mca(0, 0, 0);
        let bytes = mca.to_bytes().unwrap();

        // File must be at least 8192 (header) + some data sectors
        assert!(bytes.len() >= 8192 + 4096);
        // File size must be a multiple of 4096 (sector-aligned)
        assert_eq!(bytes.len() % 4096, 0);

        // Location entry 0 should point to sector 2 (byte 0x2000)
        let offset = ((bytes[0] as u32) << 16) | ((bytes[1] as u32) << 8) | (bytes[2] as u32);
        let sector_count = bytes[3];
        assert_eq!(offset, 2);
        assert!(sector_count >= 1);

        // All other location entries should be zero (only one chunk)
        for i in 1..1024 {
            let off = i * 4;
            let loc = ((bytes[off] as u32) << 16)
                | ((bytes[off + 1] as u32) << 8)
                | (bytes[off + 2] as u32);
            let cnt = bytes[off + 3];
            assert_eq!(loc, 0, "slot {} should have offset 0", i);
            assert_eq!(cnt, 0, "slot {} should have count 0", i);
        }
    }

    #[test]
    fn test_mca_chunk_data_layout() {
        // Spec: chunk data starts with 4-byte BE length + 1-byte compression type + compressed data
        let mca = make_single_chunk_mca(0, 0, 0);
        let bytes = mca.to_bytes().unwrap();

        // Chunk data starts at sector 2 = byte 8192
        let data_start = 8192;

        // 4-byte big-endian length (payload size = compressed_data_len + 1 for compression byte)
        let length = ((bytes[data_start] as u32) << 24)
            | ((bytes[data_start + 1] as u32) << 16)
            | ((bytes[data_start + 2] as u32) << 8)
            | (bytes[data_start + 3] as u32);

        assert!(length > 1, "length must include at least compression byte");

        // Compression type byte
        let compression = bytes[data_start + 4];
        assert_eq!(compression, 2, "should be zlib (type 2)");

        // Compressed data length = length - 1 (subtract compression byte)
        let compressed_len = (length - 1) as usize;
        assert!(compressed_len > 0);

        // Verify the compressed data can be decompressed
        let compressed = &bytes[data_start + 5..data_start + 5 + compressed_len];
        let decompressed = decompress_chunk(compressed, CompressionType::Zlib).unwrap();
        assert!(!decompressed.is_empty());

        // Verify it's valid NBT
        let (nbt, _) =
            quartz_nbt::io::read_nbt(&mut Cursor::new(&decompressed), Flavor::Uncompressed)
                .unwrap();
        assert!(nbt.get::<_, i32>("DataVersion").is_ok());
    }

    #[test]
    fn test_mca_sector_alignment() {
        // Spec: "Minecraft always pads the last chunk's data to be a multiple-of-4096B"
        let mca = make_single_chunk_mca(0, 0, 0);
        let bytes = mca.to_bytes().unwrap();

        assert_eq!(bytes.len() % 4096, 0, "file size must be 4096-byte aligned");

        // Verify sector count in location table matches actual data
        let offset = ((bytes[0] as u32) << 16) | ((bytes[1] as u32) << 8) | (bytes[2] as u32);
        let sector_count = bytes[3] as usize;

        let chunk_data_start = (offset as usize) * 4096;
        let chunk_data_end = chunk_data_start + sector_count * 4096;
        assert!(chunk_data_end <= bytes.len());
    }

    // ─── Chunk indexing: multiple chunks at different locations ──────────────

    #[test]
    fn test_mca_multiple_chunks_indexing() {
        // Place chunks at specific indices matching spec formula: (x & 31) + (z & 31) * 32
        let mut chunks: Vec<Option<ChunkData>> = (0..1024).map(|_| None).collect();

        // Chunk at local (0, 0) → index 0
        chunks[0] = Some(make_chunk(0, 0));
        // Chunk at local (5, 3) → index 5 + 3*32 = 101
        chunks[101] = Some(make_chunk(5, 3));
        // Chunk at local (31, 31) → index 31 + 31*32 = 1023
        chunks[1023] = Some(make_chunk(31, 31));

        let mca = McaFile {
            chunks,
            region_x: 0,
            region_z: 0,
        };

        let bytes = mca.to_bytes().unwrap();
        let mca2 = McaFile::from_bytes(&bytes, 0, 0).unwrap();

        // Verify chunks are at correct indices
        assert!(mca2.chunks[0].is_some());
        assert!(mca2.chunks[101].is_some());
        assert!(mca2.chunks[1023].is_some());

        // Verify positions
        assert_eq!(mca2.chunks[0].as_ref().unwrap().x, 0);
        assert_eq!(mca2.chunks[0].as_ref().unwrap().z, 0);
        assert_eq!(mca2.chunks[101].as_ref().unwrap().x, 5);
        assert_eq!(mca2.chunks[101].as_ref().unwrap().z, 3);
        assert_eq!(mca2.chunks[1023].as_ref().unwrap().x, 31);
        assert_eq!(mca2.chunks[1023].as_ref().unwrap().z, 31);

        // Verify no ghost chunks
        let count = mca2.chunks.iter().filter(|c| c.is_some()).count();
        assert_eq!(count, 3);
    }

    #[test]
    fn test_mca_negative_region_coords() {
        // Region (-1, -2): chunks should have absolute coords in [-32..-1] x [-64..-33]
        let mut chunks: Vec<Option<ChunkData>> = (0..1024).map(|_| None).collect();
        // local (0, 0) → absolute chunk (-32, -64)
        chunks[0] = Some(make_chunk(-32, -64));

        let mca = McaFile {
            chunks,
            region_x: -1,
            region_z: -2,
        };

        let bytes = mca.to_bytes().unwrap();
        let mca2 = McaFile::from_bytes(&bytes, -1, -2).unwrap();

        let chunk = mca2.chunks[0].as_ref().unwrap();
        assert_eq!(chunk.x, -32);
        assert_eq!(chunk.z, -64);
    }

    // ─── Chunk NBT fields per spec ──────────────────────────────────────────

    #[test]
    fn test_chunk_nbt_has_required_fields() {
        let chunk = make_chunk(5, 10);
        let nbt = build_chunk_nbt(&chunk);

        // Spec required fields
        assert_eq!(nbt.get::<_, i32>("DataVersion").unwrap(), 3700);
        assert_eq!(nbt.get::<_, i32>("xPos").unwrap(), 5);
        assert_eq!(nbt.get::<_, i32>("zPos").unwrap(), 10);
        assert_eq!(nbt.get::<_, i32>("yPos").unwrap(), -4);
        assert_eq!(nbt.get::<_, &str>("Status").unwrap(), "minecraft:full");
        assert!(nbt.get::<_, &NbtList>("sections").is_ok());
        assert!(nbt.get::<_, &NbtList>("block_entities").is_ok());
    }

    #[test]
    fn test_section_nbt_structure() {
        let section = ChunkSection {
            y: 4,
            palette: vec![
                BlockState::new("minecraft:air".to_string()),
                BlockState::new("minecraft:stone".to_string()),
            ],
            block_states: vec![0u16; 4096],
            biomes: None,
        };
        let nbt = build_section_nbt(&section);

        // Spec: Y byte, block_states compound, biomes compound
        assert_eq!(nbt.get::<_, i8>("Y").unwrap(), 4);

        let bs = nbt.get::<_, &NbtCompound>("block_states").unwrap();
        assert!(bs.get::<_, &NbtList>("palette").is_ok());
        assert!(bs.get::<_, &[i64]>("data").is_ok());

        let biomes = nbt.get::<_, &NbtCompound>("biomes").unwrap();
        assert!(biomes.get::<_, &NbtList>("palette").is_ok());
    }

    #[test]
    fn test_section_single_palette_omits_data() {
        // Spec: "single-block sections omit the data field"
        let section = ChunkSection {
            y: 0,
            palette: vec![BlockState::new("minecraft:air".to_string())],
            block_states: vec![0u16; 4096],
            biomes: None,
        };
        let nbt = build_section_nbt(&section);
        let bs = nbt.get::<_, &NbtCompound>("block_states").unwrap();
        assert!(
            bs.get::<_, &[i64]>("data").is_err(),
            "single-palette section should omit data"
        );
    }

    // ─── Block state palette in NBT ─────────────────────────────────────────

    #[test]
    fn test_palette_nbt_format() {
        let section = ChunkSection {
            y: 0,
            palette: vec![
                BlockState::new("minecraft:air".to_string()),
                BlockState::new("minecraft:oak_stairs".to_string())
                    .with_property("facing".to_string(), "north".to_string())
                    .with_property("half".to_string(), "bottom".to_string()),
            ],
            block_states: vec![0u16; 4096],
            biomes: None,
        };
        let nbt = build_section_nbt(&section);
        let bs = nbt.get::<_, &NbtCompound>("block_states").unwrap();
        let palette = bs.get::<_, &NbtList>("palette").unwrap();

        // First entry: just Name
        if let NbtTag::Compound(entry) = &palette[0] {
            assert_eq!(entry.get::<_, &str>("Name").unwrap(), "minecraft:air");
            assert!(entry.get::<_, &NbtCompound>("Properties").is_err());
        } else {
            panic!("palette entry should be Compound");
        }

        // Second entry: Name + Properties
        if let NbtTag::Compound(entry) = &palette[1] {
            assert_eq!(
                entry.get::<_, &str>("Name").unwrap(),
                "minecraft:oak_stairs"
            );
            let props = entry.get::<_, &NbtCompound>("Properties").unwrap();
            assert_eq!(props.get::<_, &str>("facing").unwrap(), "north");
            assert_eq!(props.get::<_, &str>("half").unwrap(), "bottom");
        } else {
            panic!("palette entry should be Compound");
        }
    }

    // ─── Block entity roundtrip ─────────────────────────────────────────────

    #[test]
    fn test_block_entity_roundtrip() {
        let mut be = BlockEntity::new("minecraft:chest".to_string(), (10, 64, 20));
        be.nbt_mut().insert(
            "CustomName".to_string(),
            crate::utils::NbtValue::String("Test Chest".to_string()),
        );

        let section = ChunkSection {
            y: 4,
            palette: vec![
                BlockState::new("minecraft:air".to_string()),
                BlockState::new("minecraft:chest".to_string()),
            ],
            block_states: {
                let mut bs = vec![0u16; 4096];
                bs[0] = 1;
                bs
            },
            biomes: None,
        };

        let chunk = ChunkData {
            x: 0,
            z: 1,
            data_version: 3700,
            status: "minecraft:full".to_string(),
            sections: vec![section],
            block_entities: vec![be],
            entities: Vec::new(),
            y_pos: -4,
        };

        let mut chunks: Vec<Option<ChunkData>> = (0..1024).map(|_| None).collect();
        // index = (0 & 31) + (1 & 31) * 32 = 32
        chunks[32] = Some(chunk);

        let mca = McaFile {
            chunks,
            region_x: 0,
            region_z: 0,
        };

        let bytes = mca.to_bytes().unwrap();
        let mca2 = McaFile::from_bytes(&bytes, 0, 0).unwrap();
        let chunk2 = mca2.chunks[32].as_ref().unwrap();

        assert_eq!(chunk2.block_entities.len(), 1);
        assert_eq!(chunk2.block_entities[0].id, "minecraft:chest");
        assert_eq!(chunk2.block_entities[0].position, (10, 64, 20));
    }

    // ─── Compression type ───────────────────────────────────────────────────

    #[test]
    fn test_compression_type_values() {
        // Spec: 1=Gzip, 2=Zlib, 3=Uncompressed, 4=LZ4
        assert_eq!(
            CompressionType::from_byte(1).unwrap(),
            CompressionType::Gzip
        );
        assert_eq!(
            CompressionType::from_byte(2).unwrap(),
            CompressionType::Zlib
        );
        assert_eq!(
            CompressionType::from_byte(3).unwrap(),
            CompressionType::Uncompressed
        );
        // LZ4 returns error (unsupported)
        assert!(CompressionType::from_byte(4).is_err());
        // Unknown type
        assert!(CompressionType::from_byte(5).is_err());
        assert!(CompressionType::from_byte(127).is_err());
    }

    // ─── Section Y ordering ─────────────────────────────────────────────────

    #[test]
    fn test_multiple_sections_y_ordering() {
        let sections = vec![
            make_section(-4, "minecraft:bedrock"),
            make_section(0, "minecraft:stone"),
            make_section(4, "minecraft:air"),
        ];

        let chunk = ChunkData {
            x: 0,
            z: 0,
            data_version: 3700,
            status: "minecraft:full".to_string(),
            sections,
            block_entities: Vec::new(),
            entities: Vec::new(),
            y_pos: -4,
        };

        let mut chunks: Vec<Option<ChunkData>> = (0..1024).map(|_| None).collect();
        chunks[0] = Some(chunk);

        let mca = McaFile {
            chunks,
            region_x: 0,
            region_z: 0,
        };

        let bytes = mca.to_bytes().unwrap();
        let mca2 = McaFile::from_bytes(&bytes, 0, 0).unwrap();
        let chunk2 = mca2.chunks[0].as_ref().unwrap();

        assert_eq!(chunk2.sections.len(), 3);
        // Verify section Y values preserved
        let ys: Vec<i8> = chunk2.sections.iter().map(|s| s.y).collect();
        assert!(ys.contains(&-4));
        assert!(ys.contains(&0));
        assert!(ys.contains(&4));
    }

    // ─── Full MCA roundtrip with all features ───────────────────────────────

    #[test]
    fn test_mca_roundtrip() {
        let mut section = ChunkSection {
            y: 0,
            palette: vec![
                BlockState::new("minecraft:air".to_string()),
                BlockState::new("minecraft:stone".to_string()),
            ],
            block_states: vec![0u16; 4096],
            biomes: None,
        };
        section.block_states[0] = 1;
        section.block_states[1] = 1;
        section.block_states[100] = 1;

        let chunk = ChunkData {
            x: 0,
            z: 0,
            data_version: 3700,
            status: "minecraft:full".to_string(),
            sections: vec![section],
            block_entities: Vec::new(),
            entities: Vec::new(),
            y_pos: -4,
        };

        let mut chunks: Vec<Option<ChunkData>> = (0..1024).map(|_| None).collect();
        chunks[0] = Some(chunk);

        let mca = McaFile {
            chunks,
            region_x: 0,
            region_z: 0,
        };

        let bytes = mca.to_bytes().unwrap();
        assert!(is_mca(&bytes));

        let mca2 = McaFile::from_bytes(&bytes, 0, 0).unwrap();
        let chunk2 = mca2.chunks[0].as_ref().unwrap();
        assert_eq!(chunk2.x, 0);
        assert_eq!(chunk2.z, 0);
        assert_eq!(chunk2.data_version, 3700);
        assert_eq!(chunk2.status, "minecraft:full");
        assert_eq!(chunk2.y_pos, -4);
        assert_eq!(chunk2.sections.len(), 1);
        assert_eq!(chunk2.sections[0].palette.len(), 2);
        assert_eq!(chunk2.sections[0].palette[0].name, "minecraft:air");
        assert_eq!(chunk2.sections[0].palette[1].name, "minecraft:stone");
        assert_eq!(chunk2.sections[0].block_states[0], 1);
        assert_eq!(chunk2.sections[0].block_states[1], 1);
        assert_eq!(chunk2.sections[0].block_states[100], 1);
        assert_eq!(chunk2.sections[0].block_states[2], 0);
    }

    #[test]
    fn test_mca_roundtrip_with_properties() {
        // Verify block properties survive roundtrip
        let section = ChunkSection {
            y: 0,
            palette: vec![
                BlockState::new("minecraft:air".to_string()),
                BlockState::new("minecraft:redstone_wire".to_string())
                    .with_property("power".to_string(), "15".to_string())
                    .with_property("east".to_string(), "side".to_string()),
                BlockState::new("minecraft:oak_stairs".to_string())
                    .with_property("facing".to_string(), "north".to_string())
                    .with_property("half".to_string(), "top".to_string())
                    .with_property("shape".to_string(), "straight".to_string()),
            ],
            block_states: {
                let mut bs = vec![0u16; 4096];
                bs[0] = 1;
                bs[1] = 2;
                bs
            },
            biomes: None,
        };

        let chunk = ChunkData {
            x: 0,
            z: 0,
            data_version: 3700,
            status: "minecraft:full".to_string(),
            sections: vec![section],
            block_entities: Vec::new(),
            entities: Vec::new(),
            y_pos: -4,
        };

        let mut chunks: Vec<Option<ChunkData>> = (0..1024).map(|_| None).collect();
        chunks[0] = Some(chunk);

        let mca = McaFile {
            chunks,
            region_x: 0,
            region_z: 0,
        };

        let bytes = mca.to_bytes().unwrap();
        let mca2 = McaFile::from_bytes(&bytes, 0, 0).unwrap();
        let chunk2 = mca2.chunks[0].as_ref().unwrap();

        let redstone = &chunk2.sections[0].palette[1];
        assert_eq!(redstone.name, "minecraft:redstone_wire");
        assert_eq!(redstone.get_property("power"), Some(&SmolStr::from("15")));
        assert_eq!(redstone.get_property("east"), Some(&SmolStr::from("side")));

        let stairs = &chunk2.sections[0].palette[2];
        assert_eq!(stairs.name, "minecraft:oak_stairs");
        assert_eq!(stairs.get_property("facing"), Some(&SmolStr::from("north")));
        assert_eq!(stairs.get_property("half"), Some(&SmolStr::from("top")));
    }

    // ─── Helpers ────────────────────────────────────────────────────────────

    fn make_chunk(x: i32, z: i32) -> ChunkData {
        ChunkData {
            x,
            z,
            data_version: 3700,
            status: "minecraft:full".to_string(),
            sections: vec![ChunkSection {
                y: 0,
                palette: vec![
                    BlockState::new("minecraft:air".to_string()),
                    BlockState::new("minecraft:stone".to_string()),
                ],
                block_states: {
                    let mut bs = vec![0u16; 4096];
                    bs[0] = 1;
                    bs
                },
                biomes: None,
            }],
            block_entities: Vec::new(),
            entities: Vec::new(),
            y_pos: -4,
        }
    }

    fn make_section(y: i8, block_name: &str) -> ChunkSection {
        ChunkSection {
            y,
            palette: vec![
                BlockState::new("minecraft:air".to_string()),
                BlockState::new(block_name.to_string()),
            ],
            block_states: {
                let mut bs = vec![0u16; 4096];
                bs[0] = 1;
                bs
            },
            biomes: None,
        }
    }

    fn make_single_chunk_mca(index: usize, region_x: i32, region_z: i32) -> McaFile {
        let chunk_x = region_x * 32 + (index % 32) as i32;
        let chunk_z = region_z * 32 + (index / 32) as i32;
        let mut chunks: Vec<Option<ChunkData>> = (0..1024).map(|_| None).collect();
        chunks[index] = Some(make_chunk(chunk_x, chunk_z));
        McaFile {
            chunks,
            region_x,
            region_z,
        }
    }
}