libxml-rs 0.1.0-alpha.4

Phase 3: I/O, encoding, URI, catalog, serialization, HTML. Native-Rust forensic reimplementation of libxml2+libxslt with C ABI drop-in replacement. 357 tests passing, full encoding subsystem, URI parser, OASIS catalog, HTML parser/serializer, tree serialization, custom I/O buffers.
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
//! XML Catalog support (§26, §85 Phase 4).
//!
//! OASIS XML Catalog resolution, catalog lookup order, precedence,
//! catalog loading, SGML catalog compatibility.
//!
//! Implements the OASIS XML Catalog specification (xCatalog) with
//! compatibility for SGML (SOLEX) catalog format.
//!
//! # UPSTREAM-PARITY
//!
//! Matches libxml2's catalog behavior:
//! - XML Catalog format (OASIS TR 9401:1999)
//! - SGML catalog format (SOLEX)
//! - Environment variables: XML_CATALOG_FILES, SGML_CATALOG_FILES
//! - Default catalog location: /etc/xml/catalog
//! - Catalog entry types: public, system, rewriteSystem, rewriteURI,
//!   delegatePublic, delegateSystem, delegateURI, nextCatalog, group
//! - Resolution order: public → system → URI

#![allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]

use core::ffi::c_void;
use std::ffi::CStr;
use std::fs;
use std::os::raw::{c_char, c_int};
use std::path::Path;
use std::ptr;

use once_cell::sync::Lazy;
use parking_lot::RwLock;

use crate::abi::allocator::{xmlFree, xmlMalloc};
use crate::abi::structs::_xmlDoc;
use crate::abi::types::xmlChar;
use crate::xml::string::{
    bytes_to_xmlstr, c_strdup, xml_str_starts_with, xml_strcat, xml_strcmp, xml_strdup, xml_strlen,
    xmlstr_to_bytes,
};

// ═══════════════════════════════════════════════════════════════════════════════
// Constants
// ═══════════════════════════════════════════════════════════════════════════════

/// Catalog allow value: no catalogs allowed.
pub(crate) const XML_CATA_ALLOW_NONE: i32 = 0;

/// Catalog allow value: only global catalogs.
pub(crate) const XML_CATA_ALLOW_GLOBAL: i32 = 1;

/// Catalog allow value: document catalogs allowed.
pub(crate) const XML_CATA_ALLOW_DOCUMENT: i32 = 2;

/// Catalog allow value: all catalogs allowed.
pub(crate) const XML_CATA_ALLOW_ALL: i32 = 3;

/// Default catalog file path.
const DEFAULT_CATALOG: &str = "/etc/xml/catalog";

/// Environment variable for XML catalog files.
const XML_CATALOG_FILES_ENV: &str = "XML_CATALOG_FILES";

/// Environment variable for SGML catalog files.
const SGML_CATALOG_FILES_ENV: &str = "SGML_CATALOG_FILES";

/// Maximum catalog file size (10 MB).
const MAX_CATALOG_FILE_SIZE: usize = 10_485_760;

// ═══════════════════════════════════════════════════════════════════════════════
// Catalog Entry Types
// ═══════════════════════════════════════════════════════════════════════════════

/// A single catalog entry.
#[derive(Clone, Debug)]
enum CatalogEntry {
    /// `<public publicId="..." uri="..."/>`
    Public { public_id: Vec<u8>, uri: Vec<u8> },
    /// `<system systemId="..." uri="..."/>`
    System { system_id: Vec<u8>, uri: Vec<u8> },
    /// `<rewriteSystem systemIdStartString="..." rewritePrefix="..."/>`
    RewriteSystem { prefix: Vec<u8>, rewrite: Vec<u8> },
    /// `<rewriteURI uriStartString="..." rewritePrefix="..."/>`
    RewriteURI { prefix: Vec<u8>, rewrite: Vec<u8> },
    /// `<delegatePublic publicIdStartString="..." catalog="..."/>`
    DelegatePublic { prefix: Vec<u8>, catalog: Vec<u8> },
    /// `<delegateSystem systemIdStartString="..." catalog="..."/>`
    DelegateSystem { prefix: Vec<u8>, catalog: Vec<u8> },
    /// `<delegateURI uriStartString="..." catalog="..."/>`
    DelegateURI { prefix: Vec<u8>, catalog: Vec<u8> },
    /// `<nextCatalog catalog="..."/>`
    NextCatalog { catalog: Vec<u8> },
}

/// Indicates the format of a loaded catalog.
#[derive(Clone, Copy, Debug, PartialEq)]
enum CatalogFormat {
    Xml,
    Sgml,
}

/// Metadata about a loaded catalog file.
#[derive(Clone, Debug)]
struct CatalogInfo {
    path: Vec<u8>,
    format: CatalogFormat,
}

// ═══════════════════════════════════════════════════════════════════════════════
// Global Catalog State
// ═══════════════════════════════════════════════════════════════════════════════

/// Global catalog registry state.
struct CatalogState {
    /// All catalog entries, in load order.
    entries: Vec<CatalogEntry>,
    /// Information about loaded catalog files.
    catalogs: Vec<CatalogInfo>,
    /// Whether the subsystem has been initialized.
    initialized: bool,
    /// Catalog resolution allow value.
    allow: i32,
}

impl CatalogState {
    fn new() -> Self {
        Self {
            entries: Vec::new(),
            catalogs: Vec::new(),
            initialized: false,
            allow: XML_CATA_ALLOW_ALL,
        }
    }

    /// Clear all catalog data.
    fn clear(&mut self) {
        self.entries.clear();
        self.catalogs.clear();
        self.allow = XML_CATA_ALLOW_ALL;
    }
}

/// Global catalog registry, protected by a read-write lock.
static CATALOG_STATE: Lazy<RwLock<CatalogState>> = Lazy::new(|| RwLock::new(CatalogState::new()));

// ═══════════════════════════════════════════════════════════════════════════════
// Internal Helpers
// ═══════════════════════════════════════════════════════════════════════════════

/// Trim leading and trailing whitespace from a byte slice.
fn trim_whitespace(bytes: &[u8]) -> &[u8] {
    let start = bytes
        .iter()
        .position(|b| !b.is_ascii_whitespace())
        .unwrap_or(bytes.len());
    let end = bytes
        .iter()
        .rposition(|b| !b.is_ascii_whitespace())
        .map_or(0, |p| p + 1);
    &bytes[start..end]
}

/// Check if a byte slice starts with a given prefix (case-sensitive).
fn starts_with(data: &[u8], prefix: &[u8]) -> bool {
    if data.len() < prefix.len() {
        return false;
    }
    data[..prefix.len()] == prefix[..]
}

/// Check if a byte slice starts with a given prefix (case-insensitive ASCII).
fn starts_with_ignore_ascii_case(data: &[u8], prefix: &[u8]) -> bool {
    if data.len() < prefix.len() {
        return false;
    }
    data[..prefix.len()]
        .iter()
        .zip(prefix.iter())
        .all(|(a, b)| a.eq_ignore_ascii_case(b))
}

/// Extract a quoted attribute value from bytes.
///
/// Searches for `name="..."` or `name='...'` starting at position `pos`.
/// Returns `(value_bytes, end_pos)` or `None`.
fn extract_attr_value<'a>(data: &'a [u8], name: &[u8], pos: usize) -> Option<(&'a [u8], usize)> {
    let remaining = &data[pos..];
    // Find name
    let name_pos = find_subsequence(remaining, name)?;
    let after_name = name_pos + name.len();
    let after_name_slice = &remaining[after_name..];

    // Skip whitespace and =
    let eq_pos = after_name_slice.iter().position(|b| *b == b'=')?;

    // Check for quote — offset is relative to `data` (absolute)
    let rel_quote_start = after_name_slice[eq_pos + 1..]
        .iter()
        .position(|b| *b == b'"' || *b == b'\'')
        .map(|p| after_name + eq_pos + 1 + p)?;
    let abs_quote_start = pos + rel_quote_start;
    let quote_char = data[abs_quote_start];
    // Find matching close quote
    let value_start = abs_quote_start + 1;
    let value_end = data[value_start..]
        .iter()
        .position(|b| *b == quote_char)
        .map(|p| value_start + p)?;

    Some((&data[value_start..value_end], value_end + 1))
}

/// Find a subsequence in a byte slice.
fn find_subsequence(data: &[u8], seq: &[u8]) -> Option<usize> {
    if seq.is_empty() {
        return Some(0);
    }
    data.windows(seq.len()).position(|w| w == seq)
}

/// Extract a simple token (non-whitespace bytes) from a line, starting at `pos`.
fn extract_token(line: &[u8], pos: usize) -> Option<(&[u8], usize)> {
    let line = &line[pos..];
    let start = line.iter().position(|b| !b.is_ascii_whitespace())?;
    let end = line[start..]
        .iter()
        .position(|b| b.is_ascii_whitespace())
        .map(|p| start + p)
        .unwrap_or(line.len());
    Some((&line[start..end], pos + end))
}

/// Extract a quoted token from a line (may use " or ' quotes), starting at `pos`.
fn extract_quoted_token(line: &[u8], pos: usize) -> Option<(&[u8], usize)> {
    let line = &line[pos..];
    let start = line.iter().position(|b| !b.is_ascii_whitespace())?;
    if start >= line.len() {
        return None;
    }
    let quote_char = line[start];
    if quote_char != b'"' && quote_char != b'\'' {
        // Not quoted — extract as simple token
        return extract_token(line, 0);
    }
    let value_start = start + 1;
    let end = line[value_start..]
        .iter()
        .position(|b| *b == quote_char)
        .map(|p| value_start + p)?;
    Some((&line[value_start..end], pos + end + 1))
}

// ═══════════════════════════════════════════════════════════════════════════════
// Catalog Parsing — SGML Format
// ═══════════════════════════════════════════════════════════════════════════════

/// Parse a single line of an SGML catalog.
///
/// SGML catalog format lines:
/// - `PUBLIC "publicId" "uri"`
/// - `SYSTEM "systemId" "uri"`
/// - `URI "uri" "replacement"`
/// - `OVERRIDE YES|NO`
/// - `CATALOG "path"` (delegation to another catalog)
/// - `SGMLDECL "path"` (ignored)
/// - `DOCTYPE "name" "uri"` (ignored for catalog resolution)
/// - `ENTITY "name" "uri"` (ignored for catalog resolution)
/// - `LINKTYPE "name" "uri"` (ignored)
/// - `NOTATION "name" "uri"` (ignored)
/// - Comments start with `--`
fn parse_sgml_line(line: &[u8], entries: &mut Vec<CatalogEntry>) {
    let trimmed = trim_whitespace(line);
    if trimmed.is_empty() || trimmed.starts_with(b"--") {
        return;
    }

    // Extract the directive
    let Some((directive, after_directive)) = extract_token(trimmed, 0) else {
        return;
    };

    match directive {
        b"PUBLIC" | b"public" => {
            let Some((pub_id, after_pub)) = extract_quoted_token(trimmed, after_directive) else {
                return;
            };
            let Some((uri, _)) = extract_quoted_token(trimmed, after_pub) else {
                return;
            };
            entries.push(CatalogEntry::Public {
                public_id: pub_id.to_vec(),
                uri: uri.to_vec(),
            });
        }
        b"SYSTEM" | b"system" => {
            let Some((sys_id, after_sys)) = extract_quoted_token(trimmed, after_directive) else {
                return;
            };
            let Some((uri, _)) = extract_quoted_token(trimmed, after_sys) else {
                return;
            };
            entries.push(CatalogEntry::System {
                system_id: sys_id.to_vec(),
                uri: uri.to_vec(),
            });
        }
        b"URI" | b"uri" => {
            // SGML URI is treated like a system entry in libxml2
            let Some((uri_id, after_uri)) = extract_quoted_token(trimmed, after_directive) else {
                return;
            };
            let Some((replacement, _)) = extract_quoted_token(trimmed, after_uri) else {
                return;
            };
            entries.push(CatalogEntry::System {
                system_id: uri_id.to_vec(),
                uri: replacement.to_vec(),
            });
        }
        b"CATALOG" | b"catalog" => {
            let Some((path, _)) = extract_quoted_token(trimmed, after_directive) else {
                return;
            };
            entries.push(CatalogEntry::NextCatalog {
                catalog: path.to_vec(),
            });
        }
        _ => {
            // Other directives (SGMLDECL, DOCTYPE, ENTITY, etc.) are ignored
        }
    }
}

/// Parse SGML catalog content.
fn parse_sgml_catalog(data: &[u8], entries: &mut Vec<CatalogEntry>) {
    for line in data.split(|b| *b == b'\n') {
        parse_sgml_line(line, entries);
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Catalog Parsing — XML Catalog Format
// ═══════════════════════════════════════════════════════════════════════════════

/// Parse an XML Catalog file content.
///
/// Uses simple tag scanning rather than a full XML parser, matching
/// libxml2's approach which has its own catalog-specific parser.
fn parse_xml_catalog(data: &[u8], entries: &mut Vec<CatalogEntry>) {
    let mut pos = 0;
    let len = data.len();

    while pos < len {
        // Find next '<'
        let Some(lt_pos) = data[pos..].iter().position(|b| *b == b'<') else {
            break;
        };
        let tag_start = pos + lt_pos;

        // Check if this is a closing tag or self-closing
        if tag_start + 1 >= len {
            break;
        }

        let is_closing = data[tag_start + 1] == b'/';
        if is_closing {
            // Skip to '>'
            let Some(gt_pos) = data[tag_start..].iter().position(|b| *b == b'>') else {
                break;
            };
            pos = tag_start + gt_pos + 1;
            continue;
        }

        // Check if it's a comment or PI
        if data[tag_start + 1] == b'!' || data[tag_start + 1] == b'?' {
            let Some(gt_pos) = data[tag_start..].iter().position(|b| *b == b'>') else {
                break;
            };
            pos = tag_start + gt_pos + 1;
            continue;
        }

        // Find end of tag name
        let tag_name_start = tag_start + 1;
        let tag_name_end = data[tag_name_start..]
            .iter()
            .position(|b| b.is_ascii_whitespace() || *b == b'>' || *b == b'/')
            .map(|p| tag_name_start + p)
            .unwrap_or(len);

        let tag_name = &data[tag_name_start..tag_name_end];

        // Find end of tag (either '>' for open tag, or '/>' for self-closing)
        let Some(gt_or_slash_pos) = data[tag_start..]
            .iter()
            .position(|b| *b == b'>')
            .map(|p| tag_start + p)
        else {
            break;
        };

        let is_self_closing = gt_or_slash_pos > 0 && data[gt_or_slash_pos - 1] == b'/';
        let tag_content_end = if is_self_closing {
            gt_or_slash_pos + 1
        } else {
            // Open tag - find matching close
            let close_tag = {
                let mut close = Vec::with_capacity(tag_name.len() + 3);
                close.push(b'<');
                close.push(b'/');
                close.extend_from_slice(tag_name);
                close.push(b'>');
                close
            };
            let close_pos = data[gt_or_slash_pos + 1..]
                .windows(close_tag.len())
                .position(|w| w == close_tag.as_slice())
                .map(|p| gt_or_slash_pos + 1 + p + close_tag.len());

            match close_pos {
                Some(p) => p,
                None => {
                    pos = gt_or_slash_pos + 1;
                    continue;
                }
            }
        };

        let tag_body_start = gt_or_slash_pos + 1;
        let tag_body = &data[tag_body_start
            ..tag_content_end
                - if is_self_closing {
                    0
                } else {
                    tag_name.len() + 3
                }];
        let tag_body = trim_whitespace(tag_body);

        match tag_name {
            b"public" => {
                let Some((pub_id, _)) = extract_attr_value(data, b"publicId", tag_start) else {
                    pos = tag_content_end;
                    continue;
                };
                let Some((uri, _)) = extract_attr_value(data, b"uri", tag_start) else {
                    pos = tag_content_end;
                    continue;
                };
                entries.push(CatalogEntry::Public {
                    public_id: pub_id.to_vec(),
                    uri: uri.to_vec(),
                });
            }
            b"system" => {
                let Some((sys_id, _)) = extract_attr_value(data, b"systemId", tag_start) else {
                    pos = tag_content_end;
                    continue;
                };
                let Some((uri, _)) = extract_attr_value(data, b"uri", tag_start) else {
                    pos = tag_content_end;
                    continue;
                };
                entries.push(CatalogEntry::System {
                    system_id: sys_id.to_vec(),
                    uri: uri.to_vec(),
                });
            }
            b"rewriteSystem" => {
                let Some((prefix, _)) = extract_attr_value(data, b"systemIdStartString", tag_start)
                else {
                    pos = tag_content_end;
                    continue;
                };
                let Some((rewrite, _)) = extract_attr_value(data, b"rewritePrefix", tag_start)
                else {
                    pos = tag_content_end;
                    continue;
                };
                entries.push(CatalogEntry::RewriteSystem {
                    prefix: prefix.to_vec(),
                    rewrite: rewrite.to_vec(),
                });
            }
            b"rewriteURI" => {
                let Some((prefix, _)) = extract_attr_value(data, b"uriStartString", tag_start)
                else {
                    pos = tag_content_end;
                    continue;
                };
                let Some((rewrite, _)) = extract_attr_value(data, b"rewritePrefix", tag_start)
                else {
                    pos = tag_content_end;
                    continue;
                };
                entries.push(CatalogEntry::RewriteURI {
                    prefix: prefix.to_vec(),
                    rewrite: rewrite.to_vec(),
                });
            }
            b"delegatePublic" => {
                let Some((prefix, _)) = extract_attr_value(data, b"publicIdStartString", tag_start)
                else {
                    pos = tag_content_end;
                    continue;
                };
                let Some((catalog, _)) = extract_attr_value(data, b"catalog", tag_start) else {
                    pos = tag_content_end;
                    continue;
                };
                entries.push(CatalogEntry::DelegatePublic {
                    prefix: prefix.to_vec(),
                    catalog: catalog.to_vec(),
                });
            }
            b"delegateSystem" => {
                let Some((prefix, _)) = extract_attr_value(data, b"systemIdStartString", tag_start)
                else {
                    pos = tag_content_end;
                    continue;
                };
                let Some((catalog, _)) = extract_attr_value(data, b"catalog", tag_start) else {
                    pos = tag_content_end;
                    continue;
                };
                entries.push(CatalogEntry::DelegateSystem {
                    prefix: prefix.to_vec(),
                    catalog: catalog.to_vec(),
                });
            }
            b"delegateURI" => {
                let Some((prefix, _)) = extract_attr_value(data, b"uriStartString", tag_start)
                else {
                    pos = tag_content_end;
                    continue;
                };
                let Some((catalog, _)) = extract_attr_value(data, b"catalog", tag_start) else {
                    pos = tag_content_end;
                    continue;
                };
                entries.push(CatalogEntry::DelegateURI {
                    prefix: prefix.to_vec(),
                    catalog: catalog.to_vec(),
                });
            }
            b"nextCatalog" => {
                let Some((catalog, _)) = extract_attr_value(data, b"catalog", tag_start) else {
                    pos = tag_content_end;
                    continue;
                };
                entries.push(CatalogEntry::NextCatalog {
                    catalog: catalog.to_vec(),
                });
            }
            b"group" | b"catalog" => {
                // Container elements contain child entries; parse the body recursively
                parse_xml_catalog(tag_body, entries);
            }
            _ => {
                // Unknown elements are ignored
            }
        }

        pos = tag_content_end;
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Catalog Loading
// ═══════════════════════════════════════════════════════════════════════════════

/// Read a file's contents as bytes.
fn read_file_bytes(path: &str) -> Option<Vec<u8>> {
    let p = Path::new(path);
    // Check file existence and size
    let metadata = fs::metadata(p).ok()?;
    if metadata.len() > MAX_CATALOG_FILE_SIZE as u64 {
        return None;
    }
    fs::read(p).ok()
}

/// Determine whether a catalog file is XML or SGML format.
fn detect_catalog_format(data: &[u8]) -> CatalogFormat {
    let trimmed = trim_whitespace(data);
    if trimmed.starts_with(b"<?xml") || trimmed.starts_with(b"<catalog") {
        CatalogFormat::Xml
    } else {
        CatalogFormat::Sgml
    }
}

/// Load catalog entries from file data.
fn load_catalog_data(path: &str, data: &[u8], entries: &mut Vec<CatalogEntry>) {
    let format = detect_catalog_format(data);
    match format {
        CatalogFormat::Xml => {
            parse_xml_catalog(data, entries);
        }
        CatalogFormat::Sgml => {
            parse_sgml_catalog(data, entries);
        }
    }
}

/// Load a single catalog file, adding its entries to the global state.
fn load_single_catalog(path: &str, state: &mut CatalogState) {
    let data = match read_file_bytes(path) {
        Some(d) => d,
        None => return,
    };

    let format = detect_catalog_format(&data);
    state.catalogs.push(CatalogInfo {
        path: path.as_bytes().to_vec(),
        format,
    });

    load_catalog_data(path, &data, &mut state.entries);
}

/// Load catalogs from a colon-separated list of file paths.
fn load_catalog_list(catalogs: &str, state: &mut CatalogState) {
    for catalog_path in catalogs.split(':') {
        let trimmed = catalog_path.trim();
        if !trimmed.is_empty() {
            load_single_catalog(trimmed, state);
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Public API: Initialization / Cleanup
// ═══════════════════════════════════════════════════════════════════════════════

/// Initialize the catalog subsystem.
///
/// Loads catalogs from environment variables and default locations.
/// Safe to call multiple times.
pub(crate) fn init() {
    let mut state = CATALOG_STATE.write();
    if state.initialized {
        return;
    }

    // Set default allow to ALL (matching upstream behavior)
    state.allow = XML_CATA_ALLOW_ALL;
    crate::xml::globals::set_catalog_defaults(XML_CATA_ALLOW_ALL);

    // Load from XML_CATALOG_FILES environment variable
    if let Ok(catalogs) = std::env::var(XML_CATALOG_FILES_ENV) {
        load_catalog_list(&catalogs, &mut state);
    }

    // Load from SGML_CATALOG_FILES environment variable
    if let Ok(catalogs) = std::env::var(SGML_CATALOG_FILES_ENV) {
        load_catalog_list(&catalogs, &mut state);
    }

    // Load default catalog
    if Path::new(DEFAULT_CATALOG).exists() {
        load_single_catalog(DEFAULT_CATALOG, &mut state);
    }

    state.initialized = true;
}

/// Clean up the catalog subsystem.
///
/// Clears all catalog entries and resets state.
pub(crate) fn cleanup() {
    let mut state = CATALOG_STATE.write();
    state.clear();
    state.initialized = false;
}

// ═══════════════════════════════════════════════════════════════════════════════
// Public API: Catalog Loading
// ═══════════════════════════════════════════════════════════════════════════════

/// Load catalog from a colon-separated list of file paths.
///
/// Returns an opaque handle (currently just a non-null pointer on success).
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlCatalogPtr xmlCatalogLoad(const char *catalogs);
/// ```
pub(crate) fn load_catalog(catalogs: *const c_char) -> *mut c_void {
    if catalogs.is_null() {
        return ptr::null_mut();
    }

    let catalogs_str = unsafe { CStr::from_ptr(catalogs) };
    let catalogs_str = catalogs_str.to_str().unwrap_or("");

    let mut state = CATALOG_STATE.write();

    // Ensure initialized
    if !state.initialized {
        drop(state);
        init();
        state = CATALOG_STATE.write();
    }

    let count_before = state.catalogs.len();
    load_catalog_list(catalogs_str, &mut state);

    if state.catalogs.len() > count_before {
        // Return a non-null handle (the number of loaded catalogs as a magic pointer)
        (state.catalogs.len() as isize) as *mut c_void
    } else {
        ptr::null_mut()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Public API: Resolution Functions
// ═══════════════════════════════════════════════════════════════════════════════

/// Check whether catalog resolution is allowed based on the current `allow` value.
fn catalog_allowed(state: &CatalogState) -> bool {
    let allow = state.allow;
    match allow {
        XML_CATA_ALLOW_NONE => false,
        XML_CATA_ALLOW_GLOBAL | XML_CATA_ALLOW_DOCUMENT | XML_CATA_ALLOW_ALL => true,
        _ => false,
    }
}

/// Resolve a public ID to a system/URI.
///
/// Checks catalog entries in order, first matching `Public` entries,
/// then falls through to delegation.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlCharPtr xmlCatalogResolvePublic(const xmlChar *pubID);
/// ```
pub(crate) unsafe fn resolve_public(pub_id: *const xmlChar) -> *mut xmlChar {
    if pub_id.is_null() {
        return ptr::null_mut();
    }

    let state = CATALOG_STATE.read();
    if !catalog_allowed(&state) {
        return ptr::null_mut();
    }

    let pub_id_bytes = xmlstr_to_bytes(pub_id);

    // 1. Direct match on Public entries
    for entry in &state.entries {
        if let CatalogEntry::Public { public_id, uri } = entry {
            if public_id.as_slice() == pub_id_bytes {
                return bytes_to_xmlstr(uri);
            }
        }
    }

    // 2. DelegatePublic - find longest matching prefix
    let mut best_match: Option<Vec<u8>> = None;
    let mut best_prefix_len: usize = 0;

    for entry in &state.entries {
        if let CatalogEntry::DelegatePublic { prefix, catalog } = entry {
            if pub_id_bytes.starts_with(prefix) && prefix.len() > best_prefix_len {
                best_prefix_len = prefix.len();
                // Try to load the delegated catalog and resolve
                if let Some(delegated_data) = read_file_bytes(&String::from_utf8_lossy(catalog)) {
                    let mut temp_entries = Vec::new();
                    parse_xml_catalog(&delegated_data, &mut temp_entries);
                    // Check for public match in delegated catalog
                    for temp_entry in &temp_entries {
                        if let CatalogEntry::Public { public_id: dp, uri } = temp_entry {
                            if dp.as_slice() == pub_id_bytes {
                                best_match = Some(uri.clone());
                            }
                        }
                    }
                }
            }
        }
    }

    best_match
        .as_ref()
        .map_or(ptr::null_mut(), |uri| bytes_to_xmlstr(uri))
}

/// Resolve a system ID.
///
/// Checks catalog entries in order:
/// 1. Direct `System` match
/// 2. `RewriteSystem` prefix match (longest wins)
/// 3. `DelegateSystem` prefix match
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlCharPtr xmlCatalogResolveSystem(const xmlChar *sysID);
/// ```
pub(crate) unsafe fn resolve_system(sys_id: *const xmlChar) -> *mut xmlChar {
    if sys_id.is_null() {
        return ptr::null_mut();
    }

    let state = CATALOG_STATE.read();
    if !catalog_allowed(&state) {
        return ptr::null_mut();
    }

    let sys_id_bytes = xmlstr_to_bytes(sys_id);

    // 1. Direct match on System entries
    for entry in &state.entries {
        if let CatalogEntry::System { system_id, uri } = entry {
            if system_id.as_slice() == sys_id_bytes {
                return bytes_to_xmlstr(uri);
            }
        }
    }

    // 2. RewriteSystem - find longest matching prefix
    let mut best_rewrite: Option<Vec<u8>> = None;
    let mut best_prefix_len: usize = 0;

    for entry in &state.entries {
        if let CatalogEntry::RewriteSystem { prefix, rewrite } = entry {
            if sys_id_bytes.starts_with(prefix) && prefix.len() > best_prefix_len {
                best_prefix_len = prefix.len();
                // Replace the prefix with the rewrite prefix
                let suffix = &sys_id_bytes[prefix.len()..];
                let mut result = rewrite.clone();
                result.extend_from_slice(suffix);
                best_rewrite = Some(result);
            }
        }
    }

    if let Some(rewritten) = best_rewrite {
        return bytes_to_xmlstr(&rewritten);
    }

    // 3. DelegateSystem
    for entry in &state.entries {
        if let CatalogEntry::DelegateSystem { prefix, catalog } = entry {
            if sys_id_bytes.starts_with(prefix) {
                if let Some(delegated_data) = read_file_bytes(&String::from_utf8_lossy(catalog)) {
                    let mut temp_entries = Vec::new();
                    parse_xml_catalog(&delegated_data, &mut temp_entries);
                    for temp_entry in &temp_entries {
                        if let CatalogEntry::System { system_id, uri } = temp_entry {
                            if system_id.as_slice() == sys_id_bytes {
                                return bytes_to_xmlstr(uri);
                            }
                        }
                    }
                }
            }
        }
    }

    ptr::null_mut()
}

/// Resolve a URI.
///
/// Checks catalog entries in order:
/// 1. Direct `System` match (URIs are matched against system entries too)
/// 2. `RewriteURI` prefix match (longest wins)
/// 3. `DelegateURI` prefix match
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlCharPtr xmlCatalogResolveURI(const xmlChar *URI);
/// ```
pub(crate) unsafe fn resolve_uri(uri: *const xmlChar) -> *mut xmlChar {
    if uri.is_null() {
        return ptr::null_mut();
    }

    let state = CATALOG_STATE.read();
    if !catalog_allowed(&state) {
        return ptr::null_mut();
    }

    let uri_bytes = xmlstr_to_bytes(uri);

    // 1. Direct match on System entries (URIs match against systemId in libxml2)
    for entry in &state.entries {
        if let CatalogEntry::System {
            system_id,
            uri: sys_uri,
        } = entry
        {
            if system_id.as_slice() == uri_bytes {
                return bytes_to_xmlstr(sys_uri);
            }
        }
    }

    // 2. RewriteURI - find longest matching prefix
    let mut best_rewrite: Option<Vec<u8>> = None;
    let mut best_prefix_len: usize = 0;

    for entry in &state.entries {
        if let CatalogEntry::RewriteURI { prefix, rewrite } = entry {
            if uri_bytes.starts_with(prefix) && prefix.len() > best_prefix_len {
                best_prefix_len = prefix.len();
                let suffix = &uri_bytes[prefix.len()..];
                let mut result = rewrite.clone();
                result.extend_from_slice(suffix);
                best_rewrite = Some(result);
            }
        }
    }

    if let Some(rewritten) = best_rewrite {
        return bytes_to_xmlstr(&rewritten);
    }

    // 3. DelegateURI
    for entry in &state.entries {
        if let CatalogEntry::DelegateURI { prefix, catalog } = entry {
            if uri_bytes.starts_with(prefix) {
                if let Some(delegated_data) = read_file_bytes(&String::from_utf8_lossy(catalog)) {
                    let mut temp_entries = Vec::new();
                    parse_xml_catalog(&delegated_data, &mut temp_entries);
                    for temp_entry in &temp_entries {
                        if let CatalogEntry::System {
                            system_id,
                            uri: sys_uri,
                        } = temp_entry
                        {
                            if system_id.as_slice() == uri_bytes {
                                return bytes_to_xmlstr(sys_uri);
                            }
                        }
                    }
                }
            }
        }
    }

    ptr::null_mut()
}

// ═══════════════════════════════════════════════════════════════════════════════
// Public API: Catalog Defaults
// ═══════════════════════════════════════════════════════════════════════════════

/// Set catalog behavior.
///
/// Controls whether catalog resolution is allowed and which catalogs
/// are consulted.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlCatalogSetDefaults(xmlCatalogAllowValue allow);
/// ```
pub(crate) fn set_defaults(allow: c_int) {
    let mut state = CATALOG_STATE.write();
    state.allow = allow;
    crate::xml::globals::set_catalog_defaults(allow);
}

/// Get the current catalog allow value.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlCatalogAllowValue xmlCatalogGetDefaults(void);
/// ```
pub(crate) fn get_defaults() -> c_int {
    let state = CATALOG_STATE.read();
    state.allow
}

// ═══════════════════════════════════════════════════════════════════════════════
// Public API: Add / Remove Entries
// ═══════════════════════════════════════════════════════════════════════════════

/// Add a catalog entry.
///
/// `type_` is one of "public", "system", "rewriteSystem", "rewriteURI",
/// "delegatePublic", "delegateSystem", "delegateURI", or "nextCatalog".
///
/// Returns 0 on success, -1 on failure.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlCatalogAdd(const xmlChar *type, const xmlChar *orig, const xmlChar *replace);
/// ```
pub(crate) unsafe fn add(
    type_: *const xmlChar,
    orig: *const xmlChar,
    replace: *const xmlChar,
) -> c_int {
    if type_.is_null() || orig.is_null() || replace.is_null() {
        return -1;
    }

    let type_bytes = xmlstr_to_bytes(type_);
    let orig_bytes = xmlstr_to_bytes(orig);
    let replace_bytes = xmlstr_to_bytes(replace);

    let mut state = CATALOG_STATE.write();

    match type_bytes {
        b"public" => {
            state.entries.push(CatalogEntry::Public {
                public_id: orig_bytes.to_vec(),
                uri: replace_bytes.to_vec(),
            });
            0
        }
        b"system" => {
            state.entries.push(CatalogEntry::System {
                system_id: orig_bytes.to_vec(),
                uri: replace_bytes.to_vec(),
            });
            0
        }
        b"rewriteSystem" => {
            state.entries.push(CatalogEntry::RewriteSystem {
                prefix: orig_bytes.to_vec(),
                rewrite: replace_bytes.to_vec(),
            });
            0
        }
        b"rewriteURI" => {
            state.entries.push(CatalogEntry::RewriteURI {
                prefix: orig_bytes.to_vec(),
                rewrite: replace_bytes.to_vec(),
            });
            0
        }
        b"delegatePublic" => {
            state.entries.push(CatalogEntry::DelegatePublic {
                prefix: orig_bytes.to_vec(),
                catalog: replace_bytes.to_vec(),
            });
            0
        }
        b"delegateSystem" => {
            state.entries.push(CatalogEntry::DelegateSystem {
                prefix: orig_bytes.to_vec(),
                catalog: replace_bytes.to_vec(),
            });
            0
        }
        b"delegateURI" => {
            state.entries.push(CatalogEntry::DelegateURI {
                prefix: orig_bytes.to_vec(),
                catalog: replace_bytes.to_vec(),
            });
            0
        }
        b"nextCatalog" => {
            state.entries.push(CatalogEntry::NextCatalog {
                catalog: orig_bytes.to_vec(),
            });
            0
        }
        _ => -1,
    }
}

/// Remove a catalog entry by matching its value.
///
/// Removes all entries whose public ID, system ID, or prefix matches `value`.
/// Returns the number of entries removed, or -1 on error.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlCatalogRemove(const xmlChar *value);
/// ```
pub(crate) unsafe fn remove(value: *const xmlChar) -> c_int {
    if value.is_null() {
        return -1;
    }

    let value_bytes = xmlstr_to_bytes(value);
    let mut state = CATALOG_STATE.write();

    let before = state.entries.len();
    state.entries.retain(|entry| match entry {
        CatalogEntry::Public { public_id, .. } => public_id.as_slice() != value_bytes,
        CatalogEntry::System { system_id, .. } => system_id.as_slice() != value_bytes,
        CatalogEntry::RewriteSystem { prefix, .. } => prefix.as_slice() != value_bytes,
        CatalogEntry::RewriteURI { prefix, .. } => prefix.as_slice() != value_bytes,
        CatalogEntry::DelegatePublic { prefix, .. } => prefix.as_slice() != value_bytes,
        CatalogEntry::DelegateSystem { prefix, .. } => prefix.as_slice() != value_bytes,
        CatalogEntry::DelegateURI { prefix, .. } => prefix.as_slice() != value_bytes,
        CatalogEntry::NextCatalog { catalog } => catalog.as_slice() != value_bytes,
    });

    (before - state.entries.len()) as c_int
}

// ═══════════════════════════════════════════════════════════════════════════════
// Public API: SGML → XML Conversion
// ═══════════════════════════════════════════════════════════════════════════════

/// Convert the currently loaded SGML catalog entries to an XML Catalog document.
///
/// Returns a newly allocated `_xmlDoc` containing the XML catalog representation,
/// or NULL on failure. The caller is responsible for freeing the document.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlDocPtr xmlCatalogConvert(void);
/// ```
pub(crate) unsafe fn convert() -> *mut _xmlDoc {
    let state = CATALOG_STATE.read();

    if state.entries.is_empty() {
        return ptr::null_mut();
    }

    // Create the XML document
    let doc = crate::xml::tree::new_doc(ptr::null_mut());
    if doc.is_null() {
        return ptr::null_mut();
    }

    // Create root <catalog> element
    let catalog_name = b"catalog\0" as *const u8 as *const xmlChar;
    let root = crate::xml::tree::new_node(ptr::null_mut(), catalog_name);
    if root.is_null() {
        crate::xml::tree::free_doc(doc);
        return ptr::null_mut();
    }

    // Set xmlns attribute for OASIS XML Catalog namespace
    let xmlns_name = b"xmlns\0" as *const u8 as *const xmlChar;
    let ns_value = b"urn:oasis:names:tc:entity:xmlns:xml:catalog\0" as *const u8 as *const xmlChar;
    crate::xml::tree::set_prop(root, xmlns_name, ns_value);

    crate::xml::tree::doc_set_root_element(doc, root);

    // Add entries as child elements
    for entry in &state.entries {
        let (elem_name, attr1_name, attr1_value, attr2_name, attr2_value) = match entry {
            CatalogEntry::Public { public_id, uri } => {
                let elem = b"public\0" as *const u8 as *mut xmlChar;
                let attr1 = b"publicId\0" as *const u8 as *mut xmlChar;
                let val1 = bytes_to_xmlstr(public_id);
                let attr2 = b"uri\0" as *const u8 as *mut xmlChar;
                let val2 = bytes_to_xmlstr(uri);
                (elem, attr1, val1, attr2, val2)
            }
            CatalogEntry::System { system_id, uri } => {
                let elem = b"system\0" as *const u8 as *mut xmlChar;
                let attr1 = b"systemId\0" as *const u8 as *mut xmlChar;
                let val1 = bytes_to_xmlstr(system_id);
                let attr2 = b"uri\0" as *const u8 as *mut xmlChar;
                let val2 = bytes_to_xmlstr(uri);
                (elem, attr1, val1, attr2, val2)
            }
            CatalogEntry::RewriteSystem { prefix, rewrite } => {
                let elem = b"rewriteSystem\0" as *const u8 as *mut xmlChar;
                let attr1 = b"systemIdStartString\0" as *const u8 as *mut xmlChar;
                let val1 = bytes_to_xmlstr(prefix);
                let attr2 = b"rewritePrefix\0" as *const u8 as *mut xmlChar;
                let val2 = bytes_to_xmlstr(rewrite);
                (elem, attr1, val1, attr2, val2)
            }
            CatalogEntry::RewriteURI { prefix, rewrite } => {
                let elem = b"rewriteURI\0" as *const u8 as *mut xmlChar;
                let attr1 = b"uriStartString\0" as *const u8 as *mut xmlChar;
                let val1 = bytes_to_xmlstr(prefix);
                let attr2 = b"rewritePrefix\0" as *const u8 as *mut xmlChar;
                let val2 = bytes_to_xmlstr(rewrite);
                (elem, attr1, val1, attr2, val2)
            }
            CatalogEntry::DelegatePublic { prefix, catalog } => {
                let elem = b"delegatePublic\0" as *const u8 as *mut xmlChar;
                let attr1 = b"publicIdStartString\0" as *const u8 as *mut xmlChar;
                let val1 = bytes_to_xmlstr(prefix);
                let attr2 = b"catalog\0" as *const u8 as *mut xmlChar;
                let val2 = bytes_to_xmlstr(catalog);
                (elem, attr1, val1, attr2, val2)
            }
            CatalogEntry::DelegateSystem { prefix, catalog } => {
                let elem = b"delegateSystem\0" as *const u8 as *mut xmlChar;
                let attr1 = b"systemIdStartString\0" as *const u8 as *mut xmlChar;
                let val1 = bytes_to_xmlstr(prefix);
                let attr2 = b"catalog\0" as *const u8 as *mut xmlChar;
                let val2 = bytes_to_xmlstr(catalog);
                (elem, attr1, val1, attr2, val2)
            }
            CatalogEntry::DelegateURI { prefix, catalog } => {
                let elem = b"delegateURI\0" as *const u8 as *mut xmlChar;
                let attr1 = b"uriStartString\0" as *const u8 as *mut xmlChar;
                let val1 = bytes_to_xmlstr(prefix);
                let attr2 = b"catalog\0" as *const u8 as *mut xmlChar;
                let val2 = bytes_to_xmlstr(catalog);
                (elem, attr1, val1, attr2, val2)
            }
            CatalogEntry::NextCatalog { catalog } => {
                let elem = b"nextCatalog\0" as *const u8 as *mut xmlChar;
                let attr1 = b"catalog\0" as *const u8 as *mut xmlChar;
                let val1 = bytes_to_xmlstr(catalog);
                let attr2 = ptr::null_mut();
                let val2 = ptr::null_mut();
                (elem, attr1, val1, attr2, val2)
            }
        };

        let child = crate::xml::tree::new_child(root, ptr::null_mut(), elem_name);
        if child.is_null() {
            // Free allocated strings and continue
            if !attr1_value.is_null() {
                xmlFree(attr1_value as *mut c_void);
            }
            if !attr2_value.is_null() {
                xmlFree(attr2_value as *mut c_void);
            }
            continue;
        }

        crate::xml::tree::set_prop(child, attr1_name, attr1_value);
        if !attr2_name.is_null() {
            crate::xml::tree::set_prop(child, attr2_name, attr2_value);
        }

        // Free the temporary xmlChar strings we created
        if !attr1_value.is_null() {
            xmlFree(attr1_value as *mut c_void);
        }
        if !attr2_value.is_null() {
            xmlFree(attr2_value as *mut c_void);
        }
    }

    doc
}

// ═══════════════════════════════════════════════════════════════════════════════
// Tests
// ═══════════════════════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::*;
    use crate::abi::allocator::xmlFree;
    use crate::xml::string::xmlstr_to_bytes;
    use std::ffi::CString;
    use std::sync::Mutex;

    /// Serializes catalog tests to prevent interference from shared global state.
    ///
    /// # UPSTREAM-PARITY
    ///
    /// libxml2's catalog module uses global state (the catalog registry is a
    /// module-level static). Tests that modify global state cannot safely run
    /// in parallel. This mutex serializes all catalog tests, matching the
    /// observable behavior of a single-threaded caller.
    static CATALOG_TEST_MUTEX: Mutex<()> = Mutex::new(());

    /// Helper to create a null-terminated xmlChar* from a byte slice.
    unsafe fn to_xmlstr(s: &[u8]) -> *const xmlChar {
        let ptr = bytes_to_xmlstr(s);
        ptr as *const xmlChar
    }

    /// Helper to create a null-terminated xmlChar* from a string.
    unsafe fn to_xmlstr_str(s: &str) -> *const xmlChar {
        to_xmlstr(s.as_bytes())
    }

    unsafe fn free_xmlstr(ptr: *const xmlChar) {
        if !ptr.is_null() {
            xmlFree(ptr as *mut c_void);
        }
    }

    // ── Test setup / teardown ────────────────────────────────────────────

    /// Acquires the catalog test mutex and sets up a clean catalog state.
    ///
    /// Returns a guard that must be held for the duration of the test.
    /// The guard is dropped when the test completes, releasing the mutex.
    fn setup() -> std::sync::MutexGuard<'static, ()> {
        let guard = CATALOG_TEST_MUTEX.lock().unwrap();
        cleanup();
        init();
        // Reset catalog defaults to ALL for testing
        set_defaults(XML_CATA_ALLOW_ALL);
        guard
    }

    fn teardown(_guard: std::sync::MutexGuard<'static, ()>) {
        cleanup();
        // Guard is dropped here, releasing the mutex
    }

    // ── Basic public ID resolution ───────────────────────────────────────

    #[test]
    fn test_resolve_public_basic() {
        let _guard = setup();
        unsafe {
            // Add a public entry
            let type_ = to_xmlstr_str("public");
            let pub_id = to_xmlstr_str("-//OASIS//DTD DocBook XML V4.2//EN");
            let uri = to_xmlstr_str("http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd");
            assert_eq!(add(type_, pub_id, uri), 0);

            // Resolve it
            let result = resolve_public(pub_id);
            assert!(!result.is_null());
            assert_eq!(
                xmlstr_to_bytes(result),
                b"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
            );
            xmlFree(result as *mut c_void);

            // Unknown public ID returns NULL
            let unknown = to_xmlstr_str("-//Unknown//DTD Unknown//EN");
            assert!(resolve_public(unknown).is_null());
            free_xmlstr(unknown);

            free_xmlstr(type_);
            free_xmlstr(pub_id);
            free_xmlstr(uri);
            teardown(_guard);
        }
    }

    // ── Basic system ID resolution ───────────────────────────────────────

    #[test]
    fn test_resolve_system_basic() {
        let _guard = setup();
        unsafe {
            let type_ = to_xmlstr_str("system");
            let sys_id = to_xmlstr_str("http://example.com/foo.dtd");
            let uri = to_xmlstr_str("/local/foo.dtd");
            assert_eq!(add(type_, sys_id, uri), 0);

            let result = resolve_system(sys_id);
            assert!(!result.is_null());
            assert_eq!(xmlstr_to_bytes(result), b"/local/foo.dtd");
            xmlFree(result as *mut c_void);

            free_xmlstr(type_);
            free_xmlstr(sys_id);
            free_xmlstr(uri);
            teardown(_guard);
        }
    }

    // ── URI resolution ──────────────────────────────────────────────────

    #[test]
    fn test_resolve_uri_basic() {
        let _guard = setup();
        unsafe {
            // URI resolution matches against system entries
            let type_ = to_xmlstr_str("system");
            let sys_id = to_xmlstr_str("http://example.com/resource.xml");
            let uri = to_xmlstr_str("/local/resource.xml");
            assert_eq!(add(type_, sys_id, uri), 0);

            let result = resolve_uri(sys_id);
            assert!(!result.is_null());
            assert_eq!(xmlstr_to_bytes(result), b"/local/resource.xml");
            xmlFree(result as *mut c_void);

            free_xmlstr(type_);
            free_xmlstr(sys_id);
            free_xmlstr(uri);
            teardown(_guard);
        }
    }

    // ── RewriteSystem resolution ────────────────────────────────────────

    #[test]
    fn test_rewrite_system() {
        let _guard = setup();
        unsafe {
            let type_ = to_xmlstr_str("rewriteSystem");
            let prefix = to_xmlstr_str("http://example.com/old/");
            let rewrite = to_xmlstr_str("http://mirror.example.com/new/");
            assert_eq!(add(type_, prefix, rewrite), 0);

            let sys_id = to_xmlstr_str("http://example.com/old/path/file.xml");
            let result = resolve_system(sys_id);
            assert!(!result.is_null());
            assert_eq!(
                xmlstr_to_bytes(result),
                b"http://mirror.example.com/new/path/file.xml"
            );
            xmlFree(result as *mut c_void);

            free_xmlstr(type_);
            free_xmlstr(prefix);
            free_xmlstr(rewrite);
            free_xmlstr(sys_id);
            teardown(_guard);
        }
    }

    // ── RewriteURI resolution ───────────────────────────────────────────

    #[test]
    fn test_rewrite_uri() {
        let _guard = setup();
        unsafe {
            let type_ = to_xmlstr_str("rewriteURI");
            let prefix = to_xmlstr_str("http://example.com/old/");
            let rewrite = to_xmlstr_str("http://mirror.example.com/new/");
            assert_eq!(add(type_, prefix, rewrite), 0);

            let uri = to_xmlstr_str("http://example.com/old/path/file.xml");
            let result = resolve_uri(uri);
            assert!(!result.is_null());
            assert_eq!(
                xmlstr_to_bytes(result),
                b"http://mirror.example.com/new/path/file.xml"
            );
            xmlFree(result as *mut c_void);

            free_xmlstr(type_);
            free_xmlstr(prefix);
            free_xmlstr(rewrite);
            free_xmlstr(uri);
            teardown(_guard);
        }
    }

    // ── Remove entries ──────────────────────────────────────────────────

    #[test]
    fn test_remove_entries() {
        let _guard = setup();
        unsafe {
            let type_ = to_xmlstr_str("public");
            let pub_id = to_xmlstr_str("-//TEST//PUBLIC//EN");
            let uri = to_xmlstr_str("test.dtd");
            assert_eq!(add(type_, pub_id, uri), 0);

            // Should resolve
            assert!(!resolve_public(pub_id).is_null());

            // Remove
            assert_eq!(remove(pub_id), 1);

            // Should no longer resolve
            assert!(resolve_public(pub_id).is_null());

            free_xmlstr(type_);
            free_xmlstr(pub_id);
            free_xmlstr(uri);
            teardown(_guard);
        }
    }

    // ── Catalog defaults ────────────────────────────────────────────────

    #[test]
    fn test_catalog_defaults() {
        let _guard = setup();

        assert_eq!(get_defaults(), XML_CATA_ALLOW_ALL);

        set_defaults(XML_CATA_ALLOW_NONE);
        assert_eq!(get_defaults(), XML_CATA_ALLOW_NONE);

        set_defaults(XML_CATA_ALLOW_GLOBAL);
        assert_eq!(get_defaults(), XML_CATA_ALLOW_GLOBAL);

        set_defaults(XML_CATA_ALLOW_ALL);
        assert_eq!(get_defaults(), XML_CATA_ALLOW_ALL);

        teardown(_guard);
    }

    // ── XML Catalog file parsing ────────────────────────────────────────

    #[test]
    fn test_parse_xml_catalog_in_memory() {
        let _guard = setup();
        unsafe {
            let catalog_xml = br#"<?xml version="1.0"?>
<!DOCTYPE catalog PUBLIC "-//OASIS//DTD Entity Resolution XML Catalog V1.0//EN" "http://www.oasis-open.org/committees/entity/release/1.0/catalog.dtd">
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog">
  <public publicId="-//OASIS//DTD DocBook XML V4.2//EN" uri="http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"/>
  <system systemId="http://example.com/foo.dtd" uri="/local/foo.dtd"/>
  <rewriteSystem systemIdStartString="http://example.com/old/" rewritePrefix="http://mirror.example.com/new/"/>
  <rewriteURI uriStartString="http://example.com/old/" rewritePrefix="http://mirror.example.com/new/"/>
</catalog>"#;

            // Parse the XML catalog into entries
            let mut entries = Vec::new();
            parse_xml_catalog(catalog_xml, &mut entries);
            assert_eq!(entries.len(), 4);

            // Check public entry
            match &entries[0] {
                CatalogEntry::Public { public_id, uri } => {
                    assert_eq!(public_id.as_slice(), b"-//OASIS//DTD DocBook XML V4.2//EN");
                    assert_eq!(
                        uri.as_slice(),
                        b"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
                    );
                }
                _ => panic!("Expected Public entry"),
            }

            // Check system entry
            match &entries[1] {
                CatalogEntry::System { system_id, uri } => {
                    assert_eq!(system_id.as_slice(), b"http://example.com/foo.dtd");
                    assert_eq!(uri.as_slice(), b"/local/foo.dtd");
                }
                _ => panic!("Expected System entry"),
            }

            // Check rewriteSystem entry
            match &entries[2] {
                CatalogEntry::RewriteSystem { prefix, rewrite } => {
                    assert_eq!(prefix.as_slice(), b"http://example.com/old/");
                    assert_eq!(rewrite.as_slice(), b"http://mirror.example.com/new/");
                }
                _ => panic!("Expected RewriteSystem entry"),
            }

            // Check rewriteURI entry
            match &entries[3] {
                CatalogEntry::RewriteURI { prefix, rewrite } => {
                    assert_eq!(prefix.as_slice(), b"http://example.com/old/");
                    assert_eq!(rewrite.as_slice(), b"http://mirror.example.com/new/");
                }
                _ => panic!("Expected RewriteURI entry"),
            }

            teardown(_guard);
        }
    }

    // ── SGML catalog parsing ────────────────────────────────────────────

    #[test]
    fn test_parse_sgml_catalog() {
        let _guard = setup();
        unsafe {
            let sgml_data = br#"-- SGML catalog
PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" "docbookx.dtd"
SYSTEM "http://example.com/foo.dtd" "/local/foo.dtd"
URI "http://example.com/resource" "/local/resource"
"#;

            let mut entries = Vec::new();
            parse_sgml_catalog(sgml_data, &mut entries);
            assert_eq!(entries.len(), 3);

            // Check PUBLIC entry
            match &entries[0] {
                CatalogEntry::Public { public_id, uri } => {
                    assert_eq!(public_id.as_slice(), b"-//OASIS//DTD DocBook XML V4.2//EN");
                    assert_eq!(uri.as_slice(), b"docbookx.dtd");
                }
                _ => panic!("Expected Public entry"),
            }

            // Check SYSTEM entry
            match &entries[1] {
                CatalogEntry::System { system_id, uri } => {
                    assert_eq!(system_id.as_slice(), b"http://example.com/foo.dtd");
                    assert_eq!(uri.as_slice(), b"/local/foo.dtd");
                }
                _ => panic!("Expected System entry"),
            }

            // Check URI entry (maps to System in libxml2)
            match &entries[2] {
                CatalogEntry::System { system_id, uri } => {
                    assert_eq!(system_id.as_slice(), b"http://example.com/resource");
                    assert_eq!(uri.as_slice(), b"/local/resource");
                }
                _ => panic!("Expected System entry for URI"),
            }

            teardown(_guard);
        }
    }

    // ── Resolution precedence ───────────────────────────────────────────

    #[test]
    fn test_resolution_precedence() {
        let _guard = setup();
        unsafe {
            // Add a system entry
            let type_sys = to_xmlstr_str("system");
            let sys_id = to_xmlstr_str("http://example.com/target.xml");
            let uri_direct = to_xmlstr_str("/direct/uri.xml");
            assert_eq!(add(type_sys, sys_id, uri_direct), 0);

            // Add a rewriteSystem with shorter prefix (should not override direct)
            let type_rw = to_xmlstr_str("rewriteSystem");
            let prefix = to_xmlstr_str("http://example.com/");
            let rewrite = to_xmlstr_str("/rewrite/");
            assert_eq!(add(type_rw, prefix, rewrite), 0);

            // Direct match should win
            let result = resolve_system(sys_id);
            assert!(!result.is_null());
            assert_eq!(xmlstr_to_bytes(result), b"/direct/uri.xml");
            xmlFree(result as *mut c_void);

            free_xmlstr(type_sys);
            free_xmlstr(sys_id);
            free_xmlstr(uri_direct);
            free_xmlstr(type_rw);
            free_xmlstr(prefix);
            free_xmlstr(rewrite);
            teardown(_guard);
        }
    }

    // ── Convert SGML to XML ─────────────────────────────────────────────

    #[test]
    fn test_convert_sgml_to_xml() {
        let _guard = setup();
        unsafe {
            let type_ = to_xmlstr_str("public");
            let pub_id = to_xmlstr_str("-//TEST//PUBLIC//EN");
            let uri = to_xmlstr_str("test.dtd");
            assert_eq!(add(type_, pub_id, uri), 0);

            let doc = convert();
            assert!(!doc.is_null());

            // Verify the document has a root <catalog> element
            let root = crate::xml::tree::doc_get_root_element(doc);
            assert!(!root.is_null());
            let root_name = crate::xml::string::xmlstr_to_bytes((*root).name);
            assert_eq!(root_name, b"catalog");

            // Verify there's a child <public> element
            let child = (*root).children;
            assert!(!child.is_null());
            let child_name = crate::xml::string::xmlstr_to_bytes((*child).name);
            assert_eq!(child_name, b"public");

            crate::xml::tree::free_doc(doc);
            free_xmlstr(type_);
            free_xmlstr(pub_id);
            free_xmlstr(uri);
            teardown(_guard);
        }
    }

    // ── Catalog allowed / disallowed ────────────────────────────────────

    #[test]
    fn test_catalog_disallowed() {
        let _guard = setup();
        unsafe {
            // Add an entry
            let type_ = to_xmlstr_str("system");
            let sys_id = to_xmlstr_str("http://example.com/test.dtd");
            let uri = to_xmlstr_str("/local/test.dtd");
            add(type_, sys_id, uri);

            // Disable catalogs
            set_defaults(XML_CATA_ALLOW_NONE);

            // Resolution should return NULL
            assert!(resolve_system(sys_id).is_null());
            assert!(resolve_public(sys_id).is_null());
            assert!(resolve_uri(sys_id).is_null());

            set_defaults(XML_CATA_ALLOW_ALL);
            free_xmlstr(type_);
            free_xmlstr(sys_id);
            free_xmlstr(uri);
            teardown(_guard);
        }
    }

    // ── Init / Cleanup ──────────────────────────────────────────────────

    #[test]
    fn test_init_cleanup() {
        let _guard = CATALOG_TEST_MUTEX.lock().unwrap();
        cleanup();
        assert_eq!(CATALOG_STATE.read().initialized, false);

        init();
        assert_eq!(CATALOG_STATE.read().initialized, true);

        cleanup();
        assert_eq!(CATALOG_STATE.read().initialized, false);
    }

    // ── XML Catalog with group ──────────────────────────────────────────

    #[test]
    fn test_parse_xml_catalog_group() {
        let catalog_xml = br#"<?xml version="1.0"?>
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog">
  <group>
    <public publicId="-//GROUP//PUBLIC//EN" uri="group.dtd"/>
    <system systemId="http://group.example.com/" uri="/group/"/>
  </group>
</catalog>"#;

        let mut entries = Vec::new();
        parse_xml_catalog(catalog_xml, &mut entries);
        assert_eq!(entries.len(), 2);

        match &entries[0] {
            CatalogEntry::Public { public_id, .. } => {
                assert_eq!(public_id.as_slice(), b"-//GROUP//PUBLIC//EN");
            }
            _ => panic!("Expected Public entry"),
        }

        match &entries[1] {
            CatalogEntry::System { system_id, .. } => {
                assert_eq!(system_id.as_slice(), b"http://group.example.com/");
            }
            _ => panic!("Expected System entry"),
        }
    }

    // ── Multiple entries, multiple resolution ───────────────────────────

    #[test]
    fn test_multiple_entries() {
        let _guard = setup();
        unsafe {
            // Add two public entries
            let t = to_xmlstr_str("public");
            let id1 = to_xmlstr_str("-//A//PUBLIC//EN");
            let uri1 = to_xmlstr_str("a.dtd");
            let id2 = to_xmlstr_str("-//B//PUBLIC//EN");
            let uri2 = to_xmlstr_str("b.dtd");

            assert_eq!(add(t, id1, uri1), 0);
            assert_eq!(add(t, id2, uri2), 0);

            let r1 = resolve_public(id1);
            assert!(!r1.is_null());
            assert_eq!(xmlstr_to_bytes(r1), b"a.dtd");
            xmlFree(r1 as *mut c_void);

            let r2 = resolve_public(id2);
            assert!(!r2.is_null());
            assert_eq!(xmlstr_to_bytes(r2), b"b.dtd");
            xmlFree(r2 as *mut c_void);

            free_xmlstr(t);
            free_xmlstr(id1);
            free_xmlstr(uri1);
            free_xmlstr(id2);
            free_xmlstr(uri2);
            teardown(_guard);
        }
    }

    // ── Longest prefix wins for rewrite ─────────────────────────────────

    #[test]
    fn test_longest_prefix_wins() {
        let _guard = setup();
        unsafe {
            let t = to_xmlstr_str("rewriteSystem");
            let p1 = to_xmlstr_str("http://example.com/");
            let r1 = to_xmlstr_str("/general/");
            let p2 = to_xmlstr_str("http://example.com/specific/");
            let r2 = to_xmlstr_str("/specific/");

            add(t, p1, r1);
            add(t, p2, r2);

            let sys_id = to_xmlstr_str("http://example.com/specific/file.xml");
            let result = resolve_system(sys_id);
            assert!(!result.is_null());
            assert_eq!(xmlstr_to_bytes(result), b"/specific/file.xml");
            xmlFree(result as *mut c_void);

            free_xmlstr(t);
            free_xmlstr(p1);
            free_xmlstr(r1);
            free_xmlstr(p2);
            free_xmlstr(r2);
            free_xmlstr(sys_id);
            teardown(_guard);
        }
    }
}