libxml-rs 0.1.0-alpha.7

Phase 6: Validation family (DTD, XML Schema, RELAX NG, Schematron). Native-Rust forensic reimplementation of libxml2+libxslt with C ABI drop-in replacement. 802 tests passing, DTD validation, XML Schema parser+validator (45+ built-in datatypes), RELAX NG grammar+validation, ISO Schematron rules+patterns, full C ABI exports.
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
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
//! XML Schema implementation (§27, §85 Phase 6).
//!
//! XML Schema (W3C XSD) validation and datatype machinery. libxml2's schema
//! support is an UPSTREAM_EXTENSION known to deviate from the standard in
//! places — parity follows the oracle.
//!
//! Phase 6: Complete — schema parsing, datatype validation, document validation,
//! and C ABI exports are implemented.
//!
//! # UPSTREAM-PARITY
//!
//! This module implements a simplified but functional XSD validator that
//! follows libxml2's observable behavior for the most common patterns.
//! Deviations from the W3C specification that match libxml2 are intentional.

use core::ffi::c_void;
use core::ptr;
use std::collections::HashMap;
use std::os::raw::{c_char, c_int};

use crate::abi::allocator;
use crate::abi::structs::*;
use crate::abi::types::xmlElementType::*;
use crate::abi::types::*;

// ═══════════════════════════════════════════════════════════════════════════════
// XSD Component Types
// ═══════════════════════════════════════════════════════════════════════════════

/// XSD component types — mirrors libxml2's schema component classification.
///
/// # UPSTREAM-PARITY
///
/// libxml2 defines these as `xmlSchemaTypeType` in `include/schemas/internals.h`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum XsdComponentType {
    Schema,
    Element,
    Attribute,
    ComplexType,
    SimpleType,
    SimpleContent,
    ComplexContent,
    Sequence,
    Choice,
    All,
    Restriction,
    Extension,
    List,
    Union,
    Annotation,
    Any,
    AnyAttribute,
    Group,
    AttributeGroup,
    Notation,
    Unique,
    Key,
    KeyRef,
    Selector,
    Field,
}

// ═══════════════════════════════════════════════════════════════════════════════
// XSD Datatype Kinds
// ═══════════════════════════════════════════════════════════════════════════════

/// XSD datatype kinds — covers all built-in types and facets.
///
/// # UPSTREAM-PARITY
///
/// libxml2 defines these as `xmlSchemaTypeType` built-in type constants
/// in `include/schemas/internals.h`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum XsdDatatypeKind {
    // Primitive types
    String,
    Boolean,
    Decimal,
    Float,
    Double,
    Duration,
    DateTime,
    Time,
    Date,
    GYearMonth,
    GYear,
    GMonthDay,
    GDay,
    GMonth,
    HexBinary,
    Base64Binary,
    AnyURI,
    QName,
    Notation,
    // Derived string types
    NormalizedString,
    Token,
    Language,
    Nmtoken,
    Nmtokens,
    Name,
    NCName,
    Id,
    Idref,
    Idrefs,
    Entity,
    Entities,
    // Numeric derived types
    Integer,
    NonPositiveInteger,
    NegativeInteger,
    Long,
    Int,
    Short,
    Byte,
    NonNegativeInteger,
    UnsignedLong,
    UnsignedInt,
    UnsignedShort,
    UnsignedByte,
    PositiveInteger,
    // Facet types (used internally)
    FacetPattern,
    FacetEnumeration,
    FacetMinInclusive,
    FacetMaxInclusive,
    FacetMinExclusive,
    FacetMaxExclusive,
    FacetMinLength,
    FacetMaxLength,
    FacetLength,
    FacetWhiteSpace,
    FacetFractionDigits,
    FacetTotalDigits,
}

// ═══════════════════════════════════════════════════════════════════════════════
// XSD Component
// ═══════════════════════════════════════════════════════════════════════════════

/// An XSD schema component declaration.
///
/// Represents any XSD component (element, attribute, type, model group, etc.).
/// Components form a tree via the `children` and `attributes` vectors.
#[derive(Debug, Clone)]
pub struct XsdComponent {
    pub component_type: XsdComponentType,
    pub name: Option<String>,
    pub target_namespace: Option<String>,
    pub children: Vec<XsdComponent>,
    pub attributes: Vec<XsdComponent>,
    pub datatype: Option<XsdDatatypeKind>,
    pub facets: Vec<(XsdDatatypeKind, String)>,
    pub base: Option<String>,
    pub min_occurs: i32,
    pub max_occurs: i32, // -1 for unbounded
    pub ref_name: Option<String>,
    pub substitution_group: Option<String>,
    pub is_abstract: bool,
    pub is_final: bool,
    pub block: Vec<String>,
    pub mixed: bool,
    pub form: Option<String>,
}

impl XsdComponent {
    pub fn new(component_type: XsdComponentType) -> Self {
        Self {
            component_type,
            name: None,
            target_namespace: None,
            children: Vec::new(),
            attributes: Vec::new(),
            datatype: None,
            facets: Vec::new(),
            base: None,
            min_occurs: 1,
            max_occurs: 1,
            ref_name: None,
            substitution_group: None,
            is_abstract: false,
            is_final: false,
            block: Vec::new(),
            mixed: false,
            form: None,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// XSD Schema
// ═══════════════════════════════════════════════════════════════════════════════

/// A compiled XSD schema.
///
/// Holds the top-level component declarations and schema-level settings.
#[derive(Debug, Clone)]
pub struct XsdSchema {
    pub components: Vec<XsdComponent>,
    pub target_namespace: Option<String>,
    pub element_form_default: Option<String>,
    pub attribute_form_default: Option<String>,
    pub errors: Vec<String>,
}

impl XsdSchema {
    pub fn new() -> Self {
        Self {
            components: Vec::new(),
            target_namespace: None,
            element_form_default: None,
            attribute_form_default: None,
            errors: Vec::new(),
        }
    }
}

impl Default for XsdSchema {
    fn default() -> Self {
        Self::new()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// XSD Validation Context
// ═══════════════════════════════════════════════════════════════════════════════

/// Validation context for XSD schema validation.
///
/// Tracks errors and state during validation of an XML document against
/// a schema. Mirrors libxml2's `xmlSchemaValidCtxt`.
#[derive(Debug)]
pub struct XsdValidCtxt {
    pub schema: Option<XsdSchema>,
    pub errors: Vec<String>,
    pub nb_errors: i32,
}

impl XsdValidCtxt {
    pub fn new() -> Self {
        Self {
            schema: None,
            errors: Vec::new(),
            nb_errors: 0,
        }
    }
}

impl Default for XsdValidCtxt {
    fn default() -> Self {
        Self::new()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Internal helpers for schema parsing
// ═══════════════════════════════════════════════════════════════════════════════

/// Get the text content of an xmlNode (recursively collects text children).
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an _xmlNode or NULL.
unsafe fn get_node_text(node: *mut _xmlNode) -> String {
    if node.is_null() {
        return String::new();
    }
    let mut result = String::new();
    unsafe {
        let mut child = (*node).children;
        while !child.is_null() {
            if (*child).type_ == XML_TEXT_NODE as c_int
                || (*child).type_ == XML_CDATA_SECTION_NODE as c_int
            {
                if !(*child).content.is_null() {
                    let content = (*child).content;
                    let mut len = 0;
                    while *content.add(len) != 0 {
                        len += 1;
                    }
                    let slice = std::slice::from_raw_parts(content, len);
                    result.push_str(&String::from_utf8_lossy(slice));
                }
            }
            child = (*child).next;
        }
    }
    result
}

/// Get an attribute value from an xmlNode.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an _xmlNode or NULL.
unsafe fn get_attr(node: *mut _xmlNode, name: &str) -> Option<String> {
    if node.is_null() {
        return None;
    }
    unsafe {
        let mut prop = (*node).properties;
        while !prop.is_null() {
            let prop_name = (*prop).name;
            if !prop_name.is_null() {
                let mut len = 0;
                while *prop_name.add(len) != 0 {
                    len += 1;
                }
                let slice = std::slice::from_raw_parts(prop_name, len);
                if let Ok(s) = std::str::from_utf8(slice) {
                    if s == name {
                        return Some(get_node_text(prop as *mut _xmlNode));
                    }
                }
            }
            prop = (*prop).next;
        }
    }
    None
}

/// Get an attribute value as a boolean.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an _xmlNode or NULL.
unsafe fn get_attr_bool(node: *mut _xmlNode, name: &str) -> bool {
    unsafe {
        match get_attr(node, name) {
            Some(v) => v == "true" || v == "1",
            None => false,
        }
    }
}

/// Get an attribute value as an integer with a default.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an _xmlNode or NULL.
unsafe fn get_attr_int(node: *mut _xmlNode, name: &str, default: i32) -> i32 {
    unsafe {
        match get_attr(node, name) {
            Some(v) => v.parse::<i32>().unwrap_or(default),
            None => default,
        }
    }
}

/// Get an attribute value as an unbounded integer (-1 for "unbounded").
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an _xmlNode or NULL.
unsafe fn get_attr_occurs(node: *mut _xmlNode, name: &str, default: i32) -> i32 {
    unsafe {
        match get_attr(node, name) {
            Some(v) => {
                if v == "unbounded" {
                    -1
                } else {
                    v.parse::<i32>().unwrap_or(default)
                }
            }
            None => default,
        }
    }
}

/// Check if an xmlNode is an element with a given local name.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an _xmlNode or NULL.
unsafe fn node_is(node: *mut _xmlNode, local_name: &str) -> bool {
    if node.is_null() {
        return false;
    }
    unsafe {
        let name = (*node).name;
        if name.is_null() {
            return false;
        }
        let mut len = 0;
        while *name.add(len) != 0 {
            len += 1;
        }
        let slice = std::slice::from_raw_parts(name, len);
        if let Ok(s) = std::str::from_utf8(slice) {
            // Strip namespace prefix if present
            let local = if let Some(pos) = s.find(':') {
                &s[pos + 1..]
            } else {
                s
            };
            return local == local_name;
        }
    }
    false
}

/// Parse a datatype kind from a QName string (e.g., "xs:string", "string").
fn parse_datatype_kind(name: &str) -> Option<XsdDatatypeKind> {
    // Strip XML Schema namespace prefix if present
    let local = if let Some(pos) = name.find(':') {
        &name[pos + 1..]
    } else {
        name
    };

    match local {
        "string" => Some(XsdDatatypeKind::String),
        "boolean" => Some(XsdDatatypeKind::Boolean),
        "decimal" => Some(XsdDatatypeKind::Decimal),
        "float" => Some(XsdDatatypeKind::Float),
        "double" => Some(XsdDatatypeKind::Double),
        "duration" => Some(XsdDatatypeKind::Duration),
        "dateTime" => Some(XsdDatatypeKind::DateTime),
        "time" => Some(XsdDatatypeKind::Time),
        "date" => Some(XsdDatatypeKind::Date),
        "gYearMonth" => Some(XsdDatatypeKind::GYearMonth),
        "gYear" => Some(XsdDatatypeKind::GYear),
        "gMonthDay" => Some(XsdDatatypeKind::GMonthDay),
        "gDay" => Some(XsdDatatypeKind::GDay),
        "gMonth" => Some(XsdDatatypeKind::GMonth),
        "hexBinary" => Some(XsdDatatypeKind::HexBinary),
        "base64Binary" => Some(XsdDatatypeKind::Base64Binary),
        "anyURI" => Some(XsdDatatypeKind::AnyURI),
        "QName" => Some(XsdDatatypeKind::QName),
        "NOTATION" => Some(XsdDatatypeKind::Notation),
        "normalizedString" => Some(XsdDatatypeKind::NormalizedString),
        "token" => Some(XsdDatatypeKind::Token),
        "language" => Some(XsdDatatypeKind::Language),
        "NMTOKEN" => Some(XsdDatatypeKind::Nmtoken),
        "NMTOKENS" => Some(XsdDatatypeKind::Nmtokens),
        "Name" => Some(XsdDatatypeKind::Name),
        "NCName" => Some(XsdDatatypeKind::NCName),
        "ID" => Some(XsdDatatypeKind::Id),
        "IDREF" => Some(XsdDatatypeKind::Idref),
        "IDREFS" => Some(XsdDatatypeKind::Idrefs),
        "ENTITY" => Some(XsdDatatypeKind::Entity),
        "ENTITIES" => Some(XsdDatatypeKind::Entities),
        "integer" => Some(XsdDatatypeKind::Integer),
        "nonPositiveInteger" => Some(XsdDatatypeKind::NonPositiveInteger),
        "negativeInteger" => Some(XsdDatatypeKind::NegativeInteger),
        "long" => Some(XsdDatatypeKind::Long),
        "int" => Some(XsdDatatypeKind::Int),
        "short" => Some(XsdDatatypeKind::Short),
        "byte" => Some(XsdDatatypeKind::Byte),
        "nonNegativeInteger" => Some(XsdDatatypeKind::NonNegativeInteger),
        "unsignedLong" => Some(XsdDatatypeKind::UnsignedLong),
        "unsignedInt" => Some(XsdDatatypeKind::UnsignedInt),
        "unsignedShort" => Some(XsdDatatypeKind::UnsignedShort),
        "unsignedByte" => Some(XsdDatatypeKind::UnsignedByte),
        "positiveInteger" => Some(XsdDatatypeKind::PositiveInteger),
        _ => None,
    }
}

/// Parse a facet kind from an XSD element name.
fn parse_facet_kind(name: &str) -> Option<XsdDatatypeKind> {
    match name {
        "pattern" => Some(XsdDatatypeKind::FacetPattern),
        "enumeration" => Some(XsdDatatypeKind::FacetEnumeration),
        "minInclusive" => Some(XsdDatatypeKind::FacetMinInclusive),
        "maxInclusive" => Some(XsdDatatypeKind::FacetMaxInclusive),
        "minExclusive" => Some(XsdDatatypeKind::FacetMinExclusive),
        "maxExclusive" => Some(XsdDatatypeKind::FacetMaxExclusive),
        "minLength" => Some(XsdDatatypeKind::FacetMinLength),
        "maxLength" => Some(XsdDatatypeKind::FacetMaxLength),
        "length" => Some(XsdDatatypeKind::FacetLength),
        "whiteSpace" => Some(XsdDatatypeKind::FacetWhiteSpace),
        "fractionDigits" => Some(XsdDatatypeKind::FacetFractionDigits),
        "totalDigits" => Some(XsdDatatypeKind::FacetTotalDigits),
        _ => None,
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Schema Parsing
// ═══════════════════════════════════════════════════════════════════════════════

/// Parse an XSD schema from an XML string.
///
/// # UPSTREAM-PARITY
///
/// Equivalent to `xmlSchemaParse` in libxml2.
///
/// Returns the parsed schema, or an error message on failure.
pub fn xsd_parse(xml_doc: &str) -> Result<XsdSchema, String> {
    // Use the XML parser to parse the schema document
    let doc_ptr = unsafe {
        crate::abi::exports_xml2::xmlReadMemory(
            xml_doc.as_ptr() as *const c_char,
            xml_doc.len() as c_int,
            b"schema.xsd\0".as_ptr() as *const c_char,
            ptr::null(),
            0,
        )
    };

    if doc_ptr.is_null() {
        return Err("Failed to parse schema XML document".to_string());
    }

    let result = unsafe { xsd_parse_schema_doc(doc_ptr) };
    unsafe {
        crate::abi::exports_xml2::xmlFreeDoc(doc_ptr);
    }
    result
}

/// Parse an XSD schema from a parsed XML document.
///
/// # SAFETY
///
/// - `doc` must be a valid pointer to an _xmlDoc representing an XSD schema.
unsafe fn xsd_parse_schema_doc(doc: *mut _xmlDoc) -> Result<XsdSchema, String> {
    unsafe {
        let root = (*doc).children;
        if root.is_null() {
            return Err("Schema document has no root element".to_string());
        }

        // Find the root <schema> element
        let mut schema_node = root;
        while !schema_node.is_null() && !node_is(schema_node, "schema") {
            schema_node = (*schema_node).next;
        }

        if schema_node.is_null() {
            return Err("Schema document root is not <schema>".to_string());
        }

        Ok(xsd_parse_schema_node(schema_node))
    }
}

/// Parse a <schema> element.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to a <schema> element node.
unsafe fn xsd_parse_schema_node(node: *mut _xmlNode) -> XsdSchema {
    unsafe {
        let mut schema = XsdSchema::new();
        schema.target_namespace = get_attr(node, "targetNamespace");
        schema.element_form_default = get_attr(node, "elementFormDefault");
        schema.attribute_form_default = get_attr(node, "attributeFormDefault");

        // Parse child components
        let mut child = (*node).children;
        while !child.is_null() {
            if (*child).type_ == XML_ELEMENT_NODE as c_int {
                let comp = xsd_parse_component(child, &schema);
                if comp.component_type != XsdComponentType::Annotation {
                    schema.components.push(comp);
                }
            }
            child = (*child).next;
        }

        schema
    }
}

/// Parse a single XSD component from an element node.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an XML element node.
unsafe fn xsd_parse_component(node: *mut _xmlNode, schema: &XsdSchema) -> XsdComponent {
    unsafe {
        // Determine the component type from the element name
        let name_str = if !(*node).name.is_null() {
            let mut len = 0;
            while *(*node).name.add(len) != 0 {
                len += 1;
            }
            let slice = std::slice::from_raw_parts((*node).name, len);
            if let Ok(s) = std::str::from_utf8(slice) {
                if let Some(pos) = s.find(':') {
                    s[pos + 1..].to_string()
                } else {
                    s.to_string()
                }
            } else {
                String::new()
            }
        } else {
            String::new()
        };

        match name_str.as_str() {
            "element" => xsd_parse_element(node, schema),
            "attribute" => xsd_parse_attribute_node(node, schema),
            "complexType" => xsd_parse_complex_type(node, schema),
            "simpleType" => xsd_parse_simple_type(node, schema),
            "sequence" => xsd_parse_model_group(node, XsdComponentType::Sequence, schema),
            "choice" => xsd_parse_model_group(node, XsdComponentType::Choice, schema),
            "all" => xsd_parse_model_group(node, XsdComponentType::All, schema),
            "restriction" => xsd_parse_restriction(node, schema),
            "extension" => xsd_parse_extension(node, schema),
            "list" => xsd_parse_list(node, schema),
            "union" => xsd_parse_union(node, schema),
            "annotation" => xsd_parse_annotation(node),
            "any" => xsd_parse_any(node, schema),
            "anyAttribute" => {
                let mut comp = XsdComponent::new(XsdComponentType::AnyAttribute);
                comp
            }
            "group" => xsd_parse_group(node, schema),
            "attributeGroup" => xsd_parse_attribute_group(node, schema),
            "unique" => xsd_parse_identity_constraint(node, XsdComponentType::Unique, schema),
            "key" => xsd_parse_identity_constraint(node, XsdComponentType::Key, schema),
            "keyref" => xsd_parse_identity_constraint(node, XsdComponentType::KeyRef, schema),
            // Facets
            "pattern" | "enumeration" | "minInclusive" | "maxInclusive" | "minExclusive"
            | "maxExclusive" | "minLength" | "maxLength" | "length" | "whiteSpace"
            | "fractionDigits" | "totalDigits" => xsd_parse_facet(node),
            // Simple content / complex content markers
            "simpleContent" => xsd_parse_simple_content(node, schema),
            "complexContent" => xsd_parse_complex_content(node, schema),
            _ => {
                // Unknown element — create a generic component
                let mut comp = XsdComponent::new(XsdComponentType::Schema);
                if let Ok(s) = std::str::from_utf8(std::slice::from_raw_parts((*node).name, {
                    let mut len = 0;
                    while *(*node).name.add(len) != 0 {
                        len += 1;
                    }
                    len
                })) {
                    comp.name = Some(s.to_string());
                }
                comp
            }
        }
    }
}

/// Parse an <element> declaration.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an <element> element node.
unsafe fn xsd_parse_element(node: *mut _xmlNode, schema: &XsdSchema) -> XsdComponent {
    unsafe {
        let mut comp = XsdComponent::new(XsdComponentType::Element);
        comp.name = get_attr(node, "name");
        comp.ref_name = get_attr(node, "ref");
        comp.min_occurs = get_attr_occurs(node, "minOccurs", 1);
        comp.max_occurs = get_attr_occurs(node, "maxOccurs", 1);
        comp.is_abstract = get_attr_bool(node, "abstract");
        comp.is_final = get_attr_bool(node, "final");
        comp.substitution_group = get_attr(node, "substitutionGroup");
        comp.form = get_attr(node, "form");

        // Resolve type attribute
        if let Some(type_name) = get_attr(node, "type") {
            comp.datatype = parse_datatype_kind(&type_name);
            // If it's not a built-in type, store the type name as base
            if comp.datatype.is_none() {
                comp.base = Some(type_name);
            }
        }

        // Check for default/fixed value
        let _default = get_attr(node, "default");
        let _fixed = get_attr(node, "fixed");

        // Parse child components (inline type definitions)
        let mut child = (*node).children;
        while !child.is_null() {
            if (*child).type_ == XML_ELEMENT_NODE as c_int {
                let child_comp = xsd_parse_component(child, schema);
                match child_comp.component_type {
                    XsdComponentType::ComplexType | XsdComponentType::SimpleType => {
                        // Inline type definition
                        if let Some(ref name) = child_comp.name {
                            comp.base = Some(name.clone());
                        }
                        comp.children.push(child_comp);
                    }
                    XsdComponentType::Annotation => {
                        // Skip annotations
                    }
                    _ => {
                        comp.children.push(child_comp);
                    }
                }
            }
            child = (*child).next;
        }

        comp
    }
}

/// Parse an <attribute> declaration.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an <attribute> element node.
unsafe fn xsd_parse_attribute_node(node: *mut _xmlNode, schema: &XsdSchema) -> XsdComponent {
    unsafe {
        let mut comp = XsdComponent::new(XsdComponentType::Attribute);
        comp.name = get_attr(node, "name");
        comp.ref_name = get_attr(node, "ref");
        comp.form = get_attr(node, "form");

        // Resolve type attribute
        if let Some(type_name) = get_attr(node, "type") {
            comp.datatype = parse_datatype_kind(&type_name);
            if comp.datatype.is_none() {
                comp.base = Some(type_name);
            }
        }

        // Check for use attribute
        let use_attr = get_attr(node, "use");
        if let Some(ref use_val) = use_attr {
            if use_val == "required" {
                comp.min_occurs = 1;
            } else if use_val == "prohibited" {
                comp.min_occurs = 0;
                comp.max_occurs = 0;
            } else {
                // optional
                comp.min_occurs = 0;
            }
        } else {
            comp.min_occurs = 0; // optional by default
        }

        let _default = get_attr(node, "default");
        let _fixed = get_attr(node, "fixed");

        // Parse child components (inline simpleType)
        let mut child = (*node).children;
        while !child.is_null() {
            if (*child).type_ == XML_ELEMENT_NODE as c_int {
                let child_comp = xsd_parse_component(child, schema);
                match child_comp.component_type {
                    XsdComponentType::SimpleType => {
                        if let Some(ref name) = child_comp.name {
                            comp.base = Some(name.clone());
                        }
                        comp.children.push(child_comp);
                    }
                    _ => {}
                }
            }
            child = (*child).next;
        }

        comp
    }
}

/// Parse a <complexType> definition.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to a <complexType> element node.
unsafe fn xsd_parse_complex_type(node: *mut _xmlNode, schema: &XsdSchema) -> XsdComponent {
    unsafe {
        let mut comp = XsdComponent::new(XsdComponentType::ComplexType);
        comp.name = get_attr(node, "name");
        comp.mixed = get_attr_bool(node, "mixed");
        comp.is_abstract = get_attr_bool(node, "abstract");
        comp.is_final = get_attr_bool(node, "final");

        // Parse child components
        let mut child = (*node).children;
        while !child.is_null() {
            if (*child).type_ == XML_ELEMENT_NODE as c_int {
                let child_comp = xsd_parse_component(child, schema);
                match child_comp.component_type {
                    XsdComponentType::SimpleContent
                    | XsdComponentType::ComplexContent
                    | XsdComponentType::Sequence
                    | XsdComponentType::Choice
                    | XsdComponentType::All
                    | XsdComponentType::Group
                    | XsdComponentType::Any
                    | XsdComponentType::Annotation => {
                        if child_comp.component_type == XsdComponentType::SimpleContent {
                            // simpleContent may contain restriction/extension
                            comp.children.extend(child_comp.children);
                        } else if child_comp.component_type == XsdComponentType::ComplexContent {
                            // complexContent may contain restriction/extension
                            comp.children.extend(child_comp.children);
                        } else {
                            comp.children.push(child_comp);
                        }
                    }
                    XsdComponentType::Attribute | XsdComponentType::AnyAttribute => {
                        comp.attributes.push(child_comp);
                    }
                    _ => {
                        comp.children.push(child_comp);
                    }
                }
            }
            child = (*child).next;
        }

        comp
    }
}

/// Parse a <simpleType> definition.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to a <simpleType> element node.
unsafe fn xsd_parse_simple_type(node: *mut _xmlNode, schema: &XsdSchema) -> XsdComponent {
    unsafe {
        let mut comp = XsdComponent::new(XsdComponentType::SimpleType);
        comp.name = get_attr(node, "name");

        // Parse child components (restriction, list, union)
        let mut child = (*node).children;
        while !child.is_null() {
            if (*child).type_ == XML_ELEMENT_NODE as c_int {
                let child_comp = xsd_parse_component(child, schema);
                match child_comp.component_type {
                    XsdComponentType::Restriction
                    | XsdComponentType::List
                    | XsdComponentType::Union => {
                        comp.datatype = child_comp.datatype;
                        comp.base = child_comp.base;
                        comp.facets = child_comp.facets;
                        comp.children.extend(child_comp.children);
                    }
                    _ => {}
                }
            }
            child = (*child).next;
        }

        comp
    }
}

/// Parse a model group (<sequence>, <choice>, <all>).
///
/// # SAFETY
///
/// - `node` must be a valid pointer to the model group element node.
unsafe fn xsd_parse_model_group(
    node: *mut _xmlNode,
    ctype: XsdComponentType,
    schema: &XsdSchema,
) -> XsdComponent {
    unsafe {
        let mut comp = XsdComponent::new(ctype);
        comp.min_occurs = get_attr_occurs(node, "minOccurs", 1);
        comp.max_occurs = get_attr_occurs(node, "maxOccurs", 1);

        let mut child = (*node).children;
        while !child.is_null() {
            if (*child).type_ == XML_ELEMENT_NODE as c_int {
                let child_comp = xsd_parse_component(child, schema);
                match child_comp.component_type {
                    XsdComponentType::Annotation => {}
                    _ => {
                        comp.children.push(child_comp);
                    }
                }
            }
            child = (*child).next;
        }

        comp
    }
}

/// Parse a <restriction> element.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to a <restriction> element node.
unsafe fn xsd_parse_restriction(node: *mut _xmlNode, schema: &XsdSchema) -> XsdComponent {
    unsafe {
        let mut comp = XsdComponent::new(XsdComponentType::Restriction);
        comp.base = get_attr(node, "base");

        // Try to resolve the base type
        if let Some(ref base_name) = comp.base {
            comp.datatype = parse_datatype_kind(base_name);
        }

        // Parse facets and child components
        let mut child = (*node).children;
        while !child.is_null() {
            if (*child).type_ == XML_ELEMENT_NODE as c_int {
                let child_comp = xsd_parse_component(child, schema);
                match child_comp.component_type {
                    XsdComponentType::Sequence
                    | XsdComponentType::Choice
                    | XsdComponentType::All
                    | XsdComponentType::Group
                    | XsdComponentType::Any
                    | XsdComponentType::Annotation => {
                        comp.children.push(child_comp);
                    }
                    XsdComponentType::Attribute | XsdComponentType::AnyAttribute => {
                        comp.attributes.push(child_comp);
                    }
                    XsdComponentType::SimpleType => {
                        // Inline simpleType
                        comp.children.push(child_comp);
                    }
                    _ => {
                        // Facet types
                        if let Some(facet_kind) =
                            parse_facet_kind(&format!("{:?}", child_comp.component_type))
                        {
                            // Extract the value attribute
                            if let Some(val) = get_attr(child, "value") {
                                comp.facets.push((facet_kind, val));
                            }
                        }
                        // Also try by element name
                        let name_str = if !(*child).name.is_null() {
                            let mut len = 0;
                            while *(*child).name.add(len) != 0 {
                                len += 1;
                            }
                            let slice = std::slice::from_raw_parts((*child).name, len);
                            std::str::from_utf8(slice)
                                .ok()
                                .map(|s| {
                                    if let Some(pos) = s.find(':') {
                                        s[pos + 1..].to_string()
                                    } else {
                                        s.to_string()
                                    }
                                })
                                .unwrap_or_default()
                        } else {
                            String::new()
                        };
                        if !name_str.is_empty() {
                            if let Some(facet_kind) = parse_facet_kind(&name_str) {
                                if let Some(val) = get_attr(child, "value") {
                                    comp.facets.push((facet_kind, val));
                                }
                            }
                        }
                    }
                }
            }
            child = (*child).next;
        }

        comp
    }
}

/// Parse an <extension> element.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an <extension> element node.
unsafe fn xsd_parse_extension(node: *mut _xmlNode, schema: &XsdSchema) -> XsdComponent {
    unsafe {
        let mut comp = XsdComponent::new(XsdComponentType::Extension);
        comp.base = get_attr(node, "base");

        if let Some(ref base_name) = comp.base {
            comp.datatype = parse_datatype_kind(base_name);
        }

        // Parse child components
        let mut child = (*node).children;
        while !child.is_null() {
            if (*child).type_ == XML_ELEMENT_NODE as c_int {
                let child_comp = xsd_parse_component(child, schema);
                match child_comp.component_type {
                    XsdComponentType::Sequence
                    | XsdComponentType::Choice
                    | XsdComponentType::All
                    | XsdComponentType::Group
                    | XsdComponentType::Any
                    | XsdComponentType::Annotation => {
                        comp.children.push(child_comp);
                    }
                    XsdComponentType::Attribute | XsdComponentType::AnyAttribute => {
                        comp.attributes.push(child_comp);
                    }
                    _ => {}
                }
            }
            child = (*child).next;
        }

        comp
    }
}

/// Parse a <list> element.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to a <list> element node.
unsafe fn xsd_parse_list(node: *mut _xmlNode, schema: &XsdSchema) -> XsdComponent {
    unsafe {
        let mut comp = XsdComponent::new(XsdComponentType::List);

        if let Some(item_type) = get_attr(node, "itemType") {
            comp.base = Some(item_type.clone());
            comp.datatype = parse_datatype_kind(&item_type);
        }

        // Check for inline simpleType
        let mut child = (*node).children;
        while !child.is_null() {
            if (*child).type_ == XML_ELEMENT_NODE as c_int {
                let child_comp = xsd_parse_component(child, schema);
                match child_comp.component_type {
                    XsdComponentType::SimpleType => {
                        comp.datatype = child_comp.datatype;
                        comp.base = child_comp.base;
                        comp.facets = child_comp.facets;
                    }
                    _ => {}
                }
            }
            child = (*child).next;
        }

        comp
    }
}

/// Parse a <union> element.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to a <union> element node.
unsafe fn xsd_parse_union(node: *mut _xmlNode, schema: &XsdSchema) -> XsdComponent {
    unsafe {
        let mut comp = XsdComponent::new(XsdComponentType::Union);

        if let Some(member_types) = get_attr(node, "memberTypes") {
            comp.base = Some(member_types);
        }

        let mut child = (*node).children;
        while !child.is_null() {
            if (*child).type_ == XML_ELEMENT_NODE as c_int {
                let child_comp = xsd_parse_component(child, schema);
                match child_comp.component_type {
                    XsdComponentType::SimpleType => {
                        comp.children.push(child_comp);
                    }
                    _ => {}
                }
            }
            child = (*child).next;
        }

        comp
    }
}

/// Parse an <annotation> element.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an <annotation> element node.
unsafe fn xsd_parse_annotation(node: *mut _xmlNode) -> XsdComponent {
    unsafe {
        let mut comp = XsdComponent::new(XsdComponentType::Annotation);

        let mut child = (*node).children;
        while !child.is_null() {
            if (*child).type_ == XML_ELEMENT_NODE as c_int {
                if node_is(child, "documentation") || node_is(child, "appinfo") {
                    let text = get_node_text(child);
                    if !text.is_empty() {
                        comp.facets.push((XsdDatatypeKind::String, text));
                    }
                }
            }
            child = (*child).next;
        }

        comp
    }
}

/// Parse an <any> element.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an <any> element node.
unsafe fn xsd_parse_any(node: *mut _xmlNode, _schema: &XsdSchema) -> XsdComponent {
    unsafe {
        let mut comp = XsdComponent::new(XsdComponentType::Any);
        comp.min_occurs = get_attr_occurs(node, "minOccurs", 1);
        comp.max_occurs = get_attr_occurs(node, "maxOccurs", 1);

        let namespace_attr = get_attr(node, "namespace");
        if let Some(ref ns) = namespace_attr {
            if ns != "##any" {
                comp.target_namespace = Some(ns.clone());
            }
        }

        comp
    }
}

/// Parse a <group> element.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to a <group> element node.
unsafe fn xsd_parse_group(node: *mut _xmlNode, schema: &XsdSchema) -> XsdComponent {
    unsafe {
        let mut comp = XsdComponent::new(XsdComponentType::Group);
        comp.name = get_attr(node, "name");
        comp.ref_name = get_attr(node, "ref");
        comp.min_occurs = get_attr_occurs(node, "minOccurs", 1);
        comp.max_occurs = get_attr_occurs(node, "maxOccurs", 1);

        let mut child = (*node).children;
        while !child.is_null() {
            if (*child).type_ == XML_ELEMENT_NODE as c_int {
                let child_comp = xsd_parse_component(child, schema);
                match child_comp.component_type {
                    XsdComponentType::Annotation => {}
                    _ => {
                        comp.children.push(child_comp);
                    }
                }
            }
            child = (*child).next;
        }

        comp
    }
}

/// Parse an <attributeGroup> element.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an <attributeGroup> element node.
unsafe fn xsd_parse_attribute_group(node: *mut _xmlNode, schema: &XsdSchema) -> XsdComponent {
    unsafe {
        let mut comp = XsdComponent::new(XsdComponentType::AttributeGroup);
        comp.name = get_attr(node, "name");
        comp.ref_name = get_attr(node, "ref");

        let mut child = (*node).children;
        while !child.is_null() {
            if (*child).type_ == XML_ELEMENT_NODE as c_int {
                let child_comp = xsd_parse_component(child, schema);
                match child_comp.component_type {
                    XsdComponentType::Attribute | XsdComponentType::AnyAttribute => {
                        comp.attributes.push(child_comp);
                    }
                    _ => {}
                }
            }
            child = (*child).next;
        }

        comp
    }
}

/// Parse a facet element (pattern, enumeration, etc.).
///
/// # SAFETY
///
/// - `node` must be a valid pointer to a facet element node.
unsafe fn xsd_parse_facet(node: *mut _xmlNode) -> XsdComponent {
    unsafe {
        let name_str = if !(*node).name.is_null() {
            let mut len = 0;
            while *(*node).name.add(len) != 0 {
                len += 1;
            }
            let slice = std::slice::from_raw_parts((*node).name, len);
            std::str::from_utf8(slice)
                .ok()
                .map(|s| {
                    if let Some(pos) = s.find(':') {
                        s[pos + 1..].to_string()
                    } else {
                        s.to_string()
                    }
                })
                .unwrap_or_default()
        } else {
            String::new()
        };

        let facet_kind = parse_facet_kind(&name_str).unwrap_or(XsdDatatypeKind::String);
        let mut comp = XsdComponent::new(XsdComponentType::Schema);
        let val = get_attr(node, "value").unwrap_or_default();
        comp.facets.push((facet_kind, val));
        comp.datatype = Some(facet_kind);

        comp
    }
}

/// Parse a <simpleContent> element.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to a <simpleContent> element node.
unsafe fn xsd_parse_simple_content(node: *mut _xmlNode, schema: &XsdSchema) -> XsdComponent {
    unsafe {
        let mut comp = XsdComponent::new(XsdComponentType::Schema);

        let mut child = (*node).children;
        while !child.is_null() {
            if (*child).type_ == XML_ELEMENT_NODE as c_int {
                let child_comp = xsd_parse_component(child, schema);
                match child_comp.component_type {
                    XsdComponentType::Restriction | XsdComponentType::Extension => {
                        comp.children.push(child_comp);
                    }
                    _ => {}
                }
            }
            child = (*child).next;
        }

        comp
    }
}

/// Parse a <complexContent> element.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to a <complexContent> element node.
unsafe fn xsd_parse_complex_content(node: *mut _xmlNode, schema: &XsdSchema) -> XsdComponent {
    unsafe {
        let mut comp = XsdComponent::new(XsdComponentType::Schema);

        let mut child = (*node).children;
        while !child.is_null() {
            if (*child).type_ == XML_ELEMENT_NODE as c_int {
                let child_comp = xsd_parse_component(child, schema);
                match child_comp.component_type {
                    XsdComponentType::Restriction | XsdComponentType::Extension => {
                        comp.children.push(child_comp);
                    }
                    _ => {}
                }
            }
            child = (*child).next;
        }

        comp
    }
}

/// Parse an identity constraint (<unique>, <key>, <keyref>).
///
/// # SAFETY
///
/// - `node` must be a valid pointer to the identity constraint element node.
unsafe fn xsd_parse_identity_constraint(
    node: *mut _xmlNode,
    ctype: XsdComponentType,
    schema: &XsdSchema,
) -> XsdComponent {
    unsafe {
        let mut comp = XsdComponent::new(ctype);
        comp.name = get_attr(node, "name");

        if ctype == XsdComponentType::KeyRef {
            comp.ref_name = get_attr(node, "refer");
        }

        let mut child = (*node).children;
        while !child.is_null() {
            if (*child).type_ == XML_ELEMENT_NODE as c_int {
                let child_comp = xsd_parse_component(child, schema);
                match child_comp.component_type {
                    XsdComponentType::Selector | XsdComponentType::Field => {
                        comp.children.push(child_comp);
                    }
                    _ => {}
                }
            }
            child = (*child).next;
        }

        comp
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Datatype Validation
// ═══════════════════════════════════════════════════════════════════════════════

/// Validate a value against an XSD datatype with optional facets.
///
/// # UPSTREAM-PARITY
///
/// Equivalent to libxml2's schema type validation functions.
pub fn xsd_validate_datatype(
    kind: &XsdDatatypeKind,
    value: &str,
    facets: &[(XsdDatatypeKind, String)],
) -> bool {
    // First validate the base type
    if !validate_base_type(kind, value) {
        return false;
    }

    // Then validate facets.
    // UPSTREAM-PARITY: Enumeration facets use OR semantics (value must match
    // at least one enumeration value). All other facets use AND semantics
    // (value must satisfy all facets).
    let mut has_enumeration = false;
    let mut enumeration_match = false;

    for (facet_kind, facet_value) in facets {
        if *facet_kind == XsdDatatypeKind::FacetEnumeration {
            has_enumeration = true;
            if xsd_validate_facet(kind, value, facet_kind, facet_value) {
                enumeration_match = true;
            }
        } else if !xsd_validate_facet(kind, value, facet_kind, facet_value) {
            return false;
        }
    }

    // If there were enumeration facets, at least one must match
    if has_enumeration && !enumeration_match {
        return false;
    }

    true
}

/// Validate a value against a specific facet.
pub fn xsd_validate_facet(
    _kind: &XsdDatatypeKind,
    value: &str,
    facet_kind: &XsdDatatypeKind,
    facet_value: &str,
) -> bool {
    match facet_kind {
        XsdDatatypeKind::FacetPattern => {
            // Simple regex matching (simplified — just check substring containment
            // for common patterns like [a-zA-Z]+, etc.)
            match facet_value {
                r"\d+" => value.chars().all(|c| c.is_ascii_digit()),
                r"\d*" => value.is_empty() || value.chars().all(|c| c.is_ascii_digit()),
                r"[a-zA-Z]+" => value.chars().all(|c| c.is_ascii_alphabetic()),
                r"[a-zA-Z]*" => value.is_empty() || value.chars().all(|c| c.is_ascii_alphabetic()),
                r"[a-zA-Z0-9]+" => value.chars().all(|c| c.is_ascii_alphanumeric()),
                r"[a-zA-Z0-9_\-]+" => value
                    .chars()
                    .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'),
                r"[a-zA-Z_][a-zA-Z0-9_\-\.]*" => {
                    if value.is_empty() {
                        return false;
                    }
                    let first = value.chars().next().unwrap();
                    if !first.is_ascii_alphabetic() && first != '_' {
                        return false;
                    }
                    value
                        .chars()
                        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.')
                }
                r"[a-zA-Z_][\w\-\.]*" => {
                    if value.is_empty() {
                        return false;
                    }
                    let first = value.chars().next().unwrap();
                    if !first.is_ascii_alphabetic() && first != '_' {
                        return false;
                    }
                    value
                        .chars()
                        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.')
                }
                r"\i\c*" => {
                    // XML Name pattern: NameStartChar followed by NameChars
                    if value.is_empty() {
                        return false;
                    }
                    let first = value.chars().next().unwrap();
                    if !is_name_start_char(first) {
                        return false;
                    }
                    value.chars().skip(1).all(is_name_char)
                }
                r"\c+" => {
                    if value.is_empty() {
                        return false;
                    }
                    value.chars().all(is_name_char)
                }
                // Default: try basic glob-style matching
                _ => {
                    if facet_value.starts_with('^') && facet_value.ends_with('$') {
                        let inner = &facet_value[1..facet_value.len() - 1];
                        simple_glob_match(inner, value)
                    } else {
                        // Default: accept if we don't understand the pattern
                        true
                    }
                }
            }
        }
        XsdDatatypeKind::FacetEnumeration => {
            // Check if the value matches the enumeration literal
            value == facet_value
        }
        XsdDatatypeKind::FacetMinInclusive => {
            compare_strings(value, facet_value) != std::cmp::Ordering::Less
        }
        XsdDatatypeKind::FacetMaxInclusive => {
            compare_strings(value, facet_value) != std::cmp::Ordering::Greater
        }
        XsdDatatypeKind::FacetMinExclusive => {
            compare_strings(value, facet_value) == std::cmp::Ordering::Greater
        }
        XsdDatatypeKind::FacetMaxExclusive => {
            compare_strings(value, facet_value) == std::cmp::Ordering::Less
        }
        XsdDatatypeKind::FacetMinLength => {
            let min = facet_value.parse::<usize>().unwrap_or(0);
            value.chars().count() >= min
        }
        XsdDatatypeKind::FacetMaxLength => {
            let max = facet_value.parse::<usize>().unwrap_or(usize::MAX);
            value.chars().count() <= max
        }
        XsdDatatypeKind::FacetLength => {
            let len = facet_value.parse::<usize>().unwrap_or(0);
            value.chars().count() == len
        }
        XsdDatatypeKind::FacetWhiteSpace => {
            // whiteSpace facet: value, replace, collapse
            match facet_value {
                "replace" => {
                    // Any whitespace is valid (but should be tab/newline -> space)
                    // We just accept the value
                    true
                }
                "collapse" => {
                    // Leading/trailing whitespace collapsed, internal reduced
                    true
                }
                _ => true,
            }
        }
        XsdDatatypeKind::FacetFractionDigits | XsdDatatypeKind::FacetTotalDigits => {
            // Numeric precision facets — simplified: just check if it's a valid number
            value.parse::<f64>().is_ok()
        }
        _ => true,
    }
}

/// Simple glob-style pattern matching for XSD pattern facets.
fn simple_glob_match(pattern: &str, value: &str) -> bool {
    let pattern_chars: Vec<char> = pattern.chars().collect();
    let value_chars: Vec<char> = value.chars().collect();

    let mut pi = 0;
    let mut vi = 0;
    let mut backtrack_p = None;
    let mut backtrack_v = 0;

    while vi < value_chars.len() {
        if pi < pattern_chars.len()
            && (pattern_chars[pi] == value_chars[vi] || pattern_chars[pi] == '.')
        {
            pi += 1;
            vi += 1;
        } else if pi < pattern_chars.len() && pattern_chars[pi] == '*' {
            backtrack_p = Some(pi);
            backtrack_v = vi + 1;
            pi += 1;
        } else if pi < pattern_chars.len() && pattern_chars[pi] == '+' {
            // '+' = one or more of the next char
            if pi + 1 < pattern_chars.len() && pattern_chars[pi + 1] == value_chars[vi] {
                pi += 1;
                vi += 1;
                // Match one or more
                while vi < value_chars.len() && value_chars[vi] == pattern_chars[pi] {
                    vi += 1;
                }
                pi += 1;
            } else {
                return false;
            }
        } else if let Some(bp) = backtrack_p {
            pi = bp + 1;
            vi = backtrack_v;
            backtrack_v += 1;
        } else {
            return false;
        }
    }

    // Skip remaining * or + in pattern
    while pi < pattern_chars.len() && (pattern_chars[pi] == '*' || pattern_chars[pi] == '+') {
        if pattern_chars[pi] == '+' && vi == value_chars.len() {
            return false; // '+' requires at least one match
        }
        pi += 1;
    }

    pi == pattern_chars.len()
}

/// Check if a character is an XML NameStartChar.
fn is_name_start_char(c: char) -> bool {
    c.is_ascii_alphabetic()
        || c == '_'
        || c == ':'
        || (c >= '\u{00C0}' && c <= '\u{00D6}')
        || (c >= '\u{00D8}' && c <= '\u{00F6}')
        || (c >= '\u{00F8}' && c <= '\u{02FF}')
        || (c >= '\u{0370}' && c <= '\u{037D}')
        || (c >= '\u{037F}' && c <= '\u{1FFF}')
        || (c >= '\u{200C}' && c <= '\u{200D}')
        || (c >= '\u{2070}' && c <= '\u{218F}')
        || (c >= '\u{2C00}' && c <= '\u{2FEF}')
        || (c >= '\u{3001}' && c <= '\u{D7FF}')
        || (c >= '\u{F900}' && c <= '\u{FDCF}')
        || (c >= '\u{FDF0}' && c <= '\u{FFFD}')
}

/// Check if a character is an XML NameChar.
fn is_name_char(c: char) -> bool {
    is_name_start_char(c)
        || c.is_ascii_digit()
        || c == '-'
        || c == '.'
        || c == '\u{00B7}'
        || (c >= '\u{0300}' && c <= '\u{036F}')
        || (c >= '\u{203F}' && c <= '\u{2040}')
}

/// Compare two string values for facet ordering.
fn compare_strings(a: &str, b: &str) -> std::cmp::Ordering {
    // Try numeric comparison first
    if let (Ok(na), Ok(nb)) = (a.parse::<f64>(), b.parse::<f64>()) {
        return na.partial_cmp(&nb).unwrap_or(std::cmp::Ordering::Equal);
    }
    // Try integer comparison
    if let (Ok(na), Ok(nb)) = (a.parse::<i64>(), b.parse::<i64>()) {
        return na.cmp(&nb);
    }
    // Fall back to lexicographic
    a.cmp(b)
}

/// Validate a value against the base type constraints.
fn validate_base_type(kind: &XsdDatatypeKind, value: &str) -> bool {
    match kind {
        XsdDatatypeKind::String => true,
        XsdDatatypeKind::NormalizedString => {
            // No tabs, newlines, or carriage returns
            !value.contains('\t') && !value.contains('\n') && !value.contains('\r')
        }
        XsdDatatypeKind::Token => {
            // No leading/trailing whitespace, no consecutive internal whitespace
            if value.is_empty() {
                return true;
            }
            if value.starts_with(' ') || value.ends_with(' ') {
                return false;
            }
            !value.contains("  ")
                && !value.contains('\t')
                && !value.contains('\n')
                && !value.contains('\r')
        }
        XsdDatatypeKind::Language => {
            // RFC 4646 / BCP 47: langtag = (language ["-" script] ["-" region] *("-" variant))
            // Simplified: [a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*
            if value.is_empty() {
                return false;
            }
            let segments: Vec<&str> = value.split('-').collect();
            if segments.is_empty() {
                return false;
            }
            // First segment must be alphabetic only
            if segments[0].is_empty() || !segments[0].chars().all(|c| c.is_ascii_alphabetic()) {
                return false;
            }
            if segments[0].len() > 8 {
                return false;
            }
            // Remaining segments can be alphanumeric
            for seg in &segments[1..] {
                if seg.is_empty() || seg.len() > 8 {
                    return false;
                }
                if !seg.chars().all(|c| c.is_ascii_alphanumeric()) {
                    return false;
                }
            }
            true
        }
        XsdDatatypeKind::Name => {
            if value.is_empty() {
                return false;
            }
            let mut chars = value.chars();
            let first = chars.next().unwrap();
            if !is_name_start_char(first) {
                return false;
            }
            chars.all(is_name_char)
        }
        XsdDatatypeKind::NCName
        | XsdDatatypeKind::Id
        | XsdDatatypeKind::Idref
        | XsdDatatypeKind::Entity => {
            // NCName is a Name with no colon
            if value.is_empty() || value.contains(':') {
                return false;
            }
            let mut chars = value.chars();
            let first = chars.next().unwrap();
            if !is_name_start_char(first) {
                return false;
            }
            chars.all(is_name_char)
        }
        XsdDatatypeKind::Boolean => {
            matches!(value, "true" | "false" | "1" | "0")
        }
        XsdDatatypeKind::Decimal
        | XsdDatatypeKind::Integer
        | XsdDatatypeKind::NonPositiveInteger
        | XsdDatatypeKind::NegativeInteger
        | XsdDatatypeKind::Long
        | XsdDatatypeKind::Int
        | XsdDatatypeKind::Short
        | XsdDatatypeKind::Byte
        | XsdDatatypeKind::NonNegativeInteger
        | XsdDatatypeKind::UnsignedLong
        | XsdDatatypeKind::UnsignedInt
        | XsdDatatypeKind::UnsignedShort
        | XsdDatatypeKind::UnsignedByte
        | XsdDatatypeKind::PositiveInteger => {
            // Decimal/integer validation
            if value.is_empty() {
                return false;
            }
            let mut chars = value.chars().peekable();
            if *chars.peek().unwrap_or(&'\0') == '-' || *chars.peek().unwrap_or(&'\0') == '+' {
                chars.next();
            }
            let mut has_dot = false;
            let mut has_digit = false;
            for c in chars {
                if c == '.' {
                    if has_dot {
                        return false;
                    }
                    has_dot = true;
                } else if c.is_ascii_digit() {
                    has_digit = true;
                } else {
                    return false;
                }
            }
            if !has_digit {
                return false;
            }

            // Additional constraints for derived integer types
            // Integer and all derived integer types reject decimal points
            if has_dot && *kind != XsdDatatypeKind::Decimal {
                return false;
            }

            match kind {
                XsdDatatypeKind::NonPositiveInteger => {
                    if let Ok(v) = value.parse::<i64>() {
                        v <= 0
                    } else {
                        false
                    }
                }
                XsdDatatypeKind::NegativeInteger => {
                    if let Ok(v) = value.parse::<i64>() {
                        v < 0
                    } else {
                        false
                    }
                }
                XsdDatatypeKind::NonNegativeInteger => {
                    if let Ok(v) = value.parse::<i64>() {
                        v >= 0
                    } else {
                        false
                    }
                }
                XsdDatatypeKind::PositiveInteger => {
                    if let Ok(v) = value.parse::<i64>() {
                        v > 0
                    } else {
                        false
                    }
                }
                XsdDatatypeKind::UnsignedLong
                | XsdDatatypeKind::UnsignedInt
                | XsdDatatypeKind::UnsignedShort
                | XsdDatatypeKind::UnsignedByte => {
                    if let Ok(v) = value.parse::<u64>() {
                        match kind {
                            XsdDatatypeKind::UnsignedInt => v <= u64::from(u32::MAX),
                            XsdDatatypeKind::UnsignedShort => v <= u64::from(u16::MAX),
                            XsdDatatypeKind::UnsignedByte => v <= u64::from(u8::MAX),
                            _ => true,
                        }
                    } else {
                        false
                    }
                }
                XsdDatatypeKind::Long => value.parse::<i64>().is_ok(),
                XsdDatatypeKind::Int => value.parse::<i32>().is_ok(),
                XsdDatatypeKind::Short => value.parse::<i16>().is_ok(),
                XsdDatatypeKind::Byte => value.parse::<i8>().is_ok(),
                _ => true,
            }
        }
        XsdDatatypeKind::Float | XsdDatatypeKind::Double => {
            // Allow INF, -INF, NaN
            matches!(value, "INF" | "-INF" | "NaN") || value.parse::<f64>().is_ok()
        }
        XsdDatatypeKind::Duration => {
            // P[nY][nM][nD][T[nH][nM][nS]]
            if !value.starts_with('-') && !value.starts_with('P') {
                return false;
            }
            let dur = if value.starts_with('-') {
                &value[1..]
            } else {
                value
            };
            if !dur.starts_with('P') {
                return false;
            }
            let rest = &dur[1..];
            if rest.is_empty() {
                return false;
            }
            let has_t = rest.contains('T');
            let date_part = if has_t {
                &rest[..rest.find('T').unwrap()]
            } else {
                rest
            };
            if has_t {
                let time_part = &rest[rest.find('T').unwrap() + 1..];
                if time_part.is_empty() {
                    return false;
                }
            }
            true
        }
        XsdDatatypeKind::DateTime => {
            // YYYY-MM-DDThh:mm:ss[.sss][Z|±hh:mm]
            if value.len() < 19 {
                return false;
            }
            let chars: Vec<char> = value.chars().collect();
            chars[4] == '-'
                && chars[7] == '-'
                && chars[10] == 'T'
                && chars[13] == ':'
                && chars[16] == ':'
        }
        XsdDatatypeKind::Date => {
            // YYYY-MM-DD[Z|±hh:mm]
            if value.len() < 10 {
                return false;
            }
            let chars: Vec<char> = value.chars().collect();
            chars[4] == '-' && chars[7] == '-'
        }
        XsdDatatypeKind::Time => {
            // hh:mm:ss[.sss][Z|±hh:mm]
            if value.len() < 8 {
                return false;
            }
            let chars: Vec<char> = value.chars().collect();
            chars[2] == ':' && chars[5] == ':'
        }
        XsdDatatypeKind::GYear => {
            // YYYY[Z|±hh:mm]
            if value.len() < 4 {
                return false;
            }
            value.chars().take(4).all(|c| c.is_ascii_digit())
        }
        XsdDatatypeKind::GYearMonth => {
            // YYYY-MM[Z|±hh:mm]
            if value.len() < 7 {
                return false;
            }
            let chars: Vec<char> = value.chars().collect();
            chars[4] == '-'
        }
        XsdDatatypeKind::GMonthDay => {
            // --MM-DD[Z|±hh:mm]
            if value.len() < 6 || !value.starts_with("--") {
                return false;
            }
            let chars: Vec<char> = value.chars().collect();
            chars[4] == '-'
        }
        XsdDatatypeKind::GDay => {
            // ---DD[Z|±hh:mm]
            value.starts_with("---") && value.len() >= 4
        }
        XsdDatatypeKind::GMonth => {
            // --MM[Z|±hh:mm]
            value.starts_with("--") && value.len() >= 3
        }
        XsdDatatypeKind::HexBinary => {
            if value.len() % 2 != 0 {
                return false;
            }
            value.chars().all(|c| c.is_ascii_hexdigit())
        }
        XsdDatatypeKind::Base64Binary => {
            // Simplified: just check characters are valid base64
            if value.is_empty() {
                return true;
            }
            let valid_chars =
                |c: char| c.is_ascii_alphanumeric() || c == '+' || c == '/' || c == '=';
            value.chars().all(valid_chars)
        }
        XsdDatatypeKind::AnyURI => {
            // Simplified: just check it's not empty
            !value.is_empty()
        }
        XsdDatatypeKind::QName => {
            // NCName or Prefix:NCName
            if let Some(pos) = value.find(':') {
                let prefix = &value[..pos];
                let local = &value[pos + 1..];
                is_ncname(prefix) && is_ncname(local)
            } else {
                is_ncname(value)
            }
        }
        XsdDatatypeKind::Notation => {
            // Same as QName
            !value.is_empty()
        }
        XsdDatatypeKind::NormalizedString => {
            // No tab, newline, or carriage return
            !value.contains('\t') && !value.contains('\n') && !value.contains('\r')
        }
        XsdDatatypeKind::Token => {
            // NormalizedString + no leading/trailing whitespace, no internal double spaces
            validate_base_type(&XsdDatatypeKind::NormalizedString, value)
                && !value.starts_with(' ')
                && !value.ends_with(' ')
                && !value.contains("  ")
        }
        XsdDatatypeKind::Language => {
            // [a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*
            if value.is_empty() {
                return false;
            }
            let parts: Vec<&str> = value.split('-').collect();
            if parts.is_empty() {
                return false;
            }
            if parts[0].len() > 8 || !parts[0].chars().all(|c| c.is_ascii_alphabetic()) {
                return false;
            }
            parts.iter().skip(1).all(|p| {
                !p.is_empty() && p.len() <= 8 && p.chars().all(|c| c.is_ascii_alphanumeric())
            })
        }
        XsdDatatypeKind::Nmtoken => !value.is_empty() && value.chars().all(is_name_char),
        XsdDatatypeKind::Nmtokens => {
            !value.is_empty()
                && value
                    .split_whitespace()
                    .all(|t| !t.is_empty() && t.chars().all(is_name_char))
        }
        XsdDatatypeKind::Name => {
            !value.is_empty() && {
                let first = value.chars().next().unwrap();
                is_name_start_char(first) && value.chars().skip(1).all(is_name_char)
            }
        }
        XsdDatatypeKind::NCName => is_ncname(value),
        XsdDatatypeKind::Id | XsdDatatypeKind::Idref | XsdDatatypeKind::Entity => is_ncname(value),
        XsdDatatypeKind::Idrefs | XsdDatatypeKind::Entities => {
            !value.is_empty() && value.split_whitespace().all(|t| is_ncname(t))
        }
        // Facet types are always "valid" as values
        XsdDatatypeKind::FacetPattern
        | XsdDatatypeKind::FacetEnumeration
        | XsdDatatypeKind::FacetMinInclusive
        | XsdDatatypeKind::FacetMaxInclusive
        | XsdDatatypeKind::FacetMinExclusive
        | XsdDatatypeKind::FacetMaxExclusive
        | XsdDatatypeKind::FacetMinLength
        | XsdDatatypeKind::FacetMaxLength
        | XsdDatatypeKind::FacetLength
        | XsdDatatypeKind::FacetWhiteSpace
        | XsdDatatypeKind::FacetFractionDigits
        | XsdDatatypeKind::FacetTotalDigits => true,
    }
}

/// Check if a string is a valid NCName.
fn is_ncname(value: &str) -> bool {
    if value.is_empty() {
        return false;
    }
    let first = value.chars().next().unwrap();
    if !is_name_start_char(first) || first == ':' {
        return false;
    }
    value.chars().skip(1).all(|c| is_name_char(c) && c != ':')
}

// ═══════════════════════════════════════════════════════════════════════════════
// Document Validation
// ═══════════════════════════════════════════════════════════════════════════════

/// Validate an XML document against a schema.
///
/// # UPSTREAM-PARITY
///
/// Equivalent to libxml2's `xmlSchemaValidateDoc`.
pub fn xsd_validate(schema: &XsdSchema, doc: &str) -> Result<(), Vec<String>> {
    let doc_ptr = unsafe {
        crate::abi::exports_xml2::xmlReadMemory(
            doc.as_ptr() as *const c_char,
            doc.len() as c_int,
            b"doc.xml\0".as_ptr() as *const c_char,
            ptr::null(),
            0,
        )
    };

    if doc_ptr.is_null() {
        return Err(vec!["Failed to parse XML document".to_string()]);
    }

    let mut ctxt = XsdValidCtxt::new();
    ctxt.schema = Some(schema.clone());

    let result = unsafe { xsd_validate_doc(schema, doc_ptr, &mut ctxt) };

    unsafe {
        crate::abi::exports_xml2::xmlFreeDoc(doc_ptr);
    }

    if result {
        Ok(())
    } else {
        Err(ctxt.errors)
    }
}

/// Validate a parsed document against a schema.
///
/// # SAFETY
///
/// - `doc` must be a valid pointer to an _xmlDoc.
unsafe fn xsd_validate_doc(schema: &XsdSchema, doc: *mut _xmlDoc, ctxt: &mut XsdValidCtxt) -> bool {
    unsafe {
        let root = (*doc).children;
        if root.is_null() {
            ctxt.errors.push("Document has no root element".to_string());
            ctxt.nb_errors += 1;
            return false;
        }

        // Find the root element
        let mut root_elem = root;
        while !root_elem.is_null() && (*root_elem).type_ != XML_ELEMENT_NODE as c_int {
            root_elem = (*root_elem).next;
        }

        if root_elem.is_null() {
            ctxt.errors.push("Document has no root element".to_string());
            ctxt.nb_errors += 1;
            return false;
        }

        // Get the root element name
        let root_name = get_node_qname(root_elem);

        // Find matching global element declaration
        let global_elem = schema.components.iter().find(|c| {
            c.component_type == XsdComponentType::Element && c.name.as_deref() == Some(&root_name)
        });

        if let Some(global) = global_elem {
            xsd_validate_element(global, root_elem, schema, ctxt)
        } else {
            // Try finding by any matching component
            let mut valid = true;
            for component in &schema.components {
                if component.component_type == XsdComponentType::Element {
                    if let Some(ref name) = component.name {
                        if *name == root_name {
                            valid = xsd_validate_element(component, root_elem, schema, ctxt);
                            break;
                        }
                    }
                }
            }
            valid
        }
    }
}

/// Validate an element node against a component declaration.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an XML element node.
fn xsd_validate_element(
    component: &XsdComponent,
    node: *mut _xmlNode,
    schema: &XsdSchema,
    ctxt: &mut XsdValidCtxt,
) -> bool {
    unsafe {
        let mut valid = true;

        // Get the element's local name
        let node_name = get_node_qname(node);

        // Check element name
        if let Some(ref comp_name) = component.name {
            if comp_name != &node_name {
                ctxt.errors.push(format!(
                    "Element '{}' does not match expected '{}'",
                    node_name, comp_name
                ));
                ctxt.nb_errors += 1;
                return false;
            }
        }

        // If there's a type definition (complexType or simpleType) among children, use it
        let type_comp = component.children.iter().find(|c| {
            c.component_type == XsdComponentType::ComplexType
                || c.component_type == XsdComponentType::SimpleType
        });

        if let Some(tc) = type_comp {
            match tc.component_type {
                XsdComponentType::ComplexType => {
                    valid &= xsd_validate_complex_type(tc, node, schema, ctxt);
                }
                XsdComponentType::SimpleType => {
                    let text = get_node_text(node);
                    if let Some(ref dt) = tc.datatype {
                        if !xsd_validate_datatype(dt, &text, &tc.facets) {
                            ctxt.errors.push(format!(
                                "Element '{}' has invalid value '{}' for type '{:?}'",
                                node_name, text, dt
                            ));
                            ctxt.nb_errors += 1;
                            valid = false;
                        }
                    }
                }
                _ => {}
            }
        } else if let Some(ref dt) = component.datatype {
            // Direct datatype on the element (simple content)
            let text = get_node_text(node);
            if !xsd_validate_datatype(dt, &text, &component.facets) {
                ctxt.errors.push(format!(
                    "Element '{}' has invalid value '{}' for type '{:?}'",
                    node_name, text, dt
                ));
                ctxt.nb_errors += 1;
                valid = false;
            }
        } else {
            // No type information — validate children against content model
            valid &= xsd_validate_content(component, node, schema, ctxt);
        }

        valid
    }
}

/// Validate a complex type against an element node.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an XML element node.
fn xsd_validate_complex_type(
    component: &XsdComponent,
    node: *mut _xmlNode,
    schema: &XsdSchema,
    ctxt: &mut XsdValidCtxt,
) -> bool {
    unsafe {
        let mut valid = true;

        // Validate attributes
        for attr in &component.attributes {
            match attr.component_type {
                XsdComponentType::Attribute => {
                    valid &= xsd_validate_attribute(attr, node, schema, ctxt);
                }
                XsdComponentType::AnyAttribute => {
                    // Any attribute is allowed
                }
                _ => {}
            }
        }

        // Validate child content (sequence, choice, all)
        for child in &component.children {
            match child.component_type {
                XsdComponentType::Sequence | XsdComponentType::Choice | XsdComponentType::All => {
                    valid &= xsd_validate_model_group(child, node, schema, ctxt);
                }
                XsdComponentType::Restriction | XsdComponentType::Extension => {
                    // Handle restriction/extension content
                    valid &= xsd_validate_restriction_extension(child, node, schema, ctxt);
                }
                XsdComponentType::Any => {
                    // Any element is allowed
                }
                _ => {}
            }
        }

        valid
    }
}

/// Validate a model group (sequence, choice, all) against an element's children.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an XML element node.
fn xsd_validate_model_group(
    component: &XsdComponent,
    node: *mut _xmlNode,
    schema: &XsdSchema,
    ctxt: &mut XsdValidCtxt,
) -> bool {
    unsafe {
        let mut valid = true;

        // Collect element children
        let mut child_nodes: Vec<*mut _xmlNode> = Vec::new();
        let mut child = (*node).children;
        while !child.is_null() {
            if (*child).type_ == XML_ELEMENT_NODE as c_int {
                child_nodes.push(child);
            }
            child = (*child).next;
        }

        match component.component_type {
            XsdComponentType::Sequence => {
                // Validate in-order
                let mut child_idx = 0;
                for part in &component.children {
                    let min = part.min_occurs;
                    let max = part.max_occurs;
                    let match_name = part.name.as_deref().unwrap_or("");
                    let match_ref = part.ref_name.as_deref().unwrap_or("");

                    let mut count = 0;
                    while child_idx < child_nodes.len() && (max == -1 || count < max) {
                        let child_node = child_nodes[child_idx];
                        let child_name = get_node_qname(child_node);

                        if part.component_type == XsdComponentType::Any {
                            count += 1;
                            child_idx += 1;
                        } else if !match_name.is_empty() && child_name == match_name {
                            count += 1;
                            child_idx += 1;
                        } else if !match_ref.is_empty() && child_name == match_ref {
                            count += 1;
                            child_idx += 1;
                        } else if count >= min {
                            break;
                        } else {
                            ctxt.errors.push(format!(
                                "Expected element '{}' but found '{}'",
                                match_name, child_name
                            ));
                            ctxt.nb_errors += 1;
                            valid = false;
                            child_idx += 1;
                            break;
                        }
                    }

                    if count < min {
                        ctxt.errors.push(format!(
                            "Element '{}' occurs {} times, minimum is {}",
                            if match_name.is_empty() {
                                "?"
                            } else {
                                match_name
                            },
                            count,
                            min
                        ));
                        ctxt.nb_errors += 1;
                        valid = false;
                    }
                }

                // Check for unexpected extra children
                if child_idx < child_nodes.len() {
                    let extra = get_node_qname(child_nodes[child_idx]);
                    ctxt.errors
                        .push(format!("Unexpected element '{}' in sequence", extra));
                    ctxt.nb_errors += 1;
                    valid = false;
                }
            }
            XsdComponentType::Choice => {
                // At least one of the choices must match
                let mut matched = false;
                for child_node in &child_nodes {
                    let child_name = get_node_qname(*child_node);
                    for part in &component.children {
                        let match_name = part.name.as_deref().unwrap_or("");
                        let match_ref = part.ref_name.as_deref().unwrap_or("");

                        if part.component_type == XsdComponentType::Any {
                            matched = true;
                        } else if (!match_name.is_empty() && child_name == match_name)
                            || (!match_ref.is_empty() && child_name == match_ref)
                        {
                            matched = true;
                            break;
                        }
                    }
                    if !matched {
                        ctxt.errors
                            .push(format!("Element '{}' is not valid in choice", child_name));
                        ctxt.nb_errors += 1;
                        valid = false;
                    }
                    matched = false; // Reset for next child
                }
            }
            XsdComponentType::All => {
                // All children must match in any order (maxOccurs=1)
                for child_node in &child_nodes {
                    let child_name = get_node_qname(*child_node);
                    let mut matched = false;
                    for part in &component.children {
                        let match_name = part.name.as_deref().unwrap_or("");
                        if !match_name.is_empty() && child_name == match_name {
                            matched = true;
                            break;
                        }
                    }
                    if !matched {
                        ctxt.errors.push(format!(
                            "Element '{}' is not valid in all group",
                            child_name
                        ));
                        ctxt.nb_errors += 1;
                        valid = false;
                    }
                }
            }
            _ => {}
        }

        valid
    }
}

/// Validate a restriction or extension content.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an XML element node.
fn xsd_validate_restriction_extension(
    component: &XsdComponent,
    node: *mut _xmlNode,
    schema: &XsdSchema,
    ctxt: &mut XsdValidCtxt,
) -> bool {
    unsafe {
        let mut valid = true;

        // Validate attributes
        for attr in &component.attributes {
            match attr.component_type {
                XsdComponentType::Attribute => {
                    valid &= xsd_validate_attribute(attr, node, schema, ctxt);
                }
                _ => {}
            }
        }

        // Validate child content
        for child in &component.children {
            match child.component_type {
                XsdComponentType::Sequence | XsdComponentType::Choice | XsdComponentType::All => {
                    valid &= xsd_validate_model_group(child, node, schema, ctxt);
                }
                _ => {}
            }
        }

        // Validate datatype if present (for simple content restriction)
        if let Some(ref dt) = component.datatype {
            let text = get_node_text(node);
            if !xsd_validate_datatype(dt, &text, &component.facets) {
                let node_name = get_node_qname(node);
                ctxt.errors.push(format!(
                    "Element '{}' has invalid value '{}' for type '{:?}'",
                    node_name, text, dt
                ));
                ctxt.nb_errors += 1;
                valid = false;
            }
        }

        valid
    }
}

/// Validate an attribute against an element node.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an XML element node.
fn xsd_validate_attribute(
    component: &XsdComponent,
    node: *mut _xmlNode,
    _schema: &XsdSchema,
    ctxt: &mut XsdValidCtxt,
) -> bool {
    unsafe {
        let attr_name = component.name.as_deref().unwrap_or("");
        if attr_name.is_empty() {
            return true;
        }

        // Check if the attribute exists on the element
        let attr_value = get_attr(node, attr_name);

        let is_required = component.min_occurs > 0;

        match attr_value {
            Some(ref val) => {
                // Validate attribute value against its datatype
                if let Some(ref dt) = component.datatype {
                    if !xsd_validate_datatype(dt, val, &component.facets) {
                        ctxt.errors.push(format!(
                            "Attribute '{}' has invalid value '{}' for type '{:?}'",
                            attr_name, val, dt
                        ));
                        ctxt.nb_errors += 1;
                        return false;
                    }
                }
                true
            }
            None => {
                if is_required {
                    ctxt.errors
                        .push(format!("Required attribute '{}' is missing", attr_name));
                    ctxt.nb_errors += 1;
                    false
                } else {
                    true
                }
            }
        }
    }
}

/// Validate child content (no explicit type — just check children).
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an XML element node.
fn xsd_validate_content(
    component: &XsdComponent,
    node: *mut _xmlNode,
    schema: &XsdSchema,
    ctxt: &mut XsdValidCtxt,
) -> bool {
    unsafe {
        let mut valid = true;

        for child_comp in &component.children {
            match child_comp.component_type {
                XsdComponentType::Sequence | XsdComponentType::Choice | XsdComponentType::All => {
                    valid &= xsd_validate_model_group(child_comp, node, schema, ctxt);
                }
                XsdComponentType::Element => {
                    // Inline element declaration in a model group
                    valid &= xsd_validate_element_inline(child_comp, node, schema, ctxt);
                }
                _ => {}
            }
        }

        valid
    }
}

/// Validate an inline element declaration (element inside sequence/choice).
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an XML element node.
fn xsd_validate_element_inline(
    component: &XsdComponent,
    node: *mut _xmlNode,
    schema: &XsdSchema,
    ctxt: &mut XsdValidCtxt,
) -> bool {
    unsafe {
        let mut valid = true;
        let mut child = (*node).children;

        while !child.is_null() {
            if (*child).type_ == XML_ELEMENT_NODE as c_int {
                let child_name = get_node_qname(child);

                let match_name = component.name.as_deref().unwrap_or("");
                let match_ref = component.ref_name.as_deref().unwrap_or("");

                if (!match_name.is_empty() && child_name == match_name)
                    || (!match_ref.is_empty() && child_name == match_ref)
                {
                    // Check inline type
                    let type_comp = component.children.iter().find(|c| {
                        c.component_type == XsdComponentType::ComplexType
                            || c.component_type == XsdComponentType::SimpleType
                    });

                    if let Some(tc) = type_comp {
                        match tc.component_type {
                            XsdComponentType::ComplexType => {
                                valid &= xsd_validate_complex_type(tc, child, schema, ctxt);
                            }
                            XsdComponentType::SimpleType => {
                                let text = get_node_text(child);
                                if let Some(ref dt) = tc.datatype {
                                    if !xsd_validate_datatype(dt, &text, &tc.facets) {
                                        ctxt.errors.push(format!(
                                            "Element '{}' has invalid value '{}'",
                                            child_name, text
                                        ));
                                        ctxt.nb_errors += 1;
                                        valid = false;
                                    }
                                }
                            }
                            _ => {}
                        }
                    }
                }
            }
            child = (*child).next;
        }

        valid
    }
}

/// Get the qualified name of a node (with namespace prefix if available).
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an _xmlNode or NULL.
unsafe fn get_node_qname(node: *mut _xmlNode) -> String {
    if node.is_null() {
        return String::new();
    }
    unsafe {
        // Check for namespace prefix
        let ns = (*node).ns;
        let prefix = if !ns.is_null() && !(*ns).prefix.is_null() {
            let mut len = 0;
            while *(*ns).prefix.add(len) != 0 {
                len += 1;
            }
            let slice = std::slice::from_raw_parts((*ns).prefix, len);
            if let Ok(s) = std::str::from_utf8(slice) {
                format!("{}:", s)
            } else {
                String::new()
            }
        } else {
            String::new()
        };

        let name = (*node).name;
        if name.is_null() {
            return String::new();
        }
        let mut len = 0;
        while *name.add(len) != 0 {
            len += 1;
        }
        let slice = std::slice::from_raw_parts(name, len);
        if let Ok(s) = std::str::from_utf8(slice) {
            format!("{}{}", prefix, s)
        } else {
            String::new()
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// C ABI Functions
// ═══════════════════════════════════════════════════════════════════════════════

// These are the C-compatible entry points that get exported via the ABI layer.
// They use raw pointers and follow libxml2's calling conventions.

/// Create a new schema parser context from a URL.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlSchemaParserCtxtPtr xmlSchemaNewParserCtxt(const char *URL);
/// ```
///
/// # SAFETY
///
/// - `url` must be a valid null-terminated C string or NULL.
#[no_mangle]
pub unsafe extern "C" fn xmlSchemaNewParserCtxt(url: *const c_char) -> *mut c_void {
    if url.is_null() {
        // Return a simple empty context
        let ctxt = allocator::xmlMallocZero(size_of::<XsdSchema>() as usize);
        return ctxt;
    }

    // Read the URL
    let url_str = unsafe {
        if url.is_null() {
            String::new()
        } else {
            let mut len = 0;
            while *url.add(len) != 0 {
                len += 1;
            }
            let slice = std::slice::from_raw_parts(url as *const u8, len);
            String::from_utf8_lossy(slice).to_string()
        }
    };

    // Try to parse the schema from the URL
    // For now, return a placeholder context
    let ctxt = allocator::xmlMallocZero(size_of::<XsdSchema>() as usize);
    // In a full implementation, this would read the file and parse it
    if !url_str.is_empty() {
        // Store the URL for later parsing
        let _ = url_str;
    }

    ctxt
}

/// Create a new schema parser context from a memory buffer.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlSchemaParserCtxtPtr xmlSchemaNewMemParserCtxt(const char *buffer, int size);
/// ```
///
/// # SAFETY
///
/// - `buffer` must be a valid pointer to a buffer of at least `size` bytes.
#[no_mangle]
pub unsafe extern "C" fn xmlSchemaNewMemParserCtxt(
    buffer: *const c_char,
    size: c_int,
) -> *mut c_void {
    if buffer.is_null() || size <= 0 {
        return ptr::null_mut();
    }

    // Parse the schema immediately
    let buf_slice = unsafe { std::slice::from_raw_parts(buffer as *const u8, size as usize) };
    let xml_str = String::from_utf8_lossy(buf_slice).to_string();

    match xsd_parse(&xml_str) {
        Ok(schema) => {
            // Allocate and store the schema
            let schema_box = Box::new(schema);
            Box::into_raw(schema_box) as *mut c_void
        }
        Err(_) => ptr::null_mut(),
    }
}

/// Parse a schema.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlSchemaPtr xmlSchemaParse(xmlSchemaParserCtxtPtr ctxt);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be a valid pointer to a parser context, or NULL.
#[no_mangle]
pub unsafe extern "C" fn xmlSchemaParse(ctxt: *mut c_void) -> *mut c_void {
    if ctxt.is_null() {
        return ptr::null_mut();
    }

    // If the context already contains a parsed schema (from xmlSchemaNewMemParserCtxt),
    // return it. Otherwise, parse from the URL stored in the context.
    // For now, just return the context as the schema pointer.
    ctxt
}

/// Free a schema.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlSchemaFree(xmlSchemaPtr schema);
/// ```
///
/// # SAFETY
///
/// - `schema` must be a valid pointer to a schema, or NULL.
#[no_mangle]
pub unsafe extern "C" fn xmlSchemaFree(schema: *mut c_void) {
    if schema.is_null() {
        return;
    }
    // SAFETY: Reconstruct the Box to drop it.
    unsafe {
        let _ = Box::from_raw(schema as *mut XsdSchema);
    }
}

/// Validate a document against a schema.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlSchemaValidateDoc(xmlSchemaValidCtxtPtr ctxt, xmlDocPtr doc);
/// ```
///
/// Returns 0 if valid, -1 on internal error, or the number of validation errors.
///
/// # SAFETY
///
/// - `ctxt` must be a valid pointer to a validation context, or NULL.
/// - `doc` must be a valid pointer to an _xmlDoc, or NULL.
#[no_mangle]
pub unsafe extern "C" fn xmlSchemaValidateDoc(ctxt: *mut c_void, doc: *mut _xmlDoc) -> c_int {
    if ctxt.is_null() || doc.is_null() {
        return -1;
    }

    unsafe {
        let valid_ctxt = &mut *(ctxt as *mut XsdValidCtxt);
        let schema = match &valid_ctxt.schema {
            Some(s) => s,
            None => return -1,
        };

        let mut temp_ctxt = XsdValidCtxt::new();
        temp_ctxt.schema = Some(schema.clone());

        let valid = xsd_validate_doc(schema, doc, &mut temp_ctxt);

        if valid {
            0
        } else {
            valid_ctxt.errors = temp_ctxt.errors;
            valid_ctxt.nb_errors = temp_ctxt.nb_errors;
            temp_ctxt.nb_errors
        }
    }
}

/// Free a schema parser context.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlSchemaFreeParserCtxt(xmlSchemaParserCtxtPtr ctxt);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be a valid pointer to a parser context, or NULL.
#[no_mangle]
pub unsafe extern "C" fn xmlSchemaFreeParserCtxt(ctxt: *mut c_void) {
    if ctxt.is_null() {
        return;
    }
    // SAFETY: Reconstruct the Box to drop it.
    unsafe {
        let _ = Box::from_raw(ctxt as *mut XsdSchema);
    }
}

/// Free a schema validation context.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlSchemaFreeValidCtxt(xmlSchemaValidCtxtPtr ctxt);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be a valid pointer to a validation context, or NULL.
#[no_mangle]
pub unsafe extern "C" fn xmlSchemaFreeValidCtxt(ctxt: *mut c_void) {
    if ctxt.is_null() {
        return;
    }
    // SAFETY: Reconstruct the Box to drop it.
    unsafe {
        let _ = Box::from_raw(ctxt as *mut XsdValidCtxt);
    }
}

/// Create a new schema validation context.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlSchemaValidCtxtPtr xmlSchemaNewValidCtxt(xmlSchemaPtr schema);
/// ```
///
/// # SAFETY
///
/// - `schema` must be a valid pointer to a schema, or NULL.
#[no_mangle]
pub unsafe extern "C" fn xmlSchemaNewValidCtxt(schema: *mut c_void) -> *mut c_void {
    let mut ctxt = XsdValidCtxt::new();

    if !schema.is_null() {
        // SAFETY: The schema pointer is assumed to be a valid XsdSchema.
        unsafe {
            let schema_ref = &*(schema as *const XsdSchema);
            ctxt.schema = Some(schema_ref.clone());
        }
    }

    let boxed = Box::new(ctxt);
    Box::into_raw(boxed) as *mut c_void
}

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

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

    // ── Datatype Validation Tests ─────────────────────────────────────────

    #[test]
    fn test_validate_string() {
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::String,
            "hello",
            &[]
        ));
        assert!(xsd_validate_datatype(&XsdDatatypeKind::String, "", &[]));
    }

    #[test]
    fn test_validate_boolean() {
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::Boolean,
            "true",
            &[]
        ));
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::Boolean,
            "false",
            &[]
        ));
        assert!(xsd_validate_datatype(&XsdDatatypeKind::Boolean, "1", &[]));
        assert!(xsd_validate_datatype(&XsdDatatypeKind::Boolean, "0", &[]));
        assert!(!xsd_validate_datatype(
            &XsdDatatypeKind::Boolean,
            "yes",
            &[]
        ));
        assert!(!xsd_validate_datatype(&XsdDatatypeKind::Boolean, "no", &[]));
    }

    #[test]
    fn test_validate_integer() {
        assert!(xsd_validate_datatype(&XsdDatatypeKind::Integer, "42", &[]));
        assert!(xsd_validate_datatype(&XsdDatatypeKind::Integer, "-42", &[]));
        assert!(xsd_validate_datatype(&XsdDatatypeKind::Integer, "+42", &[]));
        assert!(!xsd_validate_datatype(
            &XsdDatatypeKind::Integer,
            "12.5",
            &[]
        ));
        assert!(!xsd_validate_datatype(&XsdDatatypeKind::Integer, "", &[]));
        assert!(!xsd_validate_datatype(
            &XsdDatatypeKind::Integer,
            "abc",
            &[]
        ));
    }

    #[test]
    fn test_validate_decimal() {
        assert!(xsd_validate_datatype(&XsdDatatypeKind::Decimal, "42", &[]));
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::Decimal,
            "12.5",
            &[]
        ));
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::Decimal,
            "-3.14",
            &[]
        ));
        assert!(!xsd_validate_datatype(&XsdDatatypeKind::Decimal, "", &[]));
    }

    #[test]
    fn test_validate_float() {
        assert!(xsd_validate_datatype(&XsdDatatypeKind::Float, "3.14", &[]));
        assert!(xsd_validate_datatype(&XsdDatatypeKind::Float, "INF", &[]));
        assert!(xsd_validate_datatype(&XsdDatatypeKind::Float, "-INF", &[]));
        assert!(xsd_validate_datatype(&XsdDatatypeKind::Float, "NaN", &[]));
        assert!(!xsd_validate_datatype(&XsdDatatypeKind::Float, "", &[]));
    }

    #[test]
    fn test_validate_positive_integer() {
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::PositiveInteger,
            "1",
            &[]
        ));
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::PositiveInteger,
            "100",
            &[]
        ));
        assert!(!xsd_validate_datatype(
            &XsdDatatypeKind::PositiveInteger,
            "0",
            &[]
        ));
        assert!(!xsd_validate_datatype(
            &XsdDatatypeKind::PositiveInteger,
            "-1",
            &[]
        ));
    }

    #[test]
    fn test_validate_non_negative_integer() {
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::NonNegativeInteger,
            "0",
            &[]
        ));
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::NonNegativeInteger,
            "42",
            &[]
        ));
        assert!(!xsd_validate_datatype(
            &XsdDatatypeKind::NonNegativeInteger,
            "-1",
            &[]
        ));
    }

    #[test]
    fn test_validate_int_range() {
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::Int,
            "2147483647",
            &[]
        ));
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::Int,
            "-2147483648",
            &[]
        ));
        assert!(!xsd_validate_datatype(
            &XsdDatatypeKind::Int,
            "2147483648",
            &[]
        ));
    }

    #[test]
    fn test_validate_short_range() {
        assert!(xsd_validate_datatype(&XsdDatatypeKind::Short, "32767", &[]));
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::Short,
            "-32768",
            &[]
        ));
        assert!(!xsd_validate_datatype(
            &XsdDatatypeKind::Short,
            "32768",
            &[]
        ));
    }

    #[test]
    fn test_validate_byte_range() {
        assert!(xsd_validate_datatype(&XsdDatatypeKind::Byte, "127", &[]));
        assert!(xsd_validate_datatype(&XsdDatatypeKind::Byte, "-128", &[]));
        assert!(!xsd_validate_datatype(&XsdDatatypeKind::Byte, "128", &[]));
    }

    #[test]
    fn test_validate_date_time() {
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::DateTime,
            "2023-01-15T10:30:00",
            &[]
        ));
        assert!(!xsd_validate_datatype(
            &XsdDatatypeKind::DateTime,
            "not-a-date",
            &[]
        ));
    }

    #[test]
    fn test_validate_date() {
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::Date,
            "2023-01-15",
            &[]
        ));
        assert!(!xsd_validate_datatype(
            &XsdDatatypeKind::Date,
            "2023/01/15",
            &[]
        ));
    }

    #[test]
    fn test_validate_time() {
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::Time,
            "10:30:00",
            &[]
        ));
        assert!(!xsd_validate_datatype(&XsdDatatypeKind::Time, "10:30", &[]));
    }

    #[test]
    fn test_validate_hex_binary() {
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::HexBinary,
            "0FA1",
            &[]
        ));
        assert!(xsd_validate_datatype(&XsdDatatypeKind::HexBinary, "", &[]));
        assert!(!xsd_validate_datatype(
            &XsdDatatypeKind::HexBinary,
            "0FG1",
            &[]
        ));
        assert!(!xsd_validate_datatype(
            &XsdDatatypeKind::HexBinary,
            "0FA",
            &[]
        ));
    }

    #[test]
    fn test_validate_base64() {
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::Base64Binary,
            "SGVsbG8=",
            &[]
        ));
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::Base64Binary,
            "",
            &[]
        ));
        assert!(!xsd_validate_datatype(
            &XsdDatatypeKind::Base64Binary,
            "Hello World!",
            &[]
        ));
    }

    #[test]
    fn test_validate_ncname() {
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::NCName,
            "myElement",
            &[]
        ));
        assert!(xsd_validate_datatype(&XsdDatatypeKind::NCName, "_foo", &[]));
        assert!(!xsd_validate_datatype(
            &XsdDatatypeKind::NCName,
            "123abc",
            &[]
        ));
        assert!(!xsd_validate_datatype(&XsdDatatypeKind::NCName, "", &[]));
    }

    #[test]
    fn test_validate_qname() {
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::QName,
            "ns:local",
            &[]
        ));
        assert!(xsd_validate_datatype(&XsdDatatypeKind::QName, "local", &[]));
        assert!(!xsd_validate_datatype(&XsdDatatypeKind::QName, "", &[]));
    }

    #[test]
    fn test_validate_token() {
        assert!(xsd_validate_datatype(&XsdDatatypeKind::Token, "hello", &[]));
        assert!(!xsd_validate_datatype(
            &XsdDatatypeKind::Token,
            " hello",
            &[]
        ));
        assert!(!xsd_validate_datatype(
            &XsdDatatypeKind::Token,
            "hello ",
            &[]
        ));
        assert!(!xsd_validate_datatype(
            &XsdDatatypeKind::Token,
            "hello  world",
            &[]
        ));
        assert!(!xsd_validate_datatype(
            &XsdDatatypeKind::Token,
            "hello\tworld",
            &[]
        ));
    }

    #[test]
    fn test_validate_language() {
        assert!(xsd_validate_datatype(&XsdDatatypeKind::Language, "en", &[]));
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::Language,
            "en-US",
            &[]
        ));
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::Language,
            "zh-CN",
            &[]
        ));
        assert!(!xsd_validate_datatype(&XsdDatatypeKind::Language, "", &[]));
        assert!(!xsd_validate_datatype(
            &XsdDatatypeKind::Language,
            "123",
            &[]
        ));
    }

    #[test]
    fn test_validate_name() {
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::Name,
            "myElement",
            &[]
        ));
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::Name,
            "ns:local",
            &[]
        ));
        assert!(!xsd_validate_datatype(&XsdDatatypeKind::Name, "", &[]));
    }

    #[test]
    fn test_validate_nmtoken() {
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::Nmtoken,
            "token123",
            &[]
        ));
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::Nmtoken,
            "123token",
            &[]
        ));
        assert!(!xsd_validate_datatype(&XsdDatatypeKind::Nmtoken, "", &[]));
    }

    #[test]
    fn test_validate_duration() {
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::Duration,
            "P1Y2M3DT4H5M6S",
            &[]
        ));
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::Duration,
            "P1Y",
            &[]
        ));
        assert!(!xsd_validate_datatype(&XsdDatatypeKind::Duration, "", &[]));
    }

    #[test]
    fn test_validate_g_year() {
        assert!(xsd_validate_datatype(&XsdDatatypeKind::GYear, "2023", &[]));
        assert!(!xsd_validate_datatype(&XsdDatatypeKind::GYear, "", &[]));
    }

    #[test]
    fn test_validate_g_month() {
        assert!(xsd_validate_datatype(&XsdDatatypeKind::GMonth, "--05", &[]));
        assert!(!xsd_validate_datatype(&XsdDatatypeKind::GMonth, "", &[]));
    }

    #[test]
    fn test_validate_g_day() {
        assert!(xsd_validate_datatype(&XsdDatatypeKind::GDay, "---15", &[]));
        assert!(!xsd_validate_datatype(&XsdDatatypeKind::GDay, "", &[]));
    }

    // ── Facet Validation Tests ────────────────────────────────────────────

    #[test]
    fn test_facet_min_length() {
        let facets = vec![(XsdDatatypeKind::FacetMinLength, "3".to_string())];
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::String,
            "hello",
            &facets
        ));
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::String,
            "abc",
            &facets
        ));
        assert!(!xsd_validate_datatype(
            &XsdDatatypeKind::String,
            "ab",
            &facets
        ));
    }

    #[test]
    fn test_facet_max_length() {
        let facets = vec![(XsdDatatypeKind::FacetMaxLength, "3".to_string())];
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::String,
            "ab",
            &facets
        ));
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::String,
            "abc",
            &facets
        ));
        assert!(!xsd_validate_datatype(
            &XsdDatatypeKind::String,
            "abcd",
            &facets
        ));
    }

    #[test]
    fn test_facet_length() {
        let facets = vec![(XsdDatatypeKind::FacetLength, "3".to_string())];
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::String,
            "abc",
            &facets
        ));
        assert!(!xsd_validate_datatype(
            &XsdDatatypeKind::String,
            "ab",
            &facets
        ));
        assert!(!xsd_validate_datatype(
            &XsdDatatypeKind::String,
            "abcd",
            &facets
        ));
    }

    #[test]
    fn test_facet_min_inclusive() {
        let facets = vec![(XsdDatatypeKind::FacetMinInclusive, "5".to_string())];
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::Integer,
            "5",
            &facets
        ));
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::Integer,
            "10",
            &facets
        ));
        assert!(!xsd_validate_datatype(
            &XsdDatatypeKind::Integer,
            "3",
            &facets
        ));
    }

    #[test]
    fn test_facet_max_inclusive() {
        let facets = vec![(XsdDatatypeKind::FacetMaxInclusive, "10".to_string())];
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::Integer,
            "10",
            &facets
        ));
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::Integer,
            "5",
            &facets
        ));
        assert!(!xsd_validate_datatype(
            &XsdDatatypeKind::Integer,
            "15",
            &facets
        ));
    }

    #[test]
    fn test_facet_pattern_digits() {
        let facets = vec![(XsdDatatypeKind::FacetPattern, r"\d+".to_string())];
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::String,
            "123",
            &facets
        ));
        assert!(!xsd_validate_datatype(
            &XsdDatatypeKind::String,
            "abc",
            &facets
        ));
    }

    #[test]
    fn test_facet_pattern_alpha() {
        let facets = vec![(XsdDatatypeKind::FacetPattern, r"[a-zA-Z]+".to_string())];
        assert!(xsd_validate_datatype(
            &XsdDatatypeKind::String,
            "hello",
            &facets
        ));
        assert!(!xsd_validate_datatype(
            &XsdDatatypeKind::String,
            "123",
            &facets
        ));
    }

    // ── Schema Parsing Tests ──────────────────────────────────────────────

    #[test]
    fn test_parse_empty_schema() {
        let schema_xml = r#"<?xml version="1.0"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
            </xs:schema>"#;

        let schema = xsd_parse(schema_xml).expect("Failed to parse schema");
        assert!(schema.components.is_empty());
    }

    #[test]
    fn test_parse_schema_with_target_namespace() {
        let schema_xml = r#"<?xml version="1.0"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
                       targetNamespace="http://example.com/ns">
            </xs:schema>"#;

        let schema = xsd_parse(schema_xml).expect("Failed to parse schema");
        assert_eq!(
            schema.target_namespace,
            Some("http://example.com/ns".to_string())
        );
    }

    #[test]
    fn test_parse_simple_element() {
        let schema_xml = r#"<?xml version="1.0"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
                <xs:element name="name" type="xs:string"/>
            </xs:schema>"#;

        let schema = xsd_parse(schema_xml).expect("Failed to parse schema");
        assert_eq!(schema.components.len(), 1);
        assert_eq!(
            schema.components[0].component_type,
            XsdComponentType::Element
        );
        assert_eq!(schema.components[0].name, Some("name".to_string()));
        assert_eq!(schema.components[0].datatype, Some(XsdDatatypeKind::String));
    }

    #[test]
    fn test_parse_integer_element() {
        let schema_xml = r#"<?xml version="1.0"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
                <xs:element name="age" type="xs:integer"/>
            </xs:schema>"#;

        let schema = xsd_parse(schema_xml).expect("Failed to parse schema");
        assert_eq!(schema.components.len(), 1);
        assert_eq!(schema.components[0].name, Some("age".to_string()));
        assert_eq!(
            schema.components[0].datatype,
            Some(XsdDatatypeKind::Integer)
        );
    }

    #[test]
    fn test_parse_element_with_attributes() {
        let schema_xml = r#"<?xml version="1.0"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
                <xs:element name="product">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="name" type="xs:string"/>
                            <xs:element name="price" type="xs:decimal"/>
                        </xs:sequence>
                        <xs:attribute name="id" type="xs:integer" use="required"/>
                    </xs:complexType>
                </xs:element>
            </xs:schema>"#;

        let schema = xsd_parse(schema_xml).expect("Failed to parse schema");
        assert_eq!(schema.components.len(), 1);
        assert_eq!(schema.components[0].name, Some("product".to_string()));

        // Should have a complexType child
        let ct = &schema.components[0].children;
        let complex_type = ct
            .iter()
            .find(|c| c.component_type == XsdComponentType::ComplexType);
        assert!(complex_type.is_some());
        if let Some(ctc) = complex_type {
            assert_eq!(ctc.attributes.len(), 1);
            assert_eq!(ctc.attributes[0].name, Some("id".to_string()));
            assert_eq!(ctc.attributes[0].datatype, Some(XsdDatatypeKind::Integer));
        }
    }

    #[test]
    fn test_parse_complex_type_with_sequence() {
        let schema_xml = r#"<?xml version="1.0"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
                <xs:complexType name="AddressType">
                    <xs:sequence>
                        <xs:element name="street" type="xs:string"/>
                        <xs:element name="city" type="xs:string"/>
                        <xs:element name="zip" type="xs:string"/>
                    </xs:sequence>
                </xs:complexType>
            </xs:schema>"#;

        let schema = xsd_parse(schema_xml).expect("Failed to parse schema");
        assert_eq!(schema.components.len(), 1);
        assert_eq!(
            schema.components[0].component_type,
            XsdComponentType::ComplexType
        );
        assert_eq!(schema.components[0].name, Some("AddressType".to_string()));
    }

    #[test]
    fn test_parse_restriction() {
        let schema_xml = r#"<?xml version="1.0"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
                <xs:simpleType name="AgeType">
                    <xs:restriction base="xs:integer">
                        <xs:minInclusive value="0"/>
                        <xs:maxInclusive value="150"/>
                    </xs:restriction>
                </xs:simpleType>
            </xs:schema>"#;

        let schema = xsd_parse(schema_xml).expect("Failed to parse schema");
        assert_eq!(schema.components.len(), 1);
        assert_eq!(
            schema.components[0].component_type,
            XsdComponentType::SimpleType
        );

        // Should have facets from the restriction
        let st = &schema.components[0];
        assert_eq!(st.datatype, Some(XsdDatatypeKind::Integer));
        assert!(!st.facets.is_empty());
    }

    #[test]
    fn test_parse_enumeration() {
        let schema_xml = r#"<?xml version="1.0"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
                <xs:simpleType name="ColorType">
                    <xs:restriction base="xs:string">
                        <xs:enumeration value="red"/>
                        <xs:enumeration value="green"/>
                        <xs:enumeration value="blue"/>
                    </xs:restriction>
                </xs:simpleType>
            </xs:schema>"#;

        let schema = xsd_parse(schema_xml).expect("Failed to parse schema");
        assert_eq!(schema.components.len(), 1);
        assert_eq!(schema.components[0].name, Some("ColorType".to_string()));
    }

    #[test]
    fn test_parse_min_max_occurs() {
        let schema_xml = r#"<?xml version="1.0"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
                <xs:element name="items">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="item" type="xs:string"
                                        minOccurs="0" maxOccurs="unbounded"/>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:schema>"#;

        let schema = xsd_parse(schema_xml).expect("Failed to parse schema");
        assert_eq!(schema.components.len(), 1);

        // Check the item element inside the sequence
        let elem = &schema.components[0];
        let ct = elem
            .children
            .iter()
            .find(|c| c.component_type == XsdComponentType::ComplexType);
        assert!(ct.is_some());
        if let Some(ctc) = ct {
            let seq = ctc
                .children
                .iter()
                .find(|c| c.component_type == XsdComponentType::Sequence);
            assert!(seq.is_some());
            if let Some(seqc) = seq {
                assert!(!seqc.children.is_empty());
                let item = &seqc.children[0];
                assert_eq!(item.min_occurs, 0);
                assert_eq!(item.max_occurs, -1);
            }
        }
    }

    #[test]
    fn test_parse_attribute_default() {
        let schema_xml = r#"<?xml version="1.0"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
                <xs:element name="book">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="title" type="xs:string"/>
                        </xs:sequence>
                        <xs:attribute name="lang" type="xs:string" default="en"/>
                        <xs:attribute name="id" type="xs:integer" use="required"/>
                    </xs:complexType>
                </xs:element>
            </xs:schema>"#;

        let schema = xsd_parse(schema_xml).expect("Failed to parse schema");
        let elem = &schema.components[0];
        let ct = elem
            .children
            .iter()
            .find(|c| c.component_type == XsdComponentType::ComplexType);
        assert!(ct.is_some());
        if let Some(ctc) = ct {
            let lang_attr = ctc
                .attributes
                .iter()
                .find(|a| a.name.as_deref() == Some("lang"));
            assert!(lang_attr.is_some());
            if let Some(la) = lang_attr {
                assert_eq!(la.min_occurs, 0); // optional
            }

            let id_attr = ctc
                .attributes
                .iter()
                .find(|a| a.name.as_deref() == Some("id"));
            assert!(id_attr.is_some());
        }
    }

    #[test]
    fn test_parse_element_with_ref() {
        let schema_xml = r#"<?xml version="1.0"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
                <xs:element name="root">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element ref="child" minOccurs="0"/>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
                <xs:element name="child" type="xs:string"/>
            </xs:schema>"#;

        let schema = xsd_parse(schema_xml).expect("Failed to parse schema");
        assert_eq!(schema.components.len(), 2);
        // The ref element inside the sequence
        let root = &schema.components[0];
        let ct = root
            .children
            .iter()
            .find(|c| c.component_type == XsdComponentType::ComplexType);
        assert!(ct.is_some());
        if let Some(ctc) = ct {
            let seq = ctc
                .children
                .iter()
                .find(|c| c.component_type == XsdComponentType::Sequence);
            assert!(seq.is_some());
            if let Some(seqc) = seq {
                assert!(!seqc.children.is_empty());
                let ref_elem = &seqc.children[0];
                assert_eq!(ref_elem.ref_name, Some("child".to_string()));
            }
        }
    }

    // ── Document Validation Tests ─────────────────────────────────────────

    #[test]
    fn test_validate_simple_element() {
        let schema_xml = r#"<?xml version="1.0"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
                <xs:element name="name" type="xs:string"/>
            </xs:schema>"#;

        let schema = xsd_parse(schema_xml).expect("Failed to parse schema");

        let doc = r#"<?xml version="1.0"?>
            <name>John Doe</name>"#;

        assert!(xsd_validate(&schema, doc).is_ok());
    }

    #[test]
    fn test_validate_integer_element() {
        let schema_xml = r#"<?xml version="1.0"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
                <xs:element name="age" type="xs:integer"/>
            </xs:schema>"#;

        let schema = xsd_parse(schema_xml).expect("Failed to parse schema");

        assert!(xsd_validate(&schema, r#"<?xml version="1.0"?><age>25</age>"#).is_ok());
        assert!(xsd_validate(&schema, r#"<?xml version="1.0"?><age>not-a-number</age>"#).is_err());
    }

    #[test]
    fn test_validate_complex_element() {
        let schema_xml = r#"<?xml version="1.0"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
                <xs:element name="product">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="name" type="xs:string"/>
                            <xs:element name="price" type="xs:decimal"/>
                        </xs:sequence>
                        <xs:attribute name="id" type="xs:integer" use="required"/>
                    </xs:complexType>
                </xs:element>
            </xs:schema>"#;

        let schema = xsd_parse(schema_xml).expect("Failed to parse schema");

        let valid_doc = r#"<?xml version="1.0"?>
            <product id="123">
                <name>Widget</name>
                <price>9.99</price>
            </product>"#;

        assert!(xsd_validate(&schema, valid_doc).is_ok());
    }

    #[test]
    fn test_validate_missing_required_attribute() {
        let schema_xml = r#"<?xml version="1.0"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
                <xs:element name="product">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="name" type="xs:string"/>
                        </xs:sequence>
                        <xs:attribute name="id" type="xs:integer" use="required"/>
                    </xs:complexType>
                </xs:element>
            </xs:schema>"#;

        let schema = xsd_parse(schema_xml).expect("Failed to parse schema");

        let invalid_doc = r#"<?xml version="1.0"?>
            <product>
                <name>Widget</name>
            </product>"#;

        assert!(xsd_validate(&schema, invalid_doc).is_err());
    }

    #[test]
    fn test_validate_enumeration_facet() {
        let schema_xml = r#"<?xml version="1.0"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
                <xs:element name="color">
                    <xs:simpleType>
                        <xs:restriction base="xs:string">
                            <xs:enumeration value="red"/>
                            <xs:enumeration value="green"/>
                            <xs:enumeration value="blue"/>
                        </xs:restriction>
                    </xs:simpleType>
                </xs:element>
            </xs:schema>"#;

        let schema = xsd_parse(schema_xml).expect("Failed to parse schema");

        // Note: enumeration validation is currently simplified - the facet
        // matches each individual value
        assert!(xsd_validate(&schema, r#"<?xml version="1.0"?><color>red</color>"#).is_ok());
    }

    #[test]
    fn test_validate_boolean_element() {
        let schema_xml = r#"<?xml version="1.0"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
                <xs:element name="active" type="xs:boolean"/>
            </xs:schema>"#;

        let schema = xsd_parse(schema_xml).expect("Failed to parse schema");

        assert!(xsd_validate(&schema, r#"<?xml version="1.0"?><active>true</active>"#).is_ok());
        assert!(xsd_validate(&schema, r#"<?xml version="1.0"?><active>false</active>"#).is_ok());
        assert!(xsd_validate(&schema, r#"<?xml version="1.0"?><active>1</active>"#).is_ok());
        assert!(xsd_validate(&schema, r#"<?xml version="1.0"?><active>yes</active>"#).is_err());
    }

    #[test]
    fn test_validate_element_with_range_constraint() {
        let schema_xml = r#"<?xml version="1.0"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
                <xs:element name="age">
                    <xs:simpleType>
                        <xs:restriction base="xs:integer">
                            <xs:minInclusive value="0"/>
                            <xs:maxInclusive value="150"/>
                        </xs:restriction>
                    </xs:simpleType>
                </xs:element>
            </xs:schema>"#;

        let schema = xsd_parse(schema_xml).expect("Failed to parse schema");

        assert!(xsd_validate(&schema, r#"<?xml version="1.0"?><age>25</age>"#).is_ok());
        assert!(xsd_validate(&schema, r#"<?xml version="1.0"?><age>0</age>"#).is_ok());
        assert!(xsd_validate(&schema, r#"<?xml version="1.0"?><age>150</age>"#).is_ok());
        // Note: minInclusive/maxInclusive validation currently works for facets
    }

    #[test]
    fn test_validate_optional_element() {
        let schema_xml = r#"<?xml version="1.0"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
                <xs:element name="person">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="name" type="xs:string"/>
                            <xs:element name="nickname" type="xs:string" minOccurs="0"/>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:schema>"#;

        let schema = xsd_parse(schema_xml).expect("Failed to parse schema");

        let doc_with_nick = r#"<?xml version="1.0"?>
            <person>
                <name>John</name>
                <nickname>Johnny</nickname>
            </person>"#;

        let doc_without_nick = r#"<?xml version="1.0"?>
            <person>
                <name>John</name>
            </person>"#;

        assert!(xsd_validate(&schema, doc_with_nick).is_ok());
        assert!(xsd_validate(&schema, doc_without_nick).is_ok());
    }

    #[test]
    fn test_validate_unbounded_element() {
        let schema_xml = r#"<?xml version="1.0"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
                <xs:element name="items">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="item" type="xs:string"
                                        minOccurs="0" maxOccurs="unbounded"/>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:schema>"#;

        let schema = xsd_parse(schema_xml).expect("Failed to parse schema");

        let doc = r#"<?xml version="1.0"?>
            <items>
                <item>one</item>
                <item>two</item>
                <item>three</item>
            </items>"#;

        assert!(xsd_validate(&schema, doc).is_ok());
    }

    #[test]
    fn test_validate_date_element() {
        let schema_xml = r#"<?xml version="1.0"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
                <xs:element name="birthDate" type="xs:date"/>
            </xs:schema>"#;

        let schema = xsd_parse(schema_xml).expect("Failed to parse schema");

        assert!(xsd_validate(
            &schema,
            r#"<?xml version="1.0"?><birthDate>1990-01-15</birthDate>"#
        )
        .is_ok());
        assert!(xsd_validate(
            &schema,
            r#"<?xml version="1.0"?><birthDate>not-a-date</birthDate>"#
        )
        .is_err());
    }

    #[test]
    fn test_validate_choice() {
        let schema_xml = r#"<?xml version="1.0"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
                <xs:element name="contact">
                    <xs:complexType>
                        <xs:choice>
                            <xs:element name="email" type="xs:string"/>
                            <xs:element name="phone" type="xs:string"/>
                        </xs:choice>
                    </xs:complexType>
                </xs:element>
            </xs:schema>"#;

        let schema = xsd_parse(schema_xml).expect("Failed to parse schema");

        assert!(xsd_validate(
            &schema,
            r#"<?xml version="1.0"?><contact><email>a@b.com</email></contact>"#
        )
        .is_ok());
        assert!(xsd_validate(
            &schema,
            r#"<?xml version="1.0"?><contact><phone>555-1234</phone></contact>"#
        )
        .is_ok());
    }

    #[test]
    fn test_validate_positive_integer_constraint() {
        let schema_xml = r#"<?xml version="1.0"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
                <xs:element name="quantity" type="xs:positiveInteger"/>
            </xs:schema>"#;

        let schema = xsd_parse(schema_xml).expect("Failed to parse schema");

        assert!(xsd_validate(&schema, r#"<?xml version="1.0"?><quantity>1</quantity>"#).is_ok());
        assert!(xsd_validate(&schema, r#"<?xml version="1.0"?><quantity>0</quantity>"#).is_err());
        assert!(xsd_validate(&schema, r#"<?xml version="1.0"?><quantity>-1</quantity>"#).is_err());
    }

    // ── C ABI Tests ───────────────────────────────────────────────────────

    #[test]
    fn test_xml_schema_new_mem_parser_ctxt() {
        let schema_xml = r#"<?xml version="1.0"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
                <xs:element name="name" type="xs:string"/>
            </xs:schema>"#;

        let ctxt = unsafe {
            xmlSchemaNewMemParserCtxt(
                schema_xml.as_ptr() as *const c_char,
                schema_xml.len() as c_int,
            )
        };
        assert!(!ctxt.is_null());

        let schema = unsafe { xmlSchemaParse(ctxt) };
        assert!(!schema.is_null());

        unsafe {
            xmlSchemaFree(schema);
        }
    }

    #[test]
    fn test_xml_schema_validate_doc() {
        let schema_xml = r#"<?xml version="1.0"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
                <xs:element name="name" type="xs:string"/>
            </xs:schema>"#;

        let doc_xml = r#"<?xml version="1.0"?>
            <name>John Doe</name>"#;

        let ctxt = unsafe {
            xmlSchemaNewMemParserCtxt(
                schema_xml.as_ptr() as *const c_char,
                schema_xml.len() as c_int,
            )
        };
        let schema = unsafe { xmlSchemaParse(ctxt) };
        let valid_ctxt = unsafe { xmlSchemaNewValidCtxt(schema) };

        let doc = unsafe {
            crate::abi::exports_xml2::xmlReadMemory(
                doc_xml.as_ptr() as *const c_char,
                doc_xml.len() as c_int,
                b"test.xml\0".as_ptr() as *const c_char,
                ptr::null(),
                0,
            )
        };

        let result = unsafe { xmlSchemaValidateDoc(valid_ctxt, doc) };
        assert_eq!(result, 0);

        unsafe {
            xmlSchemaFreeValidCtxt(valid_ctxt);
            xmlSchemaFree(schema);
            crate::abi::exports_xml2::xmlFreeDoc(doc);
        }
    }

    #[test]
    fn test_xml_schema_validate_invalid_doc() {
        let schema_xml = r#"<?xml version="1.0"?>
            <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
                <xs:element name="age" type="xs:integer"/>
            </xs:schema>"#;

        let doc_xml = r#"<?xml version="1.0"?>
            <age>not-a-number</age>"#;

        let ctxt = unsafe {
            xmlSchemaNewMemParserCtxt(
                schema_xml.as_ptr() as *const c_char,
                schema_xml.len() as c_int,
            )
        };
        let schema = unsafe { xmlSchemaParse(ctxt) };
        let valid_ctxt = unsafe { xmlSchemaNewValidCtxt(schema) };

        let doc = unsafe {
            crate::abi::exports_xml2::xmlReadMemory(
                doc_xml.as_ptr() as *const c_char,
                doc_xml.len() as c_int,
                b"test.xml\0".as_ptr() as *const c_char,
                ptr::null(),
                0,
            )
        };

        let result = unsafe { xmlSchemaValidateDoc(valid_ctxt, doc) };
        assert_ne!(result, 0); // Should have errors

        unsafe {
            xmlSchemaFreeValidCtxt(valid_ctxt);
            xmlSchemaFree(schema);
            crate::abi::exports_xml2::xmlFreeDoc(doc);
        }
    }

    #[test]
    fn test_xml_schema_new_valid_ctxt_null() {
        let ctxt = unsafe { xmlSchemaNewValidCtxt(ptr::null_mut()) };
        assert!(!ctxt.is_null());
        unsafe { xmlSchemaFreeValidCtxt(ctxt) };
    }

    #[test]
    fn test_xml_schema_free_null() {
        unsafe {
            xmlSchemaFree(ptr::null_mut());
            xmlSchemaFreeParserCtxt(ptr::null_mut());
            xmlSchemaFreeValidCtxt(ptr::null_mut());
        }
    }

    #[test]
    fn test_xml_schema_new_parser_ctxt_null() {
        let ctxt = unsafe { xmlSchemaNewParserCtxt(ptr::null()) };
        assert!(!ctxt.is_null());
        // Clean up
        unsafe {
            allocator::xmlFree(ctxt);
        }
    }

    #[test]
    fn test_datatype_parse_kind() {
        assert_eq!(
            parse_datatype_kind("xs:string"),
            Some(XsdDatatypeKind::String)
        );
        assert_eq!(parse_datatype_kind("string"), Some(XsdDatatypeKind::String));
        assert_eq!(
            parse_datatype_kind("xs:integer"),
            Some(XsdDatatypeKind::Integer)
        );
        assert_eq!(
            parse_datatype_kind("xs:boolean"),
            Some(XsdDatatypeKind::Boolean)
        );
        assert_eq!(
            parse_datatype_kind("xs:decimal"),
            Some(XsdDatatypeKind::Decimal)
        );
        assert_eq!(
            parse_datatype_kind("xs:float"),
            Some(XsdDatatypeKind::Float)
        );
        assert_eq!(
            parse_datatype_kind("xs:double"),
            Some(XsdDatatypeKind::Double)
        );
        assert_eq!(parse_datatype_kind("xs:date"), Some(XsdDatatypeKind::Date));
        assert_eq!(
            parse_datatype_kind("xs:dateTime"),
            Some(XsdDatatypeKind::DateTime)
        );
        assert_eq!(parse_datatype_kind("xs:time"), Some(XsdDatatypeKind::Time));
        assert_eq!(
            parse_datatype_kind("xs:hexBinary"),
            Some(XsdDatatypeKind::HexBinary)
        );
        assert_eq!(
            parse_datatype_kind("xs:base64Binary"),
            Some(XsdDatatypeKind::Base64Binary)
        );
        assert_eq!(
            parse_datatype_kind("xs:anyURI"),
            Some(XsdDatatypeKind::AnyURI)
        );
        assert_eq!(
            parse_datatype_kind("xs:QName"),
            Some(XsdDatatypeKind::QName)
        );
        assert_eq!(
            parse_datatype_kind("xs:normalizedString"),
            Some(XsdDatatypeKind::NormalizedString)
        );
        assert_eq!(
            parse_datatype_kind("xs:token"),
            Some(XsdDatatypeKind::Token)
        );
        assert_eq!(
            parse_datatype_kind("xs:language"),
            Some(XsdDatatypeKind::Language)
        );
        assert_eq!(parse_datatype_kind("xs:Name"), Some(XsdDatatypeKind::Name));
        assert_eq!(
            parse_datatype_kind("xs:NCName"),
            Some(XsdDatatypeKind::NCName)
        );
        assert_eq!(parse_datatype_kind("xs:ID"), Some(XsdDatatypeKind::Id));
        assert_eq!(
            parse_datatype_kind("xs:IDREF"),
            Some(XsdDatatypeKind::Idref)
        );
        assert_eq!(
            parse_datatype_kind("xs:integer"),
            Some(XsdDatatypeKind::Integer)
        );
        assert_eq!(parse_datatype_kind("xs:long"), Some(XsdDatatypeKind::Long));
        assert_eq!(parse_datatype_kind("xs:int"), Some(XsdDatatypeKind::Int));
        assert_eq!(
            parse_datatype_kind("xs:short"),
            Some(XsdDatatypeKind::Short)
        );
        assert_eq!(parse_datatype_kind("xs:byte"), Some(XsdDatatypeKind::Byte));
        assert_eq!(
            parse_datatype_kind("xs:positiveInteger"),
            Some(XsdDatatypeKind::PositiveInteger)
        );
        assert_eq!(
            parse_datatype_kind("xs:negativeInteger"),
            Some(XsdDatatypeKind::NegativeInteger)
        );
        assert_eq!(parse_datatype_kind("unknown"), None);
    }
}