imferno-core 3.0.1

SMPTE ST 2067 IMF parser and validator
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
//! SMPTE ST 2067-2 Core Constraints — AssetMap, PKL, and foundational IMF types.
//!
//! This module covers:
//! - Foundational primitives: [`ImfUuid`], [`SmpteUl`], [`ImfTypeError`]
//! - PKL types: [`AssetHash`], [`HashAlgorithm`], [`MimeType`]
//! - Namespace detection: [`AssetMapNamespace`], [`PklNamespace`], [`CoreConstraintsNamespace`]
//! - Document parsers: [`parse_assetmap`], [`parse_pkl`], [`parse_opl`]
//! - Re-exports from [`volindex`]: [`VolumeIndex`], [`parse_volindex`]

pub mod codes;
pub mod volindex;
pub mod volindex_codes;

// Re-export VOLINDEX types
pub use volindex::{parse_volindex, VolindexError, VolumeIndex};

use base64::Engine;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use uuid::Uuid;

// ─── Error ────────────────────────────────────────────────────────────────────

#[derive(Debug, Error, PartialEq)]
pub enum ImfTypeError {
    #[error("Invalid UUID '{0}': expected urn:uuid:<uuid> or bare UUID")]
    InvalidUuid(String),
    #[error("Invalid edit rate '{0}': expected 'numerator denominator'")]
    InvalidEditRate(String),
    #[error("Invalid hash: {0}")]
    InvalidHash(String),
    #[error("Invalid language tag '{0}': must be non-empty")]
    InvalidLanguageTag(String),
    #[error("Invalid SMPTE UL '{0}': expected 16 hex bytes in dotted groups")]
    InvalidUl(String),
}

// ─── SmpteUl ─────────────────────────────────────────────────────────────────

/// A SMPTE Universal Label — 16-byte identifier per ST 336M.
///
/// Byte layout:
/// ```text
/// Bytes 1-4:  Object Identifier (always 06.0E.2B.34)
/// Byte  5:    Category designator
/// Byte  6:    Registry designator
/// Byte  7:    Structure designator
/// Byte  8:    Version number  ← MUST BE IGNORED for comparison (ST 298M)
/// Bytes 9-16: Item-specific identification
/// ```
///
/// Per ST 298M, byte 8 (the registry version number) is masked when comparing
/// ULs for semantic identity. Two ULs that differ only in byte 8 are the same item.
#[derive(Debug, Clone, Copy)]
pub struct SmpteUl(pub [u8; 16]);

impl SmpteUl {
    /// Parse a UL from string form.
    ///
    /// Accepted formats:
    /// - `urn:smpte:ul:060e2b34.04010106.04010101.03030000` (4 groups of 4 bytes)
    /// - `060e2b34.04010106.04010101.03030000` (bare 4-group form)
    /// - `060e2b34.0401.0106.04010101.03030000` (5-group variant from some test data)
    pub fn parse(s: &str) -> Result<Self, ImfTypeError> {
        let hex_part = s.strip_prefix("urn:smpte:ul:").unwrap_or(s).trim();

        // Remove dots to get a contiguous hex string
        let hex_str: String = hex_part.chars().filter(|c| *c != '.').collect();

        if hex_str.len() != 32 {
            return Err(ImfTypeError::InvalidUl(s.to_string()));
        }

        let mut bytes = [0u8; 16];
        for i in 0..16 {
            bytes[i] = u8::from_str_radix(&hex_str[i * 2..i * 2 + 2], 16)
                .map_err(|_| ImfTypeError::InvalidUl(s.to_string()))?;
        }

        Ok(SmpteUl(bytes))
    }

    /// Compare two ULs ignoring byte 8 (index 7) — the registry version number.
    ///
    /// Per ST 298M, the version byte must be masked for semantic comparison.
    pub fn matches_ignoring_version(&self, other: &SmpteUl) -> bool {
        for i in 0..16 {
            if i == 7 {
                continue; // skip version byte
            }
            if self.0[i] != other.0[i] {
                return false;
            }
        }
        true
    }

    /// Return the UL with byte 8 zeroed for use as a canonical match key.
    pub fn normalized(&self) -> Self {
        let mut bytes = self.0;
        bytes[7] = 0;
        SmpteUl(bytes)
    }

    /// The discriminating bytes (bytes 9-16) that identify the specific item.
    pub fn item_bytes(&self) -> &[u8] {
        &self.0[8..]
    }
}

impl PartialEq for SmpteUl {
    /// Equality comparison ignores byte 8 (version), per ST 298M.
    fn eq(&self, other: &Self) -> bool {
        self.matches_ignoring_version(other)
    }
}

impl Eq for SmpteUl {}

impl std::hash::Hash for SmpteUl {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        // Hash with byte 8 zeroed so equal items hash identically
        let norm = self.normalized();
        norm.0.hash(state);
    }
}

impl std::fmt::Display for SmpteUl {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "urn:smpte:ul:{:02x}{:02x}{:02x}{:02x}.{:02x}{:02x}{:02x}{:02x}.{:02x}{:02x}{:02x}{:02x}.{:02x}{:02x}{:02x}{:02x}",
            self.0[0], self.0[1], self.0[2], self.0[3],
            self.0[4], self.0[5], self.0[6], self.0[7],
            self.0[8], self.0[9], self.0[10], self.0[11],
            self.0[12], self.0[13], self.0[14], self.0[15],
        )
    }
}

// ─── ImfUuid ──────────────────────────────────────────────────────────────────

/// A SMPTE IMF UUID.
///
/// In XML documents UUIDs appear as `urn:uuid:<uuid>`. In JSON/WASM output
/// they serialise as bare UUID strings (`"0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85"`).
/// Deserialization accepts both forms.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
#[cfg_attr(feature = "typescript", ts(type = "string"))]
pub struct ImfUuid(pub Uuid);

impl ImfUuid {
    /// Parse from `urn:uuid:...` or a bare UUID string.
    ///
    /// Lenient: accepts both forms. Useful for callers that get UUIDs
    /// from non-XML sources (JSON APIs, manual construction, test
    /// fixtures) where the URN prefix may legitimately be absent.
    ///
    /// XML deserialization should prefer [`parse_urn`](Self::parse_urn)
    /// since the SMPTE dcml:UUIDType XSD pattern explicitly requires
    /// the `urn:uuid:` prefix.
    pub fn parse(s: &str) -> Result<Self, ImfTypeError> {
        let bare = s.strip_prefix("urn:uuid:").unwrap_or(s);
        Uuid::parse_str(bare)
            .map(ImfUuid)
            .map_err(|_| ImfTypeError::InvalidUuid(s.to_string()))
    }

    /// Strict parse: requires the `urn:uuid:` prefix per
    /// SMPTE ST 433 dcml:UUIDType (xs:anyURI restricted to
    /// `urn:uuid:[hex]{8}-[hex]{4}-[hex]{4}-[hex]{4}-[hex]{12}`).
    ///
    /// Used by the XML deserializer so CPL/PKL/SCM instances with bare
    /// UUIDs (lacking the URN prefix) fail at parse time — matching
    /// what an XSD-strict validator would catch.
    pub fn parse_urn(s: &str) -> Result<Self, ImfTypeError> {
        let bare = s
            .strip_prefix("urn:uuid:")
            .ok_or_else(|| ImfTypeError::InvalidUuid(s.to_string()))?;
        Uuid::parse_str(bare)
            .map(ImfUuid)
            .map_err(|_| ImfTypeError::InvalidUuid(s.to_string()))
    }

    /// Return the URN form used in XML: `urn:uuid:<uuid>`.
    pub fn to_urn(&self) -> String {
        format!("urn:uuid:{}", self.0)
    }
}

impl std::fmt::Display for ImfUuid {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl Serialize for ImfUuid {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(&self.0.to_string())
    }
}

impl<'de> Deserialize<'de> for ImfUuid {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let s = String::deserialize(d)?;
        // Lenient: accepts both `urn:uuid:...` and bare UUIDs.
        //
        // XSD-strict UUID validation (rejecting bare UUIDs in CPL/PKL/SCM
        // XML per SMPTE dcml:UUIDType) cannot happen here without also
        // rejecting bare UUIDs in JSON wire format — same `Deserialize`
        // impl handles both formats, and JSON intentionally uses bare
        // UUIDs (see `uuid_roundtrip_serde` test). Making this strict
        // would break the JSON API contract.
        //
        // The runtime XSD validator (`crate::xsd`) is the right layer
        // for XSD-strict UUID checking. See the documented uppsala
        // v0.4.0 limitation for the current gap.
        ImfUuid::parse(&s).map_err(serde::de::Error::custom)
    }
}

#[cfg(feature = "jsonschema")]
impl schemars::JsonSchema for ImfUuid {
    fn schema_name() -> String {
        "ImfUuid".to_owned()
    }

    fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
        let mut schema = gen.subschema_for::<String>().into_object();
        schema.metadata().description = Some(
            "A SMPTE IMF UUID, serialised as a bare UUID string (e.g. \"0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85\")".to_owned()
        );
        schema.format = Some("uuid".to_owned());
        schema.into()
    }
}

// ─── AssetHash ────────────────────────────────────────────────────────────────

/// A decoded asset hash from a Packing List, per SMPTE ST 2067-2 §9.
///
/// PKL files carry base64-encoded SHA-1 or SHA-256 digests for each tracked asset.
#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AssetHash {
    algorithm: HashAlgorithm,
    bytes: Vec<u8>,
}

/// The hash algorithm used for a PKL asset digest.
///
/// Per SMPTE ST 2067-2:2020 §9, SHA-1 is the default algorithm.
/// SHA-256 is supported via the `<HashAlgorithm>` element using
/// XML Digital Signature algorithm URIs.
#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum HashAlgorithm {
    /// SHA-1 (default per ST 2067-2 §9).
    /// URI: `http://www.w3.org/2000/09/xmldsig#sha1`
    Sha1,
    /// SHA-256.
    /// URI: `http://www.w3.org/2001/04/xmlenc#sha256`
    Sha256,
}

impl HashAlgorithm {
    /// Parse a hash algorithm from an XML Digital Signature algorithm URI.
    ///
    /// Per ST 2067-2:2020 §9, the `<HashAlgorithm>` element uses
    /// `ds:DigestMethodType` which carries an `Algorithm` attribute URI.
    pub fn from_uri(uri: &str) -> Option<Self> {
        match uri.trim() {
            "http://www.w3.org/2000/09/xmldsig#sha1" => Some(Self::Sha1),
            "http://www.w3.org/2001/04/xmlenc#sha256" => Some(Self::Sha256),
            _ => None,
        }
    }

    /// Expected digest length in bytes for this algorithm.
    pub fn digest_len(&self) -> usize {
        match self {
            Self::Sha1 => 20,
            Self::Sha256 => 32,
        }
    }
}

impl std::fmt::Display for HashAlgorithm {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Sha1 => write!(f, "SHA-1"),
            Self::Sha256 => write!(f, "SHA-256"),
        }
    }
}

impl AssetHash {
    /// Return the hash algorithm (SHA-1 or SHA-256).
    pub fn algorithm(&self) -> HashAlgorithm {
        self.algorithm
    }

    /// Return the raw digest bytes.
    pub fn bytes(&self) -> &[u8] {
        &self.bytes
    }

    /// Decode a base64-encoded SHA-1 digest as found in PKL `<Hash>` elements.
    ///
    /// Per SMPTE ST 2067-2 §9, SHA-1 produces a 20-byte digest.
    pub fn from_base64_sha1(b64: &str) -> Result<Self, ImfTypeError> {
        let bytes = base64::engine::general_purpose::STANDARD
            .decode(b64)
            .map_err(|e| ImfTypeError::InvalidHash(e.to_string()))?;
        if bytes.len() != 20 {
            return Err(ImfTypeError::InvalidHash(format!(
                "SHA-1 digest must be 20 bytes, got {}",
                bytes.len()
            )));
        }
        Ok(Self {
            algorithm: HashAlgorithm::Sha1,
            bytes,
        })
    }

    /// Decode a base64-encoded SHA-256 digest.
    ///
    /// SHA-256 produces a 32-byte digest.
    pub fn from_base64_sha256(b64: &str) -> Result<Self, ImfTypeError> {
        let bytes = base64::engine::general_purpose::STANDARD
            .decode(b64)
            .map_err(|e| ImfTypeError::InvalidHash(e.to_string()))?;
        if bytes.len() != 32 {
            return Err(ImfTypeError::InvalidHash(format!(
                "SHA-256 digest must be 32 bytes, got {}",
                bytes.len()
            )));
        }
        Ok(Self {
            algorithm: HashAlgorithm::Sha256,
            bytes,
        })
    }

    /// Decode a base64-encoded digest for the given algorithm.
    pub fn from_base64(b64: &str, algorithm: HashAlgorithm) -> Result<Self, ImfTypeError> {
        match algorithm {
            HashAlgorithm::Sha1 => Self::from_base64_sha1(b64),
            HashAlgorithm::Sha256 => Self::from_base64_sha256(b64),
        }
    }

    /// Encode the hash bytes as base64, as used in PKL XML.
    pub fn to_base64(&self) -> String {
        base64::engine::general_purpose::STANDARD.encode(&self.bytes)
    }
}

// ─── MimeType ─────────────────────────────────────────────────────────────────

/// MIME type as used in `<Type>` elements in PKL assets (SMPTE ST 2067-2 §9).
#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum MimeType {
    /// `text/xml` — CPL and other XML documents
    TextXml,
    /// `application/xml` — alternative XML MIME type
    ApplicationXml,
    /// `application/mxf` — MXF essence files
    ApplicationMxf,
    /// Unrecognised; the original string is preserved.
    Other(String),
}

impl MimeType {
    pub fn parse(s: &str) -> Self {
        match s.trim() {
            "text/xml" => Self::TextXml,
            "application/xml" => Self::ApplicationXml,
            "application/mxf" => Self::ApplicationMxf,
            other => Self::Other(other.to_string()),
        }
    }

    pub fn is_xml(&self) -> bool {
        matches!(self, Self::TextXml | Self::ApplicationXml)
    }

    pub fn is_mxf(&self) -> bool {
        matches!(self, Self::ApplicationMxf)
    }
}

impl std::fmt::Display for MimeType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::TextXml => write!(f, "text/xml"),
            Self::ApplicationXml => write!(f, "application/xml"),
            Self::ApplicationMxf => write!(f, "application/mxf"),
            Self::Other(s) => write!(f, "{}", s),
        }
    }
}

// ─── AssetMapNamespace ────────────────────────────────────────────────────────

/// The detected SMPTE spec version of an AssetMap document, derived from its root xmlns.
#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum AssetMapNamespace {
    /// DCI era — `http://www.smpte-ra.org/schemas/429-9/2007/AM`
    #[default]
    Dci429_9,
    /// SMPTE ST 2067-9:2016 — `http://www.smpte-ra.org/schemas/2067-9/2016`
    ///
    /// ST 2067-9 has only the 2016 edition published; there is no
    /// 2020 successor. The SCM extension (ST 2067-9:2018) is a
    /// separate document tracked by `scm::ScmNamespace`.
    Smpte2067_9_2016,
    /// Unrecognised namespace; the original URI is preserved.
    Unknown(String),
}

impl AssetMapNamespace {
    /// Detect AssetMap spec version from a namespace URI.
    pub fn from_uri(uri: &str) -> Self {
        match uri.trim() {
            "http://www.smpte-ra.org/schemas/429-9/2007/AM" => Self::Dci429_9,
            "http://www.smpte-ra.org/schemas/2067-9/2016" => Self::Smpte2067_9_2016,
            other => Self::Unknown(other.to_string()),
        }
    }

    /// Returns the normative spec document identifier.
    pub fn spec_id(&self) -> &str {
        match self {
            Self::Dci429_9 => "ST 429-9:2007",
            Self::Smpte2067_9_2016 => "ST 2067-9:2016",
            Self::Unknown(_) => "Unknown",
        }
    }
}

impl std::fmt::Display for AssetMapNamespace {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Dci429_9 => write!(f, "http://www.smpte-ra.org/schemas/429-9/2007/AM"),
            Self::Smpte2067_9_2016 => write!(f, "http://www.smpte-ra.org/schemas/2067-9/2016"),
            Self::Unknown(s) => write!(f, "{}", s),
        }
    }
}

// ─── PklNamespace ─────────────────────────────────────────────────────────────

/// The detected SMPTE spec version of a PKL document, derived from its root xmlns.
///
/// PKL schema evolved across three eras: DCI 429-8, IMF 2067-2 (2013-2016), and 2020.
#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum PklNamespace {
    /// DCI era — `http://www.smpte-ra.org/schemas/429-8/2007/PKL`
    #[default]
    Dci429_8,
    /// SMPTE ST 2067-2:2013 — `http://www.smpte-ra.org/schemas/2067-2/2013`
    Smpte2067_2_2013,
    /// SMPTE ST 2067-2:2016 — `http://www.smpte-ra.org/schemas/2067-2/2016`
    Smpte2067_2_2016,
    /// SMPTE ST 2067-2:2016 (PKL variant) — `http://www.smpte-ra.org/schemas/2067-2/2016/PKL`
    Smpte2067_2_2016Pkl,
    /// SMPTE ST 2067-2:2020 — `http://www.smpte-ra.org/ns/2067-2/2020`
    Smpte2067_2_2020,
    /// Unrecognised namespace; the original URI is preserved.
    Unknown(String),
}

impl PklNamespace {
    /// Detect PKL spec version from a namespace URI.
    pub fn from_uri(uri: &str) -> Self {
        match uri.trim() {
            "http://www.smpte-ra.org/schemas/429-8/2007/PKL" => Self::Dci429_8,
            "http://www.smpte-ra.org/schemas/2067-2/2013" => Self::Smpte2067_2_2013,
            "http://www.smpte-ra.org/schemas/2067-2/2016" => Self::Smpte2067_2_2016,
            "http://www.smpte-ra.org/schemas/2067-2/2016/PKL" => Self::Smpte2067_2_2016Pkl,
            "http://www.smpte-ra.org/ns/2067-2/2020" => Self::Smpte2067_2_2020,
            other => Self::Unknown(other.to_string()),
        }
    }

    /// Returns the normative spec document identifier.
    pub fn spec_id(&self) -> &str {
        match self {
            Self::Dci429_8 => "ST 429-8:2007",
            Self::Smpte2067_2_2013 => "ST 2067-2:2013",
            Self::Smpte2067_2_2016 | Self::Smpte2067_2_2016Pkl => "ST 2067-2:2016",
            Self::Smpte2067_2_2020 => "ST 2067-2:2020",
            Self::Unknown(_) => "Unknown",
        }
    }
}

impl std::fmt::Display for PklNamespace {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Dci429_8 => write!(f, "http://www.smpte-ra.org/schemas/429-8/2007/PKL"),
            Self::Smpte2067_2_2013 => write!(f, "http://www.smpte-ra.org/schemas/2067-2/2013"),
            Self::Smpte2067_2_2016 => write!(f, "http://www.smpte-ra.org/schemas/2067-2/2016"),
            Self::Smpte2067_2_2016Pkl => {
                write!(f, "http://www.smpte-ra.org/schemas/2067-2/2016/PKL")
            }
            Self::Smpte2067_2_2020 => write!(f, "http://www.smpte-ra.org/ns/2067-2/2020"),
            Self::Unknown(s) => write!(f, "{}", s),
        }
    }
}

// ─── CoreConstraintsNamespace ─────────────────────────────────────────────────

/// The detected SMPTE core constraints spec version, from inner xmlns declarations in CPLs.
///
/// CPL documents reference core constraints namespaces for elements defined in ST 2067-2.
/// This is distinct from the CPL namespace (ST 2067-3) and determines which core constraint
/// rules apply.
#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum CoreConstraintsNamespace {
    /// SMPTE ST 2067-2:2013 — `http://www.smpte-ra.org/schemas/2067-2/2013`
    Smpte2067_2_2013,
    /// SMPTE ST 2067-2:2016 — `http://www.smpte-ra.org/schemas/2067-2/2016`
    #[default]
    Smpte2067_2_2016,
    /// SMPTE ST 2067-2:2020 — `http://www.smpte-ra.org/ns/2067-2/2020`
    Smpte2067_2_2020,
    /// Unrecognised namespace; the original URI is preserved.
    Unknown(String),
}

impl CoreConstraintsNamespace {
    /// Detect core constraints spec version from a namespace URI.
    pub fn from_uri(uri: &str) -> Self {
        match uri.trim() {
            "http://www.smpte-ra.org/schemas/2067-2/2013" => Self::Smpte2067_2_2013,
            "http://www.smpte-ra.org/schemas/2067-2/2016" => Self::Smpte2067_2_2016,
            "http://www.smpte-ra.org/ns/2067-2/2020" => Self::Smpte2067_2_2020,
            other => Self::Unknown(other.to_string()),
        }
    }

    /// Returns the normative spec document identifier.
    pub fn spec_id(&self) -> &str {
        match self {
            Self::Smpte2067_2_2013 => "ST 2067-2:2013",
            Self::Smpte2067_2_2016 => "ST 2067-2:2016",
            Self::Smpte2067_2_2020 => "ST 2067-2:2020",
            Self::Unknown(_) => "Unknown",
        }
    }
}

impl std::fmt::Display for CoreConstraintsNamespace {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Smpte2067_2_2013 => write!(f, "http://www.smpte-ra.org/schemas/2067-2/2013"),
            Self::Smpte2067_2_2016 => write!(f, "http://www.smpte-ra.org/schemas/2067-2/2016"),
            Self::Smpte2067_2_2020 => write!(f, "http://www.smpte-ra.org/ns/2067-2/2020"),
            Self::Unknown(s) => write!(f, "{}", s),
        }
    }
}

// ─── detect_root_namespace ────────────────────────────────────────────────────

/// Extract the default namespace URI from an XML document's root element.
///
/// Searches for the first `xmlns="..."` (non-prefixed) declaration. This is used
/// by parsers to detect which spec version a document conforms to.
pub fn detect_root_namespace(xml: &str) -> Option<String> {
    use std::sync::LazyLock;
    // Match xmlns="..." but NOT xmlns:prefix="..."
    // We look for xmlns= preceded by whitespace (not by a colon)
    static RE_XMLNS: LazyLock<regex::Regex> =
        LazyLock::new(|| regex::Regex::new(r#"(?:^|[\s<])xmlns="([^"]*)""#).unwrap());
    RE_XMLNS.captures(xml).map(|cap| cap[1].to_string())
}

// ─── Parse error ──────────────────────────────────────────────────────────────

/// Errors that can occur when parsing an AssetMap, PKL, OPL, or VOLINDEX.
#[derive(Debug, Error)]
pub enum AssetMapParseError {
    /// The XML is structurally invalid or missing required elements.
    #[error("XML parse error: {0}")]
    Xml(#[from] quick_xml::DeError),
    /// A required field contains an invalid value (bad UUID, bad hash, etc.).
    #[error("Invalid field '{field}': {source}")]
    Field {
        field: &'static str,
        #[source]
        source: ImfTypeError,
    },
}

// ─── Private raw deserialization layer ────────────────────────────────────────

mod raw {
    use serde::Deserialize;

    fn default_volume_index() -> u32 {
        1
    }

    #[derive(Deserialize)]
    pub struct AssetMap {
        #[serde(rename = "Id")]
        pub id: String,
        #[serde(rename = "AnnotationText", default)]
        pub annotation_text: Option<String>,
        #[serde(rename = "Creator", default)]
        pub creator: Option<String>,
        #[serde(rename = "VolumeCount")]
        pub volume_count: u32,
        #[serde(rename = "IssueDate")]
        pub issue_date: String,
        #[serde(rename = "Issuer", default)]
        pub issuer: Option<String>,
        #[serde(rename = "AssetList")]
        pub asset_list: AssetList,
    }

    #[derive(Deserialize)]
    pub struct AssetList {
        #[serde(rename = "Asset")]
        pub assets: Vec<Asset>,
    }

    #[derive(Deserialize)]
    pub struct Asset {
        #[serde(rename = "Id")]
        pub id: String,
        #[serde(rename = "PackingList", default)]
        pub packing_list: Option<bool>,
        #[serde(rename = "ChunkList")]
        pub chunk_list: ChunkList,
    }

    #[derive(Deserialize)]
    pub struct ChunkList {
        #[serde(rename = "Chunk")]
        pub chunks: Vec<Chunk>,
    }

    #[derive(Deserialize)]
    pub struct Chunk {
        #[serde(rename = "Path")]
        pub path: String,
        #[serde(rename = "VolumeIndex", default = "default_volume_index")]
        pub volume_index: u32,
    }

    // ── OPL (ST 2067-100) ──────────────────────────────────────────────────

    #[derive(Deserialize)]
    pub struct OutputProfileList {
        #[serde(rename = "Id")]
        pub id: String,
        #[serde(rename = "Annotation", default)]
        pub annotation: Option<String>,
        #[serde(rename = "IssueDate")]
        pub issue_date: String,
        #[serde(rename = "Issuer", default)]
        pub issuer: Option<String>,
        #[serde(rename = "Creator", default)]
        pub creator: Option<String>,
        #[serde(rename = "CompositionPlaylistId")]
        pub composition_playlist_id: String,
    }

    // ── PKL ─────────────────────────────────────────────────────────────────

    #[derive(Deserialize)]
    pub struct PackingList {
        #[serde(rename = "Id")]
        pub id: String,
        #[serde(rename = "AnnotationText", default)]
        pub annotation_text: Option<String>,
        #[serde(rename = "IssueDate")]
        pub issue_date: String,
        #[serde(rename = "Issuer", default)]
        pub issuer: Option<String>,
        #[serde(rename = "Creator", default)]
        pub creator: Option<String>,
        /// SMPTE ST 2067-2 §9: Optional group identifier for partial deliveries.
        #[serde(rename = "GroupId", default)]
        pub group_id: Option<String>,
        #[serde(rename = "AssetList")]
        pub asset_list: PklAssetList,
    }

    #[derive(Deserialize)]
    pub struct PklAssetList {
        #[serde(rename = "Asset")]
        pub assets: Vec<PklAsset>,
    }

    /// `ds:DigestMethodType` — carries an `Algorithm` attribute URI.
    /// Used in `<HashAlgorithm Algorithm="..."/>` per SMPTE ST 2067-2 §9.
    #[derive(Deserialize)]
    pub struct DigestMethod {
        #[serde(rename = "@Algorithm")]
        pub algorithm: String,
    }

    #[derive(Deserialize)]
    pub struct PklAsset {
        #[serde(rename = "Id")]
        pub id: String,
        #[serde(rename = "AnnotationText", default)]
        pub annotation_text: Option<String>,
        #[serde(rename = "Hash")]
        pub hash: String,
        #[serde(rename = "Size")]
        pub size: u64,
        #[serde(rename = "Type")]
        pub mime_type: String,
        #[serde(rename = "OriginalFileName", default)]
        pub original_file_name: Option<String>,
        /// SMPTE ST 2067-2 §9: Optional hash algorithm override.
        /// When absent, SHA-1 is assumed (default per spec).
        #[serde(rename = "HashAlgorithm", default)]
        pub hash_algorithm: Option<DigestMethod>,
    }
}

// ─── Public domain types ───────────────────────────────────────────────────────

// VolumeIndex lives in the volindex submodule and is re-exported at the top of this file.

/// ASSETMAP.xml — maps UUIDs to physical file paths (ST 429-9 §6).
#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
#[cfg_attr(feature = "typescript", ts(export, rename_all = "camelCase"))]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(into_wasm_abi, from_wasm_abi))]
pub struct AssetMap {
    /// The SMPTE spec version detected from the root xmlns.
    #[serde(skip)]
    pub namespace: AssetMapNamespace,
    /// Unique identifier for this AssetMap (ST 429-9 §6.2).
    pub id: ImfUuid,
    pub annotation_text: Option<String>,
    pub creator: Option<String>,
    pub volume_count: u32,
    /// ISO 8601 issue date (e.g. `"2016-10-06T08:35:02-00:00"`).
    pub issue_date: String,
    pub issuer: Option<String>,
    pub asset_list: AssetList,
}

impl AssetMap {
    fn from_raw(
        raw: raw::AssetMap,
        namespace: AssetMapNamespace,
    ) -> Result<Self, AssetMapParseError> {
        Ok(Self {
            namespace,
            id: ImfUuid::parse(&raw.id).map_err(|source| AssetMapParseError::Field {
                field: "Id",
                source,
            })?,
            annotation_text: raw.annotation_text,
            creator: raw.creator,
            volume_count: raw.volume_count,
            issue_date: raw.issue_date,
            issuer: raw.issuer,
            asset_list: AssetList::from_raw(raw.asset_list)?,
        })
    }
}

/// The `<AssetList>` element in ASSETMAP.xml.
#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
#[cfg_attr(feature = "typescript", ts(export, rename_all = "camelCase"))]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(into_wasm_abi, from_wasm_abi))]
pub struct AssetList {
    pub assets: Vec<Asset>,
}

impl AssetList {
    fn from_raw(raw: raw::AssetList) -> Result<Self, AssetMapParseError> {
        let assets = raw
            .assets
            .into_iter()
            .map(Asset::from_raw)
            .collect::<Result<Vec<_>, _>>()?;
        Ok(Self { assets })
    }
}

/// A single asset entry in ASSETMAP.xml.
#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
#[cfg_attr(feature = "typescript", ts(export, rename_all = "camelCase"))]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(into_wasm_abi, from_wasm_abi))]
pub struct Asset {
    /// UUID identifying this asset.
    pub id: ImfUuid,
    /// Present and `true` when this entry refers to the Packing List file.
    pub packing_list: Option<bool>,
    pub chunk_list: ChunkList,
}

impl Asset {
    fn from_raw(raw: raw::Asset) -> Result<Self, AssetMapParseError> {
        Ok(Self {
            id: ImfUuid::parse(&raw.id).map_err(|source| AssetMapParseError::Field {
                field: "Id",
                source,
            })?,
            packing_list: raw.packing_list,
            chunk_list: ChunkList::from_raw(raw.chunk_list),
        })
    }
}

/// A list of file chunks for a single asset.
#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
#[cfg_attr(feature = "typescript", ts(export, rename_all = "camelCase"))]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(into_wasm_abi, from_wasm_abi))]
pub struct ChunkList {
    pub chunks: Vec<Chunk>,
}

impl ChunkList {
    fn from_raw(raw: raw::ChunkList) -> Self {
        Self {
            chunks: raw
                .chunks
                .into_iter()
                .map(|c| Chunk {
                    path: c.path,
                    volume_index: c.volume_index,
                })
                .collect(),
        }
    }
}

/// A single file path entry in a ChunkList.
#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
#[cfg_attr(feature = "typescript", ts(export, rename_all = "camelCase"))]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(into_wasm_abi, from_wasm_abi))]
pub struct Chunk {
    /// File path relative to the IMP root directory.
    pub path: String,
    pub volume_index: u32,
}

/// OPL XML — Output Profile List (SMPTE ST 2067-100).
///
/// Defines output processing instructions for a composition: image scaling,
/// cropping, pixel encoding, and audio routing/mixing macros.
///
/// `macros` carries every `<Macro xsi:type="...">` entry from the
/// `<MacroList>`. The list is structurally extracted via a small
/// `quick_xml` walker rather than serde because the XSD uses
/// `xsi:type` polymorphism with vendor-specific extension namespaces
/// (`opl:PresetMacroType`, `arm:AudioRoutingMixingMacroType`, etc.).
/// Type-specific payload fields land in [`OplMacro::extra_fields`]
/// as `(local_name, text)` pairs so the parser doesn't have to know
/// every macro subtype to round-trip the list.
#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct OutputProfileList {
    pub id: ImfUuid,
    pub annotation: Option<String>,
    /// ISO 8601 issue date.
    pub issue_date: String,
    pub issuer: Option<String>,
    pub creator: Option<String>,
    /// The CPL that this OPL targets.
    pub composition_playlist_id: ImfUuid,
    /// Each `<Macro xsi:type="...">` entry from the `<MacroList>`.
    /// Empty when the OPL has no macros (or has `<MacroList/>`).
    #[serde(default)]
    pub macros: Vec<OplMacro>,
}

/// A single macro entry from an OPL `<MacroList>`.
///
/// Captures the polymorphic `xsi:type` attribute plus the common
/// `Name` / `Annotation` fields from the abstract `MacroType`. All
/// other children of the macro are stored as `(local_name, text)`
/// pairs in [`Self::extra_fields`] so that vendor-specific extensions
/// remain accessible without the parser knowing each subtype.
#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct OplMacro {
    /// Value of the `xsi:type` attribute, e.g. `"opl:PresetMacroType"`.
    /// `None` when the writer omitted the attribute (non-conformant,
    /// but we don't reject — the validator can flag it).
    pub xsi_type: Option<String>,
    /// `MacroType.Name` per ST 2067-100 §6.5.1; required by the XSD.
    pub name: String,
    /// `MacroType.Annotation` (optional, §6.5.2).
    pub annotation: Option<String>,
    /// Every other direct-child element of the `<Macro>` element,
    /// as `(local_name, text_body)`. Element nesting deeper than one
    /// level is flattened into the outermost name with the joined
    /// text body — callers that need structured access to nested
    /// macro extensions should re-parse the OPL with a richer model.
    pub extra_fields: Vec<(String, String)>,
}

impl OutputProfileList {
    fn from_raw(
        raw: raw::OutputProfileList,
        macros: Vec<OplMacro>,
    ) -> Result<Self, AssetMapParseError> {
        Ok(Self {
            id: ImfUuid::parse(&raw.id).map_err(|source| AssetMapParseError::Field {
                field: "Id",
                source,
            })?,
            annotation: raw.annotation,
            issue_date: raw.issue_date,
            issuer: raw.issuer,
            creator: raw.creator,
            composition_playlist_id: ImfUuid::parse(&raw.composition_playlist_id).map_err(
                |source| AssetMapParseError::Field {
                    field: "CompositionPlaylistId",
                    source,
                },
            )?,
            macros,
        })
    }
}

/// PKL XML — Packing List (SMPTE ST 2067-2 §9).
///
/// Assets carry SHA-1 (default) or SHA-256 checksums. The algorithm is
/// determined by the optional `<HashAlgorithm>` element on each asset.
#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PackingList {
    /// The SMPTE spec version detected from the root xmlns.
    #[serde(skip)]
    pub namespace: PklNamespace,
    pub id: ImfUuid,
    pub annotation_text: Option<String>,
    /// ISO 8601 issue date.
    pub issue_date: String,
    pub issuer: Option<String>,
    pub creator: Option<String>,
    /// Optional group identifier for partial deliveries (SMPTE ST 2067-2 §9).
    pub group_id: Option<ImfUuid>,
    pub asset_list: PklAssetList,
}

impl PackingList {
    fn from_raw(
        raw: raw::PackingList,
        namespace: PklNamespace,
    ) -> Result<Self, AssetMapParseError> {
        let group_id = raw
            .group_id
            .map(|s| ImfUuid::parse(&s))
            .transpose()
            .map_err(|source| AssetMapParseError::Field {
                field: "GroupId",
                source,
            })?;

        Ok(Self {
            namespace,
            id: ImfUuid::parse(&raw.id).map_err(|source| AssetMapParseError::Field {
                field: "Id",
                source,
            })?,
            annotation_text: raw.annotation_text,
            issue_date: raw.issue_date,
            issuer: raw.issuer,
            creator: raw.creator,
            group_id,
            asset_list: PklAssetList::from_raw(raw.asset_list)?,
        })
    }
}

/// The `<AssetList>` element in a PKL.
#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PklAssetList {
    pub assets: Vec<PklAsset>,
}

impl PklAssetList {
    fn from_raw(raw: raw::PklAssetList) -> Result<Self, AssetMapParseError> {
        let assets = raw
            .assets
            .into_iter()
            .map(PklAsset::from_raw)
            .collect::<Result<Vec<_>, _>>()?;
        Ok(Self { assets })
    }
}

/// A single asset entry in a PKL.
#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct PklAsset {
    pub id: ImfUuid,
    pub annotation_text: Option<String>,
    /// SHA-1 digest decoded from the base64 `<Hash>` element (SMPTE ST 2067-2 §9.3).
    pub hash: AssetHash,
    /// File size in bytes.
    pub size: u64,
    /// MIME type of the asset file (SMPTE ST 2067-2 §9.4).
    pub mime_type: MimeType,
    pub original_file_name: Option<String>,
}

impl PklAsset {
    fn from_raw(raw: raw::PklAsset) -> Result<Self, AssetMapParseError> {
        // Determine hash algorithm from <HashAlgorithm Algorithm="..."/> element.
        // Per ST 2067-2 §9, SHA-1 is the default when the element is absent.
        let algorithm = match &raw.hash_algorithm {
            Some(dm) => {
                HashAlgorithm::from_uri(&dm.algorithm).ok_or_else(|| AssetMapParseError::Field {
                    field: "HashAlgorithm",
                    source: ImfTypeError::InvalidHash(format!(
                        "unsupported hash algorithm URI: {}",
                        dm.algorithm
                    )),
                })?
            }
            None => HashAlgorithm::Sha1,
        };

        Ok(Self {
            id: ImfUuid::parse(&raw.id).map_err(|source| AssetMapParseError::Field {
                field: "Id",
                source,
            })?,
            annotation_text: raw.annotation_text,
            hash: AssetHash::from_base64(&raw.hash, algorithm).map_err(|source| {
                AssetMapParseError::Field {
                    field: "Hash",
                    source,
                }
            })?,
            size: raw.size,
            mime_type: MimeType::parse(&raw.mime_type),
            original_file_name: raw.original_file_name,
        })
    }
}

// ─── Parse functions ──────────────────────────────────────────────────────────

// parse_volindex is re-exported from the volindex module at the top of this file.

/// Parse ASSETMAP.xml (ST 429-9 §6).
///
/// Detects the SMPTE spec version from the root `xmlns` attribute and stores it
/// on the returned `AssetMap.namespace` field.
pub fn parse_assetmap(xml_content: &str) -> Result<AssetMap, AssetMapParseError> {
    // Missing root xmlns lands in Unknown rather than silently defaulting to
    // DCI 429-9 (the first enum variant) — see FIX-3 in
    // docs/parser-audit-2026-06.md.
    let namespace = detect_root_namespace(xml_content)
        .map(|uri| AssetMapNamespace::from_uri(&uri))
        .unwrap_or_else(|| AssetMapNamespace::Unknown(String::new()));
    let raw: raw::AssetMap = quick_xml::de::from_str(xml_content)?;
    AssetMap::from_raw(raw, namespace)
}

/// Parse PKL XML (SMPTE ST 2067-2 §9).
///
/// Detects the SMPTE spec version from the root `xmlns` attribute and stores it
/// on the returned `PackingList.namespace` field.
pub fn parse_pkl(xml_content: &str) -> Result<PackingList, AssetMapParseError> {
    // Missing root xmlns lands in Unknown rather than silently defaulting to
    // DCI 429-8 (the first enum variant) — see FIX-3 in
    // docs/parser-audit-2026-06.md.
    let namespace = detect_root_namespace(xml_content)
        .map(|uri| PklNamespace::from_uri(&uri))
        .unwrap_or_else(|| PklNamespace::Unknown(String::new()));
    let raw: raw::PackingList = quick_xml::de::from_str(xml_content)?;
    PackingList::from_raw(raw, namespace)
}

/// Parse OPL XML (SMPTE ST 2067-100).
///
/// Extracts the core metadata (Id, Annotation, IssueDate, Issuer, Creator,
/// CompositionPlaylistId) via serde, and then walks the `<MacroList>` with
/// an event-driven `quick_xml` reader to capture each
/// `<Macro xsi:type="...">` entry. The XSD's `xsi:type` polymorphism (with
/// vendor-specific extension namespaces) is too dynamic for serde derives,
/// so the macros are captured as flexible `OplMacro` records — the abstract
/// `MacroType` fields (`Name`, `Annotation`) plus an `extra_fields` bag of
/// `(local_name, text)` pairs for everything else. Malformed
/// `<MacroList>` content (mid-walk XML errors) is treated as "no macros"
/// rather than a parse failure, because serde already validated the
/// outer document structure and we don't want a vendor-quirk macro to
/// take down the whole parse.
pub fn parse_opl(xml_content: &str) -> Result<OutputProfileList, AssetMapParseError> {
    let raw: raw::OutputProfileList = quick_xml::de::from_str(xml_content)?;
    let macros = parse_opl_macros(xml_content).unwrap_or_default();
    OutputProfileList::from_raw(raw, macros)
}

/// Walk an OPL XML document and return every `<Macro xsi:type="...">`
/// entry found inside `<MacroList>`.
///
/// Returns `Ok(empty)` when the OPL has no `<MacroList>` or an
/// empty/self-closing one. Returns `Err` only on genuinely
/// unrecoverable XML errors during the walk — callers (see
/// `parse_opl`) treat that as "no macros" rather than propagating.
fn parse_opl_macros(xml_content: &str) -> Result<Vec<OplMacro>, quick_xml::Error> {
    use quick_xml::events::Event;
    use quick_xml::reader::Reader;

    let mut reader = Reader::from_str(xml_content);
    reader.trim_text(true);

    let mut macros: Vec<OplMacro> = Vec::new();
    let mut buf = Vec::new();
    let mut in_macro_list = 0u32;
    let mut current: Option<OplMacroBuilder> = None;
    // Tracks the local name of the element currently accumulating text;
    // `None` means we're not inside a leaf element with text content.
    let mut text_target: Option<String> = None;

    loop {
        match reader.read_event_into(&mut buf) {
            Ok(Event::Start(e)) => {
                let local = local_name(e.name().as_ref());
                if local == "MacroList" {
                    in_macro_list += 1;
                    continue;
                }
                if in_macro_list == 0 {
                    continue;
                }
                if local == "Macro" {
                    // Read the xsi:type attribute (any prefix).
                    let xsi_type = e
                        .attributes()
                        .with_checks(false)
                        .filter_map(|a| a.ok())
                        .find_map(|a| {
                            if local_name(a.key.as_ref()) == "type" {
                                std::str::from_utf8(&a.value).ok().map(str::to_string)
                            } else {
                                None
                            }
                        });
                    current = Some(OplMacroBuilder {
                        xsi_type,
                        name: String::new(),
                        annotation: None,
                        extra_fields: Vec::new(),
                    });
                    text_target = None;
                } else if current.is_some() {
                    // Direct child of a Macro — start accumulating text
                    // for it. Nested children get folded into the
                    // outermost name's text via the `text_target`.
                    if text_target.is_none() {
                        text_target = Some(local);
                    }
                }
            }
            Ok(Event::End(e)) => {
                let local = local_name(e.name().as_ref());
                if local == "MacroList" {
                    in_macro_list = in_macro_list.saturating_sub(1);
                    continue;
                }
                if local == "Macro" {
                    if let Some(builder) = current.take() {
                        macros.push(OplMacro {
                            xsi_type: builder.xsi_type,
                            name: builder.name,
                            annotation: builder.annotation,
                            extra_fields: builder.extra_fields,
                        });
                    }
                    text_target = None;
                } else if let Some(target) = &text_target {
                    if target == &local {
                        text_target = None;
                    }
                }
            }
            Ok(Event::Empty(e)) => {
                // Self-closing element: still record its presence with empty text.
                if let (true, Some(builder)) = (in_macro_list > 0, current.as_mut()) {
                    let local = local_name(e.name().as_ref());
                    match local.as_str() {
                        "Name" => {} // empty Name is structurally invalid; skip
                        "Annotation" => builder.annotation = Some(String::new()),
                        _ => builder.extra_fields.push((local, String::new())),
                    }
                }
            }
            Ok(Event::Text(t)) => {
                if let (Some(builder), Some(target)) = (current.as_mut(), text_target.as_ref()) {
                    let text = t.unescape().unwrap_or_default().into_owned();
                    match target.as_str() {
                        "Name" => builder.name.push_str(&text),
                        "Annotation" => {
                            builder.annotation =
                                Some(builder.annotation.take().map(|a| a + &text).unwrap_or(text))
                        }
                        other => {
                            // Append to an existing entry for the same
                            // element if it already exists; otherwise create.
                            if let Some(entry) =
                                builder.extra_fields.iter_mut().rfind(|(n, _)| n == other)
                            {
                                entry.1.push_str(&text);
                            } else {
                                builder.extra_fields.push((other.to_string(), text));
                            }
                        }
                    }
                }
            }
            Ok(Event::Eof) => break,
            Err(e) => return Err(e),
            _ => {}
        }
        buf.clear();
    }

    Ok(macros)
}

/// Strip an XML-namespaced tag down to its local-name component.
fn local_name(tag: &[u8]) -> String {
    let s = std::str::from_utf8(tag).unwrap_or("");
    match s.rsplit_once(':') {
        Some((_, local)) => local.to_string(),
        None => s.to_string(),
    }
}

/// Mutable builder for one macro entry; flushed into [`OplMacro`] on `</Macro>`.
struct OplMacroBuilder {
    xsi_type: Option<String>,
    name: String,
    annotation: Option<String>,
    extra_fields: Vec<(String, String)>,
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use pretty_assertions::assert_eq;
    use std::path::PathBuf;

    fn test_data(name: &str) -> PathBuf {
        PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("../../test-data")
            .join(name)
    }

    // ── ImfUuid ──────────────────────────────────────────────────────────────

    /// SMPTE ST 2067-2 §7: UUIDs are serialized as urn:uuid: URNs in XML.
    #[test]
    fn uuid_parse_urn_form() {
        let id = ImfUuid::parse("urn:uuid:0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85").unwrap();
        assert_eq!(id.to_string(), "0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85");
        assert_eq!(id.to_urn(), "urn:uuid:0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85");
    }

    #[test]
    fn uuid_parse_bare_form() {
        let id = ImfUuid::parse("0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85").unwrap();
        assert_eq!(id.to_string(), "0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85");
    }

    #[test]
    fn uuid_parse_invalid() {
        assert!(ImfUuid::parse("not-a-uuid").is_err());
        assert!(ImfUuid::parse("").is_err());
        assert!(ImfUuid::parse("urn:uuid:not-valid").is_err());
    }

    #[test]
    fn uuid_roundtrip_serde() {
        let id = ImfUuid::parse("urn:uuid:0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85").unwrap();
        let json = serde_json::to_string(&id).unwrap();
        // Serializes as bare UUID (no urn: prefix) for JSON
        assert_eq!(json, r#""0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85""#);
        let back: ImfUuid = serde_json::from_str(&json).unwrap();
        assert_eq!(id, back);
    }

    #[test]
    fn uuid_deserialize_urn_from_json() {
        // Deserializer must accept urn: form too
        let back: ImfUuid =
            serde_json::from_str(r#""urn:uuid:0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85""#).unwrap();
        assert_eq!(back.to_string(), "0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85");
    }

    // ── SmpteUl ──────────────────────────────────────────────────────────────

    /// ST 298M: Byte 8 (registry version) must be ignored for semantic identity.
    #[test]
    fn smpte_ul_parse_4group() {
        let ul = SmpteUl::parse("060e2b34.04010106.04010101.03030000").unwrap();
        assert_eq!(ul.0[0], 0x06);
        assert_eq!(ul.0[7], 0x06); // byte 8 = version
        assert_eq!(ul.0[12], 0x03);
    }

    #[test]
    fn smpte_ul_parse_urn_form() {
        let ul = SmpteUl::parse("urn:smpte:ul:060e2b34.04010106.04010101.03030000").unwrap();
        assert_eq!(ul.0[0], 0x06);
    }

    #[test]
    fn smpte_ul_parse_5group_variant() {
        // Variant format from some test data
        let ul = SmpteUl::parse("urn:smpte:ul:060e2b34.0401.0101.04010101.01020000").unwrap();
        assert_eq!(ul.0[4], 0x04);
        assert_eq!(ul.0[5], 0x01);
    }

    #[test]
    fn smpte_ul_version_agnostic_equality() {
        // Same UL at different registry versions
        let v1 = SmpteUl::parse("060e2b34.04010101.04010101.03030000").unwrap();
        let v6 = SmpteUl::parse("060e2b34.04010106.04010101.03030000").unwrap();
        let vd = SmpteUl::parse("060e2b34.0401010d.04010101.03030000").unwrap();
        assert_eq!(v1, v6, "version 01 == version 06");
        assert_eq!(v6, vd, "version 06 == version 0d");
    }

    #[test]
    fn smpte_ul_different_items_not_equal() {
        let a = SmpteUl::parse("060e2b34.04010106.04010101.03030000").unwrap();
        let b = SmpteUl::parse("060e2b34.04010106.04010101.03040000").unwrap();
        assert_ne!(a, b);
    }

    #[test]
    fn smpte_ul_display_roundtrip() {
        let ul = SmpteUl::parse("urn:smpte:ul:060e2b34.04010106.04010101.03030000").unwrap();
        let s = ul.to_string();
        assert!(s.starts_with("urn:smpte:ul:"));
        let ul2 = SmpteUl::parse(&s).unwrap();
        assert_eq!(ul, ul2);
    }

    #[test]
    fn smpte_ul_parse_invalid() {
        assert!(SmpteUl::parse("not-a-ul").is_err());
        assert!(SmpteUl::parse("060e2b34.04010106").is_err()); // too short
    }

    // ── AssetHash ────────────────────────────────────────────────────────────

    /// SMPTE ST 2067-2 §9: PKL assets carry base64-encoded SHA-1 digests.
    #[test]
    fn asset_hash_sha1_roundtrip() {
        // SHA-1 of empty bytes
        let b64 = "2jmj7l5rSw0yVb/vlWAYkK/YBwk=";
        let h = AssetHash::from_base64_sha1(b64).unwrap();
        assert_eq!(h.algorithm, HashAlgorithm::Sha1);
        assert_eq!(h.bytes.len(), 20);
        assert_eq!(h.to_base64(), b64);
    }

    /// SMPTE ST 2067-2 §9: SHA-1 digest must be exactly 20 bytes.
    #[test]
    fn asset_hash_sha1_wrong_length_rejected() {
        let err = AssetHash::from_base64_sha1("AAAA").unwrap_err();
        assert!(err.to_string().contains("20 bytes"));
    }

    #[test]
    fn asset_hash_sha256_roundtrip() {
        let b64 = "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=";
        let h = AssetHash::from_base64_sha256(b64).unwrap();
        assert_eq!(h.algorithm, HashAlgorithm::Sha256);
        assert_eq!(h.bytes.len(), 32);
        assert_eq!(h.to_base64(), b64);
    }

    #[test]
    fn asset_hash_sha256_wrong_length_rejected() {
        let err = AssetHash::from_base64_sha256("2jmj7l5rSw0yVb/vlWAYkK/YBwk=").unwrap_err();
        assert!(err.to_string().contains("32 bytes"));
    }

    #[test]
    fn asset_hash_from_base64_routes_correctly() {
        let sha1_b64 = "2jmj7l5rSw0yVb/vlWAYkK/YBwk=";
        let sha256_b64 = "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=";

        let h1 = AssetHash::from_base64(sha1_b64, HashAlgorithm::Sha1).unwrap();
        assert_eq!(h1.algorithm, HashAlgorithm::Sha1);

        let h2 = AssetHash::from_base64(sha256_b64, HashAlgorithm::Sha256).unwrap();
        assert_eq!(h2.algorithm, HashAlgorithm::Sha256);
    }

    #[test]
    fn asset_hash_invalid_base64() {
        assert!(AssetHash::from_base64_sha1("not-valid-base64!!!").is_err());
    }

    // ── HashAlgorithm ─────────────────────────────────────────────────────────

    /// SMPTE ST 2067-2 §9: HashAlgorithm URI parsing.
    #[test]
    fn hash_algorithm_from_uri() {
        assert_eq!(
            HashAlgorithm::from_uri("http://www.w3.org/2000/09/xmldsig#sha1"),
            Some(HashAlgorithm::Sha1)
        );
        assert_eq!(
            HashAlgorithm::from_uri("http://www.w3.org/2001/04/xmlenc#sha256"),
            Some(HashAlgorithm::Sha256)
        );
        assert_eq!(HashAlgorithm::from_uri("http://example.com/unknown"), None);
    }

    #[test]
    fn hash_algorithm_digest_len() {
        assert_eq!(HashAlgorithm::Sha1.digest_len(), 20);
        assert_eq!(HashAlgorithm::Sha256.digest_len(), 32);
    }

    #[test]
    fn hash_algorithm_display() {
        assert_eq!(HashAlgorithm::Sha1.to_string(), "SHA-1");
        assert_eq!(HashAlgorithm::Sha256.to_string(), "SHA-256");
    }

    // ── VOLINDEX ──────────────────────────────────────────────────────────────

    /// ST 429-9 §5: VOLINDEX.xml contains a single <Index> element.
    #[test]
    fn volindex_parses_index_element() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<VolumeIndex xmlns="http://www.smpte-ra.org/schemas/429-9/2007/AM">
    <Index>1</Index>
</VolumeIndex>"#;
        let result = parse_volindex(xml).unwrap();
        assert_eq!(result.index, 1);
    }

    // ── ASSETMAP ──────────────────────────────────────────────────────────────

    /// ST 429-9 §6.2: AssetMap Id must be a valid UUID URN.
    #[test]
    fn assetmap_id_is_imf_uuid() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<AssetMap xmlns="http://www.smpte-ra.org/schemas/429-9/2007/AM">
    <Id>urn:uuid:75864667-c65e-4aae-a5b2-fa5ea5fe31b7</Id>
    <AnnotationText>MERIDIAN</AnnotationText>
    <Creator>Clipster 6.1.0.0 Beta (build 111500)</Creator>
    <VolumeCount>1</VolumeCount>
    <IssueDate>2016-10-06T08:35:02-00:00</IssueDate>
    <Issuer>R&amp;S</Issuer>
    <AssetList>
        <Asset>
            <Id>urn:uuid:0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85</Id>
            <ChunkList>
                <Chunk>
                    <Path>CPL_0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85.xml</Path>
                    <VolumeIndex>1</VolumeIndex>
                </Chunk>
            </ChunkList>
        </Asset>
        <Asset>
            <Id>urn:uuid:f5e93462-aed2-44ad-a4ba-2adb65823e7c</Id>
            <PackingList>true</PackingList>
            <ChunkList>
                <Chunk>
                    <Path>PKL_f5e93462-aed2-44ad-a4ba-2adb65823e7c.xml</Path>
                    <VolumeIndex>1</VolumeIndex>
                </Chunk>
            </ChunkList>
        </Asset>
    </AssetList>
</AssetMap>"#;

        let result = parse_assetmap(xml).unwrap();
        assert_eq!(
            result.id,
            ImfUuid::parse("urn:uuid:75864667-c65e-4aae-a5b2-fa5ea5fe31b7").unwrap()
        );
        assert_eq!(result.annotation_text, Some("MERIDIAN".to_string()));
        assert_eq!(result.volume_count, 1);
        assert_eq!(result.asset_list.assets.len(), 2);

        // ST 429-9 §6.3: Asset entries carry UUID references to package files.
        let cpl_asset = &result.asset_list.assets[0];
        assert_eq!(
            cpl_asset.id,
            ImfUuid::parse("urn:uuid:0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85").unwrap()
        );
        assert_eq!(cpl_asset.packing_list, None);
        assert_eq!(
            cpl_asset.chunk_list.chunks[0].path,
            "CPL_0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85.xml"
        );

        // ST 429-9 §6.3: PackingList flag marks the PKL asset.
        let pkl_asset = &result.asset_list.assets[1];
        assert_eq!(pkl_asset.packing_list, Some(true));
        assert_eq!(
            pkl_asset.chunk_list.chunks[0].path,
            "PKL_f5e93462-aed2-44ad-a4ba-2adb65823e7c.xml"
        );
    }

    /// ST 429-9 §6.2: Invalid UUID in AssetMap <Id> yields a typed error.
    #[test]
    fn assetmap_invalid_uuid_returns_field_error() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<AssetMap xmlns="http://www.smpte-ra.org/schemas/429-9/2007/AM">
    <Id>not-a-valid-uuid</Id>
    <VolumeCount>1</VolumeCount>
    <IssueDate>2024-01-01T00:00:00Z</IssueDate>
    <AssetList><Asset>
        <Id>urn:uuid:00000000-0000-0000-0000-000000000001</Id>
        <ChunkList><Chunk><Path>foo.xml</Path></Chunk></ChunkList>
    </Asset></AssetList>
</AssetMap>"#;
        let err = parse_assetmap(xml).unwrap_err();
        assert!(
            matches!(err, AssetMapParseError::Field { field: "Id", .. }),
            "expected Field error for Id, got: {err}"
        );
    }

    // ── PKL ───────────────────────────────────────────────────────────────────

    /// SMPTE ST 2067-2 §9: PKL carries SHA-1 hashes, sizes, and MIME types.
    #[test]
    fn pkl_parses_assets_with_strong_types() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<PackingList xmlns="http://www.smpte-ra.org/schemas/429-8/2007/PKL">
    <Id>urn:uuid:f5e93462-aed2-44ad-a4ba-2adb65823e7c</Id>
    <AnnotationText>MERIDIAN</AnnotationText>
    <IssueDate>2016-10-06T08:35:02-00:00</IssueDate>
    <Issuer>R&amp;S</Issuer>
    <Creator>Clipster 6.1.0.0 Beta (build 111500)</Creator>
    <AssetList>
        <Asset>
            <Id>urn:uuid:0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85</Id>
            <AnnotationText>Meridian UHD 5994P</AnnotationText>
            <Hash>IW0J5IZBsAxLMCCmWtHvfHhjVUw=</Hash>
            <Size>15214</Size>
            <Type>text/xml</Type>
            <OriginalFileName>CPL_0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85.xml</OriginalFileName>
        </Asset>
        <Asset>
            <Id>urn:uuid:61d91654-2650-4abf-abbc-ad2c7f640bf8</Id>
            <Hash>fL7SnTeNskm71I4otXqr/T0D5LQ=</Hash>
            <Size>79486353</Size>
            <Type>application/mxf</Type>
            <OriginalFileName>MERIDIAN_Netflix_Photon_161006_00.mxf</OriginalFileName>
        </Asset>
    </AssetList>
</PackingList>"#;

        let result = parse_pkl(xml).unwrap();
        assert_eq!(
            result.id,
            ImfUuid::parse("urn:uuid:f5e93462-aed2-44ad-a4ba-2adb65823e7c").unwrap()
        );
        assert_eq!(result.annotation_text, Some("MERIDIAN".to_string()));
        assert_eq!(result.issuer, Some("R&S".to_string()));
        assert_eq!(result.asset_list.assets.len(), 2);

        let cpl_asset = &result.asset_list.assets[0];
        assert_eq!(cpl_asset.hash.algorithm, HashAlgorithm::Sha1);
        assert_eq!(cpl_asset.hash.bytes.len(), 20);
        assert_eq!(cpl_asset.hash.to_base64(), "IW0J5IZBsAxLMCCmWtHvfHhjVUw=");
        assert_eq!(cpl_asset.size, 15214);
        assert_eq!(cpl_asset.mime_type, MimeType::TextXml);
        assert!(cpl_asset.mime_type.is_xml());

        let mxf_asset = &result.asset_list.assets[1];
        assert_eq!(mxf_asset.mime_type, MimeType::ApplicationMxf);
        assert!(mxf_asset.mime_type.is_mxf());
    }

    /// SMPTE ST 2067-2 §9: PKL with explicit SHA-1 <HashAlgorithm> element.
    #[test]
    fn pkl_explicit_sha1_hash_algorithm() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<PackingList xmlns="http://www.smpte-ra.org/schemas/429-8/2007/PKL">
    <Id>urn:uuid:f5e93462-aed2-44ad-a4ba-2adb65823e7c</Id>
    <IssueDate>2024-01-01T00:00:00Z</IssueDate>
    <AssetList><Asset>
        <Id>urn:uuid:00000000-0000-0000-0000-000000000001</Id>
        <Hash>2jmj7l5rSw0yVb/vlWAYkK/YBwk=</Hash>
        <Size>1024</Size>
        <Type>application/mxf</Type>
        <HashAlgorithm Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
    </Asset></AssetList>
</PackingList>"#;
        let result = parse_pkl(xml).unwrap();
        assert_eq!(
            result.asset_list.assets[0].hash.algorithm,
            HashAlgorithm::Sha1
        );
    }

    /// SMPTE ST 2067-2 §9: PKL with SHA-256 <HashAlgorithm>.
    #[test]
    fn pkl_sha256_hash_algorithm() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<PackingList xmlns="http://www.smpte-ra.org/schemas/429-8/2007/PKL">
    <Id>urn:uuid:f5e93462-aed2-44ad-a4ba-2adb65823e7c</Id>
    <IssueDate>2024-01-01T00:00:00Z</IssueDate>
    <AssetList><Asset>
        <Id>urn:uuid:00000000-0000-0000-0000-000000000001</Id>
        <Hash>47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=</Hash>
        <Size>1024</Size>
        <Type>application/mxf</Type>
        <HashAlgorithm Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
    </Asset></AssetList>
</PackingList>"#;
        let result = parse_pkl(xml).unwrap();
        assert_eq!(
            result.asset_list.assets[0].hash.algorithm,
            HashAlgorithm::Sha256
        );
        assert_eq!(result.asset_list.assets[0].hash.bytes.len(), 32);
    }

    /// SMPTE ST 2067-2 §9: PKL without <HashAlgorithm> defaults to SHA-1.
    #[test]
    fn pkl_missing_hash_algorithm_defaults_to_sha1() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<PackingList xmlns="http://www.smpte-ra.org/schemas/429-8/2007/PKL">
    <Id>urn:uuid:f5e93462-aed2-44ad-a4ba-2adb65823e7c</Id>
    <IssueDate>2024-01-01T00:00:00Z</IssueDate>
    <AssetList><Asset>
        <Id>urn:uuid:00000000-0000-0000-0000-000000000001</Id>
        <Hash>2jmj7l5rSw0yVb/vlWAYkK/YBwk=</Hash>
        <Size>1024</Size>
        <Type>application/mxf</Type>
    </Asset></AssetList>
</PackingList>"#;
        let result = parse_pkl(xml).unwrap();
        assert_eq!(
            result.asset_list.assets[0].hash.algorithm,
            HashAlgorithm::Sha1
        );
    }

    /// SMPTE ST 2067-2 §9: PKL with <GroupId> for partial deliveries.
    #[test]
    fn pkl_with_group_id() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<PackingList xmlns="http://www.smpte-ra.org/schemas/429-8/2007/PKL">
    <Id>urn:uuid:f5e93462-aed2-44ad-a4ba-2adb65823e7c</Id>
    <IssueDate>2024-01-01T00:00:00Z</IssueDate>
    <GroupId>urn:uuid:aabbccdd-1122-3344-5566-778899aabbcc</GroupId>
    <AssetList><Asset>
        <Id>urn:uuid:00000000-0000-0000-0000-000000000001</Id>
        <Hash>2jmj7l5rSw0yVb/vlWAYkK/YBwk=</Hash>
        <Size>1024</Size>
        <Type>application/mxf</Type>
    </Asset></AssetList>
</PackingList>"#;
        let result = parse_pkl(xml).unwrap();
        assert_eq!(
            result.group_id,
            Some(ImfUuid::parse("urn:uuid:aabbccdd-1122-3344-5566-778899aabbcc").unwrap())
        );
    }

    /// SMPTE ST 2067-2 §9: Unrecognised MIME type is preserved as MimeType::Other.
    #[test]
    fn pkl_unknown_mime_type_preserved() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<PackingList xmlns="http://www.smpte-ra.org/schemas/429-8/2007/PKL">
    <Id>urn:uuid:f5e93462-aed2-44ad-a4ba-2adb65823e7c</Id>
    <IssueDate>2024-01-01T00:00:00Z</IssueDate>
    <AssetList><Asset>
        <Id>urn:uuid:00000000-0000-0000-0000-000000000001</Id>
        <Hash>2jmj7l5rSw0yVb/vlWAYkK/YBwk=</Hash>
        <Size>512</Size>
        <Type>application/octet-stream</Type>
    </Asset></AssetList>
</PackingList>"#;
        let result = parse_pkl(xml).unwrap();
        assert_eq!(
            result.asset_list.assets[0].mime_type,
            MimeType::Other("application/octet-stream".to_string())
        );
    }

    // ── Namespace compatibility ──────────────────────────────────────────────

    /// ST 2067-2: PKL namespace versions must all parse identically.
    #[test]
    fn pkl_parses_with_2067_2_2016_namespace() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<PackingList xmlns="http://www.smpte-ra.org/schemas/2067-2/2016">
    <Id>urn:uuid:f5e93462-aed2-44ad-a4ba-2adb65823e7c</Id>
    <IssueDate>2024-01-01T00:00:00Z</IssueDate>
    <AssetList><Asset>
        <Id>urn:uuid:00000000-0000-0000-0000-000000000001</Id>
        <Hash>2jmj7l5rSw0yVb/vlWAYkK/YBwk=</Hash>
        <Size>1024</Size>
        <Type>application/mxf</Type>
    </Asset></AssetList>
</PackingList>"#;
        let result = parse_pkl(xml).unwrap();
        assert_eq!(result.asset_list.assets.len(), 1);
        assert_eq!(result.namespace, PklNamespace::Smpte2067_2_2016);
        assert_eq!(result.namespace.spec_id(), "ST 2067-2:2016");
    }

    #[test]
    fn pkl_parses_with_2067_2_2020_namespace() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<PackingList xmlns="http://www.smpte-ra.org/ns/2067-2/2020">
    <Id>urn:uuid:f5e93462-aed2-44ad-a4ba-2adb65823e7c</Id>
    <IssueDate>2024-01-01T00:00:00Z</IssueDate>
    <AssetList><Asset>
        <Id>urn:uuid:00000000-0000-0000-0000-000000000001</Id>
        <Hash>2jmj7l5rSw0yVb/vlWAYkK/YBwk=</Hash>
        <Size>1024</Size>
        <Type>application/mxf</Type>
    </Asset></AssetList>
</PackingList>"#;
        let result = parse_pkl(xml).unwrap();
        assert_eq!(result.namespace, PklNamespace::Smpte2067_2_2020);
    }

    #[test]
    fn pkl_detects_dci_429_8_namespace() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<PackingList xmlns="http://www.smpte-ra.org/schemas/429-8/2007/PKL">
    <Id>urn:uuid:f5e93462-aed2-44ad-a4ba-2adb65823e7c</Id>
    <IssueDate>2024-01-01T00:00:00Z</IssueDate>
    <AssetList><Asset>
        <Id>urn:uuid:00000000-0000-0000-0000-000000000001</Id>
        <Hash>2jmj7l5rSw0yVb/vlWAYkK/YBwk=</Hash>
        <Size>1024</Size>
        <Type>application/mxf</Type>
    </Asset></AssetList>
</PackingList>"#;
        let result = parse_pkl(xml).unwrap();
        assert_eq!(result.namespace, PklNamespace::Dci429_8);
    }

    #[test]
    fn assetmap_parses_with_2067_9_namespace() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<AssetMap xmlns="http://www.smpte-ra.org/schemas/2067-9/2016">
    <Id>urn:uuid:75864667-c65e-4aae-a5b2-fa5ea5fe31b7</Id>
    <VolumeCount>1</VolumeCount>
    <IssueDate>2024-01-01T00:00:00Z</IssueDate>
    <AssetList>
        <Asset>
            <Id>urn:uuid:0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85</Id>
            <ChunkList><Chunk><Path>test.xml</Path></Chunk></ChunkList>
        </Asset>
    </AssetList>
</AssetMap>"#;
        let result = parse_assetmap(xml).unwrap();
        assert_eq!(result.asset_list.assets.len(), 1);
        assert_eq!(result.namespace, AssetMapNamespace::Smpte2067_9_2016);
    }

    /// `http://www.smpte-ra.org/ns/2067-9/2020` is not a registered namespace —
    /// ST 2067-9 has only the 2016 edition. A document declaring this URI
    /// still parses but lands in `Unknown`.
    #[test]
    fn assetmap_with_fake_2020_namespace_lands_in_unknown() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<AssetMap xmlns="http://www.smpte-ra.org/ns/2067-9/2020">
    <Id>urn:uuid:75864667-c65e-4aae-a5b2-fa5ea5fe31b7</Id>
    <VolumeCount>1</VolumeCount>
    <IssueDate>2024-01-01T00:00:00Z</IssueDate>
    <AssetList>
        <Asset>
            <Id>urn:uuid:0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85</Id>
            <ChunkList><Chunk><Path>test.xml</Path></Chunk></ChunkList>
        </Asset>
    </AssetList>
</AssetMap>"#;
        let result = parse_assetmap(xml).unwrap();
        assert!(matches!(result.namespace, AssetMapNamespace::Unknown(_)));
    }

    #[test]
    fn assetmap_detects_dci_429_9_namespace() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<AssetMap xmlns="http://www.smpte-ra.org/schemas/429-9/2007/AM">
    <Id>urn:uuid:75864667-c65e-4aae-a5b2-fa5ea5fe31b7</Id>
    <VolumeCount>1</VolumeCount>
    <IssueDate>2024-01-01T00:00:00Z</IssueDate>
    <AssetList>
        <Asset>
            <Id>urn:uuid:0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85</Id>
            <ChunkList><Chunk><Path>test.xml</Path></Chunk></ChunkList>
        </Asset>
    </AssetList>
</AssetMap>"#;
        let result = parse_assetmap(xml).unwrap();
        assert_eq!(result.namespace, AssetMapNamespace::Dci429_9);
    }

    /// FIX-3 regression: AssetMap without root xmlns lands in `Unknown("")`,
    /// not the first variant (`Dci429_9`).
    #[test]
    fn assetmap_without_root_xmlns_lands_in_unknown_not_dci() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<AssetMap>
    <Id>urn:uuid:75864667-c65e-4aae-a5b2-fa5ea5fe31b7</Id>
    <VolumeCount>1</VolumeCount>
    <IssueDate>2024-01-01T00:00:00Z</IssueDate>
    <AssetList>
        <Asset>
            <Id>urn:uuid:0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85</Id>
            <ChunkList><Chunk><Path>test.xml</Path></Chunk></ChunkList>
        </Asset>
    </AssetList>
</AssetMap>"#;
        let result = parse_assetmap(xml).expect("AssetMap should parse without xmlns");
        assert!(
            matches!(result.namespace, AssetMapNamespace::Unknown(ref s) if s.is_empty()),
            "expected Unknown(\"\") for missing xmlns, got {:?}",
            result.namespace
        );
    }

    /// FIX-3 regression: PKL without root xmlns lands in `Unknown("")`,
    /// not the first variant (`Dci429_8`).
    #[test]
    fn pkl_without_root_xmlns_lands_in_unknown_not_dci() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<PackingList>
    <Id>urn:uuid:75864667-c65e-4aae-a5b2-fa5ea5fe31b7</Id>
    <IssueDate>2024-01-01T00:00:00Z</IssueDate>
    <AssetList><Asset>
        <Id>urn:uuid:00000000-0000-0000-0000-000000000001</Id>
        <Hash>2jmj7l5rSw0yVb/vlWAYkK/YBwk=</Hash>
        <Size>1024</Size>
        <Type>application/xml</Type>
    </Asset></AssetList>
</PackingList>"#;
        let result = parse_pkl(xml).expect("PKL should parse without xmlns");
        assert!(
            matches!(result.namespace, PklNamespace::Unknown(ref s) if s.is_empty()),
            "expected Unknown(\"\") for missing xmlns, got {:?}",
            result.namespace
        );
    }

    // ── OPL ──────────────────────────────────────────────────────────────────

    /// SMPTE ST 2067-100: OPL metadata fields are parsed correctly.
    #[test]
    fn opl_parses_core_metadata() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<OutputProfileList xmlns="http://www.smpte-ra.org/schemas/2067-100/2014">
    <Id>urn:uuid:8cf83c32-4949-4f00-b081-01e12b18932f</Id>
    <Annotation>OPL Example</Annotation>
    <IssueDate>2016-06-14T19:22:37-00:00</IssueDate>
    <Issuer>Clipster</Issuer>
    <Creator>Clipster 5.9.3.7</Creator>
    <CompositionPlaylistId>urn:uuid:0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85</CompositionPlaylistId>
    <AliasList/>
    <MacroList/>
</OutputProfileList>"#;
        let result = parse_opl(xml).unwrap();
        assert_eq!(
            result.id.to_string(),
            "8cf83c32-4949-4f00-b081-01e12b18932f"
        );
        assert_eq!(result.annotation.as_deref(), Some("OPL Example"));
        assert_eq!(result.issuer.as_deref(), Some("Clipster"));
        assert_eq!(result.creator.as_deref(), Some("Clipster 5.9.3.7"));
        assert_eq!(
            result.composition_playlist_id.to_string(),
            "0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85"
        );
    }

    /// SMPTE ST 2067-100: OPL with complex macros parses without error.
    #[test]
    fn opl_parses_real_test_file() {
        let xml = std::fs::read_to_string(test_data(
            "OPL/OPL_8cf83c32-4949-4f00-b081-01e12b18932f.xml",
        ))
        .unwrap();
        let result = parse_opl(&xml).unwrap();
        assert_eq!(
            result.id.to_string(),
            "8cf83c32-4949-4f00-b081-01e12b18932f"
        );
        assert_eq!(
            result.composition_playlist_id.to_string(),
            "0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85"
        );
    }

    // ── FIX-8: OPL MacroList walker ──────────────────────────────────────────

    /// `<MacroList/>` produces an empty `macros` Vec, not an error.
    #[test]
    fn opl_with_empty_macro_list_yields_no_macros() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<OutputProfileList xmlns="http://www.smpte-ra.org/schemas/2067-100/2014">
    <Id>urn:uuid:8cf83c32-4949-4f00-b081-01e12b18932f</Id>
    <IssueDate>2016-06-14T19:22:37Z</IssueDate>
    <Issuer>x</Issuer>
    <Creator>x</Creator>
    <CompositionPlaylistId>urn:uuid:0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85</CompositionPlaylistId>
    <MacroList/>
</OutputProfileList>"#;
        let result = parse_opl(xml).unwrap();
        assert!(result.macros.is_empty());
    }

    /// Single preset macro: xsi:type, Name, Annotation, and the
    /// type-specific Preset field land in `extra_fields`.
    #[test]
    fn opl_with_preset_macro_captures_all_fields() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<OutputProfileList xmlns="http://www.smpte-ra.org/schemas/2067-100/2014"
    xmlns:opl="http://www.smpte-ra.org/schemas/2067-100/2014"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Id>urn:uuid:8cf83c32-4949-4f00-b081-01e12b18932f</Id>
    <IssueDate>2016-06-14T19:22:37Z</IssueDate>
    <Issuer>x</Issuer>
    <Creator>x</Creator>
    <CompositionPlaylistId>urn:uuid:0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85</CompositionPlaylistId>
    <MacroList>
        <Macro xsi:type="opl:PresetMacroType">
            <Name>HD1080p</Name>
            <Annotation>Preset for 1080p HD</Annotation>
            <Preset>urn:smpte:opl:preset:hd1080p</Preset>
        </Macro>
    </MacroList>
</OutputProfileList>"#;
        let result = parse_opl(xml).unwrap();
        assert_eq!(result.macros.len(), 1);
        let m = &result.macros[0];
        assert_eq!(m.xsi_type.as_deref(), Some("opl:PresetMacroType"));
        assert_eq!(m.name, "HD1080p");
        assert_eq!(m.annotation.as_deref(), Some("Preset for 1080p HD"));
        assert!(
            m.extra_fields
                .iter()
                .any(|(k, v)| k == "Preset" && v == "urn:smpte:opl:preset:hd1080p"),
            "expected Preset URI in extra_fields, got {:?}",
            m.extra_fields
        );
    }

    /// Multiple macros, mixed xsi:type prefixes, are all captured in order.
    #[test]
    fn opl_with_multiple_macros_captures_all_in_order() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<OutputProfileList xmlns="http://www.smpte-ra.org/schemas/2067-100/2014"
    xmlns:opl="http://www.smpte-ra.org/schemas/2067-100/2014"
    xmlns:arm="http://www.smpte-ra.org/schemas/2067-103/2014"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Id>urn:uuid:8cf83c32-4949-4f00-b081-01e12b18932f</Id>
    <IssueDate>2016-06-14T19:22:37Z</IssueDate>
    <Issuer>x</Issuer>
    <Creator>x</Creator>
    <CompositionPlaylistId>urn:uuid:0eb3d1b9-b77b-4d3f-bbe5-7c69b15dca85</CompositionPlaylistId>
    <MacroList>
        <Macro xsi:type="opl:PresetMacroType">
            <Name>P1</Name>
            <Preset>urn:p1</Preset>
        </Macro>
        <Macro xsi:type="arm:AudioRoutingMixingMacroType">
            <Name>AudioMix</Name>
            <Annotation>5.1 downmix</Annotation>
        </Macro>
    </MacroList>
</OutputProfileList>"#;
        let result = parse_opl(xml).unwrap();
        assert_eq!(result.macros.len(), 2);
        assert_eq!(result.macros[0].name, "P1");
        assert_eq!(
            result.macros[0].xsi_type.as_deref(),
            Some("opl:PresetMacroType")
        );
        assert_eq!(result.macros[1].name, "AudioMix");
        assert_eq!(
            result.macros[1].xsi_type.as_deref(),
            Some("arm:AudioRoutingMixingMacroType")
        );
        assert_eq!(result.macros[1].annotation.as_deref(), Some("5.1 downmix"));
    }

    /// SMPTE ST 2067-100: OPL with simple preset macro from ISXD test data.
    #[test]
    fn opl_parses_isxd_test_file() {
        let xml = std::fs::read_to_string(test_data(
            "ISXD/CompleteIMP/OPL_af6b288d-27e8-441f-9a36-2c4ab9025d19.xml",
        ))
        .unwrap();
        let result = parse_opl(&xml).unwrap();
        assert_eq!(
            result.id.to_string(),
            "af6b288d-27e8-441f-9a36-2c4ab9025d19"
        );
        assert_eq!(
            result.composition_playlist_id.to_string(),
            "b2d74f92-1990-41e0-869f-2179a50f7090"
        );
    }
}