wow-adt 0.6.4

Parser for World of Warcraft ADT terrain files with heightmap and texture layer support
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
// chunk.rs - Chunk structures and parsing for ADT files

use std::collections::HashMap;
use std::io::{Read, Seek, SeekFrom};
use std::str;

use crate::ParserContext;
use crate::combined_alpha_map::CombinedAlphaMap;
use crate::error::{AdtError, Result};
use crate::io_helpers::ReadLittleEndian;
use crate::mcnk_subchunks::{McnrSubchunk, McvtSubchunk};
use crate::version::AdtVersion;

/// Common chunk header structure for all chunk types
#[derive(Debug, Clone)]
pub struct ChunkHeader {
    /// Magic signature - 4 bytes identifying the chunk type
    pub magic: [u8; 4],
    /// Size of the chunk data in bytes (not including this header)
    pub size: u32,
}

impl ChunkHeader {
    /// Read a chunk header from a reader
    pub fn read<R: Read>(reader: &mut R) -> Result<Self> {
        let mut magic = [0; 4];
        if reader.read_exact(&mut magic).is_err() {
            return Err(AdtError::UnexpectedEof);
        }

        // WoW files store magic bytes in reverse order, so we need to reverse them
        magic.reverse();

        let size = reader.read_u32_le()?;

        Ok(Self { magic, size })
    }

    /// Convert the magic bytes to a string
    pub fn magic_as_string(&self) -> String {
        str::from_utf8(&self.magic).unwrap_or("????").to_string()
    }

    /// Check if the magic matches the expected value
    pub fn expect_magic(&self, expected: &[u8; 4]) -> Result<()> {
        if self.magic != *expected {
            return Err(AdtError::InvalidMagic {
                expected: str::from_utf8(expected).unwrap_or("????").to_string(),
                found: self.magic_as_string(),
            });
        }
        Ok(())
    }
}

/// MVER chunk - file version information
#[derive(Debug, Clone)]
pub struct MverChunk {
    /// Version number (usually 18)
    pub version: u32,
}

impl MverChunk {
    /// Read a MVER chunk
    pub fn read<R: Read + Seek>(reader: &mut R) -> Result<Self> {
        let header = ChunkHeader::read(reader)?;
        Self::read_with_header(
            header,
            &mut ParserContext {
                reader,
                version: AdtVersion::Vanilla, // Default, will be updated
                position: 0,
            },
        )
    }

    /// Read a MVER chunk with an existing header
    #[allow(dead_code)]
    pub(crate) fn read_with_header<R: Read + Seek>(
        header: ChunkHeader,
        context: &mut ParserContext<R>,
    ) -> Result<Self> {
        header.expect_magic(b"MVER")?;

        if header.size != 4 {
            return Err(AdtError::InvalidChunkSize {
                chunk: "MVER".to_string(),
                size: header.size,
                expected: 4,
            });
        }

        let version = context.reader.read_u32_le()?;

        Ok(Self { version })
    }
}

/// MHDR chunk - header containing offsets to other chunks
#[derive(Debug, Clone, Default)]
pub struct MhdrChunk {
    /// Flags
    pub flags: u32,
    /// Offset to MCIN chunk
    pub mcin_offset: u32,
    /// Offset to MTEX chunk
    pub mtex_offset: u32,
    /// Offset to MMDX chunk
    pub mmdx_offset: u32,
    /// Offset to MMID chunk
    pub mmid_offset: u32,
    /// Offset to MWMO chunk
    pub mwmo_offset: u32,
    /// Offset to MWID chunk
    pub mwid_offset: u32,
    /// Offset to MDDF chunk
    pub mddf_offset: u32,
    /// Offset to MODF chunk
    pub modf_offset: u32,
    /// Offset to MFBO chunk (TBC+)
    pub mfbo_offset: Option<u32>,
    /// Offset to MH2O chunk (WotLK+)
    pub mh2o_offset: Option<u32>,
    /// Offset to MTFX chunk (Cataclysm+)
    pub mtfx_offset: Option<u32>,
}

impl MhdrChunk {
    /// Read an MHDR chunk with an existing header
    #[allow(dead_code)]
    pub(crate) fn read_with_header<R: Read + Seek>(
        header: ChunkHeader,
        context: &mut ParserContext<R>,
    ) -> Result<Self> {
        header.expect_magic(b"MHDR")?;

        let flags = context.reader.read_u32_le()?;
        let mcin_offset = context.reader.read_u32_le()?;
        let mtex_offset = context.reader.read_u32_le()?;
        let mmdx_offset = context.reader.read_u32_le()?;
        let mmid_offset = context.reader.read_u32_le()?;
        let mwmo_offset = context.reader.read_u32_le()?;
        let mwid_offset = context.reader.read_u32_le()?;
        let mddf_offset = context.reader.read_u32_le()?;
        let modf_offset = context.reader.read_u32_le()?;

        // Version-specific fields
        let mut mfbo_offset = None;
        let mut mh2o_offset = None;
        let mut mtfx_offset = None;

        // Determine which version-specific fields to read based on chunk size
        // Each offset is 4 bytes, so base size is 36 (9 fields * 4 bytes)
        let base_size = 36;

        if header.size >= base_size + 4 {
            // TBC+ has MFBO offset
            mfbo_offset = Some(context.reader.read_u32_le()?);

            if header.size >= base_size + 8 {
                // WotLK+ has MH2O offset
                mh2o_offset = Some(context.reader.read_u32_le()?);

                if header.size >= base_size + 12 {
                    // Cataclysm+ has MTFX offset
                    mtfx_offset = Some(context.reader.read_u32_le()?);
                }
            }
        }

        // Skip any remaining bytes in the chunk
        let read_size = base_size
            + if mfbo_offset.is_some() { 4 } else { 0 }
            + if mh2o_offset.is_some() { 4 } else { 0 }
            + if mtfx_offset.is_some() { 4 } else { 0 };

        if header.size > read_size {
            context
                .reader
                .seek(SeekFrom::Current((header.size - read_size) as i64))?;
        }

        Ok(Self {
            flags,
            mcin_offset,
            mtex_offset,
            mmdx_offset,
            mmid_offset,
            mwmo_offset,
            mwid_offset,
            mddf_offset,
            modf_offset,
            mfbo_offset,
            mh2o_offset,
            mtfx_offset,
        })
    }
}

/// MCIN chunk - map chunk index information
#[derive(Debug, Clone)]
pub struct McinChunk {
    /// Entries for each map chunk
    pub entries: Vec<McnkEntry>,
}

/// Entry in MCIN chunk for a map chunk
#[derive(Debug, Clone)]
pub struct McnkEntry {
    /// Offset to MCNK chunk
    pub offset: u32,
    /// Size of MCNK chunk
    pub size: u32,
    /// Flags
    pub flags: u32,
    /// Async object ID (used by the client for loading, usually 0)
    pub async_id: u32,
}

impl McinChunk {
    /// Read an MCIN chunk with an existing header
    #[allow(dead_code)]
    pub(crate) fn read_with_header<R: Read + Seek>(
        header: ChunkHeader,
        context: &mut ParserContext<R>,
    ) -> Result<Self> {
        header.expect_magic(b"MCIN")?;

        // MCIN should have 256 entries (16x16 grid)
        // Each entry is 16 bytes (4 u32 values)
        if header.size != 256 * 16 {
            return Err(AdtError::InvalidChunkSize {
                chunk: "MCIN".to_string(),
                size: header.size,
                expected: 256 * 16,
            });
        }

        let mut entries = Vec::with_capacity(256);

        for _ in 0..256 {
            let offset = context.reader.read_u32_le()?;
            let size = context.reader.read_u32_le()?;
            let flags = context.reader.read_u32_le()?;
            let async_id = context.reader.read_u32_le()?;

            entries.push(McnkEntry {
                offset,
                size,
                flags,
                async_id,
            });
        }

        Ok(Self { entries })
    }
}

/// MTEX chunk - texture filenames
#[derive(Debug, Clone)]
pub struct MtexChunk {
    /// List of texture filenames
    pub filenames: Vec<String>,
}

impl MtexChunk {
    /// Read an MTEX chunk with an existing header
    #[allow(dead_code)]
    pub(crate) fn read_with_header<R: Read + Seek>(
        header: ChunkHeader,
        context: &mut ParserContext<R>,
    ) -> Result<Self> {
        header.expect_magic(b"MTEX")?;

        // Read the entire chunk data
        let mut data = vec![0u8; header.size as usize];
        context.reader.read_exact(&mut data)?;

        // Parse null-terminated strings
        let mut filenames = Vec::new();
        let mut start = 0;

        for i in 0..data.len() {
            if data[i] == 0 {
                if i > start {
                    // Found a null terminator, extract the string
                    if let Ok(filename) = str::from_utf8(&data[start..i]) {
                        filenames.push(filename.to_string());
                    }
                }
                start = i + 1;
            }
        }

        Ok(Self { filenames })
    }
}

/// MMDX chunk - model filenames
#[derive(Debug, Clone)]
pub struct MmdxChunk {
    /// List of model filenames
    pub filenames: Vec<String>,
}

impl MmdxChunk {
    /// Read an MMDX chunk with an existing header
    #[allow(dead_code)]
    pub(crate) fn read_with_header<R: Read + Seek>(
        header: ChunkHeader,
        context: &mut ParserContext<R>,
    ) -> Result<Self> {
        header.expect_magic(b"MMDX")?;

        // Read the entire chunk data
        let mut data = vec![0u8; header.size as usize];
        context.reader.read_exact(&mut data)?;

        // Parse null-terminated strings
        let mut filenames = Vec::new();
        let mut start = 0;

        for i in 0..data.len() {
            if data[i] == 0 {
                if i > start {
                    // Found a null terminator, extract the string
                    if let Ok(filename) = str::from_utf8(&data[start..i]) {
                        filenames.push(filename.to_string());
                    }
                }
                start = i + 1;
            }
        }

        Ok(Self { filenames })
    }
}

/// MMID chunk - model indices
#[derive(Debug, Clone)]
pub struct MmidChunk {
    /// List of offsets into the MMDX chunk
    pub offsets: Vec<u32>,
}

impl MmidChunk {
    /// Read an MMID chunk with an existing header
    #[allow(dead_code)]
    pub(crate) fn read_with_header<R: Read + Seek>(
        header: ChunkHeader,
        context: &mut ParserContext<R>,
    ) -> Result<Self> {
        header.expect_magic(b"MMID")?;

        // Each offset is a u32 (4 bytes)
        let count = header.size / 4;
        let mut offsets = Vec::with_capacity(count as usize);

        for _ in 0..count {
            let offset = context.reader.read_u32_le()?;
            offsets.push(offset);
        }

        Ok(Self { offsets })
    }
}

/// MWMO chunk - WMO filenames
#[derive(Debug, Clone)]
pub struct MwmoChunk {
    /// List of WMO filenames
    pub filenames: Vec<String>,
}

impl MwmoChunk {
    /// Read an MWMO chunk with an existing header
    #[allow(dead_code)]
    pub(crate) fn read_with_header<R: Read + Seek>(
        header: ChunkHeader,
        context: &mut ParserContext<R>,
    ) -> Result<Self> {
        header.expect_magic(b"MWMO")?;

        // Read the entire chunk data
        let mut data = vec![0u8; header.size as usize];
        context.reader.read_exact(&mut data)?;

        // Parse null-terminated strings
        let mut filenames = Vec::new();
        let mut start = 0;

        for i in 0..data.len() {
            if data[i] == 0 {
                if i > start {
                    // Found a null terminator, extract the string
                    if let Ok(filename) = str::from_utf8(&data[start..i]) {
                        filenames.push(filename.to_string());
                    }
                }
                start = i + 1;
            }
        }

        Ok(Self { filenames })
    }

    /// Build a lookup map from byte offsets (as stored in the raw MWMO chunk)
    /// to the corresponding index in `self.filenames`.
    ///
    /// In the ADT file, the MWMO chunk contains a contiguous, null-terminated
    /// string block. Other chunks (namely MWID / MODF) reference WMO names by
    /// storing the starting byte offset of the desired filename within this
    /// raw block. During parsing we already split this block into individual
    /// Rust `String`s; this helper reconstructs the offset→index relationship
    /// so higher‑level code can move from an offset (u32) to an O(1) index
    /// into the parsed `filenames` vector.
    ///
    /// Returns: a `HashMap<u32, usize>` where the key is the starting byte
    /// offset within the original MWMO string blob and the value is the index
    /// in `self.filenames`.
    ///
    /// Note: We recompute this map each call. If many lookups are required,
    /// consider caching the result externally instead of calling repeatedly.
    pub fn get_offset_index_map(&self) -> HashMap<u32, usize> {
        let mut offset_index_map = HashMap::new();
        let mut current_offset = 0;

        for (i, filename) in self.filenames.iter().enumerate() {
            offset_index_map.insert(current_offset, i);
            current_offset += filename.len() as u32 + 1; // +1 for null terminator
        }

        offset_index_map
    }
}

/// MWID chunk - WMO indices
#[derive(Debug, Clone)]
pub struct MwidChunk {
    /// List of offsets into the MWMO chunk
    pub offsets: Vec<u32>,
}

impl MwidChunk {
    /// Read an MWID chunk with an existing header
    #[allow(dead_code)]
    pub(crate) fn read_with_header<R: Read + Seek>(
        header: ChunkHeader,
        context: &mut ParserContext<R>,
    ) -> Result<Self> {
        header.expect_magic(b"MWID")?;

        // Each offset is a u32 (4 bytes)
        let count = header.size / 4;
        let mut offsets = Vec::with_capacity(count as usize);

        for _ in 0..count {
            let offset = context.reader.read_u32_le()?;
            offsets.push(offset);
        }

        Ok(Self { offsets })
    }

    /// Translate the raw MWID offsets into indices into the MWMO filename list.
    ///
    /// Each entry in MWID is a `u32` byte offset into the *raw* MWMO string
    /// block. After parsing MWMO we no longer keep the raw concatenated blob;
    /// instead we have the vector of `filenames`. We therefore reconstruct an
    /// offset→index map (via `MwmoChunk::get_offset_index_map`) and use it to
    /// convert every stored offset into its corresponding filename index.
    ///
    /// Invalid Offsets: If an offset does not correspond to the beginning of
    /// any known filename, we push `usize::MAX` as a sentinel. This preserves
    /// positional alignment with the original MWID data while signaling an
    /// anomalous entry. Callers should treat `usize::MAX` as "unresolved" and
    /// handle/log accordingly.
    ///
    /// Returns: `Vec<usize>` where each element is either a valid index into
    /// `mwmo.filenames` or `usize::MAX` if the offset could not be resolved.
    pub fn get_indices(&self, mwmo: &MwmoChunk) -> Vec<usize> {
        let offset_index_map = mwmo.get_offset_index_map();
        let mut indices = Vec::with_capacity(self.offsets.len());

        for &offset in &self.offsets {
            if let Some(&index) = offset_index_map.get(&offset) {
                indices.push(index);
            } else {
                // Invalid offset, push a placeholder (e.g., usize::MAX)
                indices.push(usize::MAX);
            }
        }

        indices
    }
}

/// MDDF chunk - doodad placement information
#[derive(Debug, Clone)]
pub struct MddfChunk {
    /// List of doodad placements
    pub doodads: Vec<DoodadPlacement>,
}

/// Doodad placement information
#[derive(Debug, Clone)]
pub struct DoodadPlacement {
    /// Index into the MMID list
    pub name_id: u32,
    /// Unique ID
    pub unique_id: u32,
    /// Position (x, y, z)
    pub position: [f32; 3],
    /// Rotation (x, y, z)
    pub rotation: [f32; 3],
    /// Scale (usually 1.0)
    pub scale: f32,
    /// Flags
    pub flags: u16,
}

impl MddfChunk {
    /// Read an MDDF chunk with an existing header
    #[allow(dead_code)]
    pub(crate) fn read_with_header<R: Read + Seek>(
        header: ChunkHeader,
        context: &mut ParserContext<R>,
    ) -> Result<Self> {
        header.expect_magic(b"MDDF")?;

        // Each doodad entry is 36 bytes
        if header.size % 36 != 0 {
            return Err(AdtError::InvalidChunkSize {
                chunk: "MDDF".to_string(),
                size: header.size,
                expected: header.size - (header.size % 36),
            });
        }

        let count = header.size / 36;
        let mut doodads = Vec::with_capacity(count as usize);

        for _ in 0..count {
            let name_id = context.reader.read_u32_le()?;
            let unique_id = context.reader.read_u32_le()?;

            let mut position = [0.0; 3];
            for item in &mut position {
                *item = context.reader.read_f32_le()?;
            }

            let mut rotation = [0.0; 3];
            for item in &mut rotation {
                *item = context.reader.read_f32_le()?;
            }

            let scale = context.reader.read_u16_le()? as f32 / 1024.0;
            let flags = context.reader.read_u16_le()?;

            doodads.push(DoodadPlacement {
                name_id,
                unique_id,
                position,
                rotation,
                scale,
                flags,
            });
        }

        Ok(Self { doodads })
    }
}

/// MODF chunk - model placement information
#[derive(Debug, Clone)]
pub struct ModfChunk {
    /// List of model placements
    pub models: Vec<ModelPlacement>,
}

/// Model placement information
#[derive(Debug, Clone)]
pub struct ModelPlacement {
    /// Index into the MWID list
    pub name_id: u32,
    /// Unique ID
    pub unique_id: u32,
    /// Position (x, y, z)
    pub position: [f32; 3],
    /// Rotation (x, y, z)
    pub rotation: [f32; 3],
    /// Bounds minimum (x, y, z)
    pub bounds_min: [f32; 3],
    /// Bounds maximum (x, y, z)
    pub bounds_max: [f32; 3],
    /// Flags
    pub flags: u16,
    /// Doodad set
    pub doodad_set: u16,
    /// Name set
    pub name_set: u16,
    /// Padding
    pub padding: u16,
}

impl ModfChunk {
    /// Read a MODF chunk with an existing header
    #[allow(dead_code)]
    pub(crate) fn read_with_header<R: Read + Seek>(
        header: ChunkHeader,
        context: &mut ParserContext<R>,
    ) -> Result<Self> {
        header.expect_magic(b"MODF")?;

        // Each model entry is 64 bytes
        if header.size % 64 != 0 {
            return Err(AdtError::InvalidChunkSize {
                chunk: "MODF".to_string(),
                size: header.size,
                expected: header.size - (header.size % 64),
            });
        }

        let count = header.size / 64;
        let mut models = Vec::with_capacity(count as usize);

        for _ in 0..count {
            let name_id = context.reader.read_u32_le()?;
            let unique_id = context.reader.read_u32_le()?;

            let mut position = [0.0; 3];
            for item in &mut position {
                *item = context.reader.read_f32_le()?;
            }

            let mut rotation = [0.0; 3];
            for item in &mut rotation {
                *item = context.reader.read_f32_le()?;
            }

            let mut bounds_min = [0.0; 3];
            for item in &mut bounds_min {
                *item = context.reader.read_f32_le()?;
            }

            let mut bounds_max = [0.0; 3];
            for item in &mut bounds_max {
                *item = context.reader.read_f32_le()?;
            }

            let flags = context.reader.read_u16_le()?;
            let doodad_set = context.reader.read_u16_le()?;
            let name_set = context.reader.read_u16_le()?;
            let padding = context.reader.read_u16_le()?;

            models.push(ModelPlacement {
                name_id,
                unique_id,
                position,
                rotation,
                bounds_min,
                bounds_max,
                flags,
                doodad_set,
                name_set,
                padding,
            });
        }

        Ok(Self { models })
    }
}

/// MCNK chunk - map chunk data
#[derive(Debug, Clone)]
pub struct McnkChunk {
    /// Flags
    pub flags: u32,
    /// Index X
    pub ix: u32,
    /// Index Y
    pub iy: u32,
    /// Number of layers
    pub n_layers: u32,
    /// Number of doodad references
    pub n_doodad_refs: u32,
    /// Offset to MCVT (height map)
    pub mcvt_offset: u32,
    /// Offset to MCNR (normal data)
    pub mcnr_offset: u32,
    /// Offset to MCLY (texture layers)
    pub mcly_offset: u32,
    /// Offset to MCRF (doodad references)
    pub mcrf_offset: u32,
    /// Offset to MCAL (alpha maps)
    pub mcal_offset: u32,
    /// Size of alpha maps
    pub mcal_size: u32,
    /// Offset to MCSH (shadow map)
    pub mcsh_offset: u32,
    /// Size of shadow map
    pub mcsh_size: u32,
    /// Area ID
    pub area_id: u32,
    /// Number of map object references
    pub n_map_obj_refs: u32,
    /// Holes (CMaNGOS: uint32)
    pub holes: u32,
    /// CMaNGOS: s1, s2 fields
    pub s1: u16,
    pub s2: u16,
    /// CMaNGOS: d1, d2, d3 fields
    pub d1: u32,
    pub d2: u32,
    pub d3: u32,
    /// CMaNGOS: predTex field
    pub pred_tex: u32,
    /// CMaNGOS: nEffectDoodad field
    pub n_effect_doodad: u32,
    /// Offset to MCSE (sound emitters)
    pub mcse_offset: u32,
    /// Number of sound emitters
    pub n_sound_emitters: u32,
    /// Offset to MCLQ (liquid data) - only used in pre-WotLK versions
    /// In WotLK+, water data is stored in the root MH2O chunk instead
    pub liquid_offset: u32,
    /// Size of liquid data
    pub liquid_size: u32,
    /// Position (x, y, z)
    pub position: [f32; 3],
    /// Offset to MCCV (vertex colors) / CMaNGOS: textureId in Vanilla
    pub mccv_offset: u32,
    /// Offset to MCLV (vertex lighting) / CMaNGOS: props in Vanilla
    pub mclv_offset: u32,
    /// CMaNGOS: additional fields
    pub texture_id: u32,
    pub props: u32,
    pub effect_id: u32,

    /// Height map (145 vertices, 9x9 grid + extra control points, stored as f32)
    pub height_map: Vec<f32>,
    /// Normal data (145 vertices, 9x9 grid + extra control points, stored as [u8; 3])
    pub normals: Vec<[u8; 3]>,
    /// Texture layers
    pub texture_layers: Vec<McnkTextureLayer>,
    /// Doodad references (indices into MMID)
    pub doodad_refs: Vec<u32>,
    /// Map object references (indices into MWID)
    pub map_obj_refs: Vec<u32>,
    /// Alpha maps (texture blending)
    pub alpha_maps: Vec<u8>,
    /// Legacy liquid data (pre-WotLK)
    pub mclq: Option<crate::mcnk_subchunks::MclqSubchunk>,
    /// Vertex colors (BGRA format, 145 colors for WotLK+)
    pub vertex_colors: Vec<[u8; 4]>,
}

/// MCNK texture layer information
#[derive(Debug, Clone)]
pub struct McnkTextureLayer {
    /// Texture ID (index into MTEX)
    pub texture_id: u32,
    /// Flags
    pub flags: u32,
    /// Offset to alpha map for this layer in MCAL
    pub alpha_map_offset: u32,
    /// Effect ID
    pub effect_id: u32,
}

impl McnkChunk {
    /// Read a MCNK chunk with an existing header
    #[allow(dead_code)]
    pub(crate) fn read_with_header<R: Read + Seek>(
        header: ChunkHeader,
        context: &mut ParserContext<R>,
    ) -> Result<Self> {
        header.expect_magic(b"MCNK")?;

        // The MCNK chunk was found at some offset in the file
        // We need to know where the MCNK chunk started to calculate subchunk positions
        // Since we've already read the 8-byte header, we're 8 bytes past the chunk start
        let chunk_data_start = context.reader.stream_position()?;
        let chunk_start = chunk_data_start - 8;

        // Check if we have enough data for the MCNK header
        // Based on CMaNGOS reference, the MCNK header is 128 bytes in all versions
        if header.size < 128 {
            return Err(AdtError::InvalidChunkSize {
                chunk: "MCNK".to_string(),
                size: header.size,
                expected: 128,
            });
        }

        // Read the MCNK header fields
        let flags = context.reader.read_u32_le()?;
        let ix = context.reader.read_u32_le()?;
        let iy = context.reader.read_u32_le()?;
        let n_layers = context.reader.read_u32_le()?;
        let n_doodad_refs = context.reader.read_u32_le()?;
        let mcvt_offset = context.reader.read_u32_le()?;
        let mcnr_offset = context.reader.read_u32_le()?;
        let mcly_offset = context.reader.read_u32_le()?;
        let mcrf_offset = context.reader.read_u32_le()?;
        let mcal_offset = context.reader.read_u32_le()?;
        let mcal_size = context.reader.read_u32_le()?;
        let mcsh_offset = context.reader.read_u32_le()?;
        let mcsh_size = context.reader.read_u32_le()?;
        let area_id = context.reader.read_u32_le()?;
        let n_map_obj_refs = context.reader.read_u32_le()?;
        let holes = context.reader.read_u32_le()?; // CMaNGOS: uint32, not uint16
        let s1 = context.reader.read_u16_le()?; // CMaNGOS: s1
        let s2 = context.reader.read_u16_le()?; // CMaNGOS: s2
        let d1 = context.reader.read_u32_le()?; // CMaNGOS: d1
        let d2 = context.reader.read_u32_le()?; // CMaNGOS: d2
        let d3 = context.reader.read_u32_le()?; // CMaNGOS: d3
        let pred_tex = context.reader.read_u32_le()?; // CMaNGOS: predTex
        let n_effect_doodad = context.reader.read_u32_le()?; // CMaNGOS: nEffectDoodad

        let mcse_offset = context.reader.read_u32_le()?; // CMaNGOS: ofsSndEmitters
        let n_sound_emitters = context.reader.read_u32_le()?; // CMaNGOS: nSndEmitters
        let liquid_offset = context.reader.read_u32_le()?; // CMaNGOS: ofsLiquid
        let liquid_size = context.reader.read_u32_le()?; // CMaNGOS: sizeLiquid

        // CMaNGOS: position fields (zpos, xpos, ypos)
        let z_pos = context.reader.read_f32_le()?;
        let x_pos = context.reader.read_f32_le()?;
        let y_pos = context.reader.read_f32_le()?;
        let position = [x_pos, y_pos, z_pos]; // Convert to our format

        // CMaNGOS: additional fields at the end
        let texture_id = context.reader.read_u32_le()?; // CMaNGOS: textureId
        let props = context.reader.read_u32_le()?; // CMaNGOS: props
        let effect_id = context.reader.read_u32_le()?; // CMaNGOS: effectId

        // For compatibility, set these to 0 since they don't exist in Vanilla
        let mccv_offset = texture_id; // Reuse texture_id as mccv_offset for later versions
        let mclv_offset = 0;

        // Initialize collections for subchunks
        let mut height_map = Vec::new();
        let mut normals = Vec::new();
        let mut texture_layers = Vec::new();
        let mut doodad_refs = Vec::new();
        let mut map_obj_refs = Vec::new();
        let mut alpha_maps = Vec::new();

        // Read MCVT (height map) - with bounds checking
        if mcvt_offset > 0 {
            let mcvt_abs_pos = chunk_start + mcvt_offset as u64;
            let chunk_end = chunk_start + 8 + header.size as u64;

            // Check if MCVT position is within chunk bounds with sufficient space for header
            if mcvt_abs_pos + 8 <= chunk_end {
                match context.reader.seek(SeekFrom::Start(mcvt_abs_pos)) {
                    Ok(_) => {
                        // Check for MCVT header
                        match ChunkHeader::read(context.reader) {
                            Ok(subheader) => {
                                if subheader.magic == *b"MCVT" {
                                    // Check if the entire MCVT chunk is within bounds
                                    if mcvt_abs_pos + 8 + subheader.size as u64 <= chunk_end {
                                        // Use the proper subchunk reader
                                        match McvtSubchunk::read_with_header(subheader, context) {
                                            Ok(mcvt) => {
                                                height_map = mcvt.heights.to_vec();
                                            }
                                            Err(_) => {
                                                // Silently skip malformed MCVT
                                            }
                                        }
                                    }
                                }
                            }
                            Err(_) => {
                                // Silently skip if we can't read the header
                            }
                        }
                    }
                    Err(_) => {
                        // Silently skip if we can't seek to position
                    }
                }
            }
        }

        // Read MCNR (normals) - with bounds checking
        if mcnr_offset > 0 {
            let mcnr_abs_pos = chunk_start + mcnr_offset as u64;
            let chunk_end = chunk_start + 8 + header.size as u64;

            // Check if MCNR position is within chunk bounds with sufficient space for header
            if mcnr_abs_pos + 8 <= chunk_end {
                match context.reader.seek(SeekFrom::Start(mcnr_abs_pos)) {
                    Ok(_) => {
                        // Check for MCNR header
                        match ChunkHeader::read(context.reader) {
                            Ok(subheader) => {
                                if subheader.magic == *b"MCNR" {
                                    // Check if the entire MCNR chunk is within bounds
                                    if mcnr_abs_pos + 8 + subheader.size as u64 <= chunk_end {
                                        // Use the proper subchunk reader that handles padding
                                        match McnrSubchunk::read_with_header(subheader, context) {
                                            Ok(mcnr) => {
                                                normals = mcnr
                                                    .normals
                                                    .iter()
                                                    .map(|&[x, y, z]| [x as u8, y as u8, z as u8])
                                                    .collect();
                                            }
                                            Err(_) => {
                                                // Silently skip malformed MCNR
                                            }
                                        }
                                    }
                                }
                            }
                            Err(_) => {
                                // Silently skip if we can't read the header
                            }
                        }
                    }
                    Err(_) => {
                        // Silently skip if we can't seek to position
                    }
                }
            }
        }

        // Read MCLY (texture layers)
        if mcly_offset > 0 && n_layers > 0 {
            let mcly_abs_pos = chunk_start + mcly_offset as u64;
            let chunk_end = chunk_start + 8 + header.size as u64;

            if mcly_abs_pos + 8 <= chunk_end {
                match context.reader.seek(SeekFrom::Start(mcly_abs_pos)) {
                    Ok(_) => {
                        // Check for MCLY header
                        match ChunkHeader::read(context.reader) {
                            Ok(subheader) => {
                                if subheader.magic == *b"MCLY" {
                                    // Check if the entire MCLY chunk is within bounds
                                    let expected_size = n_layers * 16; // Each layer entry is 16 bytes
                                    if mcly_abs_pos + 8 + expected_size as u64 <= chunk_end {
                                        texture_layers.reserve(n_layers as usize);

                                        for _ in 0..n_layers {
                                            if let (
                                                Ok(texture_id),
                                                Ok(flags),
                                                Ok(alpha_map_offset),
                                                Ok(effect_id),
                                            ) = (
                                                context.reader.read_u32_le(),
                                                context.reader.read_u32_le(),
                                                context.reader.read_u32_le(),
                                                context.reader.read_u32_le(),
                                            ) {
                                                texture_layers.push(McnkTextureLayer {
                                                    texture_id,
                                                    flags,
                                                    alpha_map_offset,
                                                    effect_id,
                                                });
                                            } else {
                                                break; // Stop on read error
                                            }
                                        }
                                    }
                                }
                            }
                            Err(_) => {
                                // Silently skip if we can't read the header
                            }
                        }
                    }
                    Err(_) => {
                        // Silently skip if we can't seek to position
                    }
                }
            }
        }

        // Read MCRF (doodad references)
        if mcrf_offset > 0 && n_doodad_refs > 0 {
            let mcrf_abs_pos = chunk_start + mcrf_offset as u64;
            let chunk_end = chunk_start + 8 + header.size as u64;

            if mcrf_abs_pos + 8 <= chunk_end {
                match context.reader.seek(SeekFrom::Start(mcrf_abs_pos)) {
                    Ok(_) => {
                        // Check for MCRF header
                        match ChunkHeader::read(context.reader) {
                            Ok(subheader) => {
                                if subheader.magic == *b"MCRF" {
                                    // Check if the entire MCRF chunk is within bounds
                                    let expected_size = n_doodad_refs * 4; // Each reference is a u32 (4 bytes)
                                    if mcrf_abs_pos + 8 + expected_size as u64 <= chunk_end {
                                        doodad_refs.reserve(n_doodad_refs as usize);

                                        for _ in 0..n_doodad_refs {
                                            if let Ok(doodad_ref) = context.reader.read_u32_le() {
                                                doodad_refs.push(doodad_ref);
                                            } else {
                                                break; // Stop on read error
                                            }
                                        }
                                    }
                                }
                            }
                            Err(_) => {
                                // Silently skip if we can't read the header
                            }
                        }
                    }
                    Err(_) => {
                        // Silently skip if we can't seek to position
                    }
                }
            }
        }

        // Read MCRD (map object references) - comes after MCRF
        if n_map_obj_refs > 0 && mcrf_offset > 0 {
            let mcrf_abs_pos = chunk_start + mcrf_offset as u64;
            let chunk_end = chunk_start + 8 + header.size as u64;

            if mcrf_abs_pos + 8 <= chunk_end {
                match context.reader.seek(SeekFrom::Start(mcrf_abs_pos)) {
                    Ok(_) => {
                        // Skip MCRF header and data to get to MCRD
                        match ChunkHeader::read(context.reader) {
                            Ok(subheader) => {
                                if subheader.magic == *b"MCRF" {
                                    // Skip MCRF data to get to MCRD
                                    match context
                                        .reader
                                        .seek(SeekFrom::Current(subheader.size as i64))
                                    {
                                        Ok(_) => {
                                            // Now we should be at MCRD
                                            match ChunkHeader::read(context.reader) {
                                                Ok(mcrd_header) => {
                                                    if mcrd_header.magic == *b"MCRD" {
                                                        // Each reference is a u32
                                                        map_obj_refs
                                                            .reserve(n_map_obj_refs as usize);

                                                        for _ in 0..n_map_obj_refs {
                                                            if let Ok(map_obj_ref) =
                                                                context.reader.read_u32_le()
                                                            {
                                                                map_obj_refs.push(map_obj_ref);
                                                            } else {
                                                                break; // Stop on read error
                                                            }
                                                        }
                                                    }
                                                }
                                                Err(_) => {
                                                    // Silently skip if we can't read MCRD header
                                                }
                                            }
                                        }
                                        Err(_) => {
                                            // Silently skip if we can't seek past MCRF data
                                        }
                                    }
                                }
                            }
                            Err(_) => {
                                // Silently skip if we can't read MCRF header
                            }
                        }
                    }
                    Err(_) => {
                        // Silently skip if we can't seek to MCRF position
                    }
                }
            }
        }

        // Read MCAL (alpha maps)
        if mcal_offset > 0 && mcal_size > 0 {
            let mcal_abs_pos = chunk_start + mcal_offset as u64;
            let chunk_end = chunk_start + 8 + header.size as u64;

            if mcal_abs_pos + 8 <= chunk_end {
                match context.reader.seek(SeekFrom::Start(mcal_abs_pos)) {
                    Ok(_) => {
                        // Check for MCAL header
                        match ChunkHeader::read(context.reader) {
                            Ok(subheader) => {
                                if subheader.magic == *b"MCAL" {
                                    // Check if the entire MCAL chunk is within bounds
                                    if mcal_abs_pos + 8 + subheader.size as u64 <= chunk_end {
                                        // For now, just read the whole chunk and store it
                                        alpha_maps.resize(subheader.size as usize, 0);
                                        // Silently skip if we can't read alpha data
                                        let _ = context.reader.read_exact(&mut alpha_maps);
                                    }
                                }
                            }
                            Err(_) => {
                                // Silently skip if we can't read the header
                            }
                        }
                    }
                    Err(_) => {
                        // Silently skip if we can't seek to position
                    }
                }
            }
        }

        // Read MCLQ (legacy liquid data)
        // IMPORTANT: MCLQ can exist in files detected as "WotLK" because:
        // 1. Vanilla 1.9+ had MCCV vertex colors (triggers WotLK detection)
        // 2. TBC 2.x files had MCCV but used MCLQ for water
        // 3. Early WotLK might have both MCLQ and MH2O during transition
        //
        // Strategy: If liquid_offset/liquid_size are present in MCNK header,
        // try to read MCLQ data. The presence of liquid data in MCNK headers
        // indicates pre-MH2O format, regardless of version detection.
        let mut mclq = None;

        // DEBUG: Log version detection and liquid data for first few chunks
        // Try to parse MCLQ if liquid offset/size are present in MCNK header
        // (This indicates MCLQ format regardless of detected version)
        if liquid_offset > 0 && liquid_size > 0 {
            let mclq_abs_pos = chunk_start + liquid_offset as u64;
            let chunk_end = chunk_start + 8 + header.size as u64;

            if mclq_abs_pos + 8 <= chunk_end {
                match context.reader.seek(SeekFrom::Start(mclq_abs_pos)) {
                    Ok(_) => {
                        // Check for MCLQ header
                        match ChunkHeader::read(context.reader) {
                            Ok(subheader) => {
                                if subheader.magic == *b"MCLQ" {
                                    // IMPORTANT: Use liquid_size from MCNK header, not MCLQ chunk header!
                                    // Per noggit-red: "ignore the size here, the valid size is in the header"
                                    // The MCLQ chunk header often has size=0 even when data exists
                                    let actual_size = liquid_size - 8; // Subtract 8 for MCLQ chunk header

                                    // Override subheader size with actual size from MCNK
                                    let corrected_header = ChunkHeader {
                                        magic: subheader.magic,
                                        size: actual_size,
                                    };

                                    // Check if the entire MCLQ chunk is within bounds
                                    if mclq_abs_pos + 8 + actual_size as u64 <= chunk_end {
                                        // Use the proper subchunk reader, passing MCNK flags for liquid type detection
                                        match crate::mcnk_subchunks::MclqSubchunk::read_with_header(
                                            corrected_header,
                                            flags,
                                            context,
                                        ) {
                                            Ok(mclq_data) => {
                                                mclq = Some(mclq_data);
                                            }
                                            Err(e) => {
                                                // Silently skip InvalidChunkSize errors - these are empty MCLQ placeholders
                                                // Only log other error types
                                                match e {
                                                    AdtError::InvalidChunkSize { .. } => {
                                                        // Empty MCLQ placeholder (liquid_size=8, just the header)
                                                        // This is normal and expected, skip silently
                                                    }
                                                    _ => {
                                                        // MCLQ parsing error - skip silently as these are expected for some chunks
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            Err(_) => {
                                // Silently skip if we can't read the header
                            }
                        }
                    }
                    Err(_) => {
                        // Silently skip if we can't seek to position
                    }
                }
            }
        }

        // Read MCCV (vertex colors) for WotLK+ versions
        let mut vertex_colors = Vec::new();
        if context.version >= crate::version::AdtVersion::WotLK && mccv_offset > 0 {
            let mccv_abs_pos = chunk_start + mccv_offset as u64;
            let chunk_end = chunk_start + 8 + header.size as u64;

            if mccv_abs_pos + 8 <= chunk_end {
                match context.reader.seek(SeekFrom::Start(mccv_abs_pos)) {
                    Ok(_) => {
                        // Check for MCCV header
                        match ChunkHeader::read(context.reader) {
                            Ok(subheader) => {
                                if subheader.magic == *b"MCCV" {
                                    // Check if the entire MCCV chunk is within bounds
                                    if mccv_abs_pos + 8 + subheader.size as u64 <= chunk_end {
                                        // Use the proper subchunk reader
                                        match crate::mcnk_subchunks::MccvSubchunk::read_with_header(
                                            subheader, context,
                                        ) {
                                            Ok(mccv) => {
                                                vertex_colors = mccv.colors;
                                            }
                                            Err(_) => {
                                                // Silently skip malformed MCCV
                                            }
                                        }
                                    }
                                }
                            }
                            Err(_) => {
                                // Silently skip if we can't read the header
                            }
                        }
                    }
                    Err(_) => {
                        // Silently skip if we can't seek to position
                    }
                }
            }
        }

        // Try to seek to the end of this chunk
        // Some malformed chunks might have incorrect sizes, so we handle this gracefully
        let _ = context
            .reader
            .seek(SeekFrom::Start(chunk_start + 8 + header.size as u64));

        Ok(Self {
            flags,
            ix,
            iy,
            n_layers,
            n_doodad_refs,
            mcvt_offset,
            mcnr_offset,
            mcly_offset,
            mcrf_offset,
            mcal_offset,
            mcal_size,
            mcsh_offset,
            mcsh_size,
            area_id,
            n_map_obj_refs,
            holes,
            s1,
            s2,
            d1,
            d2,
            d3,
            pred_tex,
            n_effect_doodad,
            mcse_offset,
            n_sound_emitters,
            liquid_offset,
            liquid_size,
            position,
            mccv_offset,
            mclv_offset,
            texture_id,
            props,
            effect_id,
            height_map,
            normals,
            texture_layers,
            doodad_refs,
            map_obj_refs,
            alpha_maps,
            mclq,
            vertex_colors,
        })
    }

    pub fn get_combined_alpha_map(&self, has_big_alpha: bool, fix_alpha: bool) -> CombinedAlphaMap {
        CombinedAlphaMap::new(self, has_big_alpha, fix_alpha)
    }
}

/// MFBO chunk - flight boundaries (TBC+)
///
/// Contains two planes defining flight boundaries.
/// Each plane has 9 int16 coordinates (18 bytes), totaling 36 bytes.
/// Validated against TrinityCore 3.3.5a and Cataclysm 4.3.4 implementations.
#[derive(Debug, Clone)]
pub struct MfboChunk {
    /// Maximum flight bounds plane (9 int16 values)
    pub max: [i16; 9],
    /// Minimum flight bounds plane (9 int16 values)
    pub min: [i16; 9],
}

impl MfboChunk {
    /// Read a MFBO chunk with an existing header
    #[allow(dead_code)]
    pub(crate) fn read_with_header<R: Read + Seek>(
        header: ChunkHeader,
        context: &mut ParserContext<R>,
    ) -> Result<Self> {
        header.expect_magic(b"MFBO")?;

        // MFBO is always exactly 36 bytes (2 planes × 9 int16 values)
        if header.size != 36 {
            return Err(AdtError::InvalidChunkSize {
                chunk: "MFBO".to_string(),
                size: header.size,
                expected: 36,
            });
        }

        // Read maximum flight bounds plane (9 int16 values)
        let mut max = [0i16; 9];
        for item in &mut max {
            *item = context.reader.read_i16_le()?;
        }

        // Read minimum flight bounds plane (9 int16 values)
        let mut min = [0i16; 9];
        for item in &mut min {
            *item = context.reader.read_i16_le()?;
        }

        Ok(Self { max, min })
    }
}

/// MH2O chunk - water data (WotLK+)
#[derive(Debug, Clone)]
pub struct Mh2oChunk {
    /// Water data for each chunk (256 entries)
    pub chunks: Vec<Mh2oData>,
}

/// Water data for a single chunk
#[derive(Debug, Clone)]
pub struct Mh2oData {
    /// Water flags
    pub flags: u32,
    /// Minimum height of water level
    pub min_height: f32,
    /// Maximum height of water level
    pub max_height: f32,
    /// Water vertex data (if present)
    pub vertices: Option<Vec<Mh2oVertex>>,
    /// Render flags (if present)
    pub render_flags: Option<Vec<u8>>,
}

/// Water vertex data
#[derive(Debug, Clone)]
pub struct Mh2oVertex {
    /// Depth (height) at this point
    pub depth: f32,
    /// Flow direction and velocity
    pub flow: [u8; 2],
}

impl Mh2oChunk {
    /// Read a MH2O chunk with an existing header
    #[allow(dead_code)]
    pub(crate) fn read_with_header<R: Read + Seek>(
        header: ChunkHeader,
        context: &mut ParserContext<R>,
    ) -> Result<Self> {
        header.expect_magic(b"MH2O")?;

        // MH2O starts with a header for each chunk (256 entries)
        // Each header is 6 integers (24 bytes)
        if header.size < 256 * 24 {
            return Err(AdtError::InvalidChunkSize {
                chunk: "MH2O".to_string(),
                size: header.size,
                expected: 256 * 24,
            });
        }

        // Read the headers first
        let start_pos = context.reader.stream_position()? as u32;
        let mut chunks = Vec::with_capacity(256);

        for _ in 0..256 {
            // Read header
            let offset_info = context.reader.read_u32_le()?;
            let layer_count = context.reader.read_u32_le()?;
            let offset_render = context.reader.read_u32_le()?;

            // Skip unused values
            context.reader.seek(SeekFrom::Current(12))?;

            // If this chunk has no water data, all values will be 0
            if offset_info == 0 && layer_count == 0 && offset_render == 0 {
                chunks.push(Mh2oData {
                    flags: 0,
                    min_height: 0.0,
                    max_height: 0.0,
                    vertices: None,
                    render_flags: None,
                });
                continue;
            }

            // Save current position
            let header_end = context.reader.stream_position()? as u32;

            // Read water instance data
            context
                .reader
                .seek(SeekFrom::Start((start_pos + offset_info) as u64))?;

            let flags = context.reader.read_u32_le()?;
            let min_height = context.reader.read_f32_le()?;
            let max_height = context.reader.read_f32_le()?;

            // Read render mask (typically a 8x8 grid of flags)
            let mut render_flags = None;
            if offset_render > 0 {
                context
                    .reader
                    .seek(SeekFrom::Start((start_pos + offset_render) as u64))?;

                let mut flags_data = vec![0u8; 8 * 8];
                context.reader.read_exact(&mut flags_data)?;
                render_flags = Some(flags_data);
            }

            // Read vertex data (if present)
            // This is more complex and would need additional parsing
            // For now, just add a placeholder
            let vertices = None;

            chunks.push(Mh2oData {
                flags,
                min_height,
                max_height,
                vertices,
                render_flags,
            });

            // Return to the next header
            context.reader.seek(SeekFrom::Start(header_end as u64))?;
        }

        // Seek to the end of this chunk
        context
            .reader
            .seek(SeekFrom::Start((start_pos + header.size) as u64))?;

        Ok(Self { chunks })
    }
}

/// MTFX chunk - texture effects (Cataclysm+)
#[derive(Debug, Clone)]
pub struct MtfxChunk {
    /// Texture effects
    pub effects: Vec<TextureEffect>,
}

/// Texture effect data (bitfield structure)
#[derive(Debug, Clone)]
pub struct TextureEffect {
    /// Use cubemap reflection instead of loading specular/height textures (bit 0)
    pub use_cubemap: bool,
    /// Texture scale exponent (bits 4-7): actual scale = 1 << texture_scale (MoP+)
    pub texture_scale: u8,
    /// Raw flags value (for debugging/compatibility)
    pub raw_flags: u32,
}

/// MAMP chunk - texture amplifier (Cataclysm+)
/// This chunk is exactly 4 bytes and contains a single u32 value
#[derive(Debug, Clone, PartialEq)]
pub struct MampChunk {
    /// Texture size amplifier value (typically 0 or powers of 2)
    /// Controls texture tiling/scaling for the terrain
    pub value: u32,
}

/// MTXP chunk - texture parameters (MoP+)
/// Variable size chunk containing texture transformation parameters
#[derive(Debug, Clone, PartialEq)]
pub struct MtxpChunk {
    /// Texture parameter entries
    pub entries: Vec<TextureParams>,
}

/// Texture transformation parameters
#[derive(Debug, Clone, PartialEq)]
pub struct TextureParams {
    /// Unknown texture parameter values (4 float values)
    /// These control texture transformation/scaling properties
    pub params: [f32; 4],
}

impl MampChunk {
    /// Read a MAMP chunk with an existing header
    pub(crate) fn read_with_header<R: Read + Seek>(
        header: ChunkHeader,
        context: &mut ParserContext<R>,
    ) -> Result<Self> {
        header.expect_magic(b"MAMP")?;

        // MAMP is always exactly 4 bytes
        if header.size != 4 {
            return Err(AdtError::InvalidChunkSize {
                chunk: "MAMP".to_string(),
                size: header.size,
                expected: 4,
            });
        }

        // Read the single u32 value
        let value = context.reader.read_u32_le()?;

        Ok(Self { value })
    }
}

impl MtxpChunk {
    /// Read a MTXP chunk with an existing header
    pub(crate) fn read_with_header<R: Read + Seek>(
        header: ChunkHeader,
        context: &mut ParserContext<R>,
    ) -> Result<Self> {
        header.expect_magic(b"MTXP")?;

        // MTXP contains multiple entries of 16 bytes each (4 floats per entry)
        if header.size % 16 != 0 {
            return Err(AdtError::InvalidChunkSize {
                chunk: "MTXP".to_string(),
                size: header.size,
                expected: 0, // Variable size but must be multiple of 16
            });
        }

        let num_entries = (header.size / 16) as usize;
        let mut entries = Vec::with_capacity(num_entries);

        for _ in 0..num_entries {
            let mut params = [0.0f32; 4];
            for param in &mut params {
                *param = context.reader.read_f32_le()?;
            }

            entries.push(TextureParams { params });
        }

        Ok(Self { entries })
    }
}

impl MtfxChunk {
    /// Read a MTFX chunk with an existing header
    #[allow(dead_code)]
    pub(crate) fn read_with_header<R: Read + Seek>(
        header: ChunkHeader,
        context: &mut ParserContext<R>,
    ) -> Result<Self> {
        header.expect_magic(b"MTFX")?;

        // Each effect is a u32 (4 bytes)
        let count = header.size / 4;
        let mut effects = Vec::with_capacity(count as usize);

        for _ in 0..count {
            let raw_flags = context.reader.read_u32_le()?;

            // Extract bitfields per wowdev.wiki ADT/v18 specification
            let use_cubemap = (raw_flags & 0x1) != 0; // Bit 0
            let texture_scale = ((raw_flags >> 4) & 0xF) as u8; // Bits 4-7

            effects.push(TextureEffect {
                use_cubemap,
                texture_scale,
                raw_flags,
            });
        }

        Ok(Self { effects })
    }
}

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

    #[test]
    fn test_chunk_header_parsing() {
        // Create test data with magic "REVM" (MVER reversed) and size 4
        let data = vec![0x52, 0x45, 0x56, 0x4D, 0x04, 0x00, 0x00, 0x00];
        let mut cursor = Cursor::new(data);

        let header = ChunkHeader::read(&mut cursor).unwrap();
        assert_eq!(header.magic, [b'M', b'V', b'E', b'R']);
        assert_eq!(header.size, 4);
        assert_eq!(header.magic_as_string(), "MVER");
    }

    #[test]
    fn test_chunk_header_expect_magic() {
        let header = ChunkHeader {
            magic: [b'M', b'V', b'E', b'R'],
            size: 4,
        };

        // Should succeed with correct magic
        assert!(header.expect_magic(b"MVER").is_ok());

        // Should fail with incorrect magic
        assert!(header.expect_magic(b"MHDR").is_err());
    }

    #[test]
    fn test_mver_chunk_parsing() {
        // Create test data: magic "REVM" (reversed), size 4, version 18
        let data = vec![
            0x52, 0x45, 0x56, 0x4D, // REVM (MVER reversed)
            0x04, 0x00, 0x00, 0x00, // size = 4
            0x12, 0x00, 0x00, 0x00, // version = 18
        ];
        let mut cursor = Cursor::new(data);

        let mver = MverChunk::read(&mut cursor).unwrap();
        assert_eq!(mver.version, 18);
    }

    #[test]
    fn test_empty_adt_creation() {
        // Test that we can create basic chunk structures
        let header = ChunkHeader {
            magic: [b'M', b'V', b'E', b'R'],
            size: 4,
        };
        assert_eq!(header.magic_as_string(), "MVER");
        assert_eq!(header.size, 4);
    }

    #[test]
    fn test_version_to_string() {
        assert_eq!(AdtVersion::Vanilla.to_string(), "Vanilla (1.x)");
        assert_eq!(AdtVersion::TBC.to_string(), "The Burning Crusade (2.x)");
        assert_eq!(
            AdtVersion::WotLK.to_string(),
            "Wrath of the Lich King (3.x)"
        );
        assert_eq!(AdtVersion::Cataclysm.to_string(), "Cataclysm (4.x)");
        assert_eq!(AdtVersion::MoP.to_string(), "Mists of Pandaria (5.x)");
    }

    #[test]
    fn test_version_detection() {
        // Test version detection using static logic
        let version_vanilla = AdtVersion::detect_from_chunks(false, false, false, false);
        assert_eq!(version_vanilla, AdtVersion::Vanilla);

        let version_tbc = AdtVersion::detect_from_chunks(true, false, false, false);
        assert_eq!(version_tbc, AdtVersion::TBC);

        let version_wotlk = AdtVersion::detect_from_chunks(false, true, false, false);
        assert_eq!(version_wotlk, AdtVersion::WotLK);

        let version_cata = AdtVersion::detect_from_chunks(false, false, true, false);
        assert_eq!(version_cata, AdtVersion::Cataclysm);
    }

    #[test]
    fn test_version_comparison() {
        assert!(AdtVersion::Vanilla < AdtVersion::TBC);
        assert!(AdtVersion::TBC < AdtVersion::WotLK);
        assert!(AdtVersion::WotLK < AdtVersion::Cataclysm);
        assert!(AdtVersion::Cataclysm < AdtVersion::MoP);
        assert!(AdtVersion::MoP <= AdtVersion::MoP);
    }
}