vastlint-core 0.11.8

VAST XML validator, SIMID linter, OMID validator, and VPAID detector. IAB VAST 2.0–4.4, 223 rules, pure Rust
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
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
use vastlint_core::{validate, Severity};

// ── helpers ──────────────────────────────────────────────────────────────────

fn load(name: &str) -> String {
    let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures")
        .join(name);
    std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("could not read fixture {name}: {e}"))
}

fn fixture_names() -> Vec<String> {
    let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
    let mut names = std::fs::read_dir(path)
        .unwrap_or_else(|e| panic!("could not read fixtures dir: {e}"))
        .filter_map(|entry| entry.ok())
        .map(|entry| entry.file_name())
        .map(|name| name.to_string_lossy().into_owned())
        .filter(|name| name.ends_with(".xml"))
        .collect::<Vec<_>>();
    names.sort();
    names
}

fn has_issue(result: &vastlint_core::ValidationResult, id: &str) -> bool {
    result.issues.iter().any(|i| i.id == id)
}

fn issues_with_severity(
    result: &vastlint_core::ValidationResult,
    severity: Severity,
) -> Vec<&vastlint_core::Issue> {
    result
        .issues
        .iter()
        .filter(|i| i.severity == severity)
        .collect()
}

fn minimal_valid_inline_xml(
    declared_version: &str,
    inline_extra: &str,
    creative_extra: &str,
) -> String {
    format!(
        r#"<VAST version="{declared_version}">
    <Ad id="1">
        <InLine>
            <AdSystem version="1.0">Test AdServer</AdSystem>
            <AdTitle>Acme Spring Sale 30s</AdTitle>
            {inline_extra}
            <Impression><![CDATA[https://example.com/impression]]></Impression>
            <Creatives>
                <Creative>
                    {creative_extra}
                    <Linear>
                        <Duration>00:00:30</Duration>
                        <TrackingEvents>
                            <Tracking event="start"><![CDATA[https://example.com/start]]></Tracking>
                            <Tracking event="firstQuartile"><![CDATA[https://example.com/q1]]></Tracking>
                            <Tracking event="midpoint"><![CDATA[https://example.com/mid]]></Tracking>
                            <Tracking event="thirdQuartile"><![CDATA[https://example.com/q3]]></Tracking>
                            <Tracking event="complete"><![CDATA[https://example.com/complete]]></Tracking>
                        </TrackingEvents>
                        <MediaFiles>
                            <MediaFile delivery="progressive" type="video/mp4" width="640" height="360"><![CDATA[https://example.com/video.mp4]]></MediaFile>
                        </MediaFiles>
                    </Linear>
                </Creative>
            </Creatives>
        </InLine>
    </Ad>
</VAST>"#
    )
}

fn version_rank(version: &str) -> u8 {
    match version {
        "2.0" => 20,
        "3.0" => 30,
        "4.0" => 40,
        "4.1" => 41,
        "4.2" => 42,
        "4.3" => 43,
        _ => panic!("unsupported version {version}"),
    }
}

fn assert_parse_error_only(xml: &str) {
    let result = validate(xml);
    assert!(
        has_issue(&result, "VAST-2.0-parse-error"),
        "malformed XML should fire VAST-2.0-parse-error, got: {:#?}",
        result.issues
    );
    assert_eq!(
        result.issues.len(),
        1,
        "malformed XML should short-circuit to a single parse error, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

fn assert_large_publica_warning_fixture(name: &str) {
    let result = validate(&load(name));
    let errors = issues_with_severity(&result, Severity::Error);

    assert!(
        errors.is_empty(),
        "expected no errors for {name}, got: {errors:#?}"
    );
    assert!(
        has_issue(&result, "VAST-2.0-version-mismatch"),
        "expected VAST-2.0-version-mismatch for {name}, got: {:#?}",
        result.issues
    );
    assert!(
        has_issue(&result, "VAST-2.0-extension-misplaced-element"),
        "expected VAST-2.0-extension-misplaced-element for {name}, got: {:#?}",
        result.issues
    );
    assert!(
        has_issue(&result, "VAST-3.0-skip-event-no-skipoffset"),
        "expected VAST-3.0-skip-event-no-skipoffset for {name}, got: {:#?}",
        result.issues
    );
    assert!(
        has_issue(&result, "VAST-3.0-pricing-model-case"),
        "expected VAST-3.0-pricing-model-case for {name}, got: {:#?}",
        result.issues
    );
    // 11 warnings: the tag's `AdID` (VAST 2.0 creative-id casing) is no longer
    // false-flagged as an unknown attribute.
    assert_eq!(
        result.summary.warnings, 11,
        "expected 11 warnings for {name}, got {}: {:#?}",
        result.summary.warnings, result.issues
    );
    assert!(result.summary.is_valid());
}

fn assert_no_errors(name: &str) -> vastlint_core::ValidationResult {
    let result = validate(&load(name));
    let errors = issues_with_severity(&result, Severity::Error);
    assert!(
        errors.is_empty(),
        "expected no errors for {name}, got: {errors:#?}"
    );
    result
}

// ── valid fixtures ────────────────────────────────────────────────────────────

#[test]
fn valid_2_0_produces_no_errors() {
    let result = validate(&load("valid_2.0.xml"));
    let errors = issues_with_severity(&result, Severity::Error);
    assert!(
        errors.is_empty(),
        "expected no errors for valid_2.0.xml, got: {errors:#?}"
    );
    assert!(result.summary.is_valid());
}

#[test]
fn valid_3_0_produces_no_errors() {
    let result = validate(&load("valid_3.0.xml"));
    let errors = issues_with_severity(&result, Severity::Error);
    assert!(
        errors.is_empty(),
        "expected no errors for valid_3.0.xml, got: {errors:#?}"
    );
    assert!(result.summary.is_valid());
}

#[test]
fn minimal_3_0_inline_does_not_fire_version_mismatch() {
    let result = validate(&minimal_valid_inline_xml("3.0", "", ""));
    assert!(
        !has_issue(&result, "VAST-2.0-version-mismatch"),
        "did not expect VAST-2.0-version-mismatch, got: {:#?}",
        result.issues
    );
    assert!(result.summary.is_valid());
}

#[test]
fn newer_declared_versions_do_not_fire_version_mismatch_across_structural_floors() {
    let floor_cases = [
        ("2.0", "", ""),
        (
            "3.0",
            r#"<Pricing model="cpm" currency="USD">1.50</Pricing>"#,
            "",
        ),
        (
            "4.0",
            "",
            r#"<UniversalAdId idRegistry="ad-id.org">TEST-1234</UniversalAdId>"#,
        ),
        (
            "4.1",
            r#"<AdServingId>TEST-SERVING-ID-001</AdServingId>"#,
            "",
        ),
    ];

    for declared_version in ["3.0", "4.0", "4.1", "4.2", "4.3"] {
        for (floor_version, inline_extra, creative_extra) in floor_cases {
            if version_rank(floor_version) > version_rank(declared_version) {
                continue;
            }

            let xml = minimal_valid_inline_xml(declared_version, inline_extra, creative_extra);
            let result = validate(&xml);
            assert!(
                !has_issue(&result, "VAST-2.0-version-mismatch"),
                "did not expect version mismatch for declared {declared_version} with {floor_version} structural floor, got: {:#?}",
                result.issues
            );
        }
    }
}

#[test]
fn valid_4_0_produces_no_errors() {
    let result = validate(&load("valid_4.0.xml"));
    let errors = issues_with_severity(&result, Severity::Error);
    assert!(
        errors.is_empty(),
        "expected no errors for valid_4.0.xml, got: {errors:#?}"
    );
    assert!(result.summary.is_valid());
}

#[test]
fn valid_4_1_produces_no_errors() {
    let result = validate(&load("valid_4.1.xml"));
    let errors = issues_with_severity(&result, Severity::Error);
    assert!(
        errors.is_empty(),
        "expected no errors for valid_4.1.xml, got: {errors:#?}"
    );
    assert!(result.summary.is_valid());
}

#[test]
fn valid_4_2_wrapper_clickthrough_no_error() {
    // ClickThrough inside Wrapper VideoClicks is valid from VAST 4.2 onward.
    // The VAST-4.0-wrapper-clickthrough rule must NOT fire for 4.2+ documents.
    let result = validate(&load("valid_4.2.xml"));
    assert!(
        !has_issue(&result, "VAST-4.0-wrapper-clickthrough"),
        "VAST-4.0-wrapper-clickthrough must not fire on a 4.2 document, got: {:#?}",
        result.issues
    );
}

#[test]
fn valid_4_3_produces_no_errors() {
    let result = validate(&load("valid_4.3.xml"));
    let errors = issues_with_severity(&result, Severity::Error);
    assert!(
        errors.is_empty(),
        "expected no errors for valid_4.3.xml, got: {errors:#?}"
    );
    assert!(result.summary.is_valid());
}

// ── required-element errors ───────────────────────────────────────────────────

#[test]
fn missing_version_fires_error() {
    let result = validate(&load("err_no_version.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-root-version"),
        "expected VAST-2.0-root-version, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn no_ad_fires_error() {
    let result = validate(&load("err_no_ad.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-root-has-ad-or-error"),
        "expected VAST-2.0-root-has-ad-or-error, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn ad_without_inline_or_wrapper_fires_error() {
    let result = validate(&load("err_no_inline_or_wrapper.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-ad-has-inline-or-wrapper"),
        "expected VAST-2.0-ad-has-inline-or-wrapper, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn missing_adsystem_fires_error() {
    let result = validate(&load("err_missing_adsystem.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-inline-adsystem"),
        "expected VAST-2.0-inline-adsystem, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn missing_duration_fires_error() {
    let result = validate(&load("err_missing_duration.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-linear-duration"),
        "expected VAST-2.0-linear-duration, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn empty_mediafiles_fires_error() {
    let result = validate(&load("err_missing_mediafiles.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-linear-mediafiles"),
        "expected VAST-2.0-linear-mediafiles, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn companion_without_resource_fires_error() {
    let result = validate(&load("err_companion_no_resource.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-companion-resource"),
        "expected VAST-2.0-companion-resource, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn nonlinear_without_resource_fires_error() {
    let result = validate(&load("err_nonlinear_no_resource.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-nonlinear-resource"),
        "expected VAST-2.0-nonlinear-resource, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn universaladid_empty_content_fires_error() {
    let result = validate(&load("err_universaladid_no_content.xml"));
    assert!(
        has_issue(&result, "VAST-4.1-universaladid-content"),
        "expected VAST-4.1-universaladid-content, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn root_ad_and_error_fires_warning() {
    let result = validate(&load("warn_root_ad_and_error.xml"));
    assert!(
        has_issue(&result, "VAST-4.0-wrapper-root-error"),
        "expected VAST-4.0-wrapper-root-error, got: {:#?}",
        result.issues
    );
}

// ── security / consistency warnings ──────────────────────────────────────────

#[test]
fn http_mediafile_fires_info() {
    let result = validate(&load("warn_http_mediafile.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-mediafile-https"),
        "expected VAST-2.0-mediafile-https info, got: {:#?}",
        result.issues
    );
    // HTTP is an Info, not an Error — document should still be considered valid.
    assert!(result.summary.is_valid());
}

#[test]
fn duplicate_impression_fires_warning() {
    let result = validate(&load("warn_duplicate_impression.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-duplicate-impression"),
        "expected VAST-2.0-duplicate-impression, got: {:#?}",
        result.issues
    );
    // Duplicate impression is a Warning, not an Error.
    assert!(result.summary.is_valid());
}

#[test]
fn vpaid_in_4_1_fires_warning() {
    let result = validate(&load("warn_vpaid.xml"));
    assert!(
        has_issue(&result, "VAST-4.1-vpaid-apiframework"),
        "expected VAST-4.1-vpaid-apiframework, got: {:#?}",
        result.issues
    );
    assert!(result.summary.is_valid());
}

#[test]
fn version_mismatch_fires_warning() {
    let result = validate(&load("warn_version_mismatch.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-version-mismatch"),
        "expected VAST-2.0-version-mismatch, got: {:#?}",
        result.issues
    );
    assert!(result.summary.is_valid());
}

#[test]
fn pricing_currency_bad_format_fires_warning() {
    let result = validate(&load("warn_pricing_currency_format.xml"));
    assert!(
        has_issue(&result, "VAST-3.0-pricing-currency-format"),
        "expected VAST-3.0-pricing-currency-format, got: {:#?}",
        result.issues
    );
    assert!(result.summary.is_valid());
}

#[test]
fn pricing_model_uppercase_fires_warning() {
    let result = validate(&load("warn_pricing_model_case.xml"));
    assert!(
        has_issue(&result, "VAST-3.0-pricing-model-case"),
        "expected VAST-3.0-pricing-model-case, got: {:#?}",
        result.issues
    );
    assert!(result.summary.is_valid());
}

#[test]
fn interactive_creative_no_api_fires_warning() {
    let result = validate(&load("warn_interactive_no_api.xml"));
    assert!(
        has_issue(&result, "VAST-4.0-interactive-creative-no-api"),
        "expected VAST-4.0-interactive-creative-no-api, got: {:#?}",
        result.issues
    );
    assert!(result.summary.is_valid());
}

// ── summary counts ────────────────────────────────────────────────────────────

#[test]
fn summary_counts_match_issues() {
    let result = validate(&load("err_missing_adsystem.xml"));
    let expected_errors = result
        .issues
        .iter()
        .filter(|i| i.severity == Severity::Error)
        .count();
    let expected_warnings = result
        .issues
        .iter()
        .filter(|i| i.severity == Severity::Warning)
        .count();
    let expected_infos = result
        .issues
        .iter()
        .filter(|i| i.severity == Severity::Info)
        .count();

    assert_eq!(result.summary.errors, expected_errors);
    assert_eq!(result.summary.warnings, expected_warnings);
    assert_eq!(result.summary.infos, expected_infos);
}

#[test]
fn all_fixture_xml_validates_without_panicking_and_summary_counts_match() {
    for name in fixture_names() {
        let result = validate(&load(&name));
        let expected_errors = result
            .issues
            .iter()
            .filter(|i| i.severity == Severity::Error)
            .count();
        let expected_warnings = result
            .issues
            .iter()
            .filter(|i| i.severity == Severity::Warning)
            .count();
        let expected_infos = result
            .issues
            .iter()
            .filter(|i| i.severity == Severity::Info)
            .count();

        assert_eq!(
            result.summary.errors, expected_errors,
            "summary error count mismatch for {name}: {:#?}",
            result.issues
        );
        assert_eq!(
            result.summary.warnings, expected_warnings,
            "summary warning count mismatch for {name}: {:#?}",
            result.issues
        );
        assert_eq!(
            result.summary.infos, expected_infos,
            "summary info count mismatch for {name}: {:#?}",
            result.issues
        );
    }
}

// ── rule override ─────────────────────────────────────────────────────────────

#[test]
fn rule_override_off_silences_issue() {
    use std::collections::HashMap;
    use vastlint_core::{validate_with_context, RuleLevel, ValidationContext};

    let mut overrides = HashMap::new();
    overrides.insert("VAST-2.0-root-version", RuleLevel::Off);

    let ctx = ValidationContext {
        rule_overrides: Some(overrides),
        ..Default::default()
    };

    let result = validate_with_context(&load("err_no_version.xml"), ctx);
    assert!(
        !has_issue(&result, "VAST-2.0-root-version"),
        "rule override Off should suppress VAST-2.0-root-version"
    );
}

#[test]
fn rule_override_downgrade_error_to_warning() {
    use std::collections::HashMap;
    use vastlint_core::{validate_with_context, RuleLevel, ValidationContext};

    let mut overrides = HashMap::new();
    overrides.insert("VAST-2.0-root-version", RuleLevel::Warning);

    let ctx = ValidationContext {
        rule_overrides: Some(overrides),
        ..Default::default()
    };

    let result = validate_with_context(&load("err_no_version.xml"), ctx);
    // Should still fire, but as a Warning, not an Error.
    assert!(
        has_issue(&result, "VAST-2.0-root-version"),
        "VAST-2.0-root-version should still fire when overridden to Warning"
    );
    let issue = result
        .issues
        .iter()
        .find(|i| i.id == "VAST-2.0-root-version")
        .unwrap();
    assert_eq!(
        issue.severity,
        Severity::Warning,
        "severity should be Warning after override"
    );
    // Downgraded to Warning means no errors — document is valid.
    assert!(result.summary.is_valid());
}

// ── values.rs rules ───────────────────────────────────────────────────────────

#[test]
fn bad_duration_format_fires_error() {
    let result = validate(&load("err_bad_duration.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-duration-format"),
        "expected VAST-2.0-duration-format, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn bad_delivery_enum_fires_error() {
    let result = validate(&load("err_bad_delivery_enum.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-mediafile-delivery-enum"),
        "expected VAST-2.0-mediafile-delivery-enum, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn minmaxbitrate_pair_fires_error() {
    let result = validate(&load("err_minmaxbitrate_pair.xml"));
    assert!(
        has_issue(&result, "VAST-3.0-minmaxbitrate-pair"),
        "expected VAST-3.0-minmaxbitrate-pair, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn bad_skipoffset_format_fires_warning() {
    let result = validate(&load("warn_bad_skipoffset.xml"));
    assert!(
        has_issue(&result, "VAST-3.0-skipoffset-format"),
        "expected VAST-3.0-skipoffset-format, got: {:#?}",
        result.issues
    );
    // skipoffset format is a Warning — document is still valid.
    assert!(result.summary.is_valid());
}

#[test]
fn tracking_event_removed_fires_warning() {
    let result = validate(&load("warn_tracking_event_removed.xml"));
    assert!(
        has_issue(&result, "VAST-4.0-tracking-event-removed"),
        "expected VAST-4.0-tracking-event-removed, got: {:#?}",
        result.issues
    );
    assert!(result.summary.is_valid());
}

// ── required.rs additions ─────────────────────────────────────────────────────

#[test]
fn pricing_missing_attrs_fires_error() {
    let result = validate(&load("err_pricing_attrs.xml"));
    assert!(
        has_issue(&result, "VAST-3.0-pricing-model"),
        "expected VAST-3.0-pricing-model, got: {:#?}",
        result.issues
    );
    assert!(
        has_issue(&result, "VAST-3.0-pricing-currency"),
        "expected VAST-3.0-pricing-currency, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn icon_missing_required_attrs_fires_errors() {
    let result = validate(&load("err_icon_required_attrs.xml"));
    for rule in &[
        "VAST-3.0-icon-program",
        "VAST-3.0-icon-width",
        "VAST-3.0-icon-height",
        "VAST-3.0-icon-xposition",
        "VAST-3.0-icon-yposition",
    ] {
        assert!(
            has_issue(&result, rule),
            "expected {rule}, got: {:#?}",
            result.issues
        );
    }
    assert!(!result.summary.is_valid());
}

#[test]
fn category_missing_authority_fires_error() {
    let result = validate(&load("err_category_authority.xml"));
    assert!(
        has_issue(&result, "VAST-4.0-category-authority"),
        "expected VAST-4.0-category-authority, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn mezzanine_missing_attrs_fires_errors() {
    let result = validate(&load("err_mezzanine_attrs.xml"));
    for rule in &[
        "VAST-4.1-mezzanine-delivery",
        "VAST-4.1-mezzanine-type",
        "VAST-4.1-mezzanine-width",
        "VAST-4.1-mezzanine-height",
    ] {
        assert!(
            has_issue(&result, rule),
            "expected {rule}, got: {:#?}",
            result.issues
        );
    }
    assert!(!result.summary.is_valid());
}

#[test]
fn icon_fallback_image_missing_dimensions_fires_warning() {
    let result = validate(&load("warn_icon_fallback_no_dimensions.xml"));
    assert!(
        has_issue(&result, "VAST-4.2-icon-fallback-image-width-height"),
        "expected VAST-4.2-icon-fallback-image-width-height, got: {:#?}",
        result.issues
    );
}

#[test]
fn unknown_version_value_fires_warning() {
    let result = validate(&load("warn_unknown_version.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-root-version-value"),
        "expected VAST-2.0-root-version-value, got: {:#?}",
        result.issues
    );
}

#[test]
fn mediafile_apiframework_non_vpaid_fires_info() {
    let result = validate(&load("info_mediafile_apiframework.xml"));
    assert!(
        has_issue(&result, "VAST-4.0-mediafile-apiframework"),
        "expected VAST-4.0-mediafile-apiframework, got: {:#?}",
        result.issues
    );
    // Must not also fire the VPAID-specific warning (wrong framework name).
    assert!(
        !has_issue(&result, "VAST-4.1-vpaid-apiframework"),
        "VAST-4.1-vpaid-apiframework should not fire for non-VPAID framework"
    );
}

#[test]
fn interactive_creative_data_uri_no_url_error() {
    // VAST 4.3 allows data: URIs in InteractiveCreativeFile.
    // The security rule must not flag them as invalid URLs.
    let result = validate(&load("valid_4.3_interactive_data_uri.xml"));
    assert!(
        !has_issue(&result, "VAST-2.0-url-invalid"),
        "data: URI should not trigger url-invalid, got: {:#?}",
        result.issues
    );
    assert!(
        !has_issue(&result, "VAST-2.0-url-empty"),
        "data: URI should not trigger url-empty, got: {:#?}",
        result.issues
    );
}

#[test]
fn http_tracking_urls_fire_info() {
    let result = validate(&load("info_http_tracking.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-tracking-https"),
        "expected VAST-2.0-tracking-https for HTTP impression/tracking/click URLs, got: {:#?}",
        result.issues
    );
    // Info only — document is still valid.
    assert!(result.summary.is_valid());
}

// ── SIMID / InteractiveCreativeFile rules ─────────────────────────────────────

#[test]
fn interactive_creative_missing_type_fires_warning() {
    let result = validate(&load("warn_interactive_no_type.xml"));
    assert!(
        has_issue(&result, "VAST-4.1-interactive-creative-type"),
        "expected VAST-4.1-interactive-creative-type, got: {:#?}",
        result.issues
    );
}

#[test]
fn simid_type_required_fires_error() {
    // <InteractiveCreativeFile apiFramework="SIMID"> without type="text/html"
    let result = validate(&load("err_simid_type_required.xml"));
    assert!(
        has_issue(&result, "SIMID-1.0-simid-type-required"),
        "expected SIMID-1.0-simid-type-required, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn simid_url_http_fires_error() {
    // SIMID creative URL using http:// — must be blocked as insecure.
    let result = validate(&load("err_simid_url_https.xml"));
    assert!(
        has_issue(&result, "SIMID-1.0-simid-url-https"),
        "expected SIMID-1.0-simid-url-https, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn simid_mediafile_required_fires_error() {
    // SIMID creative without an accompanying video <MediaFile> — SIMID §3.4.
    let result = validate(&load("err_simid_mediafile_required.xml"));
    assert!(
        has_issue(&result, "SIMID-1.0-simid-mediafile-required"),
        "expected SIMID-1.0-simid-mediafile-required, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn simid_variable_duration_bad_value_fires_warning() {
    // variableDuration="yes" is invalid — only "true" is allowed per SIMID §5.
    let result = validate(&load("warn_simid_variable_duration.xml"));
    assert!(
        has_issue(&result, "SIMID-1.0-simid-variable-duration-value"),
        "expected SIMID-1.0-simid-variable-duration-value, got: {:#?}",
        result.issues
    );
    // Warning only — document is still valid.
    assert!(result.summary.is_valid());
}

#[test]
fn valid_simid_linear_produces_no_simid_errors() {
    // A correct SIMID linear ad must not fire any SIMID-1.0-* rules.
    let result = validate(&load("valid_simid_linear.xml"));
    let simid_issues: Vec<_> = result
        .issues
        .iter()
        .filter(|i| i.id.starts_with("SIMID-"))
        .collect();
    assert!(
        simid_issues.is_empty(),
        "valid SIMID creative should produce no SIMID-* issues, got: {:#?}",
        simid_issues
    );
}

// ── OM SDK / Verification rules ───────────────────────────────────────────────

#[test]
fn verification_missing_vendor_fires_error() {
    let result = validate(&load("err_verification_vendor.xml"));
    assert!(
        has_issue(&result, "VAST-4.1-verification-vendor"),
        "expected VAST-4.1-verification-vendor, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn verification_resource_missing_attrs_fires_errors() {
    let result = validate(&load("err_verification_resource_attrs.xml"));
    assert!(
        has_issue(&result, "VAST-4.1-js-resource-apiframework"),
        "expected VAST-4.1-js-resource-apiframework, got: {:#?}",
        result.issues
    );
    assert!(
        has_issue(&result, "VAST-4.3-js-resource-browser-optional"),
        "expected VAST-4.3-js-resource-browser-optional, got: {:#?}",
        result.issues
    );
    assert!(
        has_issue(&result, "VAST-4.1-exec-resource-apiframework"),
        "expected VAST-4.1-exec-resource-apiframework, got: {:#?}",
        result.issues
    );
    assert!(
        has_issue(&result, "VAST-4.1-exec-resource-type"),
        "expected VAST-4.1-exec-resource-type, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn valid_4_3_with_verification_produces_no_errors() {
    let result = validate(&load("valid_4.3_with_verification.xml"));
    let errors = issues_with_severity(&result, Severity::Error);
    assert!(
        errors.is_empty(),
        "expected no errors for valid_4.3_with_verification.xml, got: {errors:#?}"
    );
    assert!(result.summary.is_valid());
}

#[test]
fn valid_4_3_with_verification_produces_no_omid_semantic_warnings() {
    let result = validate(&load("valid_4.3_with_verification.xml"));
    for rule_id in [
        "VAST-4.1-verification-vendor-format",
        "VAST-4.1-verification-duplicate-vendor",
        "VAST-4.1-verification-parameters",
        "VAST-4.1-js-resource-apiframework-value",
        "VAST-4.1-js-resource-https",
        "VAST-4.1-exec-resource-apiframework-value",
        "VAST-4.1-exec-resource-https",
    ] {
        assert!(
            !has_issue(&result, rule_id),
            "did not expect {rule_id} for valid_4.3_with_verification.xml, got: {:#?}",
            result.issues
        );
    }
}

#[test]
fn verification_vendor_format_fires_warning() {
    let result = validate(&load("warn_verification_vendor_format.xml"));
    assert!(
        has_issue(&result, "VAST-4.1-verification-vendor-format"),
        "expected VAST-4.1-verification-vendor-format, got: {:#?}",
        result.issues
    );
    assert!(result.summary.is_valid());
}

#[test]
fn duplicate_verification_vendor_fires_warning() {
    let result = validate(&load("warn_verification_duplicate_vendor.xml"));
    assert!(
        has_issue(&result, "VAST-4.1-verification-duplicate-vendor"),
        "expected VAST-4.1-verification-duplicate-vendor, got: {:#?}",
        result.issues
    );
    assert!(result.summary.is_valid());
}

#[test]
fn verification_in_extension_block_is_validated() {
    let result = validate(&load("warn_verification_extension_compat.xml"));
    assert!(
        has_issue(&result, "VAST-4.1-verification-parameters"),
        "expected VAST-4.1-verification-parameters from extension-carried verification block, got: {:#?}",
        result.issues
    );
    assert!(
        has_issue(&result, "VAST-4.1-js-resource-apiframework-value"),
        "expected VAST-4.1-js-resource-apiframework-value from extension-carried verification block, got: {:#?}",
        result.issues
    );
    assert!(result.summary.is_valid());
}

#[test]
fn omid_semantic_resource_issues_fire_warnings() {
    let result = validate(&load("warn_verification_omid_semantics.xml"));
    for rule_id in [
        "VAST-4.1-verification-parameters",
        "VAST-4.1-js-resource-apiframework-value",
        "VAST-4.1-js-resource-https",
        "VAST-4.1-exec-resource-apiframework-value",
        "VAST-4.1-exec-resource-https",
    ] {
        assert!(
            has_issue(&result, rule_id),
            "expected {rule_id}, got: {:#?}",
            result.issues
        );
    }
    assert!(result.summary.is_valid());
}

#[test]
fn verification_tracking_invalid_event_fires_error() {
    let result = validate(&load("err_verification_tracking_event.xml"));
    assert!(
        has_issue(&result, "VAST-4.1-tracking-event-value"),
        "expected VAST-4.1-tracking-event-value, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn verification_tracking_missing_reason_macro_fires_warning() {
    let result = validate(&load("warn_verification_tracking_reason.xml"));
    assert!(
        has_issue(&result, "VAST-4.1-verification-tracking-reason"),
        "expected VAST-4.1-verification-tracking-reason, got: {:#?}",
        result.issues
    );
    assert!(result.summary.is_valid());
}

// ── CTV / SSAI rules ─────────────────────────────────────────────────────────

#[test]
fn no_mezzanine_fires_info() {
    // valid_4.1.xml has no Mezzanine — the CTV rule fires at Info level.
    let result = validate(&load("valid_4.1.xml"));
    assert!(
        has_issue(&result, "VAST-4.1-mezzanine-recommended"),
        "expected VAST-4.1-mezzanine-recommended, got: {:#?}",
        result.issues
    );
    // Info only — document is still valid.
    assert!(result.summary.is_valid());
}

#[test]
fn vpaid_with_interactive_fires_warning() {
    let result = validate(&load("warn_vpaid_with_interactive.xml"));
    assert!(
        has_issue(&result, "VAST-4.1-vpaid-in-interactive-context"),
        "expected VAST-4.1-vpaid-in-interactive-context, got: {:#?}",
        result.issues
    );
}

#[test]
fn adservingid_empty_fires_warning() {
    let result = validate(&load("warn_adservingid_empty.xml"));
    assert!(
        has_issue(&result, "VAST-4.1-ad-serving-id-empty"),
        "expected VAST-4.1-ad-serving-id-empty, got: {:#?}",
        result.issues
    );
}

// ── edge cases ────────────────────────────────────────────────────────────────

#[test]
fn empty_input_produces_error() {
    // Empty string is not XML; must not panic, must produce at least one error.
    let result = validate("");
    assert!(
        !result.summary.is_valid(),
        "empty input should be invalid, got: {:#?}",
        result.issues
    );
}

#[test]
fn non_xml_input_produces_error() {
    // Plain text / JSON is not XML; must produce an error, not panic.
    let result = validate(r#"{"not": "xml"}"#);
    assert!(
        !result.summary.is_valid(),
        "non-XML input should be invalid, got: {:#?}",
        result.issues
    );
}

#[test]
fn non_vast_xml_produces_root_element_error() {
    let result = validate("<html><body>not vast</body></html>");
    assert!(
        has_issue(&result, "VAST-2.0-root-element"),
        "non-VAST XML should fire VAST-2.0-root-element, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn utf8_bom_is_handled_gracefully() {
    // A UTF-8 BOM (\xEF\xBB\xBF) before the XML declaration must not panic or
    // cause a spurious parse error — the BOM is common in files saved on Windows.
    let bom = "\u{FEFF}";
    let xml = format!(
        r#"{bom}<VAST version="4.1"><Ad id="1"><InLine><AdSystem>X</AdSystem><AdTitle>T</AdTitle><AdServingId>S</AdServingId><Impression>https://x.com/i</Impression><Creatives><Creative><UniversalAdId idRegistry="ad-id.org">U</UniversalAdId><Linear><Duration>00:00:30</Duration><MediaFiles><MediaFile delivery="progressive" type="video/mp4" width="1920" height="1080">https://x.com/v.mp4</MediaFile></MediaFiles></Linear></Creative></Creatives></InLine></Ad></VAST>"#
    );
    let result = validate(&xml);
    // BOM may trip the parser; the important contract is no panic and a clear
    // error message — we do not require the document to be valid.
    let _ = result; // just assert it doesn't panic
}

#[test]
fn malformed_xml_produces_parse_error() {
    assert_parse_error_only("<VAST version=\"4.1\"><Ad></VAST>");
}

#[test]
fn malformed_xml_matrix_short_circuits_to_parse_error_only() {
    for name in [
        "err_malformed_mismatched_close.xml",
        "err_malformed_broken_attr_quote.xml",
        "err_malformed_unclosed_cdata.xml",
    ] {
        assert_parse_error_only(&load(name));
    }
}

// ── Extension misuse rules ───────────────────────────────────────────────────

#[test]
fn extension_with_companion_fires_misplaced_warning() {
    let result = validate(&load("warn_extension_misplaced_companion.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-extension-misplaced-element"),
        "Companion inside Extension should fire misplaced-element, got: {:#?}",
        result.issues
    );
}

#[test]
fn extension_with_multiple_misplaced_elements() {
    let result = validate(&load("warn_extension_misplaced_multiple.xml"));
    let hits: Vec<_> = result
        .issues
        .iter()
        .filter(|i| i.id == "VAST-2.0-extension-misplaced-element")
        .collect();
    assert!(
        hits.len() >= 3,
        "expected at least 3 misplaced-element warnings (MediaFile, Impression, TrackingEvents), got {}: {:#?}",
        hits.len(),
        hits
    );
}

#[test]
fn creative_extension_with_simid_fires_misplaced_warning() {
    let result = validate(&load("warn_creative_extension_misplaced_simid.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-creative-extension-misplaced-element"),
        "InteractiveCreativeFile inside CreativeExtension should fire, got: {:#?}",
        result.issues
    );
}

#[test]
fn extension_with_nested_misplaced_element() {
    let result = validate(&load("warn_extension_nested_misplaced.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-extension-misplaced-element"),
        "Verification nested inside vendor wrapper in Extension should fire, got: {:#?}",
        result.issues
    );
}

#[test]
fn clean_extensions_produce_no_misplaced_warnings() {
    let result = validate(&load("valid_4.1_clean_extensions.xml"));
    assert!(
        !has_issue(&result, "VAST-2.0-extension-misplaced-element"),
        "clean Extension should not fire misplaced-element, got: {:#?}",
        result.issues
    );
    assert!(
        !has_issue(&result, "VAST-2.0-creative-extension-misplaced-element"),
        "clean CreativeExtension should not fire misplaced-element, got: {:#?}",
        result.issues
    );
}

#[test]
fn extension_leaf_text_with_sensitive_chars_needs_cdata() {
    let xml = r#"<VAST version="2.0">
    <Ad id="1">
        <InLine>
            <AdSystem>Test</AdSystem>
            <AdTitle>Test</AdTitle>
            <Impression><![CDATA[https://t.example.com/imp]]></Impression>
            <Creatives>
                <Creative>
                    <Linear>
                        <Duration>00:00:30</Duration>
                        <MediaFiles>
                            <MediaFile delivery="progressive" type="video/mp4" width="640" height="360"><![CDATA[https://cdn.example.com/ad.mp4]]></MediaFile>
                        </MediaFiles>
                    </Linear>
                </Creative>
            </Creatives>
            <Extensions>
                <Extension type="vendor">alpha&amp;beta</Extension>
            </Extensions>
        </InLine>
    </Ad>
</VAST>"#;
    let result = validate(xml);
    let issue = result
        .issues
        .iter()
        .find(|i| i.id == "VAST-2.0-extension-cdata")
        .unwrap_or_else(|| {
            panic!(
                "expected VAST-2.0-extension-cdata, got: {:#?}",
                result.issues
            )
        });
    assert!(
        issue.severity == Severity::Warning,
        "extension-cdata should stay at warning severity, got: {:#?}",
        issue
    );
}

#[test]
fn extension_leaf_text_with_cdata_does_not_warn() {
    let xml = r#"<VAST version="2.0">
    <Ad id="1">
        <InLine>
            <AdSystem>Test</AdSystem>
            <AdTitle>Test</AdTitle>
            <Impression><![CDATA[https://t.example.com/imp]]></Impression>
            <Creatives>
                <Creative>
                    <Linear>
                        <Duration>00:00:30</Duration>
                        <MediaFiles>
                            <MediaFile delivery="progressive" type="video/mp4" width="640" height="360"><![CDATA[https://cdn.example.com/ad.mp4]]></MediaFile>
                        </MediaFiles>
                    </Linear>
                </Creative>
            </Creatives>
            <Extensions>
                <Extension type="vendor"><![CDATA[alpha&beta]]></Extension>
            </Extensions>
        </InLine>
    </Ad>
</VAST>"#;
    let result = validate(xml);
    assert!(
        !has_issue(&result, "VAST-2.0-extension-cdata"),
        "CDATA-wrapped leaf Extension text should not fire extension-cdata, got: {:#?}",
        result.issues
    );
}

#[test]
fn creative_extension_leaf_text_with_sensitive_chars_needs_cdata() {
    let xml = r#"<VAST version="2.0">
    <Ad id="1">
        <InLine>
            <AdSystem>Test</AdSystem>
            <AdTitle>Test</AdTitle>
            <Impression><![CDATA[https://t.example.com/imp]]></Impression>
            <Creatives>
                <Creative>
                    <Linear>
                        <Duration>00:00:30</Duration>
                        <MediaFiles>
                            <MediaFile delivery="progressive" type="video/mp4" width="640" height="360"><![CDATA[https://cdn.example.com/ad.mp4]]></MediaFile>
                        </MediaFiles>
                    </Linear>
                    <CreativeExtensions>
                        <CreativeExtension>alpha&amp;beta</CreativeExtension>
                    </CreativeExtensions>
                </Creative>
            </Creatives>
        </InLine>
    </Ad>
</VAST>"#;
    let result = validate(xml);
    let issue = result
        .issues
        .iter()
        .find(|i| i.id == "VAST-2.0-creative-extension-cdata")
        .unwrap_or_else(|| {
            panic!(
                "expected VAST-2.0-creative-extension-cdata, got: {:#?}",
                result.issues
            )
        });
    assert!(
        issue.severity == Severity::Warning,
        "creative-extension-cdata should stay at warning severity, got: {:#?}",
        issue
    );
}

#[test]
fn creative_extension_leaf_text_with_cdata_does_not_warn() {
    let xml = r#"<VAST version="2.0">
    <Ad id="1">
        <InLine>
            <AdSystem>Test</AdSystem>
            <AdTitle>Test</AdTitle>
            <Impression><![CDATA[https://t.example.com/imp]]></Impression>
            <Creatives>
                <Creative>
                    <Linear>
                        <Duration>00:00:30</Duration>
                        <MediaFiles>
                            <MediaFile delivery="progressive" type="video/mp4" width="640" height="360"><![CDATA[https://cdn.example.com/ad.mp4]]></MediaFile>
                        </MediaFiles>
                    </Linear>
                    <CreativeExtensions>
                        <CreativeExtension><![CDATA[alpha&beta]]></CreativeExtension>
                    </CreativeExtensions>
                </Creative>
            </Creatives>
        </InLine>
    </Ad>
</VAST>"#;
    let result = validate(xml);
    assert!(
                !has_issue(&result, "VAST-2.0-creative-extension-cdata"),
                "CDATA-wrapped leaf CreativeExtension text should not fire creative-extension-cdata, got: {:#?}",
                result.issues
        );
}

// ── inline required fields ────────────────────────────────────────────────────

#[test]
fn missing_adtitle_fires_error() {
    let result = validate(&load("err_inline_missing_adtitle.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-inline-adtitle"),
        "expected VAST-2.0-inline-adtitle, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn missing_impression_fires_error() {
    let result = validate(&load("err_inline_missing_impression.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-inline-impression"),
        "expected VAST-2.0-inline-impression, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn missing_creatives_fires_error() {
    let result = validate(&load("err_inline_missing_creatives.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-inline-creatives"),
        "expected VAST-2.0-inline-creatives, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

// ── wrapper required fields ──────────────────────────────────────────────────

#[test]
fn wrapper_missing_adsystem_fires_error() {
    let result = validate(&load("err_wrapper_missing_adsystem.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-wrapper-adsystem"),
        "expected VAST-2.0-wrapper-adsystem, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn wrapper_missing_vasttag_fires_error() {
    let result = validate(&load("err_wrapper_missing_vasttag.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-wrapper-vastadtaguri"),
        "expected VAST-2.0-wrapper-vastadtaguri, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn wrapper_missing_impression_fires_error() {
    let result = validate(&load("err_wrapper_missing_impression.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-wrapper-impression"),
        "expected VAST-2.0-wrapper-impression, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

// ── mediafile attribute validation ───────────────────────────────────────────

#[test]
fn mediafile_missing_delivery_fires_error() {
    let result = validate(&load("err_mediafile_missing_attrs.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-mediafile-delivery"),
        "expected VAST-2.0-mediafile-delivery, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn mediafile_missing_dimensions_fires_error() {
    let result = validate(&load("err_mediafile_no_dimensions.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-mediafile-dimensions"),
        "expected VAST-2.0-mediafile-dimensions, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn companion_missing_dimensions_fires_warning() {
    let result = validate(&load("err_companion_no_dimensions.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-companion-dimensions"),
        "expected VAST-2.0-companion-dimensions, got: {:#?}",
        result.issues
    );
    assert!(result.summary.is_valid());
}

#[test]
fn nonlinear_missing_dimensions_fires_warning() {
    let result = validate(&load("err_nonlinear_no_dimensions.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-nonlinear-dimensions"),
        "expected VAST-2.0-nonlinear-dimensions, got: {:#?}",
        result.issues
    );
    assert!(result.summary.is_valid());
}

// ── 4.x required fields ──────────────────────────────────────────────────────

#[test]
fn adservingid_missing_fires_error() {
    let result = validate(&load("err_adservingid_missing.xml"));
    assert!(
        has_issue(&result, "VAST-4.1-adservingid-present"),
        "expected VAST-4.1-adservingid-present, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn universaladid_missing_fires_error() {
    let result = validate(&load("err_universaladid_missing.xml"));
    assert!(
        has_issue(&result, "VAST-4.0-universaladid-present"),
        "expected VAST-4.0-universaladid-present, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn universaladid_missing_idregistry_fires_error() {
    let result = validate(&load("err_universaladid_no_registry.xml"));
    assert!(
        has_issue(&result, "VAST-4.0-universaladid-idregistry"),
        "expected VAST-4.0-universaladid-idregistry, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn verification_no_resource_fires_warning() {
    let result = validate(&load("err_verification_no_resource.xml"));
    assert!(
        has_issue(&result, "VAST-4.1-verification-no-resource"),
        "expected VAST-4.1-verification-no-resource, got: {:#?}",
        result.issues
    );
    assert!(result.summary.is_valid());
}

// ── deprecated elements ──────────────────────────────────────────────────────

#[test]
fn flash_mediafile_fires_warning() {
    let result = validate(&load("warn_flash_mediafile.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-flash-mediafile"),
        "expected VAST-2.0-flash-mediafile, got: {:#?}",
        result.issues
    );
    assert!(result.summary.is_valid());
}

#[test]
fn survey_deprecated_fires_warning() {
    let result = validate(&load("warn_survey_deprecated.xml"));
    assert!(
        has_issue(&result, "VAST-4.1-survey-deprecated"),
        "expected VAST-4.1-survey-deprecated, got: {:#?}",
        result.issues
    );
    assert!(result.summary.is_valid());
}

// ── tracking event validation ────────────────────────────────────────────────

#[test]
fn tracking_event_unknown_value_fires_warning() {
    let result = validate(&load("warn_tracking_event_unknown.xml"));
    assert!(
        has_issue(&result, "VAST-4.1-tracking-event-value"),
        "expected VAST-4.1-tracking-event-value, got: {:#?}",
        result.issues
    );
}

#[test]
fn skip_event_without_skipoffset_fires_warning() {
    let result = validate(&load("warn_skip_event_no_skipoffset.xml"));
    assert!(
        has_issue(&result, "VAST-3.0-skip-event-no-skipoffset"),
        "expected VAST-3.0-skip-event-no-skipoffset, got: {:#?}",
        result.issues
    );
}

#[test]
fn progress_event_missing_offset_fires_error() {
    let result = validate(&load("err_progress_no_offset.xml"));
    assert!(
        has_issue(&result, "VAST-3.0-progress-offset"),
        "expected VAST-3.0-progress-offset, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

// ── additional edge cases ────────────────────────────────────────────────────

#[test]
fn very_large_input_does_not_panic() {
    let mut xml = String::with_capacity(1_100_000);
    xml.push_str(r#"<VAST version="2.0">"#);
    for i in 0..500 {
        xml.push_str(&format!(
            r#"<Ad id="{}"><InLine><AdSystem>X</AdSystem><AdTitle>T</AdTitle><Impression>https://t.example.com/imp</Impression><Creatives><Creative><Linear><Duration>00:00:30</Duration><MediaFiles><MediaFile delivery="progressive" type="video/mp4" width="640" height="360">https://cdn.example.com/ad.mp4</MediaFile></MediaFiles></Linear></Creative></Creatives></InLine></Ad>"#,
            i
        ));
    }
    xml.push_str("</VAST>");
    let result = validate(&xml);
    assert_eq!(result.summary.errors, 0);
}

#[test]
fn xml_with_processing_instruction_is_handled() {
    let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<VAST version="2.0">
  <Ad id="1">
    <InLine>
      <AdSystem>Test</AdSystem>
      <AdTitle>Test</AdTitle>
      <Impression>https://t.example.com/imp</Impression>
      <Creatives>
        <Creative>
          <Linear>
            <Duration>00:00:30</Duration>
            <MediaFiles>
              <MediaFile delivery="progressive" type="video/mp4" width="640" height="360">
                https://cdn.example.com/ad.mp4
              </MediaFile>
            </MediaFiles>
          </Linear>
        </Creative>
      </Creatives>
    </InLine>
  </Ad>
</VAST>"#;
    let result = validate(xml);
    assert!(
        result.summary.is_valid(),
        "XML with processing instruction should be valid, got: {:#?}",
        result.issues
    );
}

#[test]
fn cdata_in_url_is_handled() {
    let xml = r#"<VAST version="2.0">
  <Ad id="1">
    <InLine>
      <AdSystem>Test</AdSystem>
      <AdTitle>Test</AdTitle>
      <Impression><![CDATA[https://t.example.com/imp?a=1&b=2]]></Impression>
      <Creatives>
        <Creative>
          <Linear>
            <Duration>00:00:30</Duration>
            <MediaFiles>
              <MediaFile delivery="progressive" type="video/mp4" width="640" height="360">
                <![CDATA[https://cdn.example.com/ad.mp4]]>
              </MediaFile>
            </MediaFiles>
          </Linear>
        </Creative>
      </Creatives>
    </InLine>
  </Ad>
</VAST>"#;
    let result = validate(xml);
    assert!(
        result.summary.is_valid(),
        "CDATA-wrapped URLs should be valid, got: {:#?}",
        result.issues
    );
    assert!(
        !has_issue(&result, "VAST-2.0-url-cdata"),
        "CDATA-wrapped URLs should not trigger the url-cdata warning"
    );
}

#[test]
fn warns_on_non_cdata_url_inside_extension() {
    let xml = r#"<VAST version="2.0">
    <Ad id="1">
        <InLine>
            <AdSystem>Test</AdSystem>
            <AdTitle>Test</AdTitle>
            <Impression><![CDATA[https://t.example.com/imp]]></Impression>
            <Creatives>
                <Creative>
                    <Linear>
                        <Duration>00:00:30</Duration>
                        <MediaFiles>
                            <MediaFile delivery="progressive" type="video/mp4" width="640" height="360"><![CDATA[https://cdn.example.com/ad.mp4]]></MediaFile>
                        </MediaFiles>
                    </Linear>
                </Creative>
            </Creatives>
            <Extensions>
                <Extension type="vendor">
                    <TrackingUrl>https://vendor.example.com/pixel?a=1&amp;b=2</TrackingUrl>
                </Extension>
            </Extensions>
        </InLine>
    </Ad>
</VAST>"#;
    let result = validate(xml);
    assert!(
        has_issue(&result, "VAST-2.0-url-cdata"),
        "plain-text extension URLs should trigger the url-cdata warning, got: {:#?}",
        result.issues
    );
}

#[test]
fn does_not_warn_on_cdata_url_inside_extension() {
    let xml = r#"<VAST version="2.0">
    <Ad id="1">
        <InLine>
            <AdSystem>Test</AdSystem>
            <AdTitle>Test</AdTitle>
            <Impression><![CDATA[https://t.example.com/imp]]></Impression>
            <Creatives>
                <Creative>
                    <Linear>
                        <Duration>00:00:30</Duration>
                        <MediaFiles>
                            <MediaFile delivery="progressive" type="video/mp4" width="640" height="360"><![CDATA[https://cdn.example.com/ad.mp4]]></MediaFile>
                        </MediaFiles>
                    </Linear>
                </Creative>
            </Creatives>
            <Extensions>
                <Extension type="vendor">
                    <TrackingUrl><![CDATA[https://vendor.example.com/pixel?a=1&b=2]]></TrackingUrl>
                </Extension>
            </Extensions>
        </InLine>
    </Ad>
</VAST>"#;
    let result = validate(xml);
    assert!(
        !has_issue(&result, "VAST-2.0-url-cdata"),
        "CDATA-wrapped extension URLs should not trigger the url-cdata warning, got: {:#?}",
        result.issues
    );
}

#[test]
fn whitespace_only_input_produces_error() {
    let result = validate("   \n\t\n   ");
    assert!(
        !result.summary.is_valid(),
        "whitespace-only input should be invalid"
    );
}

#[test]
fn multiple_ads_each_validated_independently() {
    let xml = r#"<VAST version="2.0">
  <Ad id="good">
    <InLine>
      <AdSystem>Test</AdSystem>
      <AdTitle>Good</AdTitle>
      <Impression>https://t.example.com/imp</Impression>
      <Creatives>
        <Creative>
          <Linear>
            <Duration>00:00:30</Duration>
            <MediaFiles>
              <MediaFile delivery="progressive" type="video/mp4" width="640" height="360">
                https://cdn.example.com/ad.mp4
              </MediaFile>
            </MediaFiles>
          </Linear>
        </Creative>
      </Creatives>
    </InLine>
  </Ad>
  <Ad id="bad">
    <InLine>
      <!-- missing AdSystem, AdTitle, Impression, Creatives -->
    </InLine>
  </Ad>
</VAST>"#;
    let result = validate(xml);
    assert!(
        has_issue(&result, "VAST-2.0-inline-adsystem"),
        "second ad should fire missing adsystem"
    );
    assert!(!result.summary.is_valid());
}

// ── mediafile attribute completeness ─────────────────────────────────────────

#[test]
fn mediafile_missing_type_fires_error() {
    let result = validate(&load("err_mediafile_missing_type.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-mediafile-type"),
        "expected VAST-2.0-mediafile-type, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

// ── ad structure edge cases ───────────────────────────────────────────────────

#[test]
fn ad_with_both_inline_and_wrapper_fires_error() {
    let result = validate(&load("err_ad_both_inline_and_wrapper.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-ad-has-inline-or-wrapper"),
        "expected VAST-2.0-ad-has-inline-or-wrapper for ad with both InLine and Wrapper, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

// ── URL validation ────────────────────────────────────────────────────────────

#[test]
fn empty_url_fires_error() {
    let result = validate(&load("err_url_empty.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-url-empty"),
        "expected VAST-2.0-url-empty, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn invalid_url_fires_warning() {
    let result = validate(&load("warn_url_invalid.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-url-invalid"),
        "expected VAST-2.0-url-invalid, got: {:#?}",
        result.issues
    );
}

// ── bitrate rules ─────────────────────────────────────────────────────────────

#[test]
fn bitrate_conflict_fires_warning() {
    let result = validate(&load("warn_bitrate_conflict.xml"));
    assert!(
        has_issue(&result, "VAST-3.0-bitrate-conflict"),
        "expected VAST-3.0-bitrate-conflict, got: {:#?}",
        result.issues
    );
}

// ── progress tracking format ──────────────────────────────────────────────────

#[test]
fn progress_offset_bad_format_fires_warning() {
    let result = validate(&load("warn_progress_offset_bad_format.xml"));
    assert!(
        has_issue(&result, "VAST-3.0-progress-offset-format"),
        "expected VAST-3.0-progress-offset-format, got: {:#?}",
        result.issues
    );
}

// ── icon resource ─────────────────────────────────────────────────────────────

#[test]
fn icon_missing_resource_fires_error() {
    let result = validate(&load("err_icon_missing_resource.xml"));
    assert!(
        has_issue(&result, "VAST-3.0-icon-resource"),
        "expected VAST-3.0-icon-resource, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn icon_missing_recommended_attrs_fires_warning() {
    // err_icon_required_attrs.xml has no program/width/height/xPosition/yPosition —
    // the ambiguous.rs check fires VAST-3.0-icon-attrs as a Warning in addition to
    // the required.rs errors.
    let result = validate(&load("err_icon_required_attrs.xml"));
    assert!(
        has_issue(&result, "VAST-3.0-icon-attrs"),
        "expected VAST-3.0-icon-attrs warning, got: {:#?}",
        result.issues
    );
}

// ── companion rules ───────────────────────────────────────────────────────────

#[test]
fn companion_required_attr_bad_value_fires_warning() {
    let result = validate(&load("warn_companion_required_attr.xml"));
    assert!(
        has_issue(&result, "VAST-3.0-companion-required-attr"),
        "expected VAST-3.0-companion-required-attr, got: {:#?}",
        result.issues
    );
}

#[test]
fn companion_clicktracking_missing_id_fires_error() {
    let result = validate(&load("err_companion_clicktracking_no_id.xml"));
    assert!(
        has_issue(&result, "VAST-4.0-companion-clicktracking-id"),
        "expected VAST-4.0-companion-clicktracking-id, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn companion_renderingmode_bad_value_fires_warning() {
    let result = validate(&load("warn_companion_renderingmode.xml"));
    assert!(
        has_issue(&result, "VAST-4.1-companion-renderingmode-value"),
        "expected VAST-4.1-companion-renderingmode-value, got: {:#?}",
        result.issues
    );
}

// ── UniversalAdId value rules ─────────────────────────────────────────────────

#[test]
fn universaladid_no_idvalue_in_4_0_fires_error() {
    let result = validate(&load("err_universaladid_no_value.xml"));
    assert!(
        has_issue(&result, "VAST-4.0-universaladid-idvalue"),
        "expected VAST-4.0-universaladid-idvalue, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

#[test]
fn universaladid_idvalue_attr_in_4_1_fires_warning() {
    let result = validate(&load("warn_universaladid_idvalue_removed.xml"));
    assert!(
        has_issue(&result, "VAST-4.1-universaladid-idvalue-removed"),
        "expected VAST-4.1-universaladid-idvalue-removed, got: {:#?}",
        result.issues
    );
    // It's a Warning — document is still considered valid.
    assert!(result.summary.is_valid());
}

// ── wrapper-specific rules ────────────────────────────────────────────────────

#[test]
fn wrapper_clickthrough_in_4_1_fires_warning() {
    let result = validate(&load("warn_wrapper_clickthrough_v41.xml"));
    assert!(
        has_issue(&result, "VAST-4.0-wrapper-clickthrough"),
        "expected VAST-4.0-wrapper-clickthrough for VAST 4.1 wrapper, got: {:#?}",
        result.issues
    );
    assert!(result.summary.is_valid());
}

#[test]
fn blockedadcategories_missing_authority_fires_warning() {
    let result = validate(&load("warn_blockedadcategories_no_authority.xml"));
    assert!(
        has_issue(&result, "VAST-4.1-blockedadcategories-no-authority"),
        "expected VAST-4.1-blockedadcategories-no-authority, got: {:#?}",
        result.issues
    );
}

// ── deprecated attribute rules ────────────────────────────────────────────────

#[test]
fn conditionalad_in_4_1_fires_warning() {
    let result = validate(&load("warn_conditionalad_deprecated.xml"));
    assert!(
        has_issue(&result, "VAST-4.0-conditionalad"),
        "expected VAST-4.0-conditionalad, got: {:#?}",
        result.issues
    );
    assert!(result.summary.is_valid());
}

// ── adType value validation ───────────────────────────────────────────────────

#[test]
fn adtype_invalid_value_fires_warning() {
    let result = validate(&load("warn_adtype_invalid.xml"));
    assert!(
        has_issue(&result, "VAST-4.1-adtype-value"),
        "expected VAST-4.1-adtype-value, got: {:#?}",
        result.issues
    );
}

// ── ad sequence / pod rules ───────────────────────────────────────────────────

#[test]
fn ad_sequence_mixed_fires_warning() {
    let result = validate(&load("warn_ad_sequence_mixed.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-ad-sequence"),
        "expected VAST-2.0-ad-sequence, got: {:#?}",
        result.issues
    );
}

// ── singular-element cardinality ─────────────────────────────────────────────

// Nothing else catches these. The XSD enforced maxOccurs="1" for 2.0 through
// 4.2, but vast_4.4.xsd dropped cardinality entirely (IAB VAST issue #58), so
// for a 4.4 document neither the schema nor this validator used to notice.

#[test]
fn duplicate_vastadtaguri_fires() {
    let result = validate(&load("err_duplicate_vastadtaguri.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-duplicate-singular-element"),
        "expected VAST-2.0-duplicate-singular-element, got: {:#?}",
        result.issues
    );
}

#[test]
fn duplicate_linear_duration_fires() {
    let result = validate(&load("err_duplicate_linear_duration.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-duplicate-singular-element"),
        "expected VAST-2.0-duplicate-singular-element, got: {:#?}",
        result.issues
    );
}

// Repeatable elements must not trip it. <Impression>, <Error>, <Tracking> and
// <MediaFile> all legitimately repeat, and an earlier draft of the table that
// keyed on element name alone would have flagged them.
#[test]
fn repeatable_elements_do_not_fire_duplicate_singular() {
    for name in fixture_names() {
        let result = validate(&load(&name));
        let hit = result
            .issues
            .iter()
            .find(|i| i.id == "VAST-2.0-duplicate-singular-element");
        if let Some(issue) = hit {
            assert!(
                name.starts_with("err_duplicate_"),
                "unexpected duplicate-singular-element in {name}: {issue:?}"
            );
        }
    }
}

// ── large real-world warning fixtures ────────────────────────────────────────

#[test]
fn large_publica_fixture_stays_warning_only() {
    assert_large_publica_warning_fixture("warn_publica_large.xml");
}

#[test]
fn large_publica_pod_fixture_stays_warning_only() {
    assert_large_publica_warning_fixture("warn_publica_large_pod.xml");
}

#[test]
fn messy_vendor_wrapper_fixture_stays_warning_and_info_only() {
    let result = assert_no_errors("warn_wrapper_vendor_messy.xml");
    assert!(
        has_issue(&result, "VAST-4.0-wrapper-clickthrough"),
        "expected VAST-4.0-wrapper-clickthrough, got: {:#?}",
        result.issues
    );
    assert!(
        has_issue(&result, "VAST-2.0-tracking-https"),
        "expected VAST-2.0-tracking-https, got: {:#?}",
        result.issues
    );
    assert!(result.summary.is_valid());
}

#[test]
fn mixed_vendor_pod_fixture_stays_non_error_and_covers_pod_context_warnings() {
    let result = assert_no_errors("warn_mixed_vendor_pod.xml");
    assert!(
        has_issue(&result, "VAST-2.0-duplicate-impression"),
        "expected VAST-2.0-duplicate-impression, got: {:#?}",
        result.issues
    );
    assert!(
        has_issue(&result, "VAST-2.0-tracking-https"),
        "expected VAST-2.0-tracking-https, got: {:#?}",
        result.issues
    );
    assert!(
        has_issue(&result, "VAST-4.1-mezzanine-recommended"),
        "expected VAST-4.1-mezzanine-recommended, got: {:#?}",
        result.issues
    );
    assert!(result.summary.is_valid());
}

// ── wrapper depth ─────────────────────────────────────────────────────────────

#[test]
fn wrapper_depth_exceeded_fires_error() {
    use vastlint_core::{validate_with_context, ValidationContext};

    let xml = r#"<VAST version="4.1">
  <Ad id="1">
    <Wrapper>
      <AdSystem>Test</AdSystem>
      <Impression><![CDATA[https://track.example.com/impression]]></Impression>
      <VASTAdTagURI><![CDATA[https://ad.example.com/vast.xml]]></VASTAdTagURI>
    </Wrapper>
  </Ad>
</VAST>"#;

    let ctx = ValidationContext {
        wrapper_depth: 6,
        max_wrapper_depth: 5,
        ..Default::default()
    };
    let result = validate_with_context(xml, ctx);
    assert!(
        has_issue(&result, "VAST-2.0-wrapper-depth"),
        "expected VAST-2.0-wrapper-depth when depth exceeds max, got: {:#?}",
        result.issues
    );
    assert!(!result.summary.is_valid());
}

// ── linear quartile tracking ─────────────────────────────────────────────
#[test]
fn linear_no_quartile_tracking_fires_warning() {
    // A Linear with no TrackingEvents at all — complete measurement blackout.
    let xml = r#"<VAST version="4.1">
  <Ad id="1">
    <InLine>
      <AdSystem>Test</AdSystem>
      <AdServingId>abc123</AdServingId>
      <AdTitle>Test Ad</AdTitle>
      <Impression><![CDATA[https://track.example.com/imp]]></Impression>
      <Creatives>
        <Creative id="1">
          <UniversalAdId idRegistry="Ad-ID">abc123</UniversalAdId>
          <Linear>
            <Duration>00:00:30</Duration>
            <MediaFiles>
              <MediaFile type="video/mp4" width="1920" height="1080" bitrate="2000" delivery="progressive">
                <![CDATA[https://cdn.example.com/ad.mp4]]>
              </MediaFile>
            </MediaFiles>
          </Linear>
        </Creative>
      </Creatives>
    </InLine>
  </Ad>
</VAST>"#;
    let result = validate(xml);
    assert!(
        has_issue(&result, "VAST-2.0-linear-tracking-quartiles"),
        "expected VAST-2.0-linear-tracking-quartiles when no quartile events present, got: {:#?}",
        result.issues
    );
}

#[test]
fn linear_with_quartile_tracking_does_not_fire() {
    // A Linear with at least one quartile event — rule should not fire.
    let xml = r#"<VAST version="4.1">
  <Ad id="1">
    <InLine>
      <AdSystem>Test</AdSystem>
      <AdServingId>abc123</AdServingId>
      <AdTitle>Test Ad</AdTitle>
      <Impression><![CDATA[https://track.example.com/imp]]></Impression>
      <Creatives>
        <Creative id="1">
          <UniversalAdId idRegistry="Ad-ID">abc123</UniversalAdId>
          <Linear>
            <Duration>00:00:30</Duration>
            <TrackingEvents>
              <Tracking event="start"><![CDATA[https://track.example.com/start]]></Tracking>
              <Tracking event="firstQuartile"><![CDATA[https://track.example.com/q1]]></Tracking>
              <Tracking event="midpoint"><![CDATA[https://track.example.com/mid]]></Tracking>
              <Tracking event="thirdQuartile"><![CDATA[https://track.example.com/q3]]></Tracking>
              <Tracking event="complete"><![CDATA[https://track.example.com/complete]]></Tracking>
            </TrackingEvents>
            <MediaFiles>
              <MediaFile type="video/mp4" width="1920" height="1080" bitrate="2000" delivery="progressive">
                <![CDATA[https://cdn.example.com/ad.mp4]]>
              </MediaFile>
            </MediaFiles>
          </Linear>
        </Creative>
      </Creatives>
    </InLine>
  </Ad>
</VAST>"#;
    let result = validate(xml);
    let fired = result
        .issues
        .iter()
        .any(|i| i.id == "VAST-2.0-linear-tracking-quartiles");
    assert!(
        !fired,
        "VAST-2.0-linear-tracking-quartiles should not fire when quartile events are present, got: {:#?}",
        result.issues
    );
}

// ── catalog integrity ─────────────────────────────────────────────────────────

#[test]
fn all_rules_catalog_has_expected_count() {
    assert_eq!(
        vastlint_core::all_rules().len(),
        223,
        "catalog count changed — update this assertion and bump RULES.md"
    );
}

// ── issue path and location ───────────────────────────────────────────────────

#[test]
fn issue_path_and_location_are_populated_for_element_level_rules() {
    let result = validate(&load("err_missing_adsystem.xml"));
    let issue = result
        .issues
        .iter()
        .find(|i| i.id == "VAST-2.0-inline-adsystem")
        .expect("VAST-2.0-inline-adsystem should fire");
    assert!(
        issue.path.is_some(),
        "VAST-2.0-inline-adsystem should carry a path, got: {issue:?}"
    );
    assert!(
        issue.line.is_some(),
        "VAST-2.0-inline-adsystem should carry a line number, got: {issue:?}"
    );
    assert!(
        issue.col.is_some(),
        "VAST-2.0-inline-adsystem should carry a column number, got: {issue:?}"
    );
    let path = issue.path.as_deref().unwrap();
    assert!(
        path.contains("InLine"),
        "path should reference the InLine element, got: {path}"
    );
}

// ── rule override: upgrade severity ──────────────────────────────────────────

#[test]
fn rule_override_upgrade_info_to_error() {
    use std::collections::HashMap;
    use vastlint_core::{validate_with_context, RuleLevel, ValidationContext};

    let mut overrides = HashMap::new();
    overrides.insert("VAST-2.0-mediafile-https", RuleLevel::Error);

    let ctx = ValidationContext {
        rule_overrides: Some(overrides),
        ..Default::default()
    };

    let result = validate_with_context(&load("warn_http_mediafile.xml"), ctx);
    let issue = result
        .issues
        .iter()
        .find(|i| i.id == "VAST-2.0-mediafile-https")
        .expect("VAST-2.0-mediafile-https should fire");
    assert_eq!(
        issue.severity,
        Severity::Error,
        "severity should be Error after upgrade override"
    );
    assert!(
        !result.summary.is_valid(),
        "upgraded to Error means invalid"
    );
}

// ── version-gating negatives ──────────────────────────────────────────────────

#[test]
fn version_gated_rules_do_not_fire_below_minimum_version() {
    // VAST-4.1-adservingid-present is 4.1+; must not fire on a 4.0 document.
    let result = validate(&load("valid_4.0.xml"));
    assert!(
        !has_issue(&result, "VAST-4.1-adservingid-present"),
        "VAST-4.1-adservingid-present must not fire on a 4.0 document, got: {:#?}",
        result.issues
    );

    // VAST-4.0-universaladid-present is 4.0+; must not fire on a 3.0 document.
    let result = validate(&load("valid_3.0.xml"));
    assert!(
        !has_issue(&result, "VAST-4.0-universaladid-present"),
        "VAST-4.0-universaladid-present must not fire on a 3.0 document, got: {:#?}",
        result.issues
    );

    // Pricing rules are 3.0+; must not fire on a 2.0 document with no Pricing.
    let result = validate(&load("valid_2.0.xml"));
    assert!(
        !has_issue(&result, "VAST-3.0-pricing-model"),
        "VAST-3.0-pricing-model must not fire on a 2.0 document, got: {:#?}",
        result.issues
    );
}

// ── inspect_document ──────────────────────────────────────────────────────────

#[test]
fn inspect_document_extracts_inline_metadata() {
    use vastlint_core::{inspect_document, InspectAdType};

    let xml = minimal_valid_inline_xml("3.0", "", "");
    let meta = inspect_document(&xml);
    assert_eq!(meta.ad_type, InspectAdType::InLine);
    assert_eq!(meta.ad_system, "Test AdServer");
    assert_eq!(meta.impression_count, 1);
    // 5 tracking events: start, firstQuartile, midpoint, thirdQuartile, complete
    assert_eq!(meta.tracking_event_count, 5);
    assert_eq!(meta.media_files.len(), 1);
    assert_eq!(meta.media_files[0].mime_type, "video/mp4");
    assert_eq!(meta.media_files[0].delivery, "progressive");
    assert!(meta.wrapper_uri.is_none());
}

#[test]
fn inspect_document_extracts_wrapper_uri() {
    use vastlint_core::{inspect_document, InspectAdType};

    let xml = r#"<VAST version="4.1">
  <Ad id="1">
    <Wrapper>
      <AdSystem>SSP</AdSystem>
      <Impression><![CDATA[https://t.example.com/imp]]></Impression>
      <VASTAdTagURI><![CDATA[https://ads.example.com/next.xml]]></VASTAdTagURI>
    </Wrapper>
  </Ad>
</VAST>"#;
    let meta = inspect_document(xml);
    assert_eq!(meta.ad_type, InspectAdType::Wrapper);
    assert_eq!(meta.ad_system, "SSP");
    assert_eq!(
        meta.wrapper_uri.as_deref(),
        Some("https://ads.example.com/next.xml")
    );
    assert_eq!(meta.media_files.len(), 0);
}

// ── forced_version override ───────────────────────────────────────────────────

/// A minimal VAST 2.0 InLine document — valid for 2.0, missing 4.1+ required
/// fields (`AdServingId`, `UniversalAdId`).
const V2_INLINE_XML: &str = r#"<VAST version="2.0">
  <Ad id="1">
    <InLine>
      <AdSystem>Test</AdSystem>
      <AdTitle>Test Ad</AdTitle>
      <Impression><![CDATA[https://t.example.com/imp]]></Impression>
      <Creatives>
        <Creative>
          <Linear>
            <Duration>00:00:30</Duration>
            <MediaFiles>
              <MediaFile type="video/mp4" width="640" height="480" bitrate="500" delivery="progressive">
                <![CDATA[https://cdn.example.com/ad.mp4]]>
              </MediaFile>
            </MediaFiles>
          </Linear>
        </Creative>
      </Creatives>
    </InLine>
  </Ad>
</VAST>"#;

#[test]
fn forced_version_overrides_declared_version() {
    use vastlint_core::{validate_with_context, ValidationContext, VastVersion};

    // Force a 2.0 document to be validated as 4.1 — the 4.1-specific
    // AdServingId rule must fire even though the document declares 2.0.
    let ctx = ValidationContext {
        forced_version: Some(VastVersion::V4_1),
        ..Default::default()
    };
    let result = validate_with_context(V2_INLINE_XML, ctx);
    assert!(
        has_issue(&result, "VAST-4.1-adservingid-present"),
        "forced V4_1 should fire VAST-4.1-adservingid-present on a 2.0 doc, got: {:#?}",
        result.issues
    );
}

#[test]
fn forced_version_reported_in_result() {
    use vastlint_core::{validate_with_context, DetectedVersion, ValidationContext, VastVersion};

    let ctx = ValidationContext {
        forced_version: Some(VastVersion::V4_1),
        ..Default::default()
    };
    let result = validate_with_context(V2_INLINE_XML, ctx);
    // The reported version should reflect the override, not the XML attribute.
    assert_eq!(
        result.version,
        DetectedVersion::Declared(VastVersion::V4_1),
        "result.version should be Declared(V4_1) when forced, got: {:?}",
        result.version
    );
}

#[test]
fn no_forced_version_uses_declared_version() {
    use vastlint_core::{validate_with_context, ValidationContext};

    // Without an override the 2.0 document is validated as 2.0 and the
    // 4.1-specific AdServingId rule must NOT fire.
    let ctx = ValidationContext::default();
    let result = validate_with_context(V2_INLINE_XML, ctx);
    assert!(
        !has_issue(&result, "VAST-4.1-adservingid-present"),
        "VAST-4.1-adservingid-present must not fire on a plain 2.0 doc, got: {:#?}",
        result.issues
    );
}

#[test]
fn forced_version_downgrade_suppresses_newer_rules() {
    use vastlint_core::{validate_with_context, ValidationContext, VastVersion};

    // A fully valid 4.1 document forced to 2.0: none of the 4.x-only rules
    // should fire.
    let xml = include_str!("fixtures/valid_4.1.xml");
    let ctx = ValidationContext {
        forced_version: Some(VastVersion::V2_0),
        ..Default::default()
    };
    let result = validate_with_context(xml, ctx);
    for issue in &result.issues {
        assert!(
            !issue.id.starts_with("VAST-4."),
            "downgrading to V2_0 should suppress all 4.x rules, but {:?} fired",
            issue.id
        );
    }
}

#[test]
fn forced_version_none_is_identity() {
    use vastlint_core::{validate, validate_with_context, ValidationContext};

    // forced_version: None must produce exactly the same result as validate().
    let xml = include_str!("fixtures/valid_4.2.xml");
    let ctx = ValidationContext {
        forced_version: None,
        ..Default::default()
    };
    let result_ctx = validate_with_context(xml, ctx);
    let result_plain = validate(xml);
    assert_eq!(
        result_ctx.summary.errors, result_plain.summary.errors,
        "forced_version: None should be identical to validate() (errors)"
    );
    assert_eq!(
        result_ctx.summary.warnings, result_plain.summary.warnings,
        "forced_version: None should be identical to validate() (warnings)"
    );
    assert_eq!(
        result_ctx.issues.len(),
        result_plain.issues.len(),
        "forced_version: None issue count mismatch"
    );
}

// ── macro rules ────────────────────────────────────────────────────────────────

fn inline_with_impression(version: &str, impression_url: &str) -> String {
    minimal_valid_inline_xml(
        version,
        &format!("<Impression><![CDATA[{impression_url}]]></Impression>"),
        "",
    )
}

#[test]
fn macro_unknown_fires_on_unrecognised_token() {
    let xml = inline_with_impression("4.0", "https://e.com/i?z=[FOOBAR]");
    let result = validate(&xml);
    assert!(has_issue(&result, "VAST-2.0-macro-unknown"));
}

#[test]
fn macro_unknown_does_not_fire_on_known_macro() {
    let xml = inline_with_impression("4.0", "https://e.com/i?z=[CACHEBUSTING]");
    let result = validate(&xml);
    assert!(!has_issue(&result, "VAST-2.0-macro-unknown"));
}

#[test]
fn macro_unknown_ignores_array_indices() {
    let xml = inline_with_impression("4.0", "https://e.com/i?key[0]=5&c=[CACHEBUSTING]");
    let result = validate(&xml);
    assert!(!has_issue(&result, "VAST-2.0-macro-unknown"));
}

#[test]
fn macro_lowercase_fires_on_recognised_macro() {
    let xml = inline_with_impression("4.0", "https://e.com/i?z=[cachebusting]");
    let result = validate(&xml);
    assert!(has_issue(&result, "VAST-2.0-macro-lowercase"));
    assert!(!has_issue(&result, "VAST-2.0-macro-unknown"));
}

#[test]
fn macro_deprecated_fires_on_4_1() {
    let xml = inline_with_impression("4.1", "https://e.com/i?p=[CONTENTPLAYHEAD]");
    let result = validate(&xml);
    assert!(has_issue(&result, "VAST-4.1-macro-deprecated"));
}

#[test]
fn macro_deprecated_does_not_fire_on_3_0() {
    let xml = inline_with_impression("3.0", "https://e.com/i?p=[CONTENTPLAYHEAD]");
    let result = validate(&xml);
    assert!(!has_issue(&result, "VAST-4.1-macro-deprecated"));
    assert!(!has_issue(&result, "VAST-2.0-macro-unknown"));
}

#[test]
fn macro_wrong_context_fires_for_errorcode_outside_error() {
    let xml = inline_with_impression("4.0", "https://e.com/i?e=[ERRORCODE]");
    let result = validate(&xml);
    assert!(has_issue(&result, "VAST-2.0-macro-wrong-context"));
}

#[test]
fn macro_errorcode_in_error_element_is_valid_context() {
    let xml = minimal_valid_inline_xml(
        "4.0",
        "<Error><![CDATA[https://e.com/e?code=[ERRORCODE]]]></Error>",
        "",
    );
    let result = validate(&xml);
    assert!(!has_issue(&result, "VAST-2.0-macro-wrong-context"));
}

#[test]
fn macro_uri_unencoded_fires_on_raw_space() {
    let xml = inline_with_impression("4.0", "https://e.com/i?x=a b&c=[CACHEBUSTING]");
    let result = validate(&xml);
    assert!(has_issue(&result, "VAST-2.0-macro-uri-unencoded"));
}

#[test]
fn macro_uri_unencoded_does_not_fire_on_clean_url() {
    let xml = inline_with_impression("4.0", "https://e.com/i?c=[CACHEBUSTING]");
    let result = validate(&xml);
    assert!(!has_issue(&result, "VAST-2.0-macro-uri-unencoded"));
}

#[test]
fn macro_rules_ignore_free_text_elements() {
    // A [TOKEN] in AdTitle (not a URL field) must not be treated as a macro.
    let xml = r#"<VAST version="4.0">
    <Ad id="1">
        <InLine>
            <AdSystem>Test AdServer</AdSystem>
            <AdTitle>Buy [FOOBAR] now</AdTitle>
            <Impression><![CDATA[https://example.com/impression]]></Impression>
            <Creatives>
                <Creative>
                    <Linear>
                        <Duration>00:00:30</Duration>
                        <MediaFiles>
                            <MediaFile delivery="progressive" type="video/mp4" width="640" height="360"><![CDATA[https://example.com/video.mp4]]></MediaFile>
                        </MediaFiles>
                    </Linear>
                </Creative>
            </Creatives>
        </InLine>
    </Ad>
</VAST>"#;
    let result = validate(xml);
    assert!(!has_issue(&result, "VAST-2.0-macro-unknown"));
}

#[test]
fn macro_gdpr_is_recognised() {
    // [GDPR] (binary flag) and [GDPRCONSENT] (string) are both real macros.
    let xml = inline_with_impression("4.0", "https://e.com/i?g=[GDPR]&c=[GDPRCONSENT]");
    let result = validate(&xml);
    assert!(!has_issue(&result, "VAST-2.0-macro-unknown"));
}

#[test]
fn macro_errorcode_in_root_error_is_valid_context() {
    // Root-level <Error> (no-ad response) is a valid context for [ERRORCODE].
    let xml = r#"<VAST version="4.0">
    <Error><![CDATA[https://e.com/e?code=[ERRORCODE]]]></Error>
</VAST>"#;
    let result = validate(xml);
    assert!(!has_issue(&result, "VAST-2.0-macro-wrong-context"));
}

#[test]
fn macro_unknown_fires_in_root_error() {
    let xml = r#"<VAST version="4.0">
    <Error><![CDATA[https://e.com/e?x=[BOGUSMACRO]]]></Error>
</VAST>"#;
    let result = validate(xml);
    assert!(has_issue(&result, "VAST-2.0-macro-unknown"));
}

#[test]
fn macro_nested_open_bracket_still_detects_inner_macro() {
    let xml = inline_with_impression("4.0", "https://e.com/i?x=[[CACHEBUSTING]");
    let result = validate(&xml);
    // The inner [CACHEBUSTING] is a known macro, so no unknown warning.
    assert!(!has_issue(&result, "VAST-2.0-macro-unknown"));
}

#[test]
fn macro_unclosed_bracket_does_not_panic_or_flag() {
    let xml = inline_with_impression("4.0", "https://e.com/i?x=[CACHEBUSTING");
    let result = validate(&xml);
    // No closing bracket: not a macro reference, no macro issues.
    assert!(!has_issue(&result, "VAST-2.0-macro-unknown"));
    assert!(!has_issue(&result, "VAST-2.0-macro-lowercase"));
}

#[test]
fn macro_multibyte_text_does_not_panic() {
    // Emoji and non-ASCII around a macro must not break byte indexing.
    let xml = inline_with_impression("4.0", "https://e.com/i?q=café🎬&cb=[CACHEBUSTING]&z=[私]");
    let result = validate(&xml);
    // [私] is not a valid ASCII macro token, so it is ignored, not flagged.
    assert!(!has_issue(&result, "VAST-2.0-macro-unknown"));
}

#[test]
fn macro_overlong_bracket_content_is_ignored() {
    // A 60-char bracketed blob is past MAX_MACRO_LEN and must not be flagged.
    let long = "A".repeat(60);
    let xml = inline_with_impression("4.0", &format!("https://e.com/i?x=[{long}]"));
    let result = validate(&xml);
    assert!(!has_issue(&result, "VAST-2.0-macro-unknown"));
}

#[test]
fn macro_scan_handles_pathological_brackets_quickly() {
    // Regression guard for the former O(n^2) scan: a large run of unmatched
    // '[' must still validate. (Correctness, not a hard timing assert.)
    let brackets = "[".repeat(100_000);
    let xml = inline_with_impression("4.0", &format!("https://e.com/i?x={brackets}"));
    let result = validate(&xml);
    assert!(!has_issue(&result, "VAST-2.0-macro-unknown"));
}

// ── IAB Content Taxonomy authority validation ────────────────────────────────

#[test]
fn category_authority_recognised_forms_pass() {
    let result = validate(&load("valid_category_authority_iabtc.xml"));
    assert!(
        !has_issue(&result, "VAST-4.0-category-authority-not-uri"),
        "expected no not-uri issue, got: {:#?}",
        result.issues
    );
    assert!(!has_issue(&result, "VAST-4.0-category-authority-unknown"));
}

#[test]
fn category_authority_garbage_fires_not_uri() {
    let result = validate(&load("warn_category_authority_not_uri.xml"));
    assert!(
        has_issue(&result, "VAST-4.0-category-authority-not-uri"),
        "expected VAST-4.0-category-authority-not-uri, got: {:#?}",
        result.issues
    );
    assert!(!has_issue(&result, "VAST-4.0-category-authority-unknown"));
}

#[test]
fn category_authority_empty_fires_not_uri() {
    let xml = minimal_valid_inline_xml("4.2", r#"<Category authority="">IAB1</Category>"#, "");
    let result = validate(&xml);
    assert!(has_issue(&result, "VAST-4.0-category-authority-not-uri"));
}

#[test]
fn category_authority_custom_taxonomy_fires_unknown_info() {
    let result = validate(&load("info_category_authority_unknown.xml"));
    assert!(
        has_issue(&result, "VAST-4.0-category-authority-unknown"),
        "expected VAST-4.0-category-authority-unknown, got: {:#?}",
        result.issues
    );
    assert!(!has_issue(&result, "VAST-4.0-category-authority-not-uri"));
    let info = result
        .issues
        .iter()
        .find(|i| i.id == "VAST-4.0-category-authority-unknown")
        .unwrap();
    assert_eq!(info.severity, Severity::Info);
}

#[test]
fn category_authority_iab_com_passes() {
    let xml = minimal_valid_inline_xml(
        "4.2",
        r#"<Category authority="https://www.iab.com">IAB1</Category>"#,
        "",
    );
    let result = validate(&xml);
    assert!(!has_issue(&result, "VAST-4.0-category-authority-not-uri"));
    assert!(!has_issue(&result, "VAST-4.0-category-authority-unknown"));
}

#[test]
fn category_authority_value_not_checked_before_4_0() {
    let xml = minimal_valid_inline_xml("3.0", r#"<Category authority="???">IAB1</Category>"#, "");
    let result = validate(&xml);
    assert!(!has_issue(&result, "VAST-4.0-category-authority-not-uri"));
    assert!(!has_issue(&result, "VAST-4.0-category-authority-unknown"));
}

#[test]
fn blockedadcategories_authority_garbage_fires_not_uri() {
    let result = validate(&load("warn_blockedadcategories_authority_not_uri.xml"));
    assert!(
        has_issue(&result, "VAST-4.1-blockedadcategories-authority-not-uri"),
        "expected VAST-4.1-blockedadcategories-authority-not-uri, got: {:#?}",
        result.issues
    );
    assert!(!has_issue(
        &result,
        "VAST-4.1-blockedadcategories-authority-unknown"
    ));
}

#[test]
fn blockedadcategories_authority_recognised_passes() {
    let xml = r#"<VAST version="4.1">
  <Ad id="ad-001">
    <Wrapper>
      <AdSystem>Test</AdSystem>
      <Impression><![CDATA[https://track.example.com/impression]]></Impression>
      <VASTAdTagURI><![CDATA[https://ad.example.com/vast.xml]]></VASTAdTagURI>
      <BlockedAdCategories authority="iabtechlab.com">IAB25 IAB26</BlockedAdCategories>
    </Wrapper>
  </Ad>
</VAST>"#;
    let result = validate(xml);
    assert!(!has_issue(
        &result,
        "VAST-4.1-blockedadcategories-authority-not-uri"
    ));
    assert!(!has_issue(
        &result,
        "VAST-4.1-blockedadcategories-authority-unknown"
    ));
}

#[test]
fn blockedadcategories_custom_authority_fires_unknown() {
    let xml = r#"<VAST version="4.1">
  <Ad id="ad-001">
    <Wrapper>
      <AdSystem>Test</AdSystem>
      <Impression><![CDATA[https://track.example.com/impression]]></Impression>
      <VASTAdTagURI><![CDATA[https://ad.example.com/vast.xml]]></VASTAdTagURI>
      <BlockedAdCategories authority="blocklist.example.org">IAB25</BlockedAdCategories>
    </Wrapper>
  </Ad>
</VAST>"#;
    let result = validate(xml);
    assert!(has_issue(
        &result,
        "VAST-4.1-blockedadcategories-authority-unknown"
    ));
    assert!(!has_issue(
        &result,
        "VAST-4.1-blockedadcategories-authority-not-uri"
    ));
}

// ── unknown-attribute false positives (namespaced attrs + VAST 2.0 AdID) ──────

#[test]
fn xsi_and_xmlns_attributes_do_not_trigger_unknown_attribute() {
    // A schema-annotated, namespaced-but-compliant tag: the xsi:* and xmlns*
    // attributes belong to foreign namespaces and must not be flagged.
    let xml = r#"<VAST version="4.1"
    xmlns="http://www.iab.com/VAST"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="vast.xsd">
    <Ad id="1">
        <InLine>
            <AdSystem version="1.0">Test AdServer</AdSystem>
            <AdTitle>Test Ad</AdTitle>
            <AdServingId>a532</AdServingId>
            <Impression><![CDATA[https://example.com/impression]]></Impression>
            <Creatives>
                <Creative xsi:type="LinearCreativeType">
                    <UniversalAdId idRegistry="ad-id.org">UID-1</UniversalAdId>
                    <Linear>
                        <Duration>00:00:30</Duration>
                        <MediaFiles>
                            <MediaFile delivery="progressive" type="video/mp4" width="640" height="360"><![CDATA[https://example.com/video.mp4]]></MediaFile>
                        </MediaFiles>
                    </Linear>
                </Creative>
            </Creatives>
        </InLine>
    </Ad>
</VAST>"#;
    let result = validate(xml);
    let unknown_attrs: Vec<_> = result
        .issues
        .iter()
        .filter(|i| i.id == "VAST-2.0-unknown-attribute")
        .map(|i| i.path.clone().unwrap_or_default())
        .collect();
    assert!(
        unknown_attrs.is_empty(),
        "namespaced attributes should not be flagged, got: {unknown_attrs:?}"
    );
}

#[test]
fn vast_2_0_adid_casing_not_flagged_but_bogus_attr_still_is() {
    // `AdID` is the VAST 2.0 Creative casing — accepted. A genuinely unknown
    // attribute on the same element must still fire.
    let good = minimal_valid_inline_xml("2.0", "", "");
    let good = good.replace("<Creative>", r#"<Creative AdID="12345">"#);
    let result = validate(&good);
    assert!(
        !has_issue(&result, "VAST-2.0-unknown-attribute"),
        "AdID (VAST 2.0 casing) must not be flagged"
    );

    let bad = minimal_valid_inline_xml("2.0", "", "");
    let bad = bad.replace("<Creative>", r#"<Creative totallyBogus="x">"#);
    let result = validate(&bad);
    assert!(
        has_issue(&result, "VAST-2.0-unknown-attribute"),
        "a non-namespaced unknown attribute must still fire"
    );
}

// ── quality rules ─────────────────────────────────────────────────────────────

#[test]
fn adtitle_placeholder_fires_quality_warning() {
    for title in ["test", "Test Ad", "UNKNOWN", "Ad 1", "untitled", "  "] {
        let xml = minimal_valid_inline_xml("4.0", "", "").replace(
            "<AdTitle>Acme Spring Sale 30s</AdTitle>",
            &format!("<AdTitle>{title}</AdTitle>"),
        );
        let result = validate(&xml);
        assert!(
            has_issue(&result, "VAST-2.0-adtitle-quality"),
            "expected VAST-2.0-adtitle-quality for AdTitle {title:?}"
        );
    }
}

#[test]
fn real_adtitle_does_not_fire_quality_warning() {
    let result = validate(&minimal_valid_inline_xml("4.0", "", ""));
    assert!(
        !has_issue(&result, "VAST-2.0-adtitle-quality"),
        "a real AdTitle must not be flagged, got: {:#?}",
        result.issues
    );
}

#[test]
fn adsystem_placeholder_fires_quality_info() {
    for system in ["AdSystem", "unknown", "test", ""] {
        let xml = minimal_valid_inline_xml("4.0", "", "").replace(
            r#"<AdSystem version="1.0">Test AdServer</AdSystem>"#,
            &format!(r#"<AdSystem version="1.0">{system}</AdSystem>"#),
        );
        let result = validate(&xml);
        assert!(
            has_issue(&result, "VAST-2.0-adsystem-quality"),
            "expected VAST-2.0-adsystem-quality for AdSystem {system:?}"
        );
    }
}

#[test]
fn adsystem_without_version_fires_info() {
    let xml = minimal_valid_inline_xml("4.0", "", "").replace(
        r#"<AdSystem version="1.0">Test AdServer</AdSystem>"#,
        "<AdSystem>Test AdServer</AdSystem>",
    );
    let result = validate(&xml);
    assert!(has_issue(&result, "VAST-2.0-adsystem-no-version"));

    let with_version = validate(&minimal_valid_inline_xml("4.0", "", ""));
    assert!(
        !has_issue(&with_version, "VAST-2.0-adsystem-no-version"),
        "AdSystem with a version attribute must not be flagged"
    );
}

#[test]
fn quality_rules_fire_on_wrapper_adsystem() {
    let xml = r#"<VAST version="3.0">
    <Ad id="1">
        <Wrapper>
            <AdSystem>test</AdSystem>
            <VASTAdTagURI><![CDATA[https://example.com/vast.xml]]></VASTAdTagURI>
            <Impression><![CDATA[https://example.com/impression]]></Impression>
        </Wrapper>
    </Ad>
</VAST>"#;
    let result = validate(xml);
    assert!(has_issue(&result, "VAST-2.0-adsystem-quality"));
    assert!(has_issue(&result, "VAST-2.0-adsystem-no-version"));
}

// ── CTV Ad Portfolio / VAST 4.4 ───────────────────────────────────────────────

#[test]
fn ctv_pause_static_on_4_2_validates_clean() {
    // The IAB signaling guidance ships every CTV Ad Portfolio example as a
    // version="4.2" tag. If vastlint gated the new content model on 4.4 this
    // fixture would be full of unknown-child errors.
    let result = validate(&load("ok_ctv_pause_static_4_2.xml"));
    assert!(
        issues_with_severity(&result, Severity::Error).is_empty(),
        "IAB's own Pause example must validate without errors: {:#?}",
        result.issues
    );
    assert!(!has_issue(&result, "VAST-4.4-version-attribute"));
}

#[test]
fn ctv_overlay_simid_on_4_4_validates_clean_apart_from_draft_notice() {
    let result = validate(&load("ok_ctv_overlay_simid_4_4.xml"));
    assert!(
        issues_with_severity(&result, Severity::Error).is_empty(),
        "full 4.4 CTV content model must validate without errors: {:#?}",
        result.issues
    );

    // 4.4 is a working-group draft; say so, at info.
    assert!(has_issue(&result, "VAST-4.4-version-attribute"));

    // The new SIMID location must not trip the Linear-only fallback rule or
    // the superseded-IFrameResource advice.
    assert!(!has_issue(&result, "SIMID-1.0-simid-mediafile-required"));
    assert!(!has_issue(&result, "SIMID-1.1-nonlinear-simid-no-iframe"));
    assert!(!has_issue(&result, "VAST-4.4-nonlinear-simid-iframe"));
    assert!(!has_issue(
        &result,
        "VAST-4.4-nonlinear-no-renderable-asset"
    ));
    assert!(!has_issue(&result, "VAST-4.4-nonlinear-video-no-duration"));
    assert!(!has_issue(&result, "VAST-4.4-qrcode-missing-scan-url"));
}

#[test]
fn ctv_version_4_4_is_recognised_not_unknown() {
    let result = validate(&load("ok_ctv_overlay_simid_4_4.xml"));
    assert!(
        !has_issue(&result, "VAST-2.0-root-version-value"),
        "4.4 must parse as a known version, not fall through as unrecognised"
    );
    assert_eq!(result.version.best().map(|v| v.as_str()), Some("4.4"));
}

#[test]
fn ctv_nonlinear_simid_without_fallback_fires_warning() {
    let result = validate(&load("err_ctv_nonlinear_simid_no_fallback.xml"));
    assert!(has_issue(&result, "VAST-4.4-nonlinear-no-renderable-asset"));
    assert!(
        !has_issue(&result, "SIMID-1.0-simid-mediafile-required"),
        "the Linear-only media fallback rule must not fire on NonLinear"
    );
}

#[test]
fn ctv_adcom_signal_defects_all_fire() {
    let result = validate(&load("err_ctv_adcom_signal_values.xml"));
    assert!(has_issue(&result, "VAST-4.4-adcom-plcmt-value"));
    assert!(has_issue(&result, "VAST-4.4-adcom-pos-value"));
    assert!(has_issue(&result, "VAST-4.4-adcom-playbackmethod-value"));
    assert!(has_issue(&result, "VAST-4.4-adcom-attr-not-motion"));
    assert!(has_issue(
        &result,
        "VAST-4.4-adcom-extension-unknown-signal"
    ));
    assert!(has_issue(&result, "VAST-4.4-adcom-extension-type-mismatch"));
    assert!(has_issue(&result, "VAST-4.4-adcom-signal-not-integer"));
}

#[test]
fn ctv_adcom_valid_signals_stay_quiet() {
    let result = validate(&load("ok_ctv_overlay_simid_4_4.xml"));
    for id in [
        "VAST-4.4-adcom-plcmt-value",
        "VAST-4.4-adcom-pos-value",
        "VAST-4.4-adcom-playbackmethod-value",
        "VAST-4.4-adcom-attr-not-motion",
        "VAST-4.4-adcom-extension-unknown-signal",
        "VAST-4.4-adcom-extension-type-mismatch",
        "VAST-4.4-adcom-signal-not-integer",
        "VAST-4.4-adcom-pos-format-mismatch",
        "VAST-4.4-adcom-playbackmethod-format-mismatch",
    ] {
        assert!(
            !has_issue(&result, id),
            "{id} must not fire on valid signals"
        );
    }
}

#[test]
fn ctv_non_adcom_extension_is_not_inspected() {
    // A vendor Extension that happens to carry a <pos> child is none of our
    // business unless it declares ext="adcom".
    let xml = minimal_valid_inline_xml("4.2", "", "").replace(
        "</InLine>",
        r#"<Extensions><Extension type="vendor-thing"><vendorPos>99</vendorPos></Extension></Extensions></InLine>"#,
    );
    let result = validate(&xml);
    assert!(!has_issue(
        &result,
        "VAST-4.4-adcom-extension-unknown-signal"
    ));
    assert!(!has_issue(&result, "VAST-4.4-adcom-pos-value"));
}

#[test]
fn ctv_qrcode_geometry_defects_fire() {
    let result = validate(&load("err_ctv_qrcode_geometry.xml"));
    assert!(has_issue(&result, "VAST-4.4-qrcode-position-percent"));
    assert!(has_issue(&result, "VAST-4.4-qrcode-size-attr"));
    assert!(has_issue(&result, "VAST-4.4-qrcode-missing-scan-url"));
}

#[test]
fn ctv_creative_extension_without_qr_is_untouched() {
    // Only CreativeExtensions carrying QR elements are inspected.
    let xml = minimal_valid_inline_xml("4.2", "", "").replace(
        "</Creative>",
        r#"<CreativeExtensions><CreativeExtension type="vendor"><thing>1</thing></CreativeExtension></CreativeExtensions></Creative>"#,
    );
    let result = validate(&xml);
    assert!(!has_issue(&result, "VAST-4.4-qrcode-missing-scan-url"));
    assert!(!has_issue(&result, "VAST-4.4-qrcode-position-attrs"));
}

#[test]
fn ctv_nonlinear_content_model_still_rejected_below_4_0() {
    // Regression guard: relaxing NonLinear for 4.x must not relax it for 3.0.
    let result = validate(&load("err_ctv_nonlinear_mediafiles_in_4_2_only.xml"));
    assert!(
        has_issue(&result, "VAST-2.0-nonlinear-unknown-child"),
        "MediaFiles/Duration under NonLinear must still error on VAST 3.0: {:#?}",
        result.issues
    );
    assert!(
        has_issue(&result, "VAST-2.0-nonlinearads-unknown-child"),
        "Icons under NonLinearAds must still error on VAST 3.0: {:#?}",
        result.issues
    );
}

#[test]
fn ctv_nonlinear_video_without_duration_fires_warning() {
    let xml = load("ok_ctv_overlay_simid_4_4.xml").replace("<Duration>00:00:15</Duration>", "");
    let result = validate(&xml);
    assert!(has_issue(&result, "VAST-4.4-nonlinear-video-no-duration"));
}

#[test]
fn ctv_nonlinear_simid_iframe_pattern_flagged_as_superseded() {
    let xml = r#"<VAST version="4.2">
    <Ad id="1">
        <InLine>
            <AdSystem version="1.0">Test AdServer</AdSystem>
            <AdTitle>Overlay SIMID legacy pattern</AdTitle>
            <Impression><![CDATA[https://example.com/impression]]></Impression>
            <AdServingId>abc-123</AdServingId>
            <Creatives>
                <Creative id="1" adId="1">
                    <UniversalAdId idRegistry="ad-id.org">CNPA0484000H</UniversalAdId>
                    <NonLinearAds>
                        <NonLinear width="480" height="70">
                            <IFrameResource apiFramework="SIMID" type="text/html"><![CDATA[https://example.com/simid.html]]></IFrameResource>
                            <MediaFiles>
                                <MediaFile delivery="progressive" type="image/jpeg" width="480" height="70"><![CDATA[https://example.com/overlay.jpg]]></MediaFile>
                            </MediaFiles>
                        </NonLinear>
                    </NonLinearAds>
                </Creative>
            </Creatives>
        </InLine>
    </Ad>
</VAST>"#;
    let result = validate(xml);
    assert!(has_issue(&result, "VAST-4.4-nonlinear-simid-iframe"));
}

/// The per-signal `ext="adcom"` shape is defined by the 4.x guidance. A 2.0
/// document signals through `<Extension type="ctv_ad_portfolio">` instead, so
/// none of the 4.x extension-shape or NonLinear content-model rules apply.
#[test]
fn ctv_portfolio_rules_do_not_fire_on_vast_2_0() {
    let xml = load("err_ctv_adcom_signal_values.xml")
        .replace(r#"<VAST version="4.2">"#, r#"<VAST version="2.0">"#);
    let result = validate(&xml);
    for issue in &result.issues {
        assert!(
            !issue.id.starts_with("VAST-4.4-"),
            "no 4.4 rule may fire on a 2.0 document, got {}",
            issue.id
        );
    }
}

/// IAB's own conforming example from extensions/ctv_qrcode.md. The whole point
/// of the 2.0 extension path is that a tag like this is correct, so it must not
/// collect findings, and in particular must not be told its MediaFiles are
/// misplaced or its version inconsistent.
#[test]
fn ctv_portfolio_vast_2_0_example_is_clean() {
    let result = validate(&load("ok_ctv_portfolio_vast_2_0.xml"));

    for id in [
        "VAST-2.0-extension-misplaced-element",
        "VAST-2.0-version-mismatch",
        "VAST-2.0-creative-extension-misplaced-element",
    ] {
        assert!(
            !has_issue(&result, id),
            "{} must not fire on a conforming VAST 2.0 CTV Ad Portfolio tag",
            id
        );
    }

    assert!(
        result.issues.iter().all(|i| i.severity != Severity::Error),
        "unexpected errors: {:?}",
        result.issues
    );
}

/// The 2.0 container has its own failure modes, and the binding one is the
/// dangerous one: without CreativeId the extension silently attaches to
/// whichever creative the platform picks.
#[test]
fn ctv_portfolio_vast_2_0_binding_and_media_defects() {
    let result = validate(&load("err_ctv_portfolio_vast_2_0_binding.xml"));

    assert!(has_issue(
        &result,
        "VAST-2.0-ctv-portfolio-creative-id-required"
    ));
    assert!(has_issue(
        &result,
        "VAST-2.0-ctv-portfolio-creative-id-unmatched"
    ));
    assert!(has_issue(
        &result,
        "VAST-2.0-ctv-portfolio-no-renderable-asset"
    ));
    assert!(has_issue(&result, "VAST-2.0-ctv-portfolio-no-duration"));
    // Value checks are container-neutral and keep their single id.
    assert!(has_issue(&result, "VAST-4.4-adcom-plcmt-value"));
}

/// Nothing renders: the container carries no media and the creative has no
/// native `<NonLinear>` resource to fall back to.
#[test]
fn ctv_portfolio_vast_2_0_requires_media_files() {
    let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<VAST version="2.0">
  <Ad id="a">
    <InLine>
      <AdSystem version="1.0">ExampleAdServer</AdSystem>
      <AdTitle>Pause</AdTitle>
      <Impression><![CDATA[https://track.example.com/imp]]></Impression>
      <Creatives>
        <Creative id="c1">
          <NonLinearAds>
            <NonLinear id="nl" width="1920" height="1080">
              <NonLinearClickThrough><![CDATA[https://advertiser.example.com/landing]]></NonLinearClickThrough>
            </NonLinear>
          </NonLinearAds>
        </Creative>
      </Creatives>
      <Extensions>
        <Extension type="ctv_ad_portfolio">
          <plcmt>5</plcmt>
        </Extension>
      </Extensions>
    </InLine>
  </Ad>
</VAST>"#;

    let result = validate(xml);
    assert!(has_issue(
        &result,
        "VAST-2.0-ctv-portfolio-mediafiles-required"
    ));
}

/// The mirror case: signalling-only use of the container is conforming when the
/// creative renders from a native VAST 2.0 resource, which is the shape of
/// IAB's own pause example.
#[test]
fn ctv_portfolio_vast_2_0_allows_signalling_only_container() {
    let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<VAST version="2.0">
  <Ad id="a">
    <InLine>
      <AdSystem version="1.0">ExampleAdServer</AdSystem>
      <AdTitle>Pause</AdTitle>
      <Impression><![CDATA[https://track.example.com/imp]]></Impression>
      <Creatives>
        <Creative id="c1">
          <NonLinearAds>
            <NonLinear id="nl" width="1920" height="1080">
              <StaticResource creativeType="image/png"><![CDATA[https://cdn.example.com/a.png]]></StaticResource>
            </NonLinear>
          </NonLinearAds>
        </Creative>
      </Creatives>
      <Extensions>
        <Extension type="ctv_ad_portfolio">
          <plcmt>5</plcmt>
          <attr>19</attr>
        </Extension>
      </Extensions>
    </InLine>
  </Ad>
</VAST>"#;

    let result = validate(xml);
    assert!(!has_issue(
        &result,
        "VAST-2.0-ctv-portfolio-mediafiles-required"
    ));
    // 19 is a CTV Ad Portfolio attribute as of AdCOM 1.0-202607.
    assert!(!has_issue(&result, "VAST-4.4-adcom-attr-not-motion"));
}

/// The two extension documents IAB published on 2026-07-17 are written against
/// VAST 2.0, but nothing in either container reads the version, so the checks
/// are not gated on one. A 3.0 tag carrying the same container is the same
/// document with a different version string and has to report the same
/// findings, clean and defective alike.
///
/// Comparing the whole issue set rather than the portfolio ids alone is
/// deliberate: a version gate added by accident anywhere in the path, or a
/// generic rule that starts reporting the container on 3.0 only, shows up here
/// as a difference.
#[test]
fn ctv_portfolio_extension_path_reports_the_same_on_vast_3_0() {
    for fixture in [
        "ok_ctv_portfolio_vast_2_0.xml",
        "err_ctv_portfolio_vast_2_0_binding.xml",
    ] {
        let as_2_0 = load(fixture);
        let as_3_0 = as_2_0.replace(r#"<VAST version="2.0">"#, r#"<VAST version="3.0">"#);
        assert_ne!(
            as_2_0, as_3_0,
            "{fixture} no longer declares 2.0, so this test compares a document with itself"
        );

        let result_2_0 = validate(&as_2_0);
        let result_3_0 = validate(&as_3_0);

        let mut ids_2_0: Vec<&str> = result_2_0.issues.iter().map(|i| i.id).collect();
        let mut ids_3_0: Vec<&str> = result_3_0.issues.iter().map(|i| i.id).collect();
        ids_2_0.sort_unstable();
        ids_3_0.sort_unstable();

        assert_eq!(
            ids_2_0, ids_3_0,
            "{fixture}: the CTV Ad Portfolio extension path must not be version gated"
        );
    }
}

/// Every failure mode of the legacy extension path in one document, asserted as
/// an exact set rather than rule by rule.
///
/// The per-rule tests above each prove one rule fires. This proves the category
/// as a whole: that all of it is reachable from a single realistic tag, and
/// that nothing else fires alongside it. An exact-set assertion is the point,
/// because it fails in both directions. A rule that stops firing is caught, and
/// so is a new rule that starts reporting this document without anyone deciding
/// it should.
///
/// Several of these rules are mutually exclusive inside one container, so the
/// fixture isolates each in its own `<Ad>`.
#[test]
fn ctv_portfolio_legacy_path_covers_every_reachable_rule() {
    let xml = load("err_ctv_portfolio_legacy_all_modes.xml");
    let result = validate(&xml);

    let mut got: Vec<&str> = result.issues.iter().map(|i| i.id).collect();
    got.sort_unstable();
    got.dedup();

    let expected = [
        // The container's own contract.
        "VAST-2.0-ctv-portfolio-creative-id-required",
        "VAST-2.0-ctv-portfolio-creative-id-unmatched",
        "VAST-2.0-ctv-portfolio-mediafiles-empty",
        "VAST-2.0-ctv-portfolio-mediafiles-required",
        "VAST-2.0-ctv-portfolio-no-duration",
        "VAST-2.0-ctv-portfolio-no-renderable-asset",
        // Not a portfolio rule. Ads 3 and 5 carry a deliberately bare
        // <NonLinear> so the container is the only possible delivery vehicle,
        // and the pre-existing 2.0 rule is right to say so.
        "VAST-2.0-nonlinear-resource",
        // Shared with the 4.x encoding, one id per defect rather than a
        // per-container duplicate.
        "VAST-4.4-adcom-attr-not-motion",
        "VAST-4.4-adcom-playbackmethod-format-mismatch",
        "VAST-4.4-adcom-playbackmethod-value",
        "VAST-4.4-adcom-plcmt-value",
        "VAST-4.4-adcom-pos-format-mismatch",
        "VAST-4.4-adcom-pos-value",
        "VAST-4.4-adcom-signal-not-integer",
        "VAST-4.4-qrcode-missing-image-url",
        "VAST-4.4-qrcode-missing-scan-url",
        "VAST-4.4-qrcode-position-attrs",
        "VAST-4.4-qrcode-position-percent",
        "VAST-4.4-qrcode-size-attr",
        "VAST-4.4-qrcode-size-percent",
    ];

    assert_eq!(got, expected);
}

/// The coverage claim behind the fixture, checked against the catalog rather
/// than against a number written down by hand.
///
/// Every rule in the CTV Ad Portfolio category either fires on that document or
/// is one of the seven gated on 4.x, which a legacy document cannot reach by
/// definition: the four `<NonLinear>` content-model rules, the two
/// `<Extension ext="adcom">` shape rules, and the 4.4 version notice.
///
/// Guards the claim itself. Add a legacy-reachable rule to the category without
/// adding it to the fixture and this fails, so the fixture cannot silently fall
/// behind the catalog.
#[test]
fn ctv_portfolio_legacy_fixture_reaches_every_non_4x_rule() {
    let result = validate(&load("err_ctv_portfolio_legacy_all_modes.xml"));
    let fired: std::collections::HashSet<&str> = result.issues.iter().map(|i| i.id).collect();

    const FOUR_X_ONLY: [&str; 7] = [
        "VAST-4.4-version-attribute",
        "VAST-4.4-nonlinear-no-renderable-asset",
        "VAST-4.4-nonlinear-mediafiles-empty",
        "VAST-4.4-nonlinear-simid-iframe",
        "VAST-4.4-nonlinear-video-no-duration",
        "VAST-4.4-adcom-extension-unknown-signal",
        "VAST-4.4-adcom-extension-type-mismatch",
    ];

    let unreached: Vec<&str> = vastlint_core::all_rules()
        .iter()
        .map(|r| r.id)
        .filter(|id| id.starts_with("VAST-4.4-") || id.contains("ctv-portfolio"))
        .filter(|id| !fired.contains(id) && !FOUR_X_ONLY.contains(id))
        .collect();

    assert!(
        unreached.is_empty(),
        "legacy-reachable CTV Ad Portfolio rules with no coverage in the fixture: {:?}",
        unreached
    );
}

/// The whole question the fixture exists to answer: the same document declared
/// 3.0 reports exactly the same thing. IAB wrote the extension documents
/// against 2.0 and published no 3.0 variant, but neither container reads the
/// version, so nothing about the output may depend on it.
#[test]
fn ctv_portfolio_legacy_fixture_is_identical_on_vast_3_0() {
    let as_2_0 = load("err_ctv_portfolio_legacy_all_modes.xml");
    let as_3_0 = as_2_0.replace(r#"<VAST version="2.0">"#, r#"<VAST version="3.0">"#);
    assert_ne!(
        as_2_0, as_3_0,
        "fixture no longer declares 2.0, so this compares a document with itself"
    );

    let result_2_0 = validate(&as_2_0);
    let result_3_0 = validate(&as_3_0);

    let mut ids_2_0: Vec<&str> = result_2_0.issues.iter().map(|i| i.id).collect();
    let mut ids_3_0: Vec<&str> = result_3_0.issues.iter().map(|i| i.id).collect();
    ids_2_0.sort_unstable();
    ids_3_0.sort_unstable();

    assert_eq!(ids_2_0, ids_3_0);
}

/// Geometry with no image is the same defect as geometry with no destination,
/// for the other asset. The schema requires neither, so both come from the
/// guidance.
#[test]
fn ctv_qrcode_geometry_without_an_image_url_fires() {
    let xml = load("err_ctv_qrcode_geometry.xml");
    assert!(has_issue(
        &validate(&xml),
        "VAST-4.4-qrcode-missing-image-url"
    ));

    // A QR extension that supplies the image must not be reported.
    let with_image = load("ok_ctv_portfolio_vast_2_0.xml");
    assert!(!has_issue(
        &validate(&with_image),
        "VAST-4.4-qrcode-missing-image-url"
    ));
}

/// `xmlEncoded` is a boolean the player reads to decide whether to XML decode
/// the payload before handing it to VPAID or SIMID. Nothing looked at the value
/// before, so `xmlEncoded="yes"` validated clean.
///
/// Dispatched by element name, so the same rule covers `<Linear>` and the CTV
/// Ad Portfolio extension container without a second traversal. That is the
/// architecture paying for itself.
#[test]
fn adparameters_xmlencoded_must_be_a_boolean() {
    let creative = |ad_params: &str| {
        format!(
            r#"<VAST version="3.0"><Ad id="a"><InLine>
                 <AdSystem version="1.0">X</AdSystem><AdTitle>T</AdTitle>
                 <Impression><![CDATA[https://t.example.com/i]]></Impression>
                 <Creatives><Creative id="c1"><Linear>
                   <Duration>00:00:15</Duration>
                   {ad_params}
                   <MediaFiles><MediaFile delivery="progressive" type="video/mp4" width="640" height="360"><![CDATA[https://cdn.example.com/a.mp4]]></MediaFile></MediaFiles>
                 </Linear></Creative></Creatives>
               </InLine></Ad></VAST>"#
        )
    };

    const ID: &str = "VAST-3.0-adparameters-xmlencoded-value";
    assert!(has_issue(
        &validate(&creative(
            r#"<AdParameters xmlEncoded="yes">x</AdParameters>"#
        )),
        ID
    ));
    for ok in ["true", "false", "1", "0", "TRUE"] {
        let xml = creative(&format!(
            r#"<AdParameters xmlEncoded="{ok}">x</AdParameters>"#
        ));
        assert!(!has_issue(&validate(&xml), ID), "{ok} is a valid boolean");
    }
    // Absent is legal; the attribute is optional.
    assert!(!has_issue(
        &validate(&creative("<AdParameters>x</AdParameters>")),
        ID
    ));

    // The same rule inside the legacy container, reached by dispatch rather
    // than by a second hand-written traversal.
    let in_container = r#"<VAST version="2.0"><Ad id="a"><InLine>
         <AdSystem version="1.0">X</AdSystem><AdTitle>T</AdTitle>
         <Impression><![CDATA[https://t.example.com/i]]></Impression>
         <Creatives><Creative id="c1"><NonLinearAds><NonLinear id="nl" width="1" height="1">
           <StaticResource creativeType="image/png"><![CDATA[https://cdn.example.com/a.png]]></StaticResource>
         </NonLinear></NonLinearAds></Creative></Creatives>
         <Extensions><Extension type="ctv_ad_portfolio"><CreativeId>c1</CreativeId><plcmt>5</plcmt>
           <AdParameters xmlEncoded="yes">x</AdParameters>
           <MediaFiles><MediaFile delivery="progressive" type="image/png" width="1" height="1"><![CDATA[https://cdn.example.com/a.png]]></MediaFile></MediaFiles>
         </Extension></Extensions>
       </InLine></Ad></VAST>"#;
    assert!(has_issue(&validate(in_container), ID));
}

/// Migrating `<Duration>` to name dispatch closed a gap nobody had filed.
///
/// The old code checked it under `<Linear>` and, since 0.11.4, inside the
/// extension container. The CTV Ad Portfolio also put a `<Duration>` under
/// `<NonLinear>` on 4.x, and that one was never format-checked. No traversal
/// was written for it and no fixture covered it, so nothing failed. Dispatching
/// by element name covered it without a line of code aimed at the case.
#[test]
fn duration_format_is_checked_under_nonlinear_too() {
    let xml = r#"<VAST version="4.2"><Ad id="a"><InLine>
         <AdSystem version="1.0">X</AdSystem><AdTitle>T</AdTitle><AdServingId>s</AdServingId>
         <Impression><![CDATA[https://t.example.com/i]]></Impression>
         <Creatives><Creative id="c1"><UniversalAdId idRegistry="ad-id">A</UniversalAdId>
           <NonLinearAds><NonLinear id="nl" width="1" height="1">
             <Duration>banana</Duration>
             <MediaFiles><MediaFile delivery="progressive" type="video/mp4" width="1" height="1"><![CDATA[https://cdn.example.com/a.mp4]]></MediaFile></MediaFiles>
           </NonLinear></NonLinearAds>
         </Creative></Creatives></InLine></Ad></VAST>"#;
    assert!(has_issue(&validate(xml), "VAST-2.0-duration-format"));
}

/// `<Tracking>` is one of the few elements whose meaning depends on where it
/// sits. `<Verification>` tracking uses its own vocabulary
/// (`verificationNotExecuted`) and has its own checker, so the Linear and
/// NonLinear event enum must not be applied there.
///
/// Dispatching it by name without this guard reported a conforming
/// AdVerifications block as defective. Caught by the corpus diff, not by any
/// existing test, which is why this one exists.
#[test]
fn verification_tracking_events_keep_their_own_vocabulary() {
    let result = validate(&load("warn_verification_tracking_reason.xml"));
    let on_verification = result.issues.iter().any(|i| {
        i.id == "VAST-4.1-tracking-event-value"
            && i.path
                .as_deref()
                .is_some_and(|p| p.contains("Verification"))
    });
    assert!(
        !on_verification,
        "the Linear tracking enum must not be applied to <Verification> tracking: {:?}",
        result.issues.iter().map(|i| i.id).collect::<Vec<_>>()
    );
}

/// The element gates have to be per element, not per subtree.
///
/// `<AdParameters>` is valid under a VAST 2.0 `<NonLinear>`. An early version of
/// the dispatch skipped everything inside a `<NonLinear>` below 4.0, to avoid
/// double-reporting the 4.x-only content model, and silently took this with it.
#[test]
fn adparameters_is_still_checked_under_a_vast_2_0_nonlinear() {
    let xml = r#"<VAST version="2.0"><Ad id="a"><InLine>
         <AdSystem version="1.0">X</AdSystem><AdTitle>T</AdTitle>
         <Impression><![CDATA[https://t.example.com/i]]></Impression>
         <Creatives><Creative id="c1"><NonLinearAds><NonLinear id="nl" width="1" height="1">
           <StaticResource creativeType="image/png"><![CDATA[https://cdn.example.com/a.png]]></StaticResource>
           <AdParameters xmlEncoded="yes">x</AdParameters>
         </NonLinear></NonLinearAds></Creative></Creatives>
       </InLine></Ad></VAST>"#;
    assert!(has_issue(
        &validate(xml),
        "VAST-3.0-adparameters-xmlencoded-value"
    ));
}

/// The property that makes the traversal class of bug impossible rather than
/// merely fixed.
///
/// The same defective `<MediaFile>` is placed in every container the spec has
/// ever put one in, and every location must report the same rules. This test
/// would have failed before 0.11.1 (NonLinear unvalidated) and again before
/// 0.11.4 (the extension container unvalidated). Both were found by hand, one
/// of them only because someone asked the right question.
///
/// Adding a location to this list is the whole cost of covering a new one. If
/// the element dispatch in `elements.rs` regresses to a hand-written traversal
/// that forgets a spot, this fails on the spot.
#[test]
fn the_same_defective_media_file_reports_identically_everywhere() {
    const BARE: &str = r#"<MediaFile><![CDATA[https://cdn.example.com/a.mp4]]></MediaFile>"#;

    // 4.2 throughout: the only version where all three containers are legal at
    // once. The NonLinear content model is 4.x, and the extension container is
    // valid on any version.
    let under_linear = format!(
        r#"<VAST version="4.2"><Ad id="a"><InLine>
             <AdSystem version="1.0">X</AdSystem><AdTitle>T</AdTitle>
             <AdServingId>s</AdServingId>
             <Impression><![CDATA[https://t.example.com/i]]></Impression>
             <Creatives><Creative id="c1">
               <UniversalAdId idRegistry="ad-id">AD</UniversalAdId>
               <Linear><Duration>00:00:15</Duration><MediaFiles>{BARE}</MediaFiles></Linear>
             </Creative></Creatives>
           </InLine></Ad></VAST>"#
    );

    let under_non_linear = format!(
        r#"<VAST version="4.2"><Ad id="a"><InLine>
             <AdSystem version="1.0">X</AdSystem><AdTitle>T</AdTitle>
             <AdServingId>s</AdServingId>
             <Impression><![CDATA[https://t.example.com/i]]></Impression>
             <Creatives><Creative id="c1">
               <UniversalAdId idRegistry="ad-id">AD</UniversalAdId>
               <NonLinearAds><NonLinear id="nl" width="1920" height="1080">
                 <MediaFiles>{BARE}</MediaFiles>
               </NonLinear></NonLinearAds>
             </Creative></Creatives>
           </InLine></Ad></VAST>"#
    );

    let inside_portfolio_extension = format!(
        r#"<VAST version="4.2"><Ad id="a"><InLine>
             <AdSystem version="1.0">X</AdSystem><AdTitle>T</AdTitle>
             <AdServingId>s</AdServingId>
             <Impression><![CDATA[https://t.example.com/i]]></Impression>
             <Creatives><Creative id="c1">
               <UniversalAdId idRegistry="ad-id">AD</UniversalAdId>
               <NonLinearAds><NonLinear id="nl" width="1920" height="1080">
                 <StaticResource creativeType="image/jpeg"><![CDATA[https://cdn.example.com/a.jpg]]></StaticResource>
               </NonLinear></NonLinearAds>
             </Creative></Creatives>
             <Extensions><Extension type="ctv_ad_portfolio">
               <CreativeId>c1</CreativeId><plcmt>5</plcmt>
               <MediaFiles>{BARE}</MediaFiles>
             </Extension></Extensions>
           </InLine></Ad></VAST>"#
    );

    let media_file_rules = |xml: &str| {
        let mut ids: Vec<&str> = validate(xml)
            .issues
            .iter()
            .filter(|i| i.id.contains("mediafile"))
            .map(|i| i.id)
            .collect();
        ids.sort_unstable();
        ids.dedup();
        ids
    };

    let baseline = media_file_rules(&under_linear);
    assert!(
        !baseline.is_empty(),
        "the Linear case must report something, or this test proves nothing"
    );

    for (location, xml) in [
        (
            "NonLinear <MediaFiles> (4.x content model)",
            &under_non_linear,
        ),
        (
            "<Extension type=\"ctv_ad_portfolio\"> (legacy encoding)",
            &inside_portfolio_extension,
        ),
    ] {
        assert_eq!(
            media_file_rules(xml),
            baseline,
            "a <MediaFile> in {location} must report the same rules as one under <Linear>"
        );
    }
}

/// The container holds the ad's real media, duration, icons and tracking,
/// because VAST 2.0 has no other element that can. So the rules for those
/// elements have to reach inside it, exactly as 0.11.1 took them inside
/// `<NonLinear>` for the 4.x content model.
///
/// Before this traversal existed the whole document below reported nothing at
/// all. The identical elements under `<Linear>` are 11 errors and 2 warnings.
#[test]
fn ctv_portfolio_container_contents_get_the_element_rules() {
    let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<VAST version="2.0">
  <Ad id="a">
    <InLine>
      <AdSystem version="1.0">ExampleAdServer</AdSystem>
      <AdTitle>Pause</AdTitle>
      <Impression><![CDATA[https://track.example.com/imp]]></Impression>
      <Creatives>
        <Creative id="c1">
          <NonLinearAds>
            <NonLinear id="nl" width="1920" height="1080">
              <StaticResource creativeType="image/jpeg"><![CDATA[https://cdn.example.com/a.jpg]]></StaticResource>
            </NonLinear>
          </NonLinearAds>
        </Creative>
      </Creatives>
      <Extensions>
        <Extension type="ctv_ad_portfolio">
          <CreativeId>c1</CreativeId>
          <plcmt>5</plcmt>
          <Duration>banana</Duration>
          <TrackingEvents>
            <Tracking event="notARealEvent"><![CDATA[https://track.example.com/e]]></Tracking>
          </TrackingEvents>
          <Icons>
            <Icon><StaticResource creativeType="image/png"><![CDATA[https://cdn.example.com/ac.png]]></StaticResource></Icon>
          </Icons>
          <MediaFiles>
            <MediaFile><![CDATA[https://cdn.example.com/a.mp4]]></MediaFile>
            <InteractiveCreativeFile><![CDATA[https://cdn.example.com/s.html]]></InteractiveCreativeFile>
          </MediaFiles>
        </Extension>
      </Extensions>
    </InLine>
  </Ad>
</VAST>"#;

    let result = validate(xml);
    for id in [
        "VAST-2.0-mediafile-delivery",
        "VAST-2.0-mediafile-type",
        "VAST-2.0-mediafile-dimensions",
        "VAST-4.0-interactive-creative-no-api",
        "VAST-4.1-interactive-creative-type",
        "VAST-3.0-icon-program",
        "VAST-3.0-icon-width",
        "VAST-3.0-icon-height",
        "VAST-3.0-icon-xposition",
        "VAST-3.0-icon-yposition",
        "VAST-3.0-icon-attrs",
        "VAST-2.0-duration-format",
        "VAST-4.1-tracking-event-value",
    ] {
        assert!(
            has_issue(&result, id),
            "{id} must fire inside <Extension type=\"ctv_ad_portfolio\">"
        );
    }

    // The findings have to point at the element, not at the container, or a CI
    // annotation sends someone to the wrong line.
    let mf = result
        .issues
        .iter()
        .find(|i| i.id == "VAST-2.0-mediafile-delivery")
        .expect("checked above");
    assert_eq!(
        mf.path.as_deref(),
        Some("/VAST/Ad[0]/InLine/Extensions/Extension[0]/MediaFiles/MediaFile[0]")
    );

    // Same document on 3.0. The container is the legacy encoding, so the
    // traversal must not be gated on a version the way the NonLinear one is.
    let as_3_0 = xml.replace(r#"<VAST version="2.0">"#, r#"<VAST version="3.0">"#);
    let mut ids_2_0: Vec<&str> = result.issues.iter().map(|i| i.id).collect();
    let result_3_0 = validate(&as_3_0);
    let mut ids_3_0: Vec<&str> = result_3_0.issues.iter().map(|i| i.id).collect();
    ids_2_0.sort_unstable();
    ids_3_0.sort_unstable();
    assert_eq!(ids_2_0, ids_3_0);
}

/// The traversal is not version gated, but the rules it reaches still are, and
/// the two must compose. `<Mezzanine>` is the case that proves it: 4.0 declares
/// it as a bare `xs:anyURI` with no attributes and 4.1 makes it a complexType,
/// so the attribute rules are 4.1+.
///
/// Reaching into the container must not hand a VAST 2.0 document a requirement
/// its schema never had. That is the 0.11.2 bug class, and a traversal that
/// deliberately ignores the version is exactly where it would come back.
#[test]
fn ctv_portfolio_container_still_honours_per_rule_version_gates() {
    let xml = |version: &str| {
        format!(
            r#"<?xml version="1.0" encoding="UTF-8"?>
<VAST version="{version}">
  <Ad id="a">
    <InLine>
      <AdSystem version="1.0">ExampleAdServer</AdSystem>
      <AdTitle>Pause</AdTitle>
      <Impression><![CDATA[https://track.example.com/imp]]></Impression>
      <Creatives>
        <Creative id="c1">
          <NonLinearAds>
            <NonLinear id="nl" width="1920" height="1080">
              <StaticResource creativeType="image/jpeg"><![CDATA[https://cdn.example.com/a.jpg]]></StaticResource>
            </NonLinear>
          </NonLinearAds>
        </Creative>
      </Creatives>
      <Extensions>
        <Extension type="ctv_ad_portfolio">
          <CreativeId>c1</CreativeId>
          <plcmt>5</plcmt>
          <pos>7</pos>
          <MediaFiles>
            <MediaFile delivery="progressive" type="image/jpeg" width="1" height="1"><![CDATA[https://cdn.example.com/a.jpg]]></MediaFile>
            <Mezzanine><![CDATA[https://cdn.example.com/mezz.mp4]]></Mezzanine>
          </MediaFiles>
        </Extension>
      </Extensions>
    </InLine>
  </Ad>
</VAST>"#
        )
    };

    let on_4_2 = validate(&xml("4.2"));
    for id in [
        "VAST-4.1-mezzanine-delivery",
        "VAST-4.1-mezzanine-type",
        "VAST-4.1-mezzanine-width",
        "VAST-4.1-mezzanine-height",
    ] {
        assert!(
            has_issue(&on_4_2, id),
            "{id} must fire inside the container on 4.2"
        );
    }

    let on_2_0 = validate(&xml("2.0"));
    assert!(
        !on_2_0.issues.iter().any(|i| i.id.contains("mezzanine")),
        "VAST 2.0 has no <Mezzanine> requirement to report: {:?}",
        on_2_0.issues.iter().map(|i| i.id).collect::<Vec<_>>()
    );
}

/// A vendor `<Extension>` is a private payload. Its children may happen to be
/// named like VAST elements and are none of the linter's business, so the
/// traversal above must key off the standardised-container allowlist rather
/// than off the presence of a `<MediaFiles>` child.
#[test]
fn vendor_extension_contents_are_left_alone() {
    let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<VAST version="2.0">
  <Ad id="a">
    <InLine>
      <AdSystem version="1.0">ExampleAdServer</AdSystem>
      <AdTitle>Pause</AdTitle>
      <Impression><![CDATA[https://track.example.com/imp]]></Impression>
      <Creatives>
        <Creative id="c1">
          <NonLinearAds>
            <NonLinear id="nl" width="1920" height="1080">
              <StaticResource creativeType="image/jpeg"><![CDATA[https://cdn.example.com/a.jpg]]></StaticResource>
            </NonLinear>
          </NonLinearAds>
        </Creative>
      </Creatives>
      <Extensions>
        <Extension type="acme-private-format">
          <Duration>banana</Duration>
          <MediaFiles>
            <MediaFile><![CDATA[https://cdn.example.com/a.mp4]]></MediaFile>
          </MediaFiles>
        </Extension>
      </Extensions>
    </InLine>
  </Ad>
</VAST>"#;

    let result = validate(xml);
    for id in [
        "VAST-2.0-mediafile-delivery",
        "VAST-2.0-mediafile-type",
        "VAST-2.0-mediafile-dimensions",
        "VAST-2.0-duration-format",
    ] {
        assert!(
            !has_issue(&result, id),
            "{id} must not fire inside a vendor extension payload"
        );
    }
}

/// The other half of that boundary. The per-signal `<Extension ext="adcom">`
/// shape belongs to the 4.x guidance, so it stays off below 4.0 whichever
/// legacy version the document declares, not just on the 2.0 the extension
/// documents name. Without this, a 3.0 tag would be told about AdCOM signal
/// shapes that have no 3.0 encoding.
#[test]
fn ctv_portfolio_rules_do_not_fire_on_vast_3_0() {
    let xml = load("err_ctv_adcom_signal_values.xml")
        .replace(r#"<VAST version="4.2">"#, r#"<VAST version="3.0">"#);
    let result = validate(&xml);
    for issue in &result.issues {
        assert!(
            !issue.id.starts_with("VAST-4.4-"),
            "no 4.4 rule may fire on a 3.0 document, got {}",
            issue.id
        );
    }
}

// ── the CTV content model reuses the existing element rules ───────────────────

/// A `<MediaFile>` is the same element wherever it hangs. The CTV Ad Portfolio
/// moved it under `<NonLinear>`; it did not relax delivery, type, width or
/// height, and every NonLinear media example IAB publishes declares all four.
#[test]
fn ctv_nonlinear_mediafile_requires_the_same_attrs_as_linear() {
    let xml = r#"<VAST version="4.2">
    <Ad id="1"><InLine>
        <AdSystem version="1.0">ExampleAdServer</AdSystem>
        <AdTitle>Overlay with a bare MediaFile</AdTitle>
        <Impression><![CDATA[https://example.com/impression]]></Impression>
        <AdServingId>abc-123</AdServingId>
        <Creatives><Creative id="1" adId="1">
            <UniversalAdId idRegistry="ad-id.org">CNPA0484000H</UniversalAdId>
            <NonLinearAds><NonLinear width="480" height="70">
                <MediaFiles>
                    <MediaFile><![CDATA[https://example.com/overlay.mp4]]></MediaFile>
                </MediaFiles>
            </NonLinear></NonLinearAds>
        </Creative></Creatives>
    </InLine></Ad>
</VAST>"#;
    let result = validate(xml);
    assert!(has_issue(&result, "VAST-2.0-mediafile-delivery"));
    assert!(has_issue(&result, "VAST-2.0-mediafile-type"));
    assert!(has_issue(&result, "VAST-2.0-mediafile-dimensions"));
}

/// The rest of the `<MediaFiles>` container travels with it. `<Mezzanine>` and
/// `<InteractiveCreativeFile>` are the same elements with the same attribute
/// expectations wherever the container hangs.
#[test]
fn ctv_nonlinear_mezzanine_and_interactive_file_are_checked() {
    let with_bare_mezzanine = load("ok_ctv_inscene_video_4_2.xml").replace(
        "</MediaFiles>",
        "<Mezzanine><![CDATA[https://cdn.example.com/mezz.mov]]></Mezzanine></MediaFiles>",
    );
    let result = validate(&with_bare_mezzanine);
    for id in [
        "VAST-4.1-mezzanine-delivery",
        "VAST-4.1-mezzanine-type",
        "VAST-4.1-mezzanine-width",
        "VAST-4.1-mezzanine-height",
    ] {
        assert!(has_issue(&result, id), "{id} must fire under NonLinear");
    }

    let bare_interactive = load("ok_ctv_overlay_simid_4_4.xml").replace(
        r#"<InteractiveCreativeFile type="text/html" apiFramework="SIMID">"#,
        "<InteractiveCreativeFile>",
    );
    let result = validate(&bare_interactive);
    assert!(has_issue(&result, "VAST-4.0-interactive-creative-no-api"));
    assert!(has_issue(&result, "VAST-4.1-interactive-creative-type"));
}

/// Same element, same required attributes, new location: `<Icons>` under
/// `<NonLinearAds>` so a NonLinear placement can carry an ad-choices icon.
#[test]
fn ctv_nonlinearads_icon_requires_the_same_attrs_as_linear() {
    let xml = r#"<VAST version="4.2">
    <Ad id="1"><InLine>
        <AdSystem version="1.0">ExampleAdServer</AdSystem>
        <AdTitle>Overlay with a bare Icon</AdTitle>
        <Impression><![CDATA[https://example.com/impression]]></Impression>
        <AdServingId>abc-123</AdServingId>
        <Creatives><Creative id="1" adId="1">
            <UniversalAdId idRegistry="ad-id.org">CNPA0484000H</UniversalAdId>
            <NonLinearAds>
                <Icons><Icon>
                    <StaticResource creativeType="image/png"><![CDATA[https://example.com/adchoices.png]]></StaticResource>
                </Icon></Icons>
                <NonLinear width="480" height="70">
                    <StaticResource creativeType="image/png"><![CDATA[https://example.com/overlay.png]]></StaticResource>
                </NonLinear>
            </NonLinearAds>
        </Creative></Creatives>
    </InLine></Ad>
</VAST>"#;
    let result = validate(xml);
    for id in [
        "VAST-3.0-icon-program",
        "VAST-3.0-icon-width",
        "VAST-3.0-icon-height",
        "VAST-3.0-icon-xposition",
        "VAST-3.0-icon-yposition",
        "VAST-3.0-icon-attrs",
    ] {
        assert!(has_issue(&result, id), "{id} must fire under NonLinearAds");
    }
}

/// Regression guard for both of the above: below 4.0 neither construct is
/// valid, so the only finding must be the unknown-child error. Running the
/// attribute rules there as well would report the same tag twice.
#[test]
fn ctv_content_model_rules_do_not_double_report_below_4_0() {
    let result = validate(&load("err_ctv_nonlinear_mediafiles_in_4_2_only.xml"));
    for id in [
        "VAST-2.0-mediafile-delivery",
        "VAST-2.0-mediafile-type",
        "VAST-2.0-mediafile-dimensions",
        "VAST-3.0-icon-program",
        "VAST-3.0-icon-attrs",
    ] {
        assert!(
            !has_issue(&result, id),
            "{id} must not fire on a 3.0 document, where the construct is already an unknown-child error"
        );
    }
}

/// The three error-severity rules that shipped without a regression test.
#[test]
fn ctv_empty_containers_and_pixel_qr_size_fire() {
    let empty_nonlinear_mediafiles = load("ok_ctv_inscene_video_4_2.xml").replace(
        r#"<MediaFile delivery="progressive" type="video/mp4" width="1400" height="400" bitrate="6000"><![CDATA[https://cdn.example.com/creatives/iscene_video_asset.mp4]]></MediaFile>"#,
        "",
    );
    assert!(has_issue(
        &validate(&empty_nonlinear_mediafiles),
        "VAST-4.4-nonlinear-mediafiles-empty"
    ));

    let empty_portfolio_mediafiles = r#"<VAST version="2.0">
    <Ad id="a"><InLine>
        <AdSystem version="1.0">ExampleAdServer</AdSystem>
        <AdTitle>Pause</AdTitle>
        <Impression><![CDATA[https://track.example.com/imp]]></Impression>
        <Creatives><Creative id="c1"><NonLinearAds><NonLinear id="nl" width="1920" height="1080">
            <StaticResource creativeType="image/png"><![CDATA[https://cdn.example.com/a.png]]></StaticResource>
        </NonLinear></NonLinearAds></Creative></Creatives>
        <Extensions><Extension type="ctv_ad_portfolio">
            <plcmt>5</plcmt>
            <MediaFiles></MediaFiles>
        </Extension></Extensions>
    </InLine></Ad>
</VAST>"#;
    assert!(has_issue(
        &validate(empty_portfolio_mediafiles),
        "VAST-2.0-ctv-portfolio-mediafiles-empty"
    ));

    let pixel_size = load("ok_ctv_overlay_simid_4_4.xml").replace(r#"size="15%""#, r#"size="120""#);
    let result = validate(&pixel_size);
    assert!(has_issue(&result, "VAST-4.4-qrcode-size-percent"));
    assert!(!has_issue(&result, "VAST-4.4-qrcode-size-attr"));
}

/// The QR geometry fixture covers position-percent; this covers the attribute
/// being absent entirely.
#[test]
fn ctv_qrcode_position_missing_coordinate_fires() {
    let xml = load("ok_ctv_overlay_simid_4_4.xml").replace(
        r#"<QrCodePosition xPosition="10%" yPosition="70%"/>"#,
        r#"<QrCodePosition xPosition="10%"/>"#,
    );
    let result = validate(&xml);
    assert!(has_issue(&result, "VAST-4.4-qrcode-position-attrs"));
}

// ── format-to-signal consistency ──────────────────────────────────────────────

/// Every signal in range, and the set still contradicts itself: plcmt says
/// Overlay, pos says Squeezeback.
#[test]
fn ctv_pos_outside_the_declared_format_fires_warning() {
    let xml = load("ok_ctv_overlay_simid_4_4.xml").replace("<pos>14</pos>", "<pos>12</pos>");
    let result = validate(&xml);
    assert!(has_issue(&result, "VAST-4.4-adcom-pos-format-mismatch"));
    assert!(
        !has_issue(&result, "VAST-4.4-adcom-pos-value"),
        "12 is inside the Placement Positions range; only the pairing is wrong"
    );
}

/// 8 and 9 are Pause playback methods by definition, so one under an Overlay
/// plcmt is a contradiction rather than an unusual choice.
#[test]
fn ctv_playbackmethod_naming_another_format_fires_warning() {
    let xml = load("ok_ctv_overlay_simid_4_4.xml").replace(
        "<playbackmethod>2</playbackmethod>",
        "<playbackmethod>9</playbackmethod>",
    );
    let result = validate(&xml);
    assert!(has_issue(
        &result,
        "VAST-4.4-adcom-playbackmethod-format-mismatch"
    ));
}

/// Pause and Screensaver are the two rows the reference table states without
/// hedging, so a generic playback method under them is reported.
#[test]
fn ctv_generic_playbackmethod_under_pause_fires_warning() {
    let xml = load("ok_ctv_portfolio_vast_2_0.xml").replace(
        "<playbackmethod>9</playbackmethod>",
        "<playbackmethod>2</playbackmethod>",
    );
    let result = validate(&xml);
    assert!(has_issue(
        &result,
        "VAST-4.4-adcom-playbackmethod-format-mismatch"
    ));
}

/// The remaining three rows say "typically 1 or 2", which is guidance rather
/// than a constraint. Overlay with an autoplay playback method stays quiet.
#[test]
fn ctv_generic_playbackmethod_under_overlay_stays_quiet() {
    let xml = load("ok_ctv_overlay_simid_4_4.xml").replace(
        "<playbackmethod>2</playbackmethod>",
        "<playbackmethod>3</playbackmethod>",
    );
    let result = validate(&xml);
    assert!(!has_issue(
        &result,
        "VAST-4.4-adcom-playbackmethod-format-mismatch"
    ));
}

/// pos 0 is AdCOM "unknown" and carries no claim to contradict.
#[test]
fn ctv_pos_unknown_never_mismatches() {
    let xml = load("ok_ctv_overlay_simid_4_4.xml").replace("<pos>14</pos>", "<pos>0</pos>");
    let result = validate(&xml);
    assert!(!has_issue(&result, "VAST-4.4-adcom-pos-format-mismatch"));
}

/// In-Scene reads "NA" in the pos column, so no position is wrong for it.
#[test]
fn ctv_in_scene_accepts_any_pos() {
    let xml = load("ok_ctv_overlay_simid_4_4.xml")
        .replace("<plcmt>7</plcmt>", "<plcmt>9</plcmt>")
        .replace("<pos>14</pos>", "<pos>11</pos>");
    let result = validate(&xml);
    assert!(!has_issue(&result, "VAST-4.4-adcom-pos-format-mismatch"));
}

/// The consistency check spans the whole `<Extensions>` block on 4.x and the
/// single container on 2.0, so it has to fire on both encodings.
#[test]
fn ctv_portfolio_vast_2_0_container_cross_checks_signals() {
    let xml = load("ok_ctv_portfolio_vast_2_0.xml").replace("<pos>7</pos>", "<pos>14</pos>");
    let result = validate(&xml);
    assert!(has_issue(&result, "VAST-4.4-adcom-pos-format-mismatch"));
}

/// The three formats that had no fixture of their own. Each carries the
/// pairing the reference table gives it, so a false positive in either
/// -format-mismatch rule shows up here.
#[test]
fn ctv_screensaver_squeezeback_and_inscene_examples_validate_clean() {
    for fixture in [
        "ok_ctv_screensaver_static_4_2.xml",
        "ok_ctv_squeezeback_video_4_2.xml",
        "ok_ctv_inscene_video_4_2.xml",
    ] {
        let result = validate(&load(fixture));
        assert!(
            result.issues.is_empty(),
            "{fixture} must validate with no issues at all: {:#?}",
            result.issues
        );
    }
}

/// In-Scene is the one format whose pos cell reads NA. pos 11 is a Squeezeback
/// layout and must still pass under plcmt 9.
#[test]
fn ctv_inscene_fixture_accepts_a_pos_from_another_format() {
    let result = validate(&load("ok_ctv_inscene_video_4_2.xml"));
    assert!(!has_issue(&result, "VAST-4.4-adcom-pos-format-mismatch"));
}

/// An out-of-range plcmt is already reported on its own; pairing anything with
/// it would be guesswork.
#[test]
fn ctv_unknown_plcmt_suppresses_the_pairing_checks() {
    let result = validate(&load("err_ctv_adcom_signal_values.xml"));
    assert!(has_issue(&result, "VAST-4.4-adcom-plcmt-value"));
    assert!(!has_issue(&result, "VAST-4.4-adcom-pos-format-mismatch"));
    assert!(!has_issue(
        &result,
        "VAST-4.4-adcom-playbackmethod-format-mismatch"
    ));
}

// ── requirements that arrived in a later version than the rule id ────────────

fn issue_of(result: &vastlint_core::ValidationResult, id: &str) -> vastlint_core::Issue {
    result
        .issues
        .iter()
        .find(|i| i.id == id)
        .unwrap_or_else(|| panic!("expected {id}, got: {:#?}", result.issues))
        .clone()
}

/// VAST 1.0's root element is `<VideoAdServingTemplate>`. "Root element must be
/// <VAST>" describes such a document as malformed when it is only older, so the
/// rule names the version instead and stops: 1.0 has its own vocabulary and the
/// 2.0+ rules would report every element of it as unknown.
#[test]
fn vast_1_0_is_named_rather_than_called_malformed() {
    let result = validate(&load("warn_vast_1_0_document.xml"));
    let issue = issue_of(&result, "VAST-2.0-root-element");
    assert_eq!(
        issue.severity,
        Severity::Warning,
        "a valid 1.0 document is not an invalid 2.0 document: {issue:#?}"
    );
    assert!(
        issue.message.contains("VAST 1.0"),
        "the message must name the version it found: {issue:#?}"
    );
    assert_eq!(
        result.issues.len(),
        1,
        "nothing after the root check applies to 1.0: {:#?}",
        result.issues
    );
}

/// 4.0 declares `<Mezzanine>` as a bare `xs:anyURI`. delivery, type, width and
/// height only exist from 4.1, so requiring them of a 4.0 document reports four
/// errors against a tag its own schema accepts.
#[test]
fn mezzanine_attrs_are_not_required_before_4_1() {
    let result =
        validate(&load("err_mezzanine_attrs.xml").replace("version=\"4.1\"", "version=\"4.0\""));
    for rule in &[
        "VAST-4.1-mezzanine-delivery",
        "VAST-4.1-mezzanine-type",
        "VAST-4.1-mezzanine-width",
        "VAST-4.1-mezzanine-height",
    ] {
        assert!(
            !has_issue(&result, rule),
            "{rule} must not fire on 4.0: {:#?}",
            result.issues
        );
    }
}

/// The same fixture at its declared 4.1 still reports all four, so the gate is
/// on the version and not on the check having been dropped.
#[test]
fn mezzanine_attrs_stay_required_from_4_1() {
    let result = validate(&load("err_mezzanine_attrs.xml"));
    assert!(has_issue(&result, "VAST-4.1-mezzanine-delivery"));
    assert!(has_issue(&result, "VAST-4.1-mezzanine-height"));
}

/// 3.0 §2.3.6.4 marks the Icon placement attributes required. The 4.1 and 4.2
/// XSDs declare every one of them optional and the 4.3 attribute table has no
/// required column, so a 4.x omission is worth reporting but not as an error.
#[test]
fn icon_attrs_drop_to_warning_on_4_x() {
    let result = validate(
        &load("err_icon_required_attrs.xml").replace("version=\"3.0\"", "version=\"4.2\""),
    );
    for rule in &[
        "VAST-3.0-icon-program",
        "VAST-3.0-icon-width",
        "VAST-3.0-icon-height",
        "VAST-3.0-icon-xposition",
        "VAST-3.0-icon-yposition",
    ] {
        let issue = issue_of(&result, rule);
        assert_eq!(
            issue.severity,
            Severity::Warning,
            "{rule} is optional in the 4.x schemas: {issue:#?}"
        );
    }
}

/// 3.0 keeps them as errors, which is what the spec that made them required
/// says.
#[test]
fn icon_attrs_stay_errors_on_3_0() {
    let result = validate(&load("err_icon_required_attrs.xml"));
    assert_eq!(
        issue_of(&result, "VAST-3.0-icon-program").severity,
        Severity::Error
    );
    assert!(!result.summary.is_valid());
}

/// 4.0 introduced `<AdVerifications>` with `vendor` and `apiFramework` declared
/// `use="optional"`. The requirement is 4.1 prose, so a 4.0 document gets a
/// warning rather than an error it could not have avoided.
#[test]
fn verification_attrs_drop_to_warning_on_4_0() {
    let vendor = validate(
        &load("err_verification_vendor.xml").replace("version=\"4.1\"", "version=\"4.0\""),
    );
    assert_eq!(
        issue_of(&vendor, "VAST-4.1-verification-vendor").severity,
        Severity::Warning
    );

    let api = validate(
        &load("err_verification_resource_attrs.xml").replace("version=\"4.1\"", "version=\"4.0\""),
    );
    assert_eq!(
        issue_of(&api, "VAST-4.1-js-resource-apiframework").severity,
        Severity::Warning
    );
}

/// From 4.1 both stay errors.
#[test]
fn verification_attrs_stay_errors_from_4_1() {
    let result = validate(&load("err_verification_vendor.xml"));
    assert_eq!(
        issue_of(&result, "VAST-4.1-verification-vendor").severity,
        Severity::Error
    );
}