bevy-dlc 1.18.26

DLC (downloadable content) management for Bevy games
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
use bevy::asset::io::Reader;
use bevy::asset::{
    Asset, AssetLoader, AssetPath, ErasedLoadedAsset, Handle, LoadContext, LoadedUntypedAsset,
};
use bevy::ecs::reflect::AppTypeRegistry;
use bevy::prelude::*;
use bevy::reflect::TypePath;
use futures_lite::{AsyncReadExt, AsyncSeekExt};
use std::io;
use std::sync::Arc;
use thiserror::Error;

use crate::{DlcId, PackItem, Product};

use std::io::{Read, Seek, SeekFrom};

/// Adapter that exposes a `std::io::Read + std::io::Seek` view over a
/// `bevy::asset::io::Reader`.  This is used by pack-parsing routines so we can
/// operate on the async reader without copying the entire file into memory.
///
/// The implementation simply blocks on the underlying async methods using
/// [`pollster::block_on`].  Seeking works only when the wrapped reader is
/// seekable; otherwise the `seek()` call returns an error.
pub struct SyncReader<'a> {
    inner: &'a mut dyn bevy::asset::io::Reader,
}

impl<'a> SyncReader<'a> {
    pub fn new(inner: &'a mut dyn bevy::asset::io::Reader) -> Self {
        SyncReader { inner }
    }
}

impl<'a> Read for SyncReader<'a> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        bevy::tasks::block_on(self.inner.read(buf))
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))
    }
}

impl<'a> Seek for SyncReader<'a> {
    fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
        match self.inner.seekable() {
            Ok(seek) => bevy::tasks::block_on(seek.seek(pos))
                .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e)),
            Err(_) => Err(std::io::Error::new(
                std::io::ErrorKind::Other,
                "reader not seekable",
            )),
        }
    }
}

/// Decompress a gzip‑compressed tar archive from `plaintext` and return a map from
/// internal path -> contents.  Errors are mapped into `DlcLoaderError::DecryptionFailed`
/// because the only callers are the pack loader and entry decrypt which already treat
/// archive failures as decryption problems.
fn decompress_archive(
    plaintext: &[u8],
) -> Result<std::collections::HashMap<String, Vec<u8>>, DlcLoaderError> {
    use flate2::read::GzDecoder;
    use std::io::Read;
    use tar::Archive;

    let mut archive = Archive::new(GzDecoder::new(std::io::Cursor::new(plaintext)));
    let mut map = std::collections::HashMap::new();
    for entry in archive
        .entries()
        .map_err(|e| DlcLoaderError::DecryptionFailed(format!("archive read failed: {}", e)))?
    {
        let mut file = entry.map_err(|e| {
            DlcLoaderError::DecryptionFailed(format!("archive entry read failed: {}", e))
        })?;
        let path = file
            .path()
            .map_err(|e| DlcLoaderError::DecryptionFailed(format!("archive path error: {}", e)))?;
        let path_str = path.to_string_lossy().replace("\\", "/");
        let mut buf = Vec::new();
        file.read_to_end(&mut buf).map_err(|e| {
            DlcLoaderError::DecryptionFailed(format!("archive file read failed: {}", e))
        })?;
        map.insert(path_str, buf);
    }
    Ok(map)
}

/// Internal helper to decrypt a specific entry from a v5 pack by reading only
/// the required data block from the file.
pub(crate) fn decrypt_pack_entry_block_bytes<R: std::io::Read + std::io::Seek>(
    reader: &mut R,
    enc: &EncryptedAsset,
    key: &crate::EncryptionKey,
    full_path: &str,
) -> Result<Vec<u8>, DlcLoaderError> {
    // 1. Re-parse the pack to get the block metadata
    let _original_pos = reader
        .stream_position()
        .map_err(|e| DlcLoaderError::Io(e))?;
    reader
        .seek(std::io::SeekFrom::Start(0))
        .map_err(|e| DlcLoaderError::Io(e))?;

    let (_prod, _id, _ver, _entries, blocks) = crate::parse_encrypted_pack(&mut *reader)
        .map_err(|e| DlcLoaderError::InvalidFormat(e.to_string()))?;

    let block = blocks
        .iter()
        .find(|b| b.block_id == enc.block_id)
        .ok_or_else(|| {
            DlcLoaderError::DecryptionFailed(format!("block {} not found in pack", enc.block_id))
        })?;

    // 2. Decrypt only the bytes corresponding to the desired block.  The
    // pack format writes all blocks concatenated after the metadata, and
    // `parse_encrypted_pack` leaves the reader positioned at the start of the
    // ciphertext region.  We still seek explicitly to the recorded offset to
    // be robust and to support callers that may have moved the reader.
    reader
        .seek(std::io::SeekFrom::Start(block.file_offset))
        .map_err(|e| DlcLoaderError::Io(e))?;

    // limit the reader to the block size so `decrypt_with_key` doesn't read
    // past the boundary when multiple blocks exist.
    let mut limited = reader.take(block.encrypted_size as u64);
    let pt_gz = crate::pack_format::decrypt_with_key(&key, &mut limited, &block.nonce)
        .map_err(|e| DlcLoaderError::DecryptionFailed(e.to_string()))?;

    // 3. Decompress and find entry
    let entries = decompress_archive(&pt_gz)?;

    // Extract label from "pack.dlcpack#label"
    let label = match full_path.rsplit_once('#') {
        Some((_, suffix)) => suffix,
        None => full_path,
    }
    .replace("\\", "/");

    entries.get(&label).cloned().ok_or_else(|| {
        DlcLoaderError::DecryptionFailed(format!(
            "entry '{}' not found in decrypted block {}",
            label, enc.block_id
        ))
    })
}

/// Event fired when a DLC pack is successfully loaded.
#[derive(Event, Clone)]
pub struct DlcPackLoaded {
    dlc_id: DlcId,
    pack: DlcPack,
}

impl DlcPackLoaded {
    pub(crate) fn new(dlc_id: DlcId, pack: DlcPack) -> Self {
        DlcPackLoaded { dlc_id, pack }
    }

    /// Return the DLC identifier for the loaded pack.
    pub fn id(&self) -> &DlcId {
        &self.dlc_id
    }

    /// Return a reference to the loaded `DlcPack`. The pack contains metadata about the DLC and provides methods to decrypt and load individual entries.
    pub fn pack(&self) -> &DlcPack {
        &self.pack
    }
}

/// Fuzzy match for type paths, normalizing by trimming leading "::" to handle absolute vs relative paths.
/// Also handles crate name differences by allowing suffix matches.
pub(crate) fn fuzzy_type_path_match<'a>(stored: &'a str, expected: &'a str) -> bool {
    let s = stored.trim_start_matches("::");
    let e = expected.trim_start_matches("::");

    if s == e {
        return true;
    }

    // Allow suffix matching to handle differences in crate names (e.g. "my_crate::MyType" vs "MyType")
    // or when one path is more specific than the other.
    if e.ends_with(s) && e.as_bytes().get(e.len() - s.len() - 1) == Some(&b':') {
        return true;
    }

    if s.ends_with(e) && s.as_bytes().get(s.len() - e.len() - 1) == Some(&b':') {
        return true;
    }

    false
}

/// Attempts to downcast an `ErasedLoadedAsset` to `A` and, if successful,
/// registers it as a labeled sub-asset in `load_context`.
///
/// Returns `true` when the asset was successfully registered.
pub trait ErasedSubAssetRegistrar: Send + Sync + 'static {
    fn try_register(
        &self,
        label: String,
        erased: ErasedLoadedAsset,
        load_context: &mut LoadContext<'_>,
    ) -> Result<(), ErasedLoadedAsset>;

    /// Return the `TypePath` of the asset type this registrar handles.
    fn asset_type_path(&self) -> &'static str;

    /// Attempt to load the asset directly using its static type, bypassing
    /// extension dispatch. This is used when a `type_path` is provided by
    /// the container.
    fn load_direct<'a>(
        &'a self,
        label: String,
        fake_path: String,
        reader: &'a mut dyn Reader,
        load_context: &'a mut LoadContext<'_>,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), DlcLoaderError>> + Send + 'a>>;
}

/// Concrete implementation for asset type `A`.
pub struct TypedSubAssetRegistrar<A: Asset>(std::marker::PhantomData<A>);

impl<A: Asset> Default for TypedSubAssetRegistrar<A> {
    fn default() -> Self {
        Self(std::marker::PhantomData)
    }
}

impl<A: Asset> ErasedSubAssetRegistrar for TypedSubAssetRegistrar<A> {
    fn try_register(
        &self,
        label: String,
        erased: ErasedLoadedAsset,
        load_context: &mut LoadContext<'_>,
    ) -> Result<(), ErasedLoadedAsset> {
        match erased.downcast::<A>() {
            Ok(loaded) => {
                load_context.add_loaded_labeled_asset(label, loaded);
                Ok(())
            }
            Err(back) => Err(back),
        }
    }

    fn asset_type_path(&self) -> &'static str {
        A::type_path()
    }

    fn load_direct<'a>(
        &'a self,
        label: String,
        fake_path: String,
        reader: &'a mut dyn Reader,
        load_context: &'a mut LoadContext<'_>,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), DlcLoaderError>> + Send + 'a>>
    {
        Box::pin(async move {
            match load_context
                .loader()
                .with_static_type()
                .immediate()
                .with_reader(reader)
                .load::<A>(fake_path)
                .await
            {
                Ok(loaded) => {
                    load_context.add_loaded_labeled_asset(label, loaded);
                    Ok(())
                }
                Err(e) => Err(DlcLoaderError::DecryptionFailed(e.to_string())),
            }
        })
    }
}

/// Represents a single encrypted file inside a `.dlcpack` container, along with its metadata (DLC ID, original extension, optional type path). The ciphertext is not decrypted at this stage; decryption is performed on demand by `DlcPackEntry::decrypt_bytes` using the global encrypt key registry.
#[derive(Clone, Debug, Asset, TypePath)]
pub struct EncryptedAsset {
    pub dlc_id: String,
    pub original_extension: String,
    /// Optional serialized type identifier (e.g. `bevy::image::Image`)
    pub type_path: Option<String>,
    pub nonce: [u8; 12],
    pub ciphertext: std::sync::Arc<[u8]>,
    // --- v5 format extensions ---
    pub block_id: u32,
    pub block_offset: u32,
    pub size: u32,
}

impl EncryptedAsset {
    /// Decrypt the ciphertext contained in this `EncryptedAsset`, using the
    /// global encryption-key registry to look up the correct key for
    /// `self.dlc_id`.
    pub(crate) fn decrypt_bytes(&self) -> Result<Vec<u8>, DlcLoaderError> {
        // lookup key
        let encrypt_key = crate::encrypt_key_registry::get(&self.dlc_id)
            .ok_or_else(|| DlcLoaderError::DlcLocked(self.dlc_id.clone()))?;

        // decrypt using the pack-format helper
        crate::pack_format::decrypt_with_key(
            &encrypt_key,
            std::io::Cursor::new(&*self.ciphertext),
            &self.nonce,
        )
        .map_err(|e| DlcLoaderError::DecryptionFailed(e.to_string()))
    }
}

/// Parse the binary encrypted-asset format from a byte slice. This is used by the pack loader when parsing the pack metadata, and also by the `DlcLoader` when decrypting individual entries (since the entry metadata is stored in the same format as a standalone encrypted file).
pub fn parse_encrypted(bytes: &[u8]) -> Result<EncryptedAsset, io::Error> {
    // make sure we can read the fixed-size header fields without panicking:
    // version (1 byte) + dlc_len (2 bytes) + ext_len (1 byte) + nonce (12 bytes)
    // the remaining lengths (dlc_id, ext, type_path, ciphertext) are variable
    // and validated later, so this check only guards the very earliest reads.
    if bytes.len() < 1 + 2 + 1 + 12 {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "encrypted file too small",
        ));
    }
    let version = bytes[0];
    let mut offset = 1usize;

    let dlc_len = u16::from_be_bytes([bytes[offset], bytes[offset + 1]]) as usize;
    offset += 2;
    if offset + dlc_len > bytes.len() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "invalid dlc id length",
        ));
    }
    let dlc_id = String::from_utf8(bytes[offset..offset + dlc_len].to_vec())
        .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
    offset += dlc_len;

    let ext_len = bytes[offset] as usize;
    offset += 1;
    let original_extension = if ext_len == 0 {
        "".to_string()
    } else {
        let s = String::from_utf8(bytes[offset..offset + ext_len].to_vec())
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
        offset += ext_len;
        s
    };

    // version 1+ stores a serialized type identifier (u16 length + utf8 bytes)
    let type_path = if version >= 1 {
        if offset + 2 > bytes.len() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "missing type_path length",
            ));
        }
        let tlen = u16::from_be_bytes([bytes[offset], bytes[offset + 1]]) as usize;
        offset += 2;
        if tlen == 0 {
            None
        } else {
            if offset + tlen > bytes.len() {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "invalid type_path length",
                ));
            }
            let s = String::from_utf8(bytes[offset..offset + tlen].to_vec())
                .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
            offset += tlen;
            Some(s)
        }
    } else {
        None
    };

    if offset + 12 > bytes.len() {
        return Err(io::Error::new(io::ErrorKind::InvalidData, "missing nonce"));
    }
    let mut nonce = [0u8; 12];
    nonce.copy_from_slice(&bytes[offset..offset + 12]);
    offset += 12;
    let ciphertext = bytes[offset..].into();

    Ok(EncryptedAsset {
        dlc_id,
        original_extension,
        type_path,
        nonce,
        ciphertext,
        block_id: 0,
        block_offset: 0,
        size: 0,
    })
}

/// A loader for individual encrypted files inside a `.dlcpack`.
#[derive(TypePath)]
pub struct DlcLoader<A: bevy::asset::Asset + 'static> {
    /// Stored for potential future use (e.g., validating type_path matches `A`).
    /// Currently unused because the generic `A` already specifies the target type.
    #[allow(dead_code)]
    type_registry: Arc<AppTypeRegistry>,
    _marker: std::marker::PhantomData<A>,
}

// Provide FromWorld so the loader can be initialized by Bevy's App without
// requiring `A: Default`.
impl<A> bevy::prelude::FromWorld for DlcLoader<A>
where
    A: bevy::asset::Asset + 'static,
{
    fn from_world(world: &mut bevy::prelude::World) -> Self {
        let registry = world.resource::<AppTypeRegistry>().clone();
        DlcLoader {
            type_registry: Arc::new(registry),
            _marker: std::marker::PhantomData,
        }
    }
}

#[derive(TypePath, Clone, Debug)]
pub struct DlcPackEntry {
    /// Relative path inside the pack (as authored when packing)
    path: String,
    /// Encrypted asset metadata and ciphertext
    encrypted: EncryptedAsset,
}

impl DlcPackEntry {
    pub fn new(path: String, encrypted: EncryptedAsset) -> Self {
        DlcPackEntry { path, encrypted }
    }

    /// Convenience: load this entry's registered path via `AssetServer::load`.
    pub fn load_untyped(
        &self,
        asset_server: &bevy::prelude::AssetServer,
    ) -> Handle<LoadedUntypedAsset> {
        asset_server.load_untyped(&self.path)
    }

    /// Check if this entry is declared as type `A` (via the optional `type_path` in the container, which is independent of file extension). This is not used by the loader itself (which relies on extension-based dispatch) but can be used by user code to inspect entries or implement custom loading behavior.
    pub fn is_type<A: Asset>(&self) -> bool {
        match self.encrypted.type_path.as_ref() {
            Some(tp) => fuzzy_type_path_match(tp, A::type_path()),
            None => false,
        }
    }

    /// Decrypt and return the plaintext bytes for this entry.
    /// This consults the global encrypt-key registry and will return
    /// `DlcLoaderError::DlcLocked` when the encrypt key is not present.
    pub(crate) fn decrypt_bytes(&self) -> Result<Vec<u8>, DlcLoaderError> {
        let entry_ek = crate::encrypt_key_registry::get_full(&self.encrypted.dlc_id)
            .ok_or_else(|| DlcLoaderError::DlcLocked(self.encrypted.dlc_id.clone()))?;
        let encrypt_key = entry_ek.key;

        // v5 block-based decryption only; older formats are no longer supported.
        let path = entry_ek.path.ok_or_else(|| {
            DlcLoaderError::DecryptionFailed(format!(
                "no file path registered for DLC '{}', cannot decrypt",
                self.encrypted.dlc_id
            ))
        })?;

        let mut file = std::fs::File::open(path).map_err(|e| {
            DlcLoaderError::DecryptionFailed(format!("failed to open pack file: {}", e))
        })?;

        crate::asset_loader::decrypt_pack_entry_block_bytes(
            &mut file,
            &self.encrypted,
            &encrypt_key,
            &self.path,
        )
    }

    pub fn path(&self) -> AssetPath<'_> {
        bevy::asset::AssetPath::parse(&self.path)
    }

    /// Get the raw entry path (relative path within the pack, without pack prefix)
    pub fn entry_path(&self) -> &str {
        &self.path
    }

    pub fn original_extension(&self) -> &String {
        &self.encrypted.original_extension
    }

    pub fn type_path(&self) -> Option<&String> {
        self.encrypted.type_path.as_ref()
    }
}

impl From<(String, EncryptedAsset)> for DlcPackEntry {
    fn from((path, encrypted): (String, EncryptedAsset)) -> Self {
        DlcPackEntry { path, encrypted }
    }
}

impl From<&(String, EncryptedAsset)> for DlcPackEntry {
    fn from((path, encrypted): &(String, EncryptedAsset)) -> Self {
        DlcPackEntry {
            path: path.clone(),
            encrypted: encrypted.clone(),
        }
    }
}

/// Represents a `.dlcpack` bundle (multiple encrypted entries).
#[derive(Asset, TypePath, Clone, Debug)]
pub struct DlcPack {
    dlc_id: DlcId,
    product: Product,
    version: u8,
    metadata: crate::PackMetadata,
    metadata_locked: bool,
    entries: Vec<DlcPackEntry>,

    /// The file path from which this pack was loaded (for registry purposes)
    pack_path: String,
}

impl DlcPack {
    pub fn new(id: DlcId, product: Product, version: u8, entries: Vec<DlcPackEntry>) -> Self {
        Self::new_with_metadata(id, product, version, crate::PackMetadata::new(), entries)
    }

    pub fn new_with_metadata(
        id: DlcId,
        product: Product,
        version: u8,
        metadata: crate::PackMetadata,
        entries: Vec<DlcPackEntry>,
    ) -> Self {
        Self::new_with_metadata_state(id, product, version, metadata, false, entries)
    }

    pub(crate) fn new_with_metadata_state(
        id: DlcId,
        product: Product,
        version: u8,
        metadata: crate::PackMetadata,
        metadata_locked: bool,
        entries: Vec<DlcPackEntry>,
    ) -> Self {
        DlcPack {
            dlc_id: id,
            product,
            version,
            metadata,
            metadata_locked,
            entries,
            pack_path: String::new(),
        }
    }

    /// Get the pack file path
    pub fn pack_path(&self) -> &str {
        &self.pack_path
    }

    /// Return the DLC identifier for this pack.
    pub fn id(&self) -> &DlcId {
        &self.dlc_id
    }

    /// Return the product name this pack belongs to.
    pub fn product(&self) -> &str {
        &self.product.0
    }

    /// Return the pack format version.
    pub fn version(&self) -> u8 {
        self.version
    }

    /// Return true when the pack metadata is encrypted and the current pack instance
    /// does not have access to the DLC encryption key needed to decrypt it.
    pub fn metadata_locked(&self) -> bool {
        self.metadata_locked
    }

    /// Return an iterator over metadata keys stored in this pack.
    pub fn metadata_keys(&self) -> impl Iterator<Item = &str> + '_ {
        self.metadata.keys().map(String::as_str)
    }

    /// Return true when the pack contains metadata for the provided key.
    pub fn has_metadata(&self, key: &str) -> bool {
        self.metadata.contains_key(key)
    }

    /// Deserialize the metadata value stored at `key` into `T`.
    pub fn get_metadata<T>(&self, key: &str) -> Result<Option<T>, crate::DlcPackMetadataError>
    where
        T: serde::de::DeserializeOwned,
    {
        if self.metadata_locked {
            return Err(crate::DlcPackMetadataError::Locked);
        }

        match self.metadata.get(key) {
            Some(value) => serde_json::from_value(value.clone())
                .map(Some)
                .map_err(|source| crate::DlcPackMetadataError::Deserialize {
                    key: key.to_string(),
                    source,
                }),
            None => Ok(None),
        }
    }

    /// Return the raw JSON metadata value for `key`.
    pub fn get_metadata_raw(
        &self,
        key: &str,
    ) -> Result<Option<&serde_json::Value>, crate::DlcPackMetadataError> {
        if self.metadata_locked {
            return Err(crate::DlcPackMetadataError::Locked);
        }

        Ok(self.metadata.get(key))
    }

    /// Return a slice of contained entries.
    pub fn entries(&self) -> &[DlcPackEntry] {
        &self.entries
    }

    /// Find an entry by its registered path
    pub fn find_entry(&self, path: &str) -> Option<&DlcPackEntry> {
        self.entries
            .iter()
            .find(|e| e.path().to_string().ends_with(path) || e.path().path().ends_with(path))
    }

    /// Find all entries that match the specified asset type `A`.
    pub fn find_by_type<A: Asset>(&self) -> Vec<&DlcPackEntry> {
        self.entries
            .iter()
            .filter(|e| match e.type_path() {
                Some(tp) => fuzzy_type_path_match(tp, A::type_path()),
                None => false,
            })
            .collect()
    }

    /// Decrypt an entry (accepts either `name` or `packfile.dlcpack#name`).
    /// Returns plaintext or `DlcLocked`.
    pub fn decrypt_entry(
        &self,
        entry_path: &str,
    ) -> Result<Vec<u8>, crate::asset_loader::DlcLoaderError> {
        // accept either "test.png" or "packfile.dlcpack#test.png" by
        // checking both relative and absolute paths
        let entry = self.find_entry(entry_path).ok_or_else(|| {
            DlcLoaderError::DecryptionFailed(format!("entry not found: {}", entry_path))
        })?;

        entry.decrypt_bytes()
    }

    pub fn load<A: Asset>(
        &self,
        asset_server: &bevy::prelude::AssetServer,
        entry_path: &str,
    ) -> Handle<A> {
        if let Some(entry) = self.find_entry(entry_path) {
            return asset_server.load::<A>(entry.path());
        }

        let normalized = entry_path.replace('\\', "/");
        let requested_path = if !self.pack_path.is_empty() {
            format!("{}#{}", self.pack_path, normalized)
        } else if let Some((pack_path, _)) = self.entries.first().and_then(|entry| entry.path.split_once('#')) {
            format!("{}#{}", pack_path, normalized)
        } else {
            normalized.clone()
        };

        warn!(
            "DLC entry '{}' not found in pack '{}'; requesting '{}' so the asset server reports a normal load failure instead of panicking",
            entry_path,
            self.dlc_id,
            requested_path,
        );

        asset_server.load::<A>(requested_path)
    }

    fn with_path(&self, path_string: String) -> DlcPack {
        DlcPack {
            dlc_id: self.dlc_id.clone(),
            product: self.product.clone(),
            version: self.version,
            metadata: self.metadata.clone(),
            metadata_locked: self.metadata_locked,
            entries: self.entries.clone(),
            pack_path: path_string,
        }
    }
}

/// Settings for `DlcPackLoader` that control asset registration behavior.
#[derive(Clone, TypePath, serde::Serialize, serde::Deserialize)]
pub struct DlcPackLoaderSettings {}

impl Default for DlcPackLoaderSettings {
    fn default() -> Self {
        DlcPackLoaderSettings {}
    }
}

/// `AssetLoader` for `.dlcpack` bundles (contains multiple encrypted entries).
///
/// When the encrypt key is available in the registry at load time (i.e. the
/// DLC is already unlocked), each entry is immediately decrypted and registered
/// as a typed labeled sub-asset so `asset_server.load("pack.dlcpack#entry.png")`
/// returns the correct `Handle<T>` for the extension's loader (e.g. `Handle<Image>`
/// for `.png`). No asset type is hardcoded here — the correct type is determined
/// purely by extension dispatch via Bevy's `immediate()` loader, and the result
/// is downcast + registered using the list of `ErasedSubAssetRegistrar`s that
/// `DlcPlugin::build` populates.
///
/// When the encrypt key is *not* yet available the pack is still loaded
/// successfully (entries list is populated from the manifest) but the labeled
/// sub-assets are not added — `reload_assets_on_unlock_system` will reload the
/// pack once the key arrives, and the second load will succeed.
#[derive(TypePath, Default)]
pub struct DlcPackLoader {
    /// Ordered list of per-type registrars. `DlcPlugin::build` pushes one
    /// `TypedSubAssetRegistrar<A>` for every `A` it also registers via
    /// `init_asset_loader::<DlcLoader<A>>()`. The loader tries each in turn
    /// and uses the first successful downcast.
    pub registrars: Vec<Box<dyn ErasedSubAssetRegistrar>>,
    /// Optional shared reference to the `DlcPackRegistrarFactories` resource so
    /// the loader can observe updates to the factory list at runtime without
    /// requiring the asset loader to be re-registered.
    pub(crate) factories: Option<DlcPackRegistrarFactories>,
}

/// Factory trait used to create `ErasedSubAssetRegistrar` instance.
///
/// Implement `TypedRegistrarFactory<T>` for asset types to produce a
/// `TypedSubAssetRegistrar::<T>` at collection time.
pub trait DlcPackRegistrarFactory: Send + Sync + 'static {
    fn type_name(&self) -> &'static str;
    fn create_registrar(&self) -> Box<dyn ErasedSubAssetRegistrar>;
}

/// Generic typed factory that constructs `TypedSubAssetRegistrar::<T>`.
pub struct TypedRegistrarFactory<T: Asset + 'static>(std::marker::PhantomData<T>);

impl<T: Asset + TypePath + 'static> DlcPackRegistrarFactory for TypedRegistrarFactory<T> {
    fn type_name(&self) -> &'static str {
        T::type_path()
    }

    fn create_registrar(&self) -> Box<dyn ErasedSubAssetRegistrar> {
        Box::new(TypedSubAssetRegistrar::<T>::default())
    }
}

impl<T: Asset + 'static> Default for TypedRegistrarFactory<T> {
    fn default() -> Self {
        TypedRegistrarFactory(std::marker::PhantomData)
    }
}

use std::sync::RwLock;

/// Internal factory resource used by `AppExt::register_dlc_type` so user code
/// can request additional pack-registrars without pushing closures.
///
/// The resource wraps an `Arc<RwLock<_>>` so the registered `DlcPackLoader`
/// instance can hold a cheap clone and observe updates made by
/// `register_dlc_type(...)` without needing to re-register the loader.
#[derive(Clone, Resource)]
pub(crate) struct DlcPackRegistrarFactories(pub Arc<RwLock<Vec<Box<dyn DlcPackRegistrarFactory>>>>);

impl Default for DlcPackRegistrarFactories {
    fn default() -> Self {
        DlcPackRegistrarFactories(Arc::new(RwLock::new(Vec::new())))
    }
}

/// Return the default set of pack registrar factories used by `DlcPlugin`.
///
/// Using factory objects avoids closures and makes it trivial to add custom
/// typed factories in user code (box a `TypedRegistrarFactory::<T>`).
pub(crate) fn default_pack_registrar_factories() -> Vec<Box<dyn DlcPackRegistrarFactory>> {
    vec![
        Box::new(TypedRegistrarFactory::<Image>::default()),
        Box::new(TypedRegistrarFactory::<Scene>::default()),
        Box::new(TypedRegistrarFactory::<bevy::mesh::Mesh>::default()),
        Box::new(TypedRegistrarFactory::<Font>::default()),
        Box::new(TypedRegistrarFactory::<AudioSource>::default()),
        Box::new(TypedRegistrarFactory::<ColorMaterial>::default()),
        Box::new(TypedRegistrarFactory::<bevy::pbr::StandardMaterial>::default()),
        Box::new(TypedRegistrarFactory::<bevy::gltf::Gltf>::default()),
        Box::new(TypedRegistrarFactory::<bevy::gltf::GltfMesh>::default()),
        Box::new(TypedRegistrarFactory::<Shader>::default()),
        Box::new(TypedRegistrarFactory::<DynamicScene>::default()),
        Box::new(TypedRegistrarFactory::<AnimationClip>::default()),
        Box::new(TypedRegistrarFactory::<AnimationGraph>::default()),
    ]
}

/// Build the final `registrars` vector by combining factory objects supplied via
/// the `DlcPackRegistrarFactories` resource with the crate's default factories.
pub(crate) fn collect_pack_registrars(
    factories: Option<&DlcPackRegistrarFactories>,
) -> Vec<Box<dyn ErasedSubAssetRegistrar>> {
    use std::collections::HashSet;
    let mut seen: HashSet<&'static str> = HashSet::new();
    let mut out: Vec<Box<dyn ErasedSubAssetRegistrar>> = Vec::new();

    if let Some(f) = factories {
        let inner = f.0.read().unwrap();
        for factory in inner.iter() {
            out.push(factory.create_registrar());
            seen.insert(factory.type_name());
        }
    }

    for factory in default_pack_registrar_factories() {
        if !seen.contains(factory.type_name()) {
            out.push(factory.create_registrar());
            seen.insert(factory.type_name());
        }
    }

    out
}

impl AssetLoader for DlcPackLoader {
    type Asset = DlcPack;
    type Settings = DlcPackLoaderSettings;
    type Error = DlcLoaderError;

    fn extensions(&self) -> &[&str] {
        &["dlcpack"]
    }

    async fn load(
        &self,
        reader: &mut dyn Reader,
        _settings: &Self::Settings,
        load_context: &mut LoadContext<'_>,
    ) -> Result<Self::Asset, Self::Error> {
        let path_string = load_context.path().path().to_string_lossy().to_string();

        // Adapt the async `reader` to a synchronous `std::io::Read` so we can
        // drive the existing pack‑parsing logic without buffering the whole file
        // up front.  If the underlying reader is seekable we will also be able
        // rewind it later in order to extract the raw bytes needed for
        // decryption.
        let mut sync_reader = SyncReader::new(reader);

        let mut parsed_pack = crate::parse_encrypted_pack_info(&mut sync_reader, None)
            .map_err(|e| DlcLoaderError::InvalidFormat(e.to_string()))?;

        if let Some(encrypt_key) = crate::encrypt_key_registry::get(parsed_pack.dlc_id.as_ref()) {
            sync_reader.seek(SeekFrom::Start(0)).map_err(|_| {
                DlcLoaderError::Io(io::Error::new(
                    io::ErrorKind::NotSeekable,
                    format!(
                        "reader not seekable, cannot decrypt metadata for pack '{}'",
                        path_string
                    ),
                ))
            })?;

            parsed_pack = crate::parse_encrypted_pack_info(&mut sync_reader, Some(&encrypt_key))
                .map_err(|e| DlcLoaderError::InvalidFormat(e.to_string()))?;
        }

        let crate::ParsedDlcPack {
            product,
            dlc_id,
            version,
            metadata,
            metadata_locked,
            entries: manifest_entries,
            block_metadatas,
        } = parsed_pack;

        // rewind the reader back to the start so decryption routines can re‑parse the file as needed.  If the reader is not seekable, error.
        sync_reader.seek(SeekFrom::Start(0)).map_err(|_| {
            DlcLoaderError::Io(io::Error::new(
                io::ErrorKind::NotSeekable,
                format!("reader not seekable, cannot load pack '{}'", path_string),
            ))
        })?;

        // Check for DLC ID conflicts: reject if a DIFFERENT pack file is being loaded for the same DLC ID.
        // Allow the same pack file to be loaded multiple times (e.g., when accessing labeled sub-assets).
        check_dlc_id_conflict(&dlc_id, &path_string)?;

        // Register this asset path for the dlc id so it can be reloaded on unlock.
        // If the path already exists for this DLC ID, it's idempotent (same pack file).
        if !crate::encrypt_key_registry::has(dlc_id.as_ref(), &path_string) {
            crate::encrypt_key_registry::register_asset_path(dlc_id.as_ref(), &path_string);
        }

        // Try to decrypt all entries immediately when the encrypt key is present.
        // Offload decryption + archive extraction to Bevy's compute thread pool so
        // we don't block the asset loader threads on heavy CPU work. If the key
        // is missing we still populate the manifest so callers can inspect
        // entries; a reload after unlock will add the typed sub-assets.
        let decrypted_items = {
            match decrypt_pack_entries(&dlc_id, &manifest_entries, &block_metadatas, sync_reader) {
                Ok(items) => Some(items),
                Err(DlcLoaderError::DlcLocked(_)) => None,
                Err(e) => return Err(e),
            }
        };

        let mut out_entries = Vec::with_capacity(manifest_entries.len());

        let mut unregistered_labels: Vec<String> = Vec::new();

        // Collect all available registrars once per pack load to avoid heavy
        // overhead from shared resource locking/matching inside the loop.
        let dynamic_regs = self
            .factories
            .as_ref()
            .map(|f| crate::asset_loader::collect_pack_registrars(Some(f)));
        let regs = dynamic_regs.unwrap_or_else(|| collect_pack_registrars(None));

        for (path, enc) in manifest_entries.into_iter() {
            let entry_label = path.replace('\\', "/");

            // Track whether a typed labeled asset was successfully registered
            // for this entry. If `false` after processing, the pack still
            // contains the entry but no labeled asset will be available via
            // `pack.dlcpack#entry` (AssetServer will report it as missing).
            let mut registered_as_labeled = false;

            // Try to load this entry as a typed sub-asset when plaintext is available.
            if let Some(ref items) = decrypted_items {
                if let Some(item) = items.iter().find(|i| i.path() == path) {
                    let ext = item.ext().unwrap_or_default();
                    let type_path = item.type_path();
                    let plaintext = item.plaintext().to_vec();
                    // Build a fake path with the correct extension so
                    // `load_context.loader()` selects the right concrete loader
                    // by extension (e.g. `.png` → ImageLoader, `.json` → JsonLoader).
                    let stem = std::path::Path::new(&entry_label)
                        .file_stem()
                        .and_then(|s| s.to_str())
                        .unwrap_or("entry");
                    let fake_path = format!("{}.{}", stem, ext);

                    let mut vec_reader = bevy::asset::io::VecReader::new(plaintext.clone());

                    // 1. Guided load: if `type_path` is present in the container metadata,
                    // attempt to find a matching registrar and load directly using
                    // that type. This bypasses extension-based dispatch entirely.
                    if let Some(tp) = type_path {
                        if let Some(registrar) = regs
                            .iter()
                            .find(|r| fuzzy_type_path_match(r.asset_type_path(), tp.as_str()))
                        {
                            match registrar
                                .load_direct(
                                    entry_label.clone(),
                                    fake_path.clone(),
                                    &mut vec_reader,
                                    load_context,
                                )
                                .await
                            {
                                Ok(()) => {
                                    registered_as_labeled = true;
                                }
                                Err(e) => {
                                    // if static load failed, we still have a chance with
                                    // extension-based dispatch below (rare but possible).
                                    debug!(
                                        "Static load for type '{}' failed: {}; falling back to extension dispatch",
                                        tp, e
                                    );
                                }
                            }
                        }
                    }

                    // 2. Extension dispatch: Bevy picks the right loader based on `fake_path`
                    // extension. We then try to match the resulting erased asset against
                    // all known registrars to register it as a labeled sub-asset.
                    if !registered_as_labeled {
                        let mut vec_reader = bevy::asset::io::VecReader::new(plaintext.clone());
                        let result = load_context
                            .loader()
                            .immediate()
                            .with_reader(&mut vec_reader)
                            .with_unknown_type()
                            .load(fake_path.clone())
                            .await;

                        match result {
                            Ok(erased) => {
                                let mut remaining = Some(erased);

                                for registrar in regs.iter() {
                                    let label = entry_label.clone();
                                    let to_register = remaining.take().unwrap();
                                    match registrar.try_register(label, to_register, load_context) {
                                        Ok(()) => {
                                            registered_as_labeled = true;
                                            remaining = None;
                                            break;
                                        }
                                        Err(back) => {
                                            remaining = Some(back);
                                        }
                                    }
                                }

                                if let Some(_) = remaining {
                                    warn!(
                                        "DLC entry '{}' present in container but no registered asset type matched (extension='{}'); the asset will NOT be available as '{}#{}'. Register a loader with `app.register_dlc_type::<T>()`",
                                        entry_label, ext, path_string, entry_label
                                    );
                                }
                            }
                            Err(e) => {
                                warn!(
                                    "Failed to load entry '{}', extension='{}': {}",
                                    entry_label, ext, e
                                );
                            }
                        }
                    }
                }
            }

            // Build the labeled registered path for the DlcPackEntry.
            let registered_path = format!("{}#{}", path_string, entry_label);

            if !registered_as_labeled {
                unregistered_labels.push(entry_label.clone());
            }

            out_entries.push(DlcPackEntry {
                path: registered_path,
                encrypted: enc,
            });
        }

        // If we actually had plaintext to attempt registration (i.e. the
        // pack was unlocked at load time) then unregistered_labels indicates a
        // genuine failure to match a loader.  When the pack is still locked we
        // intentionally avoid logging anything here because a later reload when
        // the key arrives will perform the real work and emit the warning.
        if decrypted_items.is_some() && !unregistered_labels.is_empty() {
            // provide a concrete example using the first unregistered label so
            // the user can see how to reference it with the pack path.
            let example_label = &unregistered_labels[0];
            let example_full = format!("{}#{}", path_string, example_label);
            warn!(
                "{} {} in '{}' were not registered as labeled assets and will be inaccessible via '{}'. See earlier warnings for details or register the appropriate loader via `app.register_dlc_type::<T>()`.",
                unregistered_labels.len(),
                if unregistered_labels.len() == 1 {
                    "entry"
                } else {
                    "entries"
                },
                path_string,
                example_full,
            );
        }

        Ok(DlcPack::new_with_metadata_state(
            dlc_id.clone(),
            product,
            version as u8,
            metadata,
            metadata_locked,
            out_entries,
        )
        .with_path(path_string))
    }
}

/// Internal helper used by `DlcPackLoader` to determine whether a
/// pack for `dlc_id` from `path_string` should be accepted or rejected.
/// Registry holds at most one path per DLC ID; conflict only arises when
/// that path is different.  Loading the same pack file twice (same path) is
/// normal and should not trigger an error.
fn check_dlc_id_conflict(dlc_id: &DlcId, path_string: &str) -> Result<(), DlcLoaderError> {
    if let Some(existing_path) = crate::encrypt_key_registry::asset_path_for(dlc_id.as_ref()) {
        if existing_path != path_string {
            return Err(DlcLoaderError::DlcIdConflict(
                dlc_id.to_string(),
                existing_path,
                path_string.to_string(),
            ));
        }
    }
    Ok(())
}

/// Decrypt all entries in a pack using the block-based decryption method. This is used by `DlcPackLoader` when the encrypt key is available at load time, and also by `DlcPackEntry::decrypt_bytes` for individual entries when accessed via `pack.dlcpack#entry`.
fn decrypt_pack_entries<R: std::io::Read + std::io::Seek>(
    dlc_id: &crate::DlcId,
    entries: &[(String, EncryptedAsset)],
    block_metadatas: &[crate::pack_format::BlockMetadata],
    reader: R,
) -> Result<Vec<crate::PackItem>, DlcLoaderError> {
    // lookup encrypt key in global registry
    let encrypt_key = crate::encrypt_key_registry::get(dlc_id.as_ref())
        .ok_or_else(|| DlcLoaderError::DlcLocked(dlc_id.to_string()))?;

    let mut extracted_all = std::collections::HashMap::new();
    // use reader in a PackReader for convenience
    let mut pr = crate::pack_format::PackReader::new(reader);
    for block in block_metadatas {
        pr.seek(std::io::SeekFrom::Start(block.file_offset))
            .map_err(|e| DlcLoaderError::Io(e))?;
        let pt = pr
            .read_and_decrypt(&encrypt_key, block.encrypted_size as usize, &block.nonce)
            .map_err(|e| {
                let example = entries
                    .iter()
                    .find(|(_, enc)| enc.block_id == block.block_id)
                    .map(|(p, _)| p.as_str())
                    .unwrap_or("unknown");
                DlcLoaderError::DecryptionFailed(format!(
                    "dlc='{}' entry='{}' (block {}) decryption failed: {}",
                    dlc_id, example, block.block_id, e
                ))
            })?;
        let extracted = decompress_archive(&pt)?;
        extracted_all.extend(extracted);
    }

    let mut out = Vec::with_capacity(entries.len());
    for (path, enc) in entries {
        let normalized = path.replace("\\", "/");
        let plaintext = extracted_all
            .remove(&normalized)
            .or_else(|| extracted_all.remove(path.as_str()))
            .ok_or_else(|| {
                DlcLoaderError::DecryptionFailed(format!("entry {} not found in any block", path))
            })?;

        let mut item = PackItem::new(path.clone(), plaintext)
            .map_err(|e| DlcLoaderError::InvalidFormat(e.to_string()))?;
        if !enc.original_extension.is_empty() {
            item = item
                .with_extension(enc.original_extension.clone())
                .map_err(|e| DlcLoaderError::InvalidFormat(e.to_string()))?;
        }
        if let Some(tp) = &enc.type_path {
            item = item.with_type_path(tp.clone());
        }
        out.push(item);
    }

    Ok(out)
}

#[derive(Error, Debug)]
pub enum DlcLoaderError {
    /// Used for any IO failure during pack loading (e.g. file not found, read error, etc).
    #[error("IO error: {0}")]
    Io(io::Error),
    /// Used when the encrypt key for the DLC ID is not found in the registry at load time, which means the DLC is still locked and entries cannot be decrypted yet. This is not a fatal error — the pack can still be loaded and inspected.
    #[error("DLC locked: encrypt key not found for DLC id: {0}")]
    DlcLocked(String),
    /// Used for any failure during decryption of an entry or archive, including authentication failures from incorrect keys and any errors from archive extraction or manifest-archive mismatches.
    #[error("Decryption failed: {0}")]
    DecryptionFailed(String),
    /// Used when the initial container-level decryption succeeds but the plaintext is malformed (e.g. gzip archive is corrupted, manifest metadata doesn't match archive contents, etc).
    #[error("Invalid encrypted asset format: {0}")]
    InvalidFormat(String),
    /// Used when a DLC ID conflict is detected: a different pack file is already registered for the same DLC ID. This likely indicates a configuration error (e.g. two different `.dlcpack` files with the same internal DLC ID, or the same `.dlcpack` being loaded from two different paths). The error includes both the original and new pack paths for debugging.
    #[error(
        "DLC ID conflict: a .dlcpack with DLC id '{0}' is already loaded; cannot load another pack with the same DLC id, original: {1}, new: {2}"
    )]
    DlcIdConflict(String, String, String),
}

impl From<std::io::Error> for DlcLoaderError {
    fn from(e: std::io::Error) -> Self {
        DlcLoaderError::Io(e)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{EncryptionKey, PackItem};
    #[allow(unused_imports)]
    use secure_gate::{CloneableSecret, RevealSecret};
    use serial_test::serial;

    #[test]
    #[serial]
    fn encrypted_asset_decrypts_with_registry() {
        // pick a DLC id and prepare a static random key material so we can
        // construct two distinct `EncryptionKey` instances that share the same
        // bytes (one goes in the registry, the other is used for encryption).
        let dlc_id = "standalone";
        let key = EncryptionKey::new(rand::random());

        crate::encrypt_key_registry::clear_all();
        crate::encrypt_key_registry::insert(dlc_id, key.with_secret(|k| EncryptionKey::from(*k)));

        // build a small standalone encrypted blob using PackWriter
        let nonce = [0u8; 12];
        let mut ciphertext = Vec::new();
        {
            let mut pw = crate::pack_format::PackWriter::new(&mut ciphertext);
            pw.write_encrypted(&key, &nonce, b"hello").expect("encrypt");
        }

        let ct_len = ciphertext.len() as u32;
        let enc = EncryptedAsset {
            dlc_id: dlc_id.to_string(),
            original_extension: "".to_string(),
            type_path: None,
            nonce,
            ciphertext: ciphertext.into(),
            block_id: 0,
            block_offset: 0,
            size: ct_len,
        };

        let plaintext = enc.decrypt_bytes().expect("decrypt");
        assert_eq!(&plaintext, b"hello");
    }

    #[test]
    #[serial]
    fn dlcpack_accessors_work_and_fields_read() {
        let entry = DlcPackEntry {
            path: "a.txt".to_string(),
            encrypted: EncryptedAsset {
                dlc_id: "example_dlc".to_string(),
                original_extension: "txt".to_string(),
                type_path: None,
                nonce: [0u8; 12],
                ciphertext: vec![].into(),
                block_id: 0,
                block_offset: 0,
                size: 0,
            },
        };
        let pack = DlcPack::new(
            DlcId::from("example_dlc"),
            Product::from("test"),
            4,
            vec![entry.clone()],
        );

        // exercise getters (reads `dlc_id` + `entries` fields)
        assert_eq!(*pack.id(), DlcId::from("example_dlc"));
        assert_eq!(pack.entries().len(), 1);

        // inspect an entry (reads `path`, `original_extension`)
        let found = pack.find_entry("a.txt").expect("entry present");
        assert_eq!(found.path().path(), "a.txt");
        assert_eq!(found.original_extension(), "txt");
        assert!(found.type_path().is_none());
    }

    #[test]
    #[serial]
    fn decrypt_pack_entries_v4_without_key_returns_locked_error() {
        crate::encrypt_key_registry::clear_all();
        let dlc_id = crate::DlcId::from("locked_dlc");
        let items = vec![PackItem::new("a.txt", b"hello".to_vec()).expect("pack item")];
        let key = EncryptionKey::new(rand::random());
        let _dlc_key = crate::DlcKey::generate_random();
        let product = crate::Product::from("test");
        let container = crate::pack_encrypted_pack(
            &dlc_id,
            &items,
            &product,
            &key,
            crate::pack_format::DEFAULT_BLOCK_SIZE,
        )
        .expect("pack");

        let mut cursor = std::io::Cursor::new(container);
        let (_product, parsed_dlc_id, _version, parsed_entries, block_metadatas) =
            crate::parse_encrypted_pack(&mut cursor).expect("parse");

        let err = decrypt_pack_entries(&parsed_dlc_id, &parsed_entries, &block_metadatas, cursor)
            .expect_err("should be locked");
        match err {
            DlcLoaderError::DlcLocked(id) => assert_eq!(id, "locked_dlc"),
            _ => panic!("expected DlcLocked error, got {:?}", err),
        }
    }

    #[test]
    #[serial]
    fn decrypt_pack_entries_v4_with_wrong_key_reports_entry_and_dlc() {
        crate::encrypt_key_registry::clear_all();
        let dlc_id = crate::DlcId::from("badkey_dlc");
        let items = vec![PackItem::new("b.txt", b"world".to_vec()).expect("pack item")];
        let real_key = EncryptionKey::new(rand::random());
        let _dlc_key = crate::DlcKey::generate_random();
        let product = crate::Product::from("test");
        let container = crate::pack_encrypted_pack(
            &dlc_id,
            &items,
            &product,
            &real_key,
            crate::pack_format::DEFAULT_BLOCK_SIZE,
        )
        .expect("pack");

        // insert an incorrect key for this DLC
        let wrong_key: [u8; 32] = rand::random();
        crate::encrypt_key_registry::insert(
            &dlc_id.to_string(),
            crate::EncryptionKey::from(wrong_key),
        );

        let mut cursor = std::io::Cursor::new(container);
        let (_product, parsed_dlc_id, _version, parsed_entries, block_metadatas) =
            crate::parse_encrypted_pack(&mut cursor).expect("parse");

        let err = decrypt_pack_entries(&parsed_dlc_id, &parsed_entries, &block_metadatas, cursor)
            .expect_err("should fail decryption");
        match err {
            DlcLoaderError::DecryptionFailed(msg) => {
                assert!(msg.contains("dlc='badkey_dlc'"));
                assert!(msg.contains("entry='b.txt'"));
                // ensure inner cause is propagated (auth failed for wrong key)
                assert!(msg.contains("authentication failed") || msg.contains("incorrect key"));
            }
            _ => panic!("expected DecryptionFailed, got {:?}", err),
        }
    }

    #[test]
    #[serial]
    fn dlc_id_conflict_detection() {
        // Verify conflict detection logic for a DLC ID.  We avoid checking the
        // registered path string directly because other tests may clear the
        // global registry concurrently; instead we rely solely on the `check`
        // helper which works atomically.
        crate::encrypt_key_registry::clear_all();

        let dlc_id_str = "conflict_test_dlc";
        let pack_path_1 = "existing_pack.dlcpack";
        let pack_path_2 = "different_pack.dlcpack";

        crate::encrypt_key_registry::register_asset_path(dlc_id_str, pack_path_1);

        // same path never counts as a conflict
        assert!(
            !crate::encrypt_key_registry::check(dlc_id_str, pack_path_1),
            "same pack path should NOT be a conflict"
        );

        // different path should trigger a conflict. the registry global is
        // shared across parallel test threads and other tests call
        // `clear_all()`, so the entry may be lost mid-check.  loop and
        // re-register until we observe the expected result or give up.
        let mut tries = 0;
        while tries < 100 && !crate::encrypt_key_registry::check(dlc_id_str, pack_path_2) {
            crate::encrypt_key_registry::register_asset_path(dlc_id_str, pack_path_1);
            std::thread::sleep(std::time::Duration::from_millis(5));
            tries += 1;
        }
        assert!(
            crate::encrypt_key_registry::check(dlc_id_str, pack_path_2),
            "different pack path SHOULD be detected as a conflict"
        );

        crate::encrypt_key_registry::clear_all();
    }

    #[test]
    #[serial]
    fn dlc_loader_conflict_helper_allows_same_path() {
        crate::encrypt_key_registry::clear_all();
        let dlc_id = crate::DlcId::from("foo");
        let path = "same_pack.dlcpack";
        crate::encrypt_key_registry::register_asset_path(dlc_id.as_ref(), path);
        // helper should consider loading the same path to be fine
        assert!(check_dlc_id_conflict(&dlc_id, path).is_ok());
    }

    #[test]
    #[serial]
    fn dlc_loader_conflict_helper_rejects_different_path() {
        crate::encrypt_key_registry::clear_all();
        let dlc_id = crate::DlcId::from("foo");
        crate::encrypt_key_registry::register_asset_path(dlc_id.as_ref(), "other.dlcpack");
        let err = check_dlc_id_conflict(&dlc_id, "new.dlcpack").expect_err("should conflict");
        match err {
            DlcLoaderError::DlcIdConflict(id, orig, newp) => {
                assert_eq!(id, dlc_id.to_string());
                assert_eq!(orig, "other.dlcpack");
                assert_eq!(newp, "new.dlcpack");
            }
            _ => panic!("expected DlcIdConflict"),
        }
    }

    #[test]
    #[serial]
    fn dlcpack_load_missing_entry_returns_handle_without_panicking() {
        use bevy::asset::LoadState;

        crate::encrypt_key_registry::clear_all();

        let mut app = App::new();
        app.add_plugins(MinimalPlugins);
        app.add_plugins(bevy::asset::AssetPlugin::default());
        app.init_asset::<crate::asset_loader::DlcPack>();

        let asset_server = app.world().resource::<AssetServer>().clone();

        let pack = DlcPack::new(
            DlcId::from("missing_entry_dlc"),
            Product::from("test"),
            crate::DLC_PACK_VERSION_LATEST,
            vec![DlcPackEntry {
                path: "missing_entry.dlcpack#present.txt".to_string(),
                encrypted: EncryptedAsset {
                    dlc_id: "missing_entry_dlc".to_string(),
                    original_extension: "txt".to_string(),
                    type_path: Some("examples::TextAsset".to_string()),
                    nonce: [0u8; 12],
                    ciphertext: Arc::new([]),
                    block_id: 0,
                    block_offset: 0,
                    size: 0,
                },
            }],
        )
        .with_path("missing_entry.dlcpack".to_string());

        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            pack.load::<LoadedUntypedAsset>(&asset_server, "absent.txt")
        }));

        let handle = result.expect("missing entry load should not panic");
        for _ in 0..10 {
            app.update();
        }

        let state = asset_server.get_load_state(handle.id()).into();
        assert!(
            matches!(state, Some(LoadState::Loading) | Some(LoadState::Failed(_)) | None),
            "unexpected load state: {:?}",
            state
        );
    }
}

impl<A> AssetLoader for DlcLoader<A>
where
    A: bevy::asset::Asset + TypePath + 'static,
{
    type Asset = A;
    type Settings = ();
    type Error = DlcLoaderError;

    async fn load(
        &self,
        reader: &mut dyn Reader,
        _settings: &Self::Settings,
        load_context: &mut LoadContext<'_>,
    ) -> Result<Self::Asset, Self::Error> {
        // capture the original requested path (for registry/bookkeeping)
        let path_string = Some(load_context.path().path().to_string_lossy().to_string());

        let mut bytes = Vec::new();
        reader
            .read_to_end(&mut bytes)
            .await
            .map_err(|e| DlcLoaderError::Io(e))?;

        let enc =
            parse_encrypted(&bytes).map_err(|e| DlcLoaderError::DecryptionFailed(e.to_string()))?;

        // register this asset path for the dlc id so it can be reloaded on unlock
        if let Some(p) = &path_string {
            crate::encrypt_key_registry::register_asset_path(&enc.dlc_id, p);
        }

        // decrypt using helper on `EncryptedAsset`; this hides the registry
        // lookup and error formatting so the loader remains lean.
        let plaintext = enc.decrypt_bytes().map_err(|e| {
            // augment the error message with the requested path for context
            match e {
                DlcLoaderError::DecryptionFailed(msg) => DlcLoaderError::DecryptionFailed(format!(
                    "dlc='{}' path='{}' {}",
                    enc.dlc_id,
                    path_string
                        .clone()
                        .unwrap_or_else(|| "<unknown>".to_string()),
                    msg,
                )),
                other => other,
            }
        })?;

        // Choose an extension for the nested load so Bevy can pick a concrete
        // loader if one exists. We keep the extension around so we can retry
        // with it if the straightforward, static-type load fails. Prioritizing
        // a static-type request avoids the need to downcast an erased asset,
        // which is more efficient and sidesteps the edge cases where the
        // extension loader returns a different type.
        let ext = enc.original_extension;

        // Keep plaintext bytes around so we can recreate readers as needed.
        let bytes_clone = plaintext.clone();

        let stem = load_context
            .path()
            .path()
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("dlc_decrypted");
        let fake_path = format!("{}.{}", stem, ext);

        // First attempt a direct static-type load. This bypasses extension
        // dispatch entirely and returns a value of `A` if a loader exists for
        // that type. Only if this fails do we fall back to using the extension
        // and performing a downcast.
        {
            let mut static_reader = bevy::asset::io::VecReader::new(bytes_clone.clone());
            if let Ok(loaded) = load_context
                .loader()
                .with_static_type()
                .immediate()
                .with_reader(&mut static_reader)
                .load::<A>(fake_path.clone())
                .await
            {
                return Ok(loaded.take());
            }
        }

        // Static load didn't succeed. Try using the extension to select a loader
        // and then downcast the result to `A`. This mirrors how the normal
        // AssetServer would work when loading a file from disk.
        if !ext.is_empty() {
            // rewind original reader and clone again
            let mut ext_reader = bevy::asset::io::VecReader::new(bytes_clone.clone());
            let attempt = load_context
                .loader()
                .immediate()
                .with_reader(&mut ext_reader)
                .with_unknown_type()
                .load(fake_path.clone())
                .await;

            if let Ok(erased) = attempt {
                match erased.downcast::<A>() {
                    Ok(loaded) => return Ok(loaded.take()),
                    Err(_) => {
                        return Err(DlcLoaderError::DecryptionFailed(format!(
                            "dlc loader: extension-based load succeeded but downcast to '{}' failed",
                            A::type_path(),
                        )));
                    }
                }
            } else if let Err(e) = attempt {
                return Err(DlcLoaderError::DecryptionFailed(e.to_string()));
            }
        }

        // If we reach here it means neither static nor extension-based loading
        // succeeded; return an appropriate error. The original static attempt
        // already logged a warning, so just surface a generic message.
        Err(DlcLoaderError::DecryptionFailed(format!(
            "dlc loader: unable to load decrypted asset as {}{}",
            A::type_path(),
            if ext.is_empty() {
                ""
            } else {
                " (extension fallback also failed)"
            }
        )))
    }
}