ltk_modpkg 0.10.0

League Toolkit mod package (.modpkg) reader/writer and utilities
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
use binrw::BinWrite;
use byteorder::{WriteBytesExt, LE};
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::io::{self, BufWriter, Seek, SeekFrom, Write};
use std::path::Path;
use xxhash_rust::xxh3::xxh3_64;

use crate::{
    chunk::ModpkgChunk,
    metadata::{ModpkgMetadata, METADATA_CHUNK_PATH},
    thumbnail::THUMBNAIL_CHUNK_PATH,
    ChunkKey, LayerHash, LayerIndex, ModpkgCompression, PathHash, WadIndex, WadNameHash,
};
use crate::{ChunkPath, Slug, BASE_LAYER_NAME, LICENSE_CHUNK_PATH, README_CHUNK_PATH};

#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ModpkgBuilderError {
    #[error("io error")]
    Io(#[from] io::Error),

    /// A chunk's binary layout could not be written.
    ///
    /// The underlying writer error is boxed so the crate used to write it is
    /// not part of this crate's public API.
    #[error("Failed to write binary layout")]
    BinWrite(#[source] Box<dyn std::error::Error + Send + Sync>),

    #[error("modpkg error")]
    Modpkg(#[from] crate::error::ModpkgError),

    #[error("unsupported compression type: {0:?}")]
    UnsupportedCompressionType(ModpkgCompression),

    #[error("missing base layer")]
    MissingBaseLayer,

    #[error("layer not found: {0}")]
    LayerNotFound(String),

    #[error("invalid chunk name: {0}")]
    InvalidChunkName(String),

    #[error("invalid layer name")]
    InvalidLayerName(#[from] crate::error::InvalidSlugError),

    /// A hashtable manifest named a chunk path outside `_meta_/hashes/`.
    ///
    /// The manifest is what pairs a declared table with its stored chunk, so
    /// a path that leaves the hashes directory - or smuggles separators past
    /// it - would unpair the two.
    #[error("hashtable chunk path is not directly under _meta_/hashes/: {0}")]
    HashtablePathOutsideHashesDir(String),

    /// One hashtable chunk path was declared twice with different content.
    ///
    /// Two manifest entries may declare one chunk (one table, two shapes),
    /// but only over identical bytes - otherwise the declarations describe
    /// two different tables under one path.
    #[error("inconsistent content for hashtable chunk {0}")]
    InconsistentHashtable(String),

    /// One chunk received different content for different WADs.
    ///
    /// Entries that share a `(path, layer)` identity are one chunk registered
    /// under several WADs, so they must be given byte-identical content.
    #[error(
        "inconsistent content for chunk {path} in layer {layer}: \
         WADs {first_wad} and {second_wad}"
    )]
    InconsistentChunk {
        path: String,
        layer: String,
        first_wad: String,
        second_wad: String,
    },
}

// See the matching impl on `ModpkgError`: the conversion names `binrw::Error`
// so `?` keeps working, while the variant does not.
impl From<binrw::Error> for ModpkgBuilderError {
    fn from(error: binrw::Error) -> Self {
        Self::BinWrite(Box::new(error))
    }
}

/// Provides an interface to build a Modpkg file.
///
/// Meta chunks (metadata, readme, license text, thumbnail) are not held as
/// chunk builders: they are derived from the content fields by
/// [`meta_chunks`](Self::meta_chunks) at build time.
///
/// The readme and license text are bytes, not `String`. They are copied
/// byte-for-byte from the project and never inspected, so decoding them would
/// only create the chance to mangle a file whose exact contents matter. Callers
/// that display one decode it at that point.
#[derive(Debug, Clone, Default)]
pub struct ModpkgBuilder {
    readme: Option<Vec<u8>>,
    license_text: Option<Vec<u8>>,
    thumbnail: Option<Vec<u8>>,
    metadata: ModpkgMetadata,
    /// Declared tables, in declaration order: `(manifest entry, table bytes)`.
    ///
    /// The builder owns the manifest: `meta_chunks` writes these entries into
    /// the metadata it serializes, so declaration and storage cannot disagree.
    hashtables: Vec<(crate::ModpkgHashtable, Vec<u8>)>,
    // The WAD is part of the key so one chunk identity can be registered
    // under several WADs; see `with_chunk`.
    chunks: HashMap<(ChunkKey, WadNameHash), ModpkgChunkBuilder>,
    layers: Vec<ModpkgLayerBuilder>,
}

/// The identity of a chunk's data: `(uncompressed_checksum, uncompressed_size)`.
type ContentKey = (u64, u64);

/// A meta chunk to be written, resolved from the builder's content fields.
#[derive(Debug)]
struct MetaChunk<'builder> {
    /// Borrowed for the four fixed chunks; hashtable chunk paths come from
    /// the manifest, so the `Cow` is what lets both in.
    path: Cow<'builder, str>,
    data: Cow<'builder, [u8]>,
    compression: ModpkgCompression,
}

impl MetaChunk<'_> {
    fn path_hash(&self) -> PathHash {
        ChunkPath::new(self.path.as_ref()).hash()
    }
}

#[derive(Debug, Clone, Default)]
pub struct ModpkgChunkBuilder {
    path_hash: PathHash,
    path: String,
    compression: ModpkgCompression,
    layer: String,
    wad: String,
}

#[derive(Debug, Clone)]
pub struct ModpkgLayerBuilder {
    name: Slug,
    priority: i32,
}

impl Default for ModpkgLayerBuilder {
    fn default() -> Self {
        Self::base()
    }
}

impl ModpkgBuilder {
    /// Add a layer to the builder.
    pub fn with_layer(mut self, layer: ModpkgLayerBuilder) -> Self {
        self.layers.push(layer);
        self
    }

    /// Add a chunk to the builder.
    ///
    /// Chunks are stored by `(path, layer, WAD)`: a chunk with all three equal
    /// to an existing one replaces it. Chunks that share a `(path, layer)`
    /// identity under different WADs are all kept - they register one chunk
    /// under several WADs, and [`build_to_writer`](Self::build_to_writer)
    /// rejects them unless their content is byte-identical.
    pub fn with_chunk(mut self, chunk: ModpkgChunkBuilder) -> Self {
        let key = chunk.full_key();
        self.chunks.insert(key, chunk);
        self
    }

    /// Declare an embedded hashtable and the chunk that stores it.
    ///
    /// `data` is the table file's bytes, copied verbatim like the readme and
    /// license text - validation belongs to the caller that read the file.
    /// The manifest entry is written into the metadata this builder
    /// serializes, and the bytes into the chunk at `manifest.path`, so the
    /// declaration and the stored chunk cannot disagree.
    ///
    /// One file, two shapes is legal: a second declaration of an
    /// already-declared chunk path re-declares the stored chunk (the metadata
    /// carries both entries, the chunk is stored once), so its bytes must be
    /// identical to the first declaration's.
    ///
    /// # Errors
    ///
    /// [`ModpkgBuilderError::HashtablePathOutsideHashesDir`] when
    /// `manifest.path` is not one the extraction placement rule
    /// ([`hashtable_file_name`](crate::hashtable_file_name)) carries whole:
    /// `_meta_/hashes/{plain file name}`.
    /// [`ModpkgBuilderError::InconsistentHashtable`] when the chunk path was
    /// already declared with different bytes.
    pub fn with_hashtable(
        mut self,
        manifest: crate::ModpkgHashtable,
        data: impl Into<Vec<u8>>,
    ) -> Result<Self, ModpkgBuilderError> {
        // Valid exactly when the placement rule carries the whole tail: the
        // declared chunk and its extracted file then cannot part ways.
        let tail = manifest
            .path
            .strip_prefix(crate::HASHTABLES_CHUNK_DIR)
            .and_then(|rest| rest.strip_prefix('/'));
        if tail.is_none() || crate::hashtable_file_name(&manifest.path) != tail {
            return Err(ModpkgBuilderError::HashtablePathOutsideHashesDir(
                manifest.path,
            ));
        }

        let data = data.into();
        let declared = self
            .hashtables
            .iter()
            .find(|(existing, _)| existing.path.eq_ignore_ascii_case(&manifest.path));
        if let Some((_, existing_data)) = declared {
            if *existing_data != data {
                return Err(ModpkgBuilderError::InconsistentHashtable(manifest.path));
            }
        }

        self.hashtables.push((manifest, data));
        Ok(self)
    }

    /// Build the Modpkg file and write it to the given writer.
    ///
    /// * `writer` - The writer to write the Modpkg file to.
    /// * `provide_chunk_data` - A function that returns the uncompressed data
    ///   for each chunk; it is called once per registered chunk.
    pub fn build_to_writer<
        TWriter: io::Write + io::Seek,
        TChunkDataProvider: FnMut(&ModpkgChunkBuilder) -> Result<Vec<u8>, ModpkgBuilderError>,
    >(
        self,
        writer: &mut TWriter,
        provide_chunk_data: TChunkDataProvider,
    ) -> Result<(), ModpkgBuilderError> {
        let mut writer = BufWriter::new(writer);

        // Resolve exactly what will be written before writing anything: the
        // header's chunk count and the reserved TOC are both derived from these
        // two lists, so they cannot disagree with the entries written later.
        let meta_chunks = self.meta_chunks()?;
        let meta_path_hashes: HashSet<PathHash> =
            meta_chunks.iter().map(MetaChunk::path_hash).collect();
        let regular_chunks = self.collect_regular_chunks(&meta_path_hashes);

        // Collect all unique paths, layers, and wads
        let (chunk_paths, chunk_path_indices) =
            Self::collect_unique_paths(&meta_chunks, &regular_chunks);
        let (layers, _) = Self::collect_unique_layers(&regular_chunks);
        let (wads, wad_indices) = Self::collect_unique_wads(&regular_chunks);

        Self::validate_layers(&self.layers, &layers)?;

        let total_chunks = meta_chunks.len() + regular_chunks.len();

        Self::write_header(&mut writer, total_chunks)?;
        Self::write_layers(&mut writer, &self.layers)?;
        Self::write_chunk_paths(&mut writer, &chunk_paths)?;
        Self::write_wads(&mut writer, &wads)?;
        Self::write_alignment(&mut writer)?;

        // Reserve space for chunk TOC
        let chunk_toc_offset = writer.stream_position()?;
        writer.write_all(&vec![0; total_chunks * ModpkgChunk::RECORD_SIZE])?;

        let layer_index_map = Self::build_layer_index_map(&self.layers);

        let all_chunks = Self::process_all_chunks(
            &mut writer,
            provide_chunk_data,
            &meta_chunks,
            &regular_chunks,
            &chunk_path_indices,
            &layer_index_map,
            &wad_indices,
        )?;

        // Go back and write the actual chunk TOC
        Self::write_chunk_toc(&mut writer, chunk_toc_offset, &all_chunks)?;

        Ok(())
    }

    fn write_header<W: io::Write>(
        writer: &mut W,
        total_chunks: usize,
    ) -> Result<(), ModpkgBuilderError> {
        // Write magic header
        writer.write_all(b"_modpkg_")?;

        // Write version
        writer.write_u32::<LE>(1)?;

        // Write signature size and chunk count
        writer.write_u32::<LE>(0)?; // Placeholder for signature size
        writer.write_u32::<LE>(total_chunks as u32)?;

        // Write signature (empty for now)
        let signature = Vec::new();
        writer.write_all(&signature)?;

        Ok(())
    }

    fn write_layers<W: io::Write>(
        writer: &mut W,
        layers: &[ModpkgLayerBuilder],
    ) -> Result<(), ModpkgBuilderError> {
        writer.write_u32::<LE>(layers.len() as u32)?;
        for layer in layers {
            writer.write_u32::<LE>(layer.name.as_str().len() as u32)?;
            writer.write_all(layer.name.as_str().as_bytes())?;
            writer.write_i32::<LE>(layer.priority)?;
        }
        Ok(())
    }

    fn write_chunk_paths<W: io::Write>(
        writer: &mut W,
        chunk_paths: &[String],
    ) -> Result<(), ModpkgBuilderError> {
        // Write count
        writer.write_u32::<LE>(chunk_paths.len() as u32)?;

        // Write all chunk paths (including meta chunks)
        for path in chunk_paths {
            writer.write_all(path.as_bytes())?;
            writer.write_all(&[0])?; // Null terminator
        }

        Ok(())
    }

    fn write_wads<W: io::Write>(writer: &mut W, wads: &[String]) -> Result<(), ModpkgBuilderError> {
        writer.write_u32::<LE>(wads.len() as u32)?;
        for wad in wads {
            writer.write_all(wad.as_bytes())?;
            writer.write_all(&[0])?; // Null terminator
        }
        Ok(())
    }

    fn write_alignment<W: io::Write + io::Seek>(writer: &mut W) -> Result<(), ModpkgBuilderError> {
        let current_pos = writer.stream_position()?;
        let padding = (8 - (current_pos % 8)) % 8;
        for _ in 0..padding {
            writer.write_all(&[0])?;
        }
        Ok(())
    }

    fn build_layer_index_map(layers: &[ModpkgLayerBuilder]) -> HashMap<LayerHash, LayerIndex> {
        let mut layer_index_map = HashMap::new();
        for (idx, layer) in layers.iter().enumerate() {
            layer_index_map.insert(
                LayerHash::from_name(layer.name.as_str()),
                LayerIndex::new(idx as u32),
            );
        }
        layer_index_map
    }

    fn process_all_chunks<
        TWriter: io::Write + io::Seek,
        TChunkDataProvider: FnMut(&ModpkgChunkBuilder) -> Result<Vec<u8>, ModpkgBuilderError>,
    >(
        writer: &mut BufWriter<TWriter>,
        provide_chunk_data: TChunkDataProvider,
        meta_chunks: &[MetaChunk<'_>],
        regular_chunks: &[&ModpkgChunkBuilder],
        chunk_path_indices: &HashMap<PathHash, u32>,
        layer_index_map: &HashMap<LayerHash, LayerIndex>,
        wad_indices: &HashMap<WadNameHash, WadIndex>,
    ) -> Result<Vec<ModpkgChunk>, ModpkgBuilderError> {
        let mut all_chunks = Self::process_meta_chunks(writer, meta_chunks, chunk_path_indices)?;
        let mut processed_regular_chunks = Self::process_chunks(
            regular_chunks,
            writer,
            provide_chunk_data,
            chunk_path_indices,
            layer_index_map,
            wad_indices,
        )?;

        all_chunks.append(&mut processed_regular_chunks);

        Ok(all_chunks)
    }

    /// Collect all non-meta chunks, sorted by WAD name then layer.
    ///
    /// This groups related chunks physically in the file,
    /// enabling more sequential I/O when reading all overrides for a WAD.
    fn collect_regular_chunks(
        &self,
        meta_path_hashes: &HashSet<PathHash>,
    ) -> Vec<&ModpkgChunkBuilder> {
        let mut regular_chunks: Vec<_> = self
            .chunks
            .values()
            .filter(|chunk| !meta_path_hashes.contains(&chunk.path_hash))
            .collect();
        regular_chunks.sort_by(|a, b| a.wad.cmp(&b.wad).then(a.layer.cmp(&b.layer)));

        regular_chunks
    }

    fn write_chunk_toc<W: io::Write + io::Seek>(
        writer: &mut W,
        chunk_toc_offset: u64,
        chunks: &[ModpkgChunk],
    ) -> Result<(), ModpkgBuilderError> {
        writer.seek(SeekFrom::Start(chunk_toc_offset))?;
        for chunk in chunks {
            chunk.write(writer)?;
        }
        Ok(())
    }

    /// The meta chunks this builder will write, in write order.
    ///
    /// This is the only place that decides which meta chunks exist and how each
    /// is stored; the metadata chunk is always present, the rest follow their
    /// content field.
    fn meta_chunks(&self) -> Result<Vec<MetaChunk<'_>>, ModpkgBuilderError> {
        // The builder owns the hashtable manifest: the entries declared with
        // `with_hashtable` are what the serialized metadata carries, so the
        // manifest and the stored chunks cannot disagree.
        let mut metadata = self.metadata.clone();
        metadata.hashtables = self
            .hashtables
            .iter()
            .map(|(manifest, _)| manifest.clone())
            .collect();
        let mut metadata_bytes = Vec::new();
        metadata.write(&mut metadata_bytes)?;

        let mut meta_chunks = vec![MetaChunk {
            path: Cow::Borrowed(METADATA_CHUNK_PATH),
            data: Cow::Owned(metadata_bytes),
            compression: ModpkgCompression::None,
        }];

        if let Some(thumbnail) = self.thumbnail.as_deref() {
            meta_chunks.push(MetaChunk {
                path: Cow::Borrowed(THUMBNAIL_CHUNK_PATH),
                data: Cow::Borrowed(thumbnail),
                compression: ModpkgCompression::None,
            });
        }

        if let Some(readme) = self.readme.as_deref() {
            meta_chunks.push(MetaChunk {
                path: Cow::Borrowed(README_CHUNK_PATH),
                data: Cow::Borrowed(readme),
                compression: ModpkgCompression::None,
            });
        }

        // License texts are boilerplate-heavy and compress well (a CC license
        // runs to tens of kilobytes), so the chunk requests Zstd. Short texts
        // that don't pay for it fall back to raw storage in `write_meta_chunk`.
        if let Some(license_text) = self.license_text.as_deref() {
            meta_chunks.push(MetaChunk {
                path: Cow::Borrowed(LICENSE_CHUNK_PATH),
                data: Cow::Borrowed(license_text),
                compression: ModpkgCompression::Zstd,
            });
        }

        // Hashtables are line-per-name text, boilerplate-heavy like a
        // license, so their chunks request Zstd too. A chunk two manifest
        // entries declare (one table, two shapes; `with_hashtable` verified
        // the bytes match) is stored once - the manifest above still carries
        // every entry.
        let mut stored_paths = HashSet::new();
        for (manifest, data) in &self.hashtables {
            if stored_paths.insert(manifest.path.to_ascii_lowercase()) {
                meta_chunks.push(MetaChunk {
                    path: Cow::Borrowed(manifest.path.as_str()),
                    data: Cow::Borrowed(data),
                    compression: ModpkgCompression::Zstd,
                });
            }
        }

        Ok(meta_chunks)
    }

    fn process_meta_chunks<TWriter: io::Write + io::Seek>(
        writer: &mut BufWriter<TWriter>,
        meta_chunks: &[MetaChunk<'_>],
        chunk_path_indices: &HashMap<PathHash, u32>,
    ) -> Result<Vec<ModpkgChunk>, ModpkgBuilderError> {
        let mut processed = Vec::with_capacity(meta_chunks.len());

        for meta_chunk in meta_chunks {
            processed.push(Self::write_meta_chunk(
                meta_chunk.path_hash(),
                &meta_chunk.data,
                meta_chunk.compression,
                writer,
                chunk_path_indices,
            )?);
        }

        Ok(processed)
    }

    /// Write a meta chunk's data and return its TOC entry.
    ///
    /// `compression` is a request, not a guarantee: as with regular chunks, the
    /// data is stored raw when compressing it doesn't meaningfully pay, and the
    /// returned entry records the form actually stored.
    fn write_meta_chunk<TWriter: io::Write + io::Seek>(
        path_hash: PathHash,
        data: &[u8],
        compression: ModpkgCompression,
        writer: &mut BufWriter<TWriter>,
        chunk_path_indices: &HashMap<PathHash, u32>,
    ) -> Result<ModpkgChunk, ModpkgBuilderError> {
        let uncompressed_size = data.len();
        let uncompressed_checksum = xxh3_64(data);

        let (stored_data, compression) = Self::compress_chunk_data(data, compression)?;
        let compressed_size = stored_data.len();
        let compressed_checksum = xxh3_64(&stored_data);

        let data_offset = writer.stream_position()?;
        writer.write_all(&stored_data)?;

        Ok(ModpkgChunk {
            path_hash,
            data_offset,
            compression,
            compressed_size: compressed_size as u64,
            uncompressed_size: uncompressed_size as u64,
            compressed_checksum,
            uncompressed_checksum,
            path_index: *chunk_path_indices.get(&path_hash).unwrap_or(&0),
            layer_index: LayerIndex::NONE,
            wad_index: WadIndex::NONE,
        })
    }

    /// Maximum size of the compressed data relative to the original, in percent,
    /// for compression to be considered worthwhile. Chunks that don't compress
    /// below this threshold (already-compressed content like Vorbis audio or
    /// JPEG/WebP images) are stored uncompressed.
    const MAX_COMPRESSED_SIZE_PERCENT: u64 = 95;

    fn compress_chunk_data(
        data: &[u8],
        compression: ModpkgCompression,
    ) -> Result<(Vec<u8>, ModpkgCompression), ModpkgBuilderError> {
        match compression {
            ModpkgCompression::None => Ok((data.to_vec(), ModpkgCompression::None)),
            ModpkgCompression::Zstd => {
                let compressed = zstd::bulk::compress(data, 3)?;

                if (compressed.len() as u64) * 100
                    >= (data.len() as u64) * Self::MAX_COMPRESSED_SIZE_PERCENT
                {
                    Ok((data.to_vec(), ModpkgCompression::None))
                } else {
                    Ok((compressed, ModpkgCompression::Zstd))
                }
            }
        }
    }

    fn collect_unique_layers(
        chunks: &[&ModpkgChunkBuilder],
    ) -> (Vec<String>, HashMap<LayerHash, LayerIndex>) {
        let mut layers = Vec::new();
        let mut layer_indices = HashMap::new();
        for chunk in chunks {
            // Skip empty layer names (they represent chunks with no layer)
            if chunk.layer.is_empty() {
                continue;
            }
            let hash = LayerHash::from_name(&chunk.layer);
            layer_indices.entry(hash).or_insert_with(|| {
                let index = layers.len();
                layers.push(chunk.layer.clone());
                LayerIndex::new(index as u32)
            });
        }

        (layers, layer_indices)
    }

    fn collect_unique_paths(
        meta_chunks: &[MetaChunk<'_>],
        regular_chunks: &[&ModpkgChunkBuilder],
    ) -> (Vec<String>, HashMap<PathHash, u32>) {
        let mut paths = Vec::new();
        let mut path_indices = HashMap::new();

        // Collect paths from both meta chunks and regular chunks
        let meta_paths = meta_chunks
            .iter()
            .map(|meta| (meta.path_hash(), meta.path.to_string()));
        let regular_paths = regular_chunks
            .iter()
            .map(|chunk| (chunk.path_hash, chunk.path.clone()));

        for (path_hash, path) in meta_paths.chain(regular_paths) {
            path_indices.entry(path_hash).or_insert_with(|| {
                let index = paths.len();
                paths.push(path);
                index as u32
            });
        }

        (paths, path_indices)
    }

    fn collect_unique_wads(
        chunks: &[&ModpkgChunkBuilder],
    ) -> (Vec<String>, HashMap<WadNameHash, WadIndex>) {
        let mut wads = Vec::new();
        let mut wad_indices = HashMap::new();
        for chunk in chunks {
            // Skip empty wad names (they represent chunks with no wad)
            if chunk.wad.is_empty() {
                continue;
            }
            wad_indices
                .entry(WadNameHash::from_name(&chunk.wad))
                .or_insert_with(|| {
                    let index = wads.len();
                    wads.push(chunk.wad.clone());
                    WadIndex::new(index as u32)
                });
        }
        (wads, wad_indices)
    }

    fn validate_layers(
        defined_layers: &[ModpkgLayerBuilder],
        unique_layers: &[String],
    ) -> Result<(), ModpkgBuilderError> {
        // Check if defined layers have base layer
        if !defined_layers
            .iter()
            .any(|layer| layer.name == BASE_LAYER_NAME)
        {
            return Err(ModpkgBuilderError::MissingBaseLayer);
        }

        // Check if all unique layers are defined
        for layer in unique_layers {
            // Skip validation for empty layer names (they represent chunks with no layer)
            if layer.is_empty() {
                continue;
            }
            if !defined_layers.iter().any(|l| l.name == layer.as_str()) {
                return Err(ModpkgBuilderError::LayerNotFound(layer.to_string()));
            }
        }

        Ok(())
    }

    fn process_chunks<
        TWriter: io::Write + io::Seek,
        TChunkDataProvider: FnMut(&ModpkgChunkBuilder) -> Result<Vec<u8>, ModpkgBuilderError>,
    >(
        chunks: &[&ModpkgChunkBuilder],
        writer: &mut BufWriter<TWriter>,
        mut provide_chunk_data: TChunkDataProvider,
        chunk_path_indices: &HashMap<PathHash, u32>,
        layer_indices: &HashMap<LayerHash, LayerIndex>,
        wad_indices: &HashMap<WadNameHash, WadIndex>,
    ) -> Result<Vec<ModpkgChunk>, ModpkgBuilderError> {
        let mut final_chunks = Vec::new();

        // Identical chunk content is stored once: chunks whose data matches an
        // already written chunk point at the first copy's `data_offset`. The
        // stored form (and thus the recorded compression) is that of the first
        // occurrence, regardless of what compression later duplicates requested.
        let mut written_by_content: HashMap<ContentKey, (u64, u64, u64, ModpkgCompression)> =
            HashMap::new();

        // Entries sharing an identity register one chunk under several WADs,
        // so the format requires their content to be identical.
        let mut content_by_identity: HashMap<ChunkKey, (ContentKey, &str)> = HashMap::new();

        for chunk_builder in chunks {
            let uncompressed_data = provide_chunk_data(chunk_builder)?;
            let uncompressed_size = uncompressed_data.len();
            let uncompressed_checksum = xxh3_64(&uncompressed_data);

            let content_key: ContentKey = (uncompressed_checksum, uncompressed_size as u64);

            match content_by_identity.get(&chunk_builder.key()) {
                Some(&(first_content, first_wad)) => {
                    if first_content != content_key {
                        return Err(ModpkgBuilderError::InconsistentChunk {
                            path: chunk_builder.path.clone(),
                            layer: chunk_builder.layer.clone(),
                            first_wad: first_wad.to_string(),
                            second_wad: chunk_builder.wad.clone(),
                        });
                    }
                }
                None => {
                    content_by_identity.insert(
                        chunk_builder.key(),
                        (content_key, chunk_builder.wad.as_str()),
                    );
                }
            }
            let (data_offset, compressed_size, compressed_checksum, compression) =
                match written_by_content.get(&content_key) {
                    Some(&existing) => existing,
                    None => {
                        let (compressed_data, compression) = Self::compress_chunk_data(
                            &uncompressed_data,
                            chunk_builder.compression,
                        )?;

                        let compressed_size = compressed_data.len() as u64;
                        let compressed_checksum = xxh3_64(&compressed_data);

                        let data_offset = writer.stream_position()?;
                        writer.write_all(&compressed_data)?;

                        let written = (
                            data_offset,
                            compressed_size,
                            compressed_checksum,
                            compression,
                        );
                        written_by_content.insert(content_key, written);
                        written
                    }
                };

            let path_hash = chunk_builder.path_hash;
            let layer_index = if chunk_builder.layer.is_empty() {
                LayerIndex::NONE
            } else {
                layer_indices
                    .get(&LayerHash::from_name(&chunk_builder.layer))
                    .copied()
                    .unwrap_or(LayerIndex::NONE)
            };
            let wad_index = if chunk_builder.wad.is_empty() {
                WadIndex::NONE
            } else {
                wad_indices
                    .get(&WadNameHash::from_name(&chunk_builder.wad))
                    .copied()
                    .unwrap_or(WadIndex::NONE)
            };

            let chunk = ModpkgChunk {
                path_hash,
                data_offset,
                compression,
                compressed_size,
                uncompressed_size: uncompressed_size as u64,
                compressed_checksum,
                uncompressed_checksum,
                path_index: *chunk_path_indices.get(&path_hash).unwrap_or(&0),
                layer_index,
                wad_index,
            };

            final_chunks.push(chunk);
        }

        Ok(final_chunks)
    }
}

impl ModpkgChunkBuilder {
    const DEFAULT_LAYER: &'static str = "base";

    /// Create a new chunk builder with the default layer.
    pub fn new() -> Self {
        Self {
            path_hash: PathHash::new(0),
            path: String::new(),
            compression: ModpkgCompression::None,
            layer: Self::DEFAULT_LAYER.to_string(),
            wad: String::new(),
        }
    }

    /// Set the path of the chunk (input path is case insensitive).
    ///
    /// The path is normalized into a [`ChunkPath`] and hashed from that form.
    pub fn with_path(mut self, path: &str) -> Self {
        let path = ChunkPath::new(path);
        self.path_hash = path.hash();
        self.path = path.into_string();
        self
    }

    /// Set the path hash from a hex-encoded chunk name that represents the actual path hash.
    ///
    /// The input must have a base filename of exactly 16 hexadecimal characters. Any number of
    /// extensions after the base is allowed (only the base is parsed). The `0x` prefix is NOT
    /// allowed.
    /// The builder stores the (ASCII-lowercased) string as the chunk's stored path and parses
    /// the base as hexadecimal for the `path_hash`.
    pub fn with_hashed_chunk_name(mut self, hashed_name: &str) -> Result<Self, ModpkgBuilderError> {
        let stored_path = hashed_name.to_ascii_lowercase();

        let filename = Path::new(&stored_path)
            .file_name()
            .and_then(|s| s.to_str())
            .unwrap_or(&stored_path);

        self.path_hash = PathHash::from_hex_name(filename)
            .ok_or_else(|| ModpkgBuilderError::InvalidChunkName(stored_path.clone()))?;
        self.path = stored_path;

        Ok(self)
    }

    /// Request a compression type for the chunk's data.
    ///
    /// This is an upper bound rather than a guarantee: the builder stores the
    /// chunk uncompressed when compression does not meaningfully reduce its
    /// size (e.g. already-compressed audio or image formats). The chunk's TOC
    /// entry always records the form actually stored.
    pub fn with_compression(mut self, compression: ModpkgCompression) -> Self {
        self.compression = compression;
        self
    }

    pub fn with_layer(mut self, layer: &str) -> Self {
        self.layer = layer.to_string();
        self
    }

    /// Set the WAD association for this chunk.
    ///
    /// This enables efficient WAD-based lookups via the secondary index.
    pub fn with_wad(mut self, wad: &str) -> Self {
        self.wad = wad.to_ascii_lowercase();
        self
    }

    /// The hash of the chunk's canonical path.
    pub fn path_hash(&self) -> PathHash {
        self.path_hash
    }

    /// The chunk's canonical path (or hex chunk name).
    pub fn path(&self) -> &str {
        &self.path
    }

    /// The compression requested for the chunk's data.
    pub fn compression(&self) -> ModpkgCompression {
        self.compression
    }

    /// The name of the layer the chunk belongs to.
    pub fn layer(&self) -> &str {
        &self.layer
    }

    /// The lowercased name of the chunk's WAD, or `""` without a WAD.
    pub fn wad(&self) -> &str {
        &self.wad
    }

    /// Compute the identity of this chunk.
    ///
    /// This mirrors how chunks are keyed in the final [`Modpkg`](crate::Modpkg).
    pub fn key(&self) -> ChunkKey {
        let layer_hash = if self.layer.is_empty() {
            LayerHash::NONE
        } else {
            LayerHash::from_name(&self.layer)
        };
        ChunkKey::new(self.path_hash, layer_hash)
    }

    /// The hash of this chunk's WAD name, or [`WadNameHash::NONE`] without a WAD.
    pub fn wad_hash(&self) -> WadNameHash {
        if self.wad.is_empty() {
            WadNameHash::NONE
        } else {
            WadNameHash::from_name(&self.wad)
        }
    }

    /// Compute the storage key for this chunk: its identity plus its WAD.
    ///
    /// Unlike [`key`](Self::key), this tells apart entries that register one
    /// chunk identity under several WADs.
    pub fn full_key(&self) -> (ChunkKey, WadNameHash) {
        (self.key(), self.wad_hash())
    }
}

// The `with_*` meta setters below only assign a field. The corresponding chunk
// is derived at build time by [`ModpkgBuilder::meta_chunks`].
impl ModpkgBuilder {
    /// Set the metadata for the builder.
    pub fn with_metadata(mut self, metadata: ModpkgMetadata) -> Self {
        self.metadata = metadata;
        self
    }

    /// Set the readme for the builder.
    ///
    /// The bytes are not decoded, so a readme that is not valid UTF-8 survives
    /// the round trip unchanged.
    pub fn with_readme(mut self, readme: impl Into<Vec<u8>>) -> Self {
        self.readme = Some(readme.into());
        self
    }

    /// Set the license text for the builder.
    ///
    /// The bytes are not decoded: a license is a legal document, and a
    /// `LICENSE` saved in Latin-1 must not come back out with its copyright
    /// symbol replaced.
    ///
    /// The chunk is stored compressed; see [`meta_chunks`](Self::meta_chunks).
    pub fn with_license_text(mut self, license_text: impl Into<Vec<u8>>) -> Self {
        self.license_text = Some(license_text.into());
        self
    }

    /// Set the thumbnail for the builder.
    pub fn with_thumbnail(mut self, thumbnail: impl Into<Vec<u8>>) -> Self {
        self.thumbnail = Some(thumbnail.into());
        self
    }
}

impl ModpkgLayerBuilder {
    /// Create a layer builder, validating `name` as a [`Slug`].
    pub fn new(name: impl AsRef<str>) -> Result<Self, ModpkgBuilderError> {
        Ok(Self {
            name: Slug::new(name)?,
            priority: 0,
        })
    }

    /// Create a layer builder from an already-validated name.
    pub fn from_slug(name: Slug) -> Self {
        Self { name, priority: 0 }
    }

    pub fn with_name(mut self, name: impl AsRef<str>) -> Result<Self, ModpkgBuilderError> {
        self.name = Slug::new(name)?;
        Ok(self)
    }

    pub fn with_priority(mut self, priority: i32) -> Self {
        self.priority = priority;
        self
    }

    /// The base layer, whose name is always valid.
    pub fn base() -> Self {
        Self {
            name: Slug::base(),
            priority: 0,
        }
    }

    /// The layer's name.
    pub fn name(&self) -> &Slug {
        &self.name
    }

    /// The layer's priority.
    pub fn priority(&self) -> i32 {
        self.priority
    }
}

#[cfg(test)]
mod tests {
    use crate::{Modpkg, ModpkgError, ModpkgLayer};

    use super::*;

    use std::io::Cursor;

    #[test]
    fn test_modpkg_builder() {
        let scratch = Vec::new();
        let mut cursor = Cursor::new(scratch);

        let builder = ModpkgBuilder::default()
            .with_metadata(ModpkgMetadata::default())
            .with_layer(ModpkgLayerBuilder::new("base").unwrap().with_priority(0))
            .with_chunk(
                ModpkgChunkBuilder::new()
                    .with_path("test.png")
                    .with_compression(ModpkgCompression::Zstd)
                    .with_layer("base"),
            );

        builder
            .build_to_writer(&mut cursor, |_| Ok(vec![0xAA; 100]))
            .expect("Failed to build Modpkg");

        // Reset cursor and verify the file was created
        cursor.set_position(0);

        let modpkg = Modpkg::mount_from_reader(&mut cursor).unwrap();

        // Now we have 2 chunks: metadata + test.png
        assert_eq!(modpkg.chunks().len(), 2);

        let chunk = modpkg
            .chunks()
            .get(&ChunkKey::new(
                ChunkPath::new("test.png").hash(),
                LayerHash::from_name("base"),
            ))
            .unwrap();

        assert_eq!(
            modpkg.chunk_paths().get(&ChunkPath::new("test.png").hash()),
            Some(&"test.png".to_string())
        );

        assert_eq!(chunk.compression, ModpkgCompression::Zstd);
        assert_eq!(chunk.uncompressed_size, 100);
        assert_eq!(chunk.compressed_size, 17);
        assert_eq!(chunk.uncompressed_checksum, xxh3_64(&[0xAA; 100]));
        // Meta chunk paths are registered first, so the metadata chunk holds
        // index 0 and content paths follow.
        assert_eq!(chunk.path_index, 1);

        assert_eq!(modpkg.layers().len(), 1);
        assert_eq!(
            modpkg.layers().get(&LayerHash::from_name("base")),
            Some(&ModpkgLayer {
                name: "base".to_string(),
                priority: 0,
            })
        );
    }

    #[test]
    fn test_with_hashed_chunk_name() {
        // Test with an extension
        let chunk = ModpkgChunkBuilder::new()
            .with_hashed_chunk_name("abcdef1234567890.dds")
            .unwrap();
        assert_eq!(chunk.path_hash(), PathHash::new(0xabcdef1234567890));
        assert_eq!(chunk.path(), "abcdef1234567890.dds");

        // Test with an extension (no 0x prefix)
        let chunk = ModpkgChunkBuilder::new()
            .with_hashed_chunk_name("fedcba9876543210.txt")
            .unwrap();
        assert_eq!(chunk.path_hash(), PathHash::new(0xfedcba9876543210));
        assert_eq!(chunk.path(), "fedcba9876543210.txt");

        // Test with an extension
        let chunk = ModpkgChunkBuilder::new()
            .with_hashed_chunk_name("1234abc456def789.dds")
            .unwrap();
        assert_eq!(chunk.path_hash(), PathHash::new(0x1234abc456def789));
        assert_eq!(chunk.path(), "1234abc456def789.dds");

        // Test without extension
        let chunk = ModpkgChunkBuilder::new()
            .with_hashed_chunk_name("789def0011223344")
            .unwrap();
        assert_eq!(chunk.path_hash(), PathHash::new(0x789def0011223344));
        assert_eq!(chunk.path(), "789def0011223344");

        // Test invalid hex should fail
        assert!(ModpkgChunkBuilder::new()
            .with_hashed_chunk_name("not_hex.bin")
            .is_err());

        // Multiple extensions are allowed as long as base is valid
        let chunk = ModpkgChunkBuilder::new()
            .with_hashed_chunk_name("abcdef1234567890.texture.dds")
            .unwrap();
        assert_eq!(chunk.path_hash(), PathHash::new(0xabcdef1234567890));

        // 0x prefix should fail
        assert!(ModpkgChunkBuilder::new()
            .with_hashed_chunk_name("0xabcdef1234567890.dds")
            .is_err());
    }

    #[test]
    fn incompressible_chunk_falls_back_to_raw_storage() {
        let scratch = Vec::new();
        let mut cursor = Cursor::new(scratch);

        // Xorshift-generated noise doesn't compress, so the builder must
        // ignore the requested Zstd compression and store the bytes raw.
        let mut state = 0x9E3779B97F4A7C15u64;
        let noise: Vec<u8> = (0..4096)
            .map(|_| {
                state ^= state << 13;
                state ^= state >> 7;
                state ^= state << 17;
                state as u8
            })
            .collect();

        let builder = ModpkgBuilder::default()
            .with_layer(ModpkgLayerBuilder::base())
            .with_chunk(
                ModpkgChunkBuilder::new()
                    .with_path("noise.bin")
                    .with_compression(ModpkgCompression::Zstd)
                    .with_layer("base"),
            );

        let noise_clone = noise.clone();
        builder
            .build_to_writer(&mut cursor, move |_| Ok(noise_clone.clone()))
            .expect("Failed to build Modpkg");

        cursor.set_position(0);
        let mut modpkg = Modpkg::mount_from_reader(cursor).unwrap();

        let chunk = *modpkg
            .chunks()
            .get(&ChunkKey::new(
                ChunkPath::new("noise.bin").hash(),
                LayerHash::from_name("base"),
            ))
            .unwrap();
        assert_eq!(chunk.compression, ModpkgCompression::None);
        assert_eq!(chunk.compressed_size, chunk.uncompressed_size);

        let loaded = modpkg
            .load_chunk_decompressed_by_path("noise.bin", Some("base"))
            .unwrap();
        assert_eq!(&loaded[..], &noise[..]);
    }

    #[test]
    fn identical_chunk_content_is_stored_once() {
        let scratch = Vec::new();
        let mut cursor = Cursor::new(scratch);

        let shared_data = vec![0xAB; 10_000];
        let unique_data = vec![0xCD; 10_000];

        let builder = ModpkgBuilder::default()
            .with_layer(ModpkgLayerBuilder::base())
            .with_chunk(
                ModpkgChunkBuilder::new()
                    .with_path("a.bin")
                    .with_compression(ModpkgCompression::Zstd)
                    .with_layer("base"),
            )
            .with_chunk(
                ModpkgChunkBuilder::new()
                    .with_path("b.bin")
                    .with_compression(ModpkgCompression::Zstd)
                    .with_layer("base"),
            )
            .with_chunk(
                ModpkgChunkBuilder::new()
                    .with_path("c.bin")
                    .with_compression(ModpkgCompression::Zstd)
                    .with_layer("base"),
            );

        let (shared_clone, unique_clone) = (shared_data.clone(), unique_data.clone());
        builder
            .build_to_writer(&mut cursor, move |chunk| {
                if chunk.path() == "c.bin" {
                    Ok(unique_clone.clone())
                } else {
                    Ok(shared_clone.clone())
                }
            })
            .expect("Failed to build Modpkg");

        cursor.set_position(0);
        let mut modpkg = Modpkg::mount_from_reader(cursor).unwrap();

        let base = LayerHash::from_name("base");
        let a = *modpkg
            .chunks()
            .get(&ChunkKey::new(ChunkPath::new("a.bin").hash(), base))
            .unwrap();
        let b = *modpkg
            .chunks()
            .get(&ChunkKey::new(ChunkPath::new("b.bin").hash(), base))
            .unwrap();
        let c = *modpkg
            .chunks()
            .get(&ChunkKey::new(ChunkPath::new("c.bin").hash(), base))
            .unwrap();

        // a and b share content: written once, both TOC entries point at it
        assert_eq!(a.data_offset, b.data_offset);
        assert_eq!(a.compressed_size, b.compressed_size);
        assert_eq!(a.compressed_checksum, b.compressed_checksum);

        // c has different content and its own data
        assert_ne!(c.data_offset, a.data_offset);
        assert_ne!(c.uncompressed_checksum, a.uncompressed_checksum);

        // All three decode to the bytes their TOC entries promise
        let loaded_a = modpkg
            .load_chunk_decompressed_by_path("a.bin", Some("base"))
            .unwrap();
        let loaded_b = modpkg
            .load_chunk_decompressed_by_path("b.bin", Some("base"))
            .unwrap();
        let loaded_c = modpkg
            .load_chunk_decompressed_by_path("c.bin", Some("base"))
            .unwrap();
        assert_eq!(&loaded_a[..], &shared_data[..]);
        assert_eq!(&loaded_b[..], &shared_data[..]);
        assert_eq!(&loaded_c[..], &unique_data[..]);
    }

    /// A chunk builder for `data/shared.bin` in the base layer of `wad`.
    fn shared_chunk(wad: &str) -> ModpkgChunkBuilder {
        ModpkgChunkBuilder::new()
            .with_path("data/shared.bin")
            .with_compression(ModpkgCompression::Zstd)
            .with_layer("base")
            .with_wad(wad)
    }

    /// One `(path, layer)` identity under two WADs: the archive stores
    /// duplicate TOC records that collapse into one `chunks` entry on mount,
    /// while both WAD groups keep the chunk's key.
    #[test]
    fn shared_chunk_across_wads_mounts_under_both() {
        let mut cursor = Cursor::new(Vec::new());

        ModpkgBuilder::default()
            .with_layer(ModpkgLayerBuilder::base())
            .with_chunk(shared_chunk("aatrox.wad.client"))
            .with_chunk(shared_chunk("ahri.wad.client"))
            .build_to_writer(&mut cursor, |_| Ok(vec![0xCC; 64]))
            .expect("Failed to build Modpkg");

        cursor.set_position(0);
        let mut modpkg = Modpkg::mount_from_reader(cursor).unwrap();

        // Metadata + one entry for the shared identity.
        assert_eq!(modpkg.chunks().len(), 2);

        let key = ChunkKey::new(
            ChunkPath::new("data/shared.bin").hash(),
            LayerHash::from_name("base"),
        );
        let layer_index = modpkg.layer_index("base").unwrap();
        for wad in ["aatrox.wad.client", "ahri.wad.client"] {
            let wad_index = modpkg.wad_index(wad).expect("wad in table");
            assert_eq!(
                modpkg.chunks_for_wad_layer(wad_index, layer_index),
                [key],
                "{wad} should hold the shared chunk"
            );
        }

        let loaded = modpkg
            .load_chunk_decompressed_by_path("data/shared.bin", Some("base"))
            .unwrap();
        assert_eq!(&loaded[..], &[0xCC; 64]);
    }

    #[test]
    fn inconsistent_shared_chunk_content_fails_the_build() {
        let mut cursor = Cursor::new(Vec::new());

        // Each WAD supplies different bytes for the shared identity.
        let err = ModpkgBuilder::default()
            .with_layer(ModpkgLayerBuilder::base())
            .with_chunk(shared_chunk("aatrox.wad.client"))
            .with_chunk(shared_chunk("ahri.wad.client"))
            .build_to_writer(&mut cursor, |chunk| Ok(chunk.wad().as_bytes().to_vec()))
            .unwrap_err();

        assert!(
            matches!(
                err,
                ModpkgBuilderError::InconsistentChunk {
                    ref path,
                    ref layer,
                    ref first_wad,
                    ref second_wad,
                } if path == "data/shared.bin"
                    && layer == "base"
                    && first_wad == "aatrox.wad.client"
                    && second_wad == "ahri.wad.client"
            ),
            "Expected InconsistentChunk, got: {err}"
        );
    }

    /// A hand-tampered archive whose duplicate records disagree must not
    /// mount: which record wins would depend on read order.
    #[test]
    fn mount_rejects_inconsistent_duplicate_records() {
        let mut cursor = Cursor::new(Vec::new());

        ModpkgBuilder::default()
            .with_layer(ModpkgLayerBuilder::base())
            .with_chunk(shared_chunk("aatrox.wad.client"))
            .with_chunk(shared_chunk("ahri.wad.client"))
            .build_to_writer(&mut cursor, |_| Ok(vec![0xCC; 64]))
            .expect("Failed to build Modpkg");

        let mut bytes = cursor.into_inner();

        // Find the two TOC records by their leading path hash and corrupt the
        // second record's uncompressed checksum (bytes 41..49 of the record).
        let path_hash = ChunkPath::new("data/shared.bin").hash();
        let needle = path_hash.value().to_le_bytes();
        let records: Vec<usize> = (0..=bytes.len() - 8)
            .filter(|&pos| bytes[pos..pos + 8] == needle)
            .collect();
        assert_eq!(records.len(), 2, "expected exactly two TOC records");
        for byte in &mut bytes[records[1] + 41..records[1] + 49] {
            *byte ^= 0xFF;
        }

        let err = Modpkg::mount_from_reader(Cursor::new(bytes)).unwrap_err();
        assert!(
            matches!(err, ModpkgError::ChunksInconsistent(hash) if hash == path_hash),
            "Expected ChunksInconsistent, got: {err}"
        );
    }

    /// The builder used to accept any string, so a caller bypassing the packer
    /// could produce a package with a layer name the packer would reject.
    #[test]
    fn layer_builder_rejects_names_the_packer_would_reject() {
        for name in ["", "High Res", "-leading", "trailing-"] {
            assert!(
                ModpkgLayerBuilder::new(name).is_err(),
                "{name} should be rejected"
            );
        }

        assert!(ModpkgLayerBuilder::new("high-res").is_ok());
    }

    fn game_manifest() -> crate::ModpkgHashtable {
        crate::ModpkgHashtable {
            path: "_meta_/hashes/game.hashes.txt".to_string(),
            category: ltk_hashtable::Category::Game,
            algorithm: ltk_hashtable::Algorithm::Xxh64,
            bits: 64,
        }
    }

    /// User story 34: a packed table comes back as a chunk the metadata
    /// declares, so declaration and storage cannot disagree.
    #[test]
    fn a_hashtable_is_stored_as_a_meta_chunk_the_metadata_declares() {
        let mut cursor = Cursor::new(Vec::new());
        let names = "ASSETS/Custom/New.tex\nASSETS/Custom/Other.tex\n";

        ModpkgBuilder::default()
            .with_layer(ModpkgLayerBuilder::base())
            .with_hashtable(game_manifest(), names)
            .unwrap()
            .build_to_writer(&mut cursor, |_| Ok(vec![0xAA; 10]))
            .unwrap();

        cursor.set_position(0);
        let mut modpkg = Modpkg::mount_from_reader(cursor).unwrap();

        assert_eq!(
            modpkg.load_metadata().unwrap().hashtables(),
            [game_manifest()]
        );

        let chunk = *modpkg.chunk("_meta_/hashes/game.hashes.txt", None).unwrap();
        assert_eq!(chunk.layer(), None, "a meta chunk belongs to no layer");
        assert_eq!(chunk.wad(), None, "a meta chunk belongs to no WAD");
        assert_eq!(
            modpkg.decoder().load_chunk_decompressed(&chunk).unwrap(),
            names.as_bytes().into()
        );
    }

    /// Table text is boilerplate-heavy like a license, so the chunk requests
    /// Zstd; short tables that don't pay for it still fall back to raw.
    #[test]
    fn a_large_hashtable_is_stored_compressed() {
        let mut cursor = Cursor::new(Vec::new());
        let names: String = (0..2000)
            .map(|i| format!("ASSETS/Characters/Aatrox/Skins/Skin{i}/Aatrox.dds\n"))
            .collect();

        ModpkgBuilder::default()
            .with_layer(ModpkgLayerBuilder::base())
            .with_hashtable(game_manifest(), names.clone())
            .unwrap()
            .build_to_writer(&mut cursor, |_| Ok(vec![0xAA; 10]))
            .unwrap();

        cursor.set_position(0);
        let mut modpkg = Modpkg::mount_from_reader(cursor).unwrap();

        let chunk = *modpkg.chunk("_meta_/hashes/game.hashes.txt", None).unwrap();
        assert_eq!(chunk.compression, ModpkgCompression::Zstd);
        assert_eq!(
            modpkg.decoder().load_chunk_decompressed(&chunk).unwrap(),
            names.as_bytes().into()
        );
    }

    /// One file, two shapes: a repeated chunk path re-declares the stored
    /// chunk, so the metadata carries both entries and the chunk is stored
    /// once.
    #[test]
    fn a_chunk_declared_twice_keeps_both_entries_and_one_chunk() {
        let names = "ASSETS/Custom/One.tex\n";
        let narrow = crate::ModpkgHashtable {
            bits: 32,
            ..game_manifest()
        };

        let mut cursor = Cursor::new(Vec::new());
        ModpkgBuilder::default()
            .with_layer(ModpkgLayerBuilder::base())
            .with_hashtable(game_manifest(), names)
            .unwrap()
            .with_hashtable(narrow.clone(), names)
            .unwrap()
            .build_to_writer(&mut cursor, |_| Ok(vec![0xAA; 10]))
            .unwrap();

        cursor.set_position(0);
        let mut modpkg = Modpkg::mount_from_reader(cursor).unwrap();

        assert_eq!(
            modpkg.load_metadata().unwrap().hashtables(),
            [game_manifest(), narrow]
        );
        let tables = modpkg.load_hashtables().unwrap();
        assert_eq!(tables.len(), 2, "both declarations answer a load");
    }

    /// A repeated chunk path over different bytes is two tables under one
    /// path, which no reader could tell apart - refused.
    #[test]
    fn a_chunk_declared_twice_with_different_bytes_is_refused() {
        let result = ModpkgBuilder::default()
            .with_hashtable(game_manifest(), "ASSETS/Custom/One.tex\n")
            .unwrap()
            .with_hashtable(game_manifest(), "ASSETS/Custom/Two.tex\n");

        assert!(matches!(
            result,
            Err(ModpkgBuilderError::InconsistentHashtable(path)) if path.ends_with("game.hashes.txt")
        ));
    }

    /// Chunk paths are case-insensitive, so declarations that differ only in
    /// case are one chunk - and one chunk over different bytes is refused
    /// just like an exact repeat.
    #[test]
    fn a_chunk_declared_under_case_variant_paths_with_different_bytes_is_refused() {
        let cased = crate::ModpkgHashtable {
            path: "_meta_/hashes/Game.hashes.txt".to_string(),
            ..game_manifest()
        };

        let result = ModpkgBuilder::default()
            .with_hashtable(cased, "ASSETS/Custom/One.tex\n")
            .unwrap()
            .with_hashtable(game_manifest(), "ASSETS/Custom/Two.tex\n");

        assert!(matches!(
            result,
            Err(ModpkgBuilderError::InconsistentHashtable(path))
                if path.eq_ignore_ascii_case("_meta_/hashes/game.hashes.txt")
        ));
    }

    /// The manifest names where the chunk goes; a path outside `_meta_/hashes/`
    /// (or one smuggling separators past it) would unpair declaration from
    /// storage, so it is refused at the seam.
    #[test]
    fn a_hashtable_declared_outside_the_hashes_dir_is_refused() {
        for path in [
            "hashes/game.hashes.txt",
            "_meta_/hashes/../license",
            "_meta_/hashes/sub/dir.txt",
            "_meta_/hashes/",
            "_meta_/hashes/.",
        ] {
            let manifest = crate::ModpkgHashtable {
                path: path.to_string(),
                ..game_manifest()
            };
            assert!(
                ModpkgBuilder::default()
                    .with_hashtable(manifest, "a/b.txt\n")
                    .is_err(),
                "{path} should be refused"
            );
        }
    }

    #[test]
    fn with_path_normalizes_backslashes() {
        let chunk = ModpkgChunkBuilder::new()
            .with_path("ASSETS\\Characters\\Aatrox\\Skins\\Base\\Aatrox.dds");

        // The stored path keeps the authored casing (ADR 0003); only the
        // separators normalize.
        assert_eq!(chunk.path, "ASSETS/Characters/Aatrox/Skins/Base/Aatrox.dds");

        // Identity is the canonical name, so any spelling hashes alike.
        let forward =
            ModpkgChunkBuilder::new().with_path("assets/characters/aatrox/skins/base/aatrox.dds");

        assert_eq!(chunk.path_hash(), forward.path_hash());
    }

    #[test]
    fn roundtrip_backslash_paths_normalized() {
        let scratch = Vec::new();
        let mut cursor = Cursor::new(scratch);

        // Build with a path that has backslashes (simulates Windows glob output)
        let builder = ModpkgBuilder::default()
            .with_layer(ModpkgLayerBuilder::base())
            .with_chunk(
                ModpkgChunkBuilder::new()
                    .with_path("ASSETS\\Characters\\Aatrox\\Aatrox.dds")
                    .with_compression(ModpkgCompression::None)
                    .with_layer("base"),
            );

        builder
            .build_to_writer(&mut cursor, |_| Ok(vec![0xBB; 50]))
            .expect("Failed to build Modpkg");

        cursor.set_position(0);
        let modpkg = Modpkg::mount_from_reader(&mut cursor).unwrap();

        // The stored path keeps the authored casing with separators
        // normalized (ADR 0003), and is keyed by its canonical name's hash.
        let stored = "ASSETS/Characters/Aatrox/Aatrox.dds";
        let path_hash = ChunkPath::new("assets/characters/aatrox/aatrox.dds").hash();

        assert_eq!(
            modpkg.chunk_paths().get(&path_hash),
            Some(&stored.to_string()),
            "chunk_paths should hold the stored path under the canonical hash"
        );

        // Chunk should be findable by the canonical hash
        assert!(
            modpkg
                .chunks()
                .contains_key(&ChunkKey::new(path_hash, LayerHash::from_name("base"))),
            "chunk should be retrievable with the canonical path hash"
        );
    }
}