cloudformation-validate-schema-validator 1.15.0

AWS CloudFormation Validate
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
//! Focused integration tests for full composition branch enforcement,
//! multipleOf, dependencies array-form, and ref siblings.

use schema_validator::{CompiledSchemaStore, SchemaOverlayError, SchemaValidator};
use serde_json::{Value, json};
use std::collections::HashMap;
use std::sync::Arc;
use template_model::SemanticModel;

fn model(template: &str) -> Arc<SemanticModel> {
    Arc::new(SemanticModel::from_bytes(template.as_bytes()).expect("template must parse"))
}

fn validator(overlays: Vec<(&str, Value)>) -> SchemaValidator {
    SchemaValidator::try_with_additional_schemas(overlays).expect("test overlays must apply")
}

fn validate(sv: &SchemaValidator, template: &str) -> Vec<diagnostics::Diagnostic> {
    sv.validate(&model(template), Some("us-east-1")).diagnostics
}

fn mentions(diags: &[diagnostics::Diagnostic], rule_id: &str, needle: &str) -> bool {
    diags.iter().any(|d| d.rule_id == rule_id && d.message.contains(needle))
}

// ─── multipleOf enforcement ─────────────────────────────────────────────────

#[test]
fn multiple_of_rejects_non_multiple_value() {
    let sv = validator(vec![(
        "AWS::Test::MultipleOf",
        json!({
            "properties": { "Count": { "type": "integer", "multipleOf": 5 } },
            "additionalProperties": false
        }),
    )]);
    let template = "Resources:\n  R:\n    Type: AWS::Test::MultipleOf\n    Properties:\n      Count: 7\n";
    let diags = validate(&sv, template);
    assert!(
        mentions(&diags, "F3034", "not a multiple of"),
        "7 is not a multiple of 5, expected F3034: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn multiple_of_accepts_valid_multiple() {
    let sv = validator(vec![(
        "AWS::Test::MultipleOf",
        json!({
            "properties": { "Count": { "type": "integer", "multipleOf": 5 } },
            "additionalProperties": false
        }),
    )]);
    let template = "Resources:\n  R:\n    Type: AWS::Test::MultipleOf\n    Properties:\n      Count: 15\n";
    let diags = validate(&sv, template);
    assert!(
        !mentions(&diags, "F3034", "not a multiple of"),
        "15 is a multiple of 5, should not fire: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn multiple_of_tolerates_floating_point_imprecision() {
    // 0.3 / 0.1 = 2.9999... in IEEE 754 - the check must tolerate this.
    let sv = validator(vec![(
        "AWS::Test::MultipleOfFloat",
        json!({
            "properties": { "Step": { "type": "number", "multipleOf": 0.1 } },
            "additionalProperties": false
        }),
    )]);
    let template = "Resources:\n  R:\n    Type: AWS::Test::MultipleOfFloat\n    Properties:\n      Step: 0.3\n";
    let diags = validate(&sv, template);
    assert!(
        !mentions(&diags, "F3034", "not a multiple of"),
        "0.3 is a multiple of 0.1 (within tolerance): {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

// ─── dependencies array-form ────────────────────────────────────────────────

#[test]
fn dependencies_array_form_is_compiled_as_dependent_required() {
    let sv = validator(vec![(
        "AWS::Test::Deps",
        json!({
            "properties": {
                "A": { "type": "string" },
                "B": { "type": "string" },
                "C": { "type": "string" }
            },
            "dependencies": { "A": ["B", "C"] },
            "additionalProperties": false
        }),
    )]);
    // Template has A but not B or C
    let template = "Resources:\n  R:\n    Type: AWS::Test::Deps\n    Properties:\n      A: val\n";
    let diags = validate(&sv, template);
    assert!(
        mentions(&diags, "F3021", "dependency of"),
        "expected F3021 for missing dependency: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn dependencies_schema_form_is_rejected() {
    let result = SchemaValidator::try_with_additional_schemas(vec![(
        "AWS::Test::SchemaDeps",
        json!({
            "properties": { "A": { "type": "string" }, "B": { "type": "string" } },
            "dependencies": { "A": { "properties": { "B": { "type": "string" } }, "required": ["B"] } }
        }),
    )]);
    match result {
        Err(error) => assert!(matches!(error, SchemaOverlayError::Unsupported { .. }), "got {error:?}"),
        Ok(_) => panic!("schema-form dependencies should be rejected"),
    }
}

// ─── anyOf/oneOf with scalar type/enum ──────────────────────────────────────

#[test]
fn any_of_with_required_validates_correctly() {
    let sv = validator(vec![(
        "AWS::Test::AnyOf",
        json!({
            "properties": {
                "A": { "type": "string" },
                "B": { "type": "string" },
                "C": { "type": "string" }
            },
            "anyOf": [{ "required": ["A"] }, { "required": ["B"] }],
            "additionalProperties": false
        }),
    )]);
    // Template has C but neither A nor B - should fail anyOf
    let template = "Resources:\n  R:\n    Type: AWS::Test::AnyOf\n    Properties:\n      C: val\n";
    let diags = validate(&sv, template);
    assert!(
        mentions(&diags, "F3017", "not valid under any"),
        "expected F3017 when neither branch matches: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn one_of_with_properties_and_additional_properties() {
    let sv = validator(vec![(
        "AWS::Test::OneOf",
        json!({
            "properties": {
                "Mode": { "type": "string" },
                "ConfigA": { "type": "string" },
                "ConfigB": { "type": "string" }
            },
            "oneOf": [
                { "required": ["ConfigA"], "properties": { "ConfigA": { "type": "string" } } },
                { "required": ["ConfigB"], "properties": { "ConfigB": { "type": "string" } } }
            ],
            "additionalProperties": false
        }),
    )]);
    // Template has neither ConfigA nor ConfigB - should fail oneOf
    let template = "Resources:\n  R:\n    Type: AWS::Test::OneOf\n    Properties:\n      Mode: test\n";
    let diags = validate(&sv, template);
    assert!(
        mentions(&diags, "F3018", "not valid under any"),
        "expected F3018 when no branch matches: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

// ─── ref in composition branches ────────────────────────────────────────────

#[test]
fn composition_branch_with_ref_resolves_definition_constraints() {
    let sv = validator(vec![(
        "AWS::Test::BranchRef",
        json!({
            "properties": {
                "A": { "type": "string" },
                "B": { "type": "string" },
                "C": { "type": "string" }
            },
            "definitions": {
                "NeedsA": { "required": ["A"] },
                "NeedsB": { "required": ["B"] }
            },
            "anyOf": [
                { "$ref": "#/definitions/NeedsA" },
                { "$ref": "#/definitions/NeedsB" }
            ],
            "additionalProperties": false
        }),
    )]);
    // Template has C but neither A nor B
    let template = "Resources:\n  R:\n    Type: AWS::Test::BranchRef\n    Properties:\n      C: val\n";
    let diags = validate(&sv, template);
    assert!(
        mentions(&diags, "F3017", "not valid under any"),
        "expected F3017 when neither referenced branch matches: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

// ─── ref siblings ───────────────────────────────────────────────────────────

#[test]
fn ref_siblings_are_enforced_at_validation_time() {
    let sv = validator(vec![(
        "AWS::Test::RefSibling",
        json!({
            "properties": {
                "Name": { "$ref": "#/definitions/NameDef", "maxLength": 5 }
            },
            "definitions": { "NameDef": { "type": "string" } },
            "required": ["Name"],
            "additionalProperties": false
        }),
    )]);
    // Name is 10 chars - exceeds maxLength of 5 stated beside the $ref
    let template = "Resources:\n  R:\n    Type: AWS::Test::RefSibling\n    Properties:\n      Name: TooLongName\n";
    let diags = validate(&sv, template);
    assert!(
        mentions(&diags, "F3033", "exceeds maximum"),
        "maxLength beside a $ref should be enforced: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

// ─── nested composition ─────────────────────────────────────────────────────

#[test]
fn nested_any_of_inside_one_of_is_compiled() {
    // Verify nested composition is accepted without error
    let sv = validator(vec![(
        "AWS::Test::Nested",
        json!({
            "properties": {
                "A": { "type": "string" },
                "B": { "type": "string" },
                "C": { "type": "string" }
            },
            "oneOf": [
                { "required": ["A"], "anyOf": [{ "required": ["B"] }, { "required": ["C"] }] },
                { "required": ["C"] }
            ],
            "additionalProperties": false
        }),
    )]);
    // Template has B only - does not satisfy either top-level oneOf branch
    let template = "Resources:\n  R:\n    Type: AWS::Test::Nested\n    Properties:\n      B: val\n";
    let diags = validate(&sv, template);
    assert!(
        mentions(&diags, "F3018", "not valid under any"),
        "expected F3018 for nested composition: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

// ─── anyOf discriminated by type+enum ─────────────────────────────────────

#[test]
fn any_of_discriminated_by_type_and_enum_rejects_wrong_enum() {
    let sv = validator(vec![(
        "AWS::Test::AnyOfTypeEnum",
        json!({
            "properties": {
                "Mode": { "type": "string" },
                "Value": { "type": "string" }
            },
            "anyOf": [
                { "properties": { "Mode": { "type": "string", "enum": ["fast"] } } },
                { "properties": { "Mode": { "type": "string", "enum": ["slow"] } } }
            ],
            "additionalProperties": false
        }),
    )]);
    // Mode is "broken" - matches neither branch
    let template =
        "Resources:\n  R:\n    Type: AWS::Test::AnyOfTypeEnum\n    Properties:\n      Mode: broken\n      Value: x\n";
    let diags = validate(&sv, template);
    assert!(
        mentions(&diags, "F3017", "not valid under any"),
        "expected F3017 when enum value matches no branch: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn any_of_discriminated_by_type_and_enum_accepts_matching_enum() {
    let sv = validator(vec![(
        "AWS::Test::AnyOfTypeEnum",
        json!({
            "properties": {
                "Mode": { "type": "string" },
                "Value": { "type": "string" }
            },
            "anyOf": [
                { "properties": { "Mode": { "type": "string", "enum": ["fast"] } } },
                { "properties": { "Mode": { "type": "string", "enum": ["slow"] } } }
            ],
            "additionalProperties": false
        }),
    )]);
    // Mode is "fast" - matches first branch
    let template =
        "Resources:\n  R:\n    Type: AWS::Test::AnyOfTypeEnum\n    Properties:\n      Mode: fast\n      Value: x\n";
    let diags = validate(&sv, template);
    assert!(
        !mentions(&diags, "F3017", ""),
        "expected no F3017 when enum value matches a branch: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

// ─── oneOf exactly-one distinguished only by enum ───────────────────────────

#[test]
fn one_of_enum_discriminator_rejects_ambiguous_value() {
    let sv = validator(vec![(
        "AWS::Test::OneOfEnum",
        json!({
            "properties": {
                "Engine": { "type": "string" }
            },
            "oneOf": [
                { "properties": { "Engine": { "type": "string", "enum": ["mysql"] } } },
                { "properties": { "Engine": { "type": "string", "enum": ["postgres"] } } }
            ],
            "additionalProperties": false
        }),
    )]);
    // Engine is "oracle" - matches neither branch
    let template = "Resources:\n  R:\n    Type: AWS::Test::OneOfEnum\n    Properties:\n      Engine: oracle\n";
    let diags = validate(&sv, template);
    assert!(
        mentions(&diags, "F3018", "not valid under any"),
        "expected F3018 when value matches no oneOf branch: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn one_of_enum_discriminator_accepts_exactly_one_match() {
    let sv = validator(vec![(
        "AWS::Test::OneOfEnum",
        json!({
            "properties": {
                "Engine": { "type": "string" }
            },
            "oneOf": [
                { "properties": { "Engine": { "type": "string", "enum": ["mysql"] } } },
                { "properties": { "Engine": { "type": "string", "enum": ["postgres"] } } }
            ],
            "additionalProperties": false
        }),
    )]);
    // Engine is "mysql" - matches exactly one branch
    let template = "Resources:\n  R:\n    Type: AWS::Test::OneOfEnum\n    Properties:\n      Engine: mysql\n";
    let diags = validate(&sv, template);
    assert!(
        !mentions(&diags, "F3018", ""),
        "expected no F3018 when value matches exactly one branch: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn one_of_enum_discriminator_rejects_multiple_matches() {
    let sv = validator(vec![(
        "AWS::Test::OneOfEnumOverlap",
        json!({
            "properties": {
                "Engine": { "type": "string" }
            },
            "oneOf": [
                { "properties": { "Engine": { "type": "string", "enum": ["mysql", "postgres"] } } },
                { "properties": { "Engine": { "type": "string", "enum": ["postgres", "oracle"] } } }
            ],
            "additionalProperties": false
        }),
    )]);
    // Engine is "postgres" - matches BOTH branches
    let template = "Resources:\n  R:\n    Type: AWS::Test::OneOfEnumOverlap\n    Properties:\n      Engine: postgres\n";
    let diags = validate(&sv, template);
    assert!(
        mentions(&diags, "F3018", "more than one"),
        "expected F3018 'more than one' when value matches two oneOf branches: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

// ─── numeric bounds/multipleOf branch ───────────────────────────────────────

#[test]
fn any_of_numeric_bounds_rejects_out_of_range() {
    let sv = validator(vec![(
        "AWS::Test::AnyOfNumeric",
        json!({
            "properties": {
                "Port": { "type": "integer" }
            },
            "anyOf": [
                { "properties": { "Port": { "type": "integer", "minimum": 1, "maximum": 1024 } } },
                { "properties": { "Port": { "type": "integer", "minimum": 8000, "maximum": 9000 } } }
            ],
            "additionalProperties": false
        }),
    )]);
    // Port is 5000 - falls between both ranges
    let template = "Resources:\n  R:\n    Type: AWS::Test::AnyOfNumeric\n    Properties:\n      Port: 5000\n";
    let diags = validate(&sv, template);
    assert!(
        mentions(&diags, "F3017", "not valid under any"),
        "expected F3017 when numeric value is out of all branch ranges: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn any_of_numeric_bounds_accepts_in_range() {
    let sv = validator(vec![(
        "AWS::Test::AnyOfNumeric",
        json!({
            "properties": {
                "Port": { "type": "integer" }
            },
            "anyOf": [
                { "properties": { "Port": { "type": "integer", "minimum": 1, "maximum": 1024 } } },
                { "properties": { "Port": { "type": "integer", "minimum": 8000, "maximum": 9000 } } }
            ],
            "additionalProperties": false
        }),
    )]);
    // Port is 443 - falls in first range
    let template = "Resources:\n  R:\n    Type: AWS::Test::AnyOfNumeric\n    Properties:\n      Port: 443\n";
    let diags = validate(&sv, template);
    assert!(
        !mentions(&diags, "F3017", ""),
        "expected no F3017 when numeric value is within a branch range: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn any_of_multiple_of_branch_matching() {
    let sv = validator(vec![(
        "AWS::Test::AnyOfMultipleOf",
        json!({
            "properties": {
                "Size": { "type": "integer" }
            },
            "anyOf": [
                { "properties": { "Size": { "type": "integer", "multipleOf": 64 } } },
                { "properties": { "Size": { "type": "integer", "multipleOf": 100 } } }
            ],
            "additionalProperties": false
        }),
    )]);
    // Size is 7 - not a multiple of 64 or 100
    let template = "Resources:\n  R:\n    Type: AWS::Test::AnyOfMultipleOf\n    Properties:\n      Size: 7\n";
    let diags = validate(&sv, template);
    assert!(
        mentions(&diags, "F3017", "not valid under any"),
        "expected F3017 when not a multiple of any branch: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );

    // Size is 128 - multiple of 64
    let template2 = "Resources:\n  R:\n    Type: AWS::Test::AnyOfMultipleOf\n    Properties:\n      Size: 128\n";
    let diags2 = validate(&sv, template2);
    assert!(
        !mentions(&diags2, "F3017", ""),
        "expected no F3017 when value is a multiple of 64: {:?}",
        diags2.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

// ─── object nested property constraint ──────────────────────────────────────

#[test]
fn any_of_nested_object_property_constraint_rejects_mismatch() {
    let sv = validator(vec![(
        "AWS::Test::AnyOfNested",
        json!({
            "properties": {
                "Config": { "type": "object", "properties": {
                    "Type": { "type": "string" },
                    "Value": { "type": "string" }
                }}
            },
            "anyOf": [
                { "properties": { "Config": {
                    "type": "object",
                    "properties": { "Type": { "type": "string", "enum": ["A"] } }
                }}},
                { "properties": { "Config": {
                    "type": "object",
                    "properties": { "Type": { "type": "string", "enum": ["B"] } }
                }}}
            ],
            "additionalProperties": false
        }),
    )]);
    // Config.Type is "C" - matches neither branch
    let template =
        r#"{"Resources":{"R":{"Type":"AWS::Test::AnyOfNested","Properties":{"Config":{"Type":"C","Value":"x"}}}}}"#;
    let diags = validate(&sv, template);
    assert!(
        mentions(&diags, "F3017", "not valid under any"),
        "expected F3017 when nested property matches no branch: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn any_of_nested_object_property_constraint_accepts_match() {
    let sv = validator(vec![(
        "AWS::Test::AnyOfNested",
        json!({
            "properties": {
                "Config": { "type": "object", "properties": {
                    "Type": { "type": "string" },
                    "Value": { "type": "string" }
                }}
            },
            "anyOf": [
                { "properties": { "Config": {
                    "type": "object",
                    "properties": { "Type": { "type": "string", "enum": ["A"] } }
                }}},
                { "properties": { "Config": {
                    "type": "object",
                    "properties": { "Type": { "type": "string", "enum": ["B"] } }
                }}}
            ],
            "additionalProperties": false
        }),
    )]);
    // Config.Type is "A" - matches first branch
    let template =
        r#"{"Resources":{"R":{"Type":"AWS::Test::AnyOfNested","Properties":{"Config":{"Type":"A","Value":"x"}}}}}"#;
    let diags = validate(&sv, template);
    assert!(
        !mentions(&diags, "F3017", ""),
        "expected no F3017 when nested property matches a branch: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

// ─── array items constraint in branch ───────────────────────────────────────

#[test]
fn any_of_array_items_constraint_rejects_wrong_item_type() {
    let sv = validator(vec![(
        "AWS::Test::AnyOfItems",
        json!({
            "properties": {
                "Tags": { "type": "array" }
            },
            "anyOf": [
                { "properties": { "Tags": { "type": "array", "items": { "type": "object" } } } },
                { "properties": { "Tags": { "type": "array", "items": { "type": "integer" } } } }
            ],
            "additionalProperties": false
        }),
    )]);
    // Tags contains a string - neither object nor integer items (string-to-integer coercion
    // only works for numeric strings; "hello" is not coercible to integer)
    let template = r#"{"Resources":{"R":{"Type":"AWS::Test::AnyOfItems","Properties":{"Tags":["hello"]}}}}"#;
    let diags = validate(&sv, template);
    assert!(
        mentions(&diags, "F3017", "not valid under any"),
        "expected F3017 when array items don't match any branch: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn any_of_array_items_constraint_accepts_matching_items() {
    let sv = validator(vec![(
        "AWS::Test::AnyOfItems",
        json!({
            "properties": {
                "Tags": { "type": "array" }
            },
            "anyOf": [
                { "properties": { "Tags": { "type": "array", "items": { "type": "object" } } } },
                { "properties": { "Tags": { "type": "array", "items": { "type": "integer" } } } }
            ],
            "additionalProperties": false
        }),
    )]);
    // Tags contains integers - matches second branch
    let template = r#"{"Resources":{"R":{"Type":"AWS::Test::AnyOfItems","Properties":{"Tags":[1,2,3]}}}}"#;
    let diags = validate(&sv, template);
    assert!(
        !mentions(&diags, "F3017", ""),
        "expected no F3017 when array items match a branch: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

// ─── conditional (if/then/else) branch ──────────────────────────────────────

#[test]
fn any_of_with_if_then_else_branch_constraint() {
    // A branch that consists of a conditional participates in matching per
    // draft-07: the branch matches when its condition selects a satisfied
    // sub-schema. Engine "mysql" satisfies the conditional branch's then
    // (Port required); engine "sqlite" matches neither branch.
    let sv = validator(vec![(
        "AWS::Test::AnyOfConditional",
        json!({
            "properties": {
                "Engine": { "type": "string" },
                "Port": { "type": "integer" }
            },
            "anyOf": [
                { "properties": { "Engine": { "type": "string", "enum": ["postgres"] } }, "required": ["Engine"] },
                {
                    "if": { "properties": { "Engine": { "enum": ["mysql"] } }, "required": ["Engine"] },
                    "then": { "required": ["Port"] },
                    "else": { "required": ["Engine", "Port"] }
                }
            ],
            "additionalProperties": false
        }),
    )]);
    // Engine mysql with Port - the conditional branch's then is satisfied.
    let satisfied = "Resources:\n  R:\n    Type: AWS::Test::AnyOfConditional\n    Properties:\n      Engine: mysql\n      Port: 3306\n";
    let diags = validate(&sv, satisfied);
    assert!(
        !mentions(&diags, "F3017", ""),
        "expected no F3017 when the conditional branch matches: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );

    // Engine mysql WITHOUT Port - then requires Port, so the conditional branch
    // fails; the enum branch fails too (not postgres) - anyOf reports.
    let violating = "Resources:\n  R:\n    Type: AWS::Test::AnyOfConditional\n    Properties:\n      Engine: mysql\n";
    let diags = validate(&sv, violating);
    assert!(
        mentions(&diags, "F3017", ""),
        "a conditional branch whose then fails must not match vacuously: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn any_of_with_conditional_allof_constraint() {
    // Use allOf with if/then/else (which IS supported by the overlay) to test
    // conditional branch value matching.
    let sv = validator(vec![(
        "AWS::Test::ConditionalAllOf",
        json!({
            "properties": {
                "Engine": { "type": "string", "enum": ["mysql", "postgres"] },
                "Port": { "type": "integer" }
            },
            "allOf": [
                {
                    "if": { "properties": { "Engine": { "enum": ["mysql"] } } },
                    "then": { "dependentRequired": { "Engine": ["Port"] } }
                }
            ],
            "additionalProperties": false
        }),
    )]);
    // Engine is mysql but Port is missing - should flag dependentRequired
    let template = "Resources:\n  R:\n    Type: AWS::Test::ConditionalAllOf\n    Properties:\n      Engine: mysql\n";
    let diags = validate(&sv, template);
    assert!(
        mentions(&diags, "F3021", "dependency"),
        "expected F3021 when conditional dependency not met: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

// ─── dangling ref non-match ─────────────────────────────────────────────────

#[test]
fn any_of_dangling_ref_marks_branch_non_matching() {
    let sv = validator(vec![(
        "AWS::Test::DanglingRef",
        json!({
            "properties": {
                "Name": { "type": "string" }
            },
            "definitions": {},
            "anyOf": [
                { "$ref": "#/definitions/NonExistent" },
                { "properties": { "Name": { "type": "string", "enum": ["valid"] } } }
            ],
            "additionalProperties": false
        }),
    )]);
    // Name is "valid" - second branch matches despite first being dangling
    let template = "Resources:\n  R:\n    Type: AWS::Test::DanglingRef\n    Properties:\n      Name: valid\n";
    let diags = validate(&sv, template);
    // The dangling-reference branch emits its own finding, so the second branch
    // being valid means anyOf passes overall.
    assert!(
        !mentions(&diags, "F3017", ""),
        "expected no F3017 when at least one non-dangling branch matches: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn any_of_all_branches_dangling_ref_fails() {
    let sv = validator(vec![(
        "AWS::Test::AllDangling",
        json!({
            "properties": {
                "Name": { "type": "string" }
            },
            "definitions": {},
            "anyOf": [
                { "$ref": "#/definitions/NonExistent1" },
                { "$ref": "#/definitions/NonExistent2" }
            ],
            "additionalProperties": false
        }),
    )]);
    let template = "Resources:\n  R:\n    Type: AWS::Test::AllDangling\n    Properties:\n      Name: anything\n";
    let diags = validate(&sv, template);
    assert!(
        mentions(&diags, "F3017", "not valid under any"),
        "expected F3017 when all branches have dangling refs: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

// ─── overlay acceptance gate ────────────────────────────────────────────────

#[test]
fn overlay_acceptance_gate_under_threshold() {
    use std::path::Path;
    // The provider-schema corpus is a maintainer-local input (gitignored under
    // `data-source/upstream/`), so a clean checkout - CI included - has no
    // directory to read. The gate runs only where the corpus exists; when it
    // does, it must be non-empty so the test cannot pass vacuously against an
    // empty directory.
    let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../data-source/upstream/schemas");
    let Ok(entries) = std::fs::read_dir(&root) else {
        eprintln!("skipping overlay_acceptance_gate_under_threshold: no provider-schema corpus at {}", root.display());
        return;
    };
    let mut paths: Vec<_> = entries
        .map(|entry| entry.expect("schema entry").path())
        .filter(|path| path.extension().is_some_and(|ext| ext == "json"))
        .collect();
    paths.sort();
    assert!(
        !paths.is_empty(),
        "the provider-schema corpus directory exists but contains no schemas: {}",
        root.display()
    );
    let mut store = CompiledSchemaStore::new();
    let mut rejected_count = 0usize;
    for path in &paths {
        let raw: Value = serde_json::from_slice(&std::fs::read(path).expect("schema file")).expect("valid schema json");
        let type_name = raw.get("typeName").and_then(|value| value.as_str()).expect("typeName");
        if store.apply_overlay(type_name, &raw).is_err() {
            rejected_count += 1;
        }
    }
    assert!(
        rejected_count <= 40,
        "overlay rejections ({rejected_count}) exceeds threshold of 40; total schemas: {}",
        paths.len()
    );
}

// ─── Property-level scalar composition ──────────────────────────────────────
// These tests validate anyOf/oneOf/allOf/if_then_else placed DIRECTLY on a
// property schema (not the root resource schema) where the property value is a
// scalar - the case that validate_prop_composition handles.

#[test]
fn prop_any_of_scalar_enum_mismatch_emits_f3017() {
    let sv = validator(vec![(
        "AWS::Test::PropAnyOfEnum",
        json!({
            "properties": {
                "Mode": {
                    "type": "string",
                    "anyOf": [
                        { "enum": ["fast", "turbo"] },
                        { "enum": ["slow", "careful"] }
                    ]
                }
            },
            "additionalProperties": false
        }),
    )]);
    let template = "Resources:\n  R:\n    Type: AWS::Test::PropAnyOfEnum\n    Properties:\n      Mode: broken\n";
    let diags = validate(&sv, template);
    assert!(
        mentions(&diags, "F3017", "not valid under any"),
        "expected F3017 when scalar value matches no anyOf branch: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn prop_any_of_scalar_enum_match_no_diagnostic() {
    let sv = validator(vec![(
        "AWS::Test::PropAnyOfEnum",
        json!({
            "properties": {
                "Mode": {
                    "type": "string",
                    "anyOf": [
                        { "enum": ["fast", "turbo"] },
                        { "enum": ["slow", "careful"] }
                    ]
                }
            },
            "additionalProperties": false
        }),
    )]);
    let template = "Resources:\n  R:\n    Type: AWS::Test::PropAnyOfEnum\n    Properties:\n      Mode: fast\n";
    let diags = validate(&sv, template);
    assert!(
        !mentions(&diags, "F3017", ""),
        "expected no F3017 when scalar value matches an anyOf branch: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn prop_any_of_type_mismatch_emits_f3017() {
    let sv = validator(vec![(
        "AWS::Test::PropAnyOfType",
        json!({
            "properties": {
                "Value": {
                    "anyOf": [
                        { "type": "integer" },
                        { "type": "boolean" }
                    ]
                }
            },
            "additionalProperties": false
        }),
    )]);
    // "hello" is a string - not coercible to integer or boolean
    let template = r#"{"Resources":{"R":{"Type":"AWS::Test::PropAnyOfType","Properties":{"Value":"hello"}}}}"#;
    let diags = validate(&sv, template);
    assert!(
        mentions(&diags, "F3017", "not valid under any"),
        "expected F3017 when value type matches no branch: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn prop_one_of_ambiguity_emits_f3018() {
    let sv = validator(vec![(
        "AWS::Test::PropOneOfAmbig",
        json!({
            "properties": {
                "Port": {
                    "type": "integer",
                    "oneOf": [
                        { "minimum": 1, "maximum": 1024 },
                        { "minimum": 500, "maximum": 2000 }
                    ]
                }
            },
            "additionalProperties": false
        }),
    )]);
    // Port 800 falls in both ranges
    let template = "Resources:\n  R:\n    Type: AWS::Test::PropOneOfAmbig\n    Properties:\n      Port: 800\n";
    let diags = validate(&sv, template);
    assert!(
        mentions(&diags, "F3018", "more than one"),
        "expected F3018 when value matches more than one oneOf branch: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn prop_one_of_no_match_emits_f3018() {
    let sv = validator(vec![(
        "AWS::Test::PropOneOfNone",
        json!({
            "properties": {
                "Size": {
                    "type": "integer",
                    "oneOf": [
                        { "minimum": 1, "maximum": 10 },
                        { "minimum": 100, "maximum": 200 }
                    ]
                }
            },
            "additionalProperties": false
        }),
    )]);
    // Size 50 falls between both ranges
    let template = "Resources:\n  R:\n    Type: AWS::Test::PropOneOfNone\n    Properties:\n      Size: 50\n";
    let diags = validate(&sv, template);
    assert!(
        mentions(&diags, "F3018", "not valid under any"),
        "expected F3018 when value matches no oneOf branch: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn prop_one_of_exactly_one_match_no_diagnostic() {
    let sv = validator(vec![(
        "AWS::Test::PropOneOfExact",
        json!({
            "properties": {
                "Size": {
                    "type": "integer",
                    "oneOf": [
                        { "minimum": 1, "maximum": 10 },
                        { "minimum": 100, "maximum": 200 }
                    ]
                }
            },
            "additionalProperties": false
        }),
    )]);
    // Size 5 matches only the first range
    let template = "Resources:\n  R:\n    Type: AWS::Test::PropOneOfExact\n    Properties:\n      Size: 5\n";
    let diags = validate(&sv, template);
    assert!(
        !mentions(&diags, "F3018", ""),
        "expected no F3018 when value matches exactly one branch: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn prop_numeric_bounds_and_multiple_of_in_any_of() {
    let sv = validator(vec![(
        "AWS::Test::PropAnyOfMultipleOf",
        json!({
            "properties": {
                "Capacity": {
                    "type": "integer",
                    "anyOf": [
                        { "multipleOf": 64 },
                        { "multipleOf": 100 }
                    ]
                }
            },
            "additionalProperties": false
        }),
    )]);
    // 7 is not a multiple of 64 or 100
    let template = "Resources:\n  R:\n    Type: AWS::Test::PropAnyOfMultipleOf\n    Properties:\n      Capacity: 7\n";
    let diags = validate(&sv, template);
    assert!(
        mentions(&diags, "F3017", "not valid under any"),
        "expected F3017 when value is not a multiple of any branch: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );

    // 128 is a multiple of 64
    let template2 =
        "Resources:\n  R:\n    Type: AWS::Test::PropAnyOfMultipleOf\n    Properties:\n      Capacity: 128\n";
    let diags2 = validate(&sv, template2);
    assert!(
        !mentions(&diags2, "F3017", ""),
        "expected no F3017 when value is a multiple of 64: {:?}",
        diags2.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn prop_object_if_then_else_rejects_failing_then_branch() {
    // Property-level if/then/else on an object property: Config.Mode selects
    // which branch applies and the selected branch constrains a nested value.
    let sv = validator(vec![(
        "AWS::Test::PropObjConditional",
        json!({
            "properties": {
                "Config": {
                    "type": "object",
                    "properties": {
                        "Mode": { "type": "string" },
                        "Threshold": { "type": "integer" }
                    },
                    "if": { "properties": { "Mode": { "enum": ["strict"] } } },
                    "then": { "properties": { "Threshold": { "maximum": 10 } } },
                    "else": { "properties": { "Threshold": { "maximum": 1000 } } }
                }
            },
            "additionalProperties": false
        }),
    )]);
    // Mode is "strict" so the then-branch applies; Threshold 50 exceeds maximum 10
    let template = r#"{"Resources":{"R":{"Type":"AWS::Test::PropObjConditional","Properties":{"Config":{"Mode":"strict","Threshold":50}}}}}"#;
    let diags = validate(&sv, template);
    assert!(
        mentions(&diags, "F3017", "does not satisfy the composition branch constraint (maximum 10)"),
        "expected conditional constraint violation when then-branch fails: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn prop_object_if_then_else_accepts_passing_then_branch() {
    // Same schema - Mode is "strict" and Threshold is within the then-branch limit.
    let sv = validator(vec![(
        "AWS::Test::PropObjConditional",
        json!({
            "properties": {
                "Config": {
                    "type": "object",
                    "properties": {
                        "Mode": { "type": "string" },
                        "Threshold": { "type": "integer" }
                    },
                    "if": { "properties": { "Mode": { "enum": ["strict"] } } },
                    "then": { "properties": { "Threshold": { "maximum": 10 } } },
                    "else": { "properties": { "Threshold": { "maximum": 1000 } } }
                }
            },
            "additionalProperties": false
        }),
    )]);
    // Mode is "strict" and Threshold 5 is within the then-branch maximum of 10
    let template = r#"{"Resources":{"R":{"Type":"AWS::Test::PropObjConditional","Properties":{"Config":{"Mode":"strict","Threshold":5}}}}}"#;
    let diags = validate(&sv, template);
    assert!(
        !mentions(&diags, "F3017", ""),
        "expected no violation when then-branch constraint is satisfied: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn prop_object_if_then_else_uses_else_branch_when_condition_fails() {
    // Mode is "relaxed" so the else-branch applies; Threshold 500 is within
    // the else-branch maximum of 1000.
    let sv = validator(vec![(
        "AWS::Test::PropObjConditional",
        json!({
            "properties": {
                "Config": {
                    "type": "object",
                    "properties": {
                        "Mode": { "type": "string" },
                        "Threshold": { "type": "integer" }
                    },
                    "if": { "properties": { "Mode": { "enum": ["strict"] } } },
                    "then": { "properties": { "Threshold": { "maximum": 10 } } },
                    "else": { "properties": { "Threshold": { "maximum": 1000 } } }
                }
            },
            "additionalProperties": false
        }),
    )]);
    // Mode is "relaxed" (not "strict"), else-branch allows up to 1000
    let template = r#"{"Resources":{"R":{"Type":"AWS::Test::PropObjConditional","Properties":{"Config":{"Mode":"relaxed","Threshold":500}}}}}"#;
    let diags = validate(&sv, template);
    assert!(
        !mentions(&diags, "F3017", ""),
        "expected no violation when else-branch allows the value: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn prop_scalar_one_of_enum_rejects_unmatched_value() {
    let sv = validator(vec![(
        "AWS::Test::PropScalarConditional",
        json!({
            "properties": {
                "Format": {
                    "type": "string",
                    "oneOf": [
                        { "enum": ["json"] },
                        { "enum": ["yaml"] },
                        { "enum": ["xml"] }
                    ]
                }
            },
            "additionalProperties": false
        }),
    )]);
    // "csv" matches no branch
    let template = "Resources:\n  R:\n    Type: AWS::Test::PropScalarConditional\n    Properties:\n      Format: csv\n";
    let diags = validate(&sv, template);
    assert!(
        mentions(&diags, "F3018", "not valid under any"),
        "expected F3018 when scalar value matches no oneOf branch: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn prop_scalar_one_of_enum_accepts_exactly_one_match() {
    let sv = validator(vec![(
        "AWS::Test::PropScalarConditional",
        json!({
            "properties": {
                "Format": {
                    "type": "string",
                    "oneOf": [
                        { "enum": ["json"] },
                        { "enum": ["yaml"] },
                        { "enum": ["xml"] }
                    ]
                }
            },
            "additionalProperties": false
        }),
    )]);
    // "json" matches exactly one branch
    let template =
        "Resources:\n  R:\n    Type: AWS::Test::PropScalarConditional\n    Properties:\n      Format: json\n";
    let diags = validate(&sv, template);
    assert!(
        !mentions(&diags, "F3018", ""),
        "expected no F3018 when value matches exactly one oneOf branch: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

// ─── KMS format anyOf (exactly the upstream schema pattern) ─────────────────

#[test]
fn kms_format_any_of_accepts_valid_arn() {
    let sv = validator(vec![(
        "AWS::Test::KmsFormat",
        json!({
            "properties": {
                "KmsKeyId": {
                    "type": "string",
                    "anyOf": [
                        { "format": "AWS::KMS::Key.Arn" },
                        { "format": "AWS::KMS::Key.Id" },
                        { "format": "AWS::KMS::Alias.AliasName" }
                    ]
                }
            },
            "additionalProperties": false
        }),
    )]);
    let template = "Resources:\n  R:\n    Type: AWS::Test::KmsFormat\n    Properties:\n      KmsKeyId: arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012\n";
    let diags = validate(&sv, template);
    assert!(
        !mentions(&diags, "F3017", ""),
        "valid KMS ARN should not trigger F3017: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn kms_format_any_of_accepts_valid_uuid() {
    let sv = validator(vec![(
        "AWS::Test::KmsFormat",
        json!({
            "properties": {
                "KmsKeyId": {
                    "type": "string",
                    "anyOf": [
                        { "format": "AWS::KMS::Key.Arn" },
                        { "format": "AWS::KMS::Key.Id" },
                        { "format": "AWS::KMS::Alias.AliasName" }
                    ]
                }
            },
            "additionalProperties": false
        }),
    )]);
    let template = "Resources:\n  R:\n    Type: AWS::Test::KmsFormat\n    Properties:\n      KmsKeyId: 12345678-1234-1234-1234-123456789012\n";
    let diags = validate(&sv, template);
    assert!(
        !mentions(&diags, "F3017", ""),
        "valid KMS UUID should not trigger F3017: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn kms_format_any_of_accepts_mrk_key_id() {
    let sv = validator(vec![(
        "AWS::Test::KmsFormat",
        json!({
            "properties": {
                "KmsKeyId": {
                    "type": "string",
                    "anyOf": [
                        { "format": "AWS::KMS::Key.Arn" },
                        { "format": "AWS::KMS::Key.Id" },
                        { "format": "AWS::KMS::Alias.AliasName" }
                    ]
                }
            },
            "additionalProperties": false
        }),
    )]);
    let template = "Resources:\n  R:\n    Type: AWS::Test::KmsFormat\n    Properties:\n      KmsKeyId: mrk-1234abcd12ab34cd56ef1234567890ab\n";
    let diags = validate(&sv, template);
    assert!(
        !mentions(&diags, "F3017", ""),
        "valid mrk- KMS Key ID should not trigger F3017: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn kms_format_any_of_accepts_alias() {
    let sv = validator(vec![(
        "AWS::Test::KmsFormat",
        json!({
            "properties": {
                "KmsKeyId": {
                    "type": "string",
                    "anyOf": [
                        { "format": "AWS::KMS::Key.Arn" },
                        { "format": "AWS::KMS::Key.Id" },
                        { "format": "AWS::KMS::Alias.AliasName" }
                    ]
                }
            },
            "additionalProperties": false
        }),
    )]);
    let template = "Resources:\n  R:\n    Type: AWS::Test::KmsFormat\n    Properties:\n      KmsKeyId: alias/my-key\n";
    let diags = validate(&sv, template);
    assert!(
        !mentions(&diags, "F3017", ""),
        "valid KMS alias should not trigger F3017: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn kms_format_any_of_rejects_invalid_value() {
    let sv = validator(vec![(
        "AWS::Test::KmsFormat",
        json!({
            "properties": {
                "KmsKeyId": {
                    "type": "string",
                    "anyOf": [
                        { "format": "AWS::KMS::Key.Arn" },
                        { "format": "AWS::KMS::Key.Id" },
                        { "format": "AWS::KMS::Alias.AliasName" }
                    ]
                }
            },
            "additionalProperties": false
        }),
    )]);
    let template =
        "Resources:\n  R:\n    Type: AWS::Test::KmsFormat\n    Properties:\n      KmsKeyId: not-a-valid-kms-ref\n";
    let diags = validate(&sv, template);
    assert!(
        mentions(&diags, "F3017", "not valid under any"),
        "invalid KMS value should trigger F3017: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn kms_format_any_of_rejects_invalid_static_join() {
    let sv = validator(vec![(
        "AWS::Test::KmsFormat",
        json!({
            "properties": {
                "KmsKeyId": {
                    "type": "string",
                    "anyOf": [
                        { "format": "AWS::KMS::Key.Arn" },
                        { "format": "AWS::KMS::Key.Id" },
                        { "format": "AWS::KMS::Alias.AliasName" }
                    ]
                }
            },
            "additionalProperties": false
        }),
    )]);
    let template = r#"
Resources:
  R:
    Type: AWS::Test::KmsFormat
    Properties:
      KmsKeyId:
        Fn::Join:
          - ""
          - - "arn:aws:kms:us-east-1:123456789012:key/"
            - "12345"
"#;
    let diags = validate(&sv, template);
    assert!(
        mentions(&diags, "F3017", "not valid under any"),
        "a fully resolved invalid Fn::Join should trigger F3017: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn kms_format_any_of_skips_dynamic_ref_value() {
    // A dynamic value (!Ref to a parameter) cannot be evaluated at author-time;
    // the validator must conservatively skip composition branch matching rather
    // than reporting a false positive.
    let sv = validator(vec![(
        "AWS::Test::KmsFormat",
        json!({
            "properties": {
                "KmsKeyId": {
                    "type": "string",
                    "anyOf": [
                        { "format": "AWS::KMS::Key.Arn" },
                        { "format": "AWS::KMS::Key.Id" },
                        { "format": "AWS::KMS::Alias.AliasName" }
                    ]
                }
            },
            "additionalProperties": false
        }),
    )]);
    let template = r#"
Parameters:
  KeyParam:
    Type: String
Resources:
  R:
    Type: AWS::Test::KmsFormat
    Properties:
      KmsKeyId: !Ref KeyParam
"#;
    let diags = validate(&sv, template);
    assert!(
        !mentions(&diags, "F3017", ""),
        "dynamic !Ref value should not trigger composition failure: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
    assert!(
        !mentions(&diags, "F3018", ""),
        "dynamic !Ref value should not trigger oneOf failure: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

// ─── Array items with property-level composition ────────────────────────────

#[test]
fn prop_any_of_on_array_items_validates_elements() {
    let sv = validator(vec![(
        "AWS::Test::PropAnyOfItems",
        json!({
            "properties": {
                "Ports": {
                    "type": "array",
                    "items": {
                        "type": "integer",
                        "anyOf": [
                            { "minimum": 1, "maximum": 1024 },
                            { "minimum": 8000, "maximum": 9000 }
                        ]
                    }
                }
            },
            "additionalProperties": false
        }),
    )]);
    // Element 5000 is between both valid ranges
    let template = r#"{"Resources":{"R":{"Type":"AWS::Test::PropAnyOfItems","Properties":{"Ports":[443, 5000]}}}}"#;
    let diags = validate(&sv, template);
    assert!(
        mentions(&diags, "F3017", "not valid under any"),
        "expected F3017 for array element outside all anyOf ranges: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn prop_any_of_on_array_items_accepts_valid_elements() {
    let sv = validator(vec![(
        "AWS::Test::PropAnyOfItems",
        json!({
            "properties": {
                "Ports": {
                    "type": "array",
                    "items": {
                        "type": "integer",
                        "anyOf": [
                            { "minimum": 1, "maximum": 1024 },
                            { "minimum": 8000, "maximum": 9000 }
                        ]
                    }
                }
            },
            "additionalProperties": false
        }),
    )]);
    // All elements in valid ranges
    let template = r#"{"Resources":{"R":{"Type":"AWS::Test::PropAnyOfItems","Properties":{"Ports":[443, 8080]}}}}"#;
    let diags = validate(&sv, template);
    assert!(
        !mentions(&diags, "F3017", ""),
        "expected no F3017 when all array elements are in valid ranges: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

// ─── Scenario-aware group decisions ─────────────────────────────────────────
// anyOf/oneOf are decided once per template condition scenario: a property
// valued through Fn::If has a different concrete value in each reachable
// scenario, and each scenario may satisfy a different branch.

#[test]
fn one_of_is_decided_per_condition_scenario() {
    // Mode is A in one scenario and B in the other; each scenario matches
    // exactly one oneOf branch, so the template is valid - deciding the group
    // across scenarios would falsely report "valid under more than one".
    let sv = validator(vec![(
        "AWS::Test::OneOfScenario",
        json!({
            "properties": { "Mode": { "type": "string" } },
            "oneOf": [
                { "properties": { "Mode": { "enum": ["A"] } }, "required": ["Mode"] },
                { "properties": { "Mode": { "enum": ["B"] } }, "required": ["Mode"] }
            ],
            "additionalProperties": false
        }),
    )]);
    let template = r#"{
        "Conditions": { "IsA": { "Fn::Equals": [{ "Ref": "AWS::Region" }, "us-east-1"] } },
        "Resources": {
            "R": {
                "Type": "AWS::Test::OneOfScenario",
                "Properties": { "Mode": { "Fn::If": ["IsA", "A", "B"] } }
            }
        }
    }"#;
    let diags = validate(&sv, template);
    assert!(
        !mentions(&diags, "F3018", "more than one"),
        "mutually exclusive scenarios each matching one branch must not be reported as ambiguous: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn any_of_reports_the_invalid_condition_scenario() {
    // Mode is A in one scenario (valid) and C in the other (matches no branch):
    // the invalid scenario must be reported even though a sibling scenario is
    // valid, and the finding must carry that scenario's condition assignment.
    let sv = validator(vec![(
        "AWS::Test::AnyOfScenario",
        json!({
            "properties": { "Mode": { "type": "string" } },
            "anyOf": [
                { "properties": { "Mode": { "enum": ["A"] } }, "required": ["Mode"] },
                { "properties": { "Mode": { "enum": ["B"] } }, "required": ["Mode"] }
            ],
            "additionalProperties": false
        }),
    )]);
    let template = r#"{
        "Conditions": { "IsA": { "Fn::Equals": [{ "Ref": "AWS::Region" }, "us-east-1"] } },
        "Resources": {
            "R": {
                "Type": "AWS::Test::AnyOfScenario",
                "Properties": { "Mode": { "Fn::If": ["IsA", "A", "C"] } }
            }
        }
    }"#;
    let diags = validate(&sv, template);
    let finding = diags.iter().find(|d| d.rule_id == "F3017").unwrap_or_else(|| {
        panic!(
            "the scenario with Mode=C matches no anyOf branch and must be reported: {:?}",
            diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
        )
    });
    let conds = finding
        .condition_scenario
        .as_ref()
        .expect("the finding must carry the condition assignment that produces the invalid value");
    assert_eq!(conds.get("IsA"), Some(&false), "the invalid value comes from the IsA=false branch: {conds:?}");
}

#[test]
fn property_level_conditional_then_required_is_enforced() {
    // A conditional stated by an overlay on an object property enforces the
    // selected branch in full - including its `required` list.
    let sv = validator(vec![(
        "AWS::Test::PropCondRequired",
        json!({
            "properties": {
                "Cfg": {
                    "type": "object",
                    "properties": { "Mode": { "type": "string" }, "Extra": { "type": "string" } },
                    "allOf": [{
                        "if": { "properties": { "Mode": { "enum": ["on"] } }, "required": ["Mode"] },
                        "then": { "required": ["Extra"] }
                    }]
                }
            }
        }),
    )]);
    let violating =
        "Resources:\n  R:\n    Type: AWS::Test::PropCondRequired\n    Properties:\n      Cfg:\n        Mode: 'on'\n";
    let diags = validate(&sv, violating);
    assert!(
        mentions(&diags, "F3003", "Extra"),
        "a property-level conditional's required list must be enforced: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
    let ok = "Resources:\n  R:\n    Type: AWS::Test::PropCondRequired\n    Properties:\n      Cfg:\n        Mode: 'on'\n        Extra: x\n";
    let diags = validate(&sv, ok);
    assert!(
        diags.is_empty(),
        "a satisfied conditional must stay clean: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

fn nested_group_schema(keyword: &str) -> Value {
    let mut schema = json!({
        "properties": {
            "Cfg": {
                "type": "object",
                "properties": { "A": { "type": "string" }, "B": { "type": "string" } }
            }
        }
    });
    schema["properties"]["Cfg"][keyword] = json!(["A", "B"]);
    schema
}

fn nested_cfg_template(resource_type: &str, cfg: &str) -> String {
    format!("Resources:\n  R:\n    Type: {resource_type}\n    Properties:\n      Cfg:{cfg}\n")
}

#[test]
fn nested_required_or_counts_only_concrete_members() {
    let resource_type = "AWS::Test::NestedReqOr";
    let sv = validator(vec![(resource_type, nested_group_schema("requiredOr"))]);
    for (cfg, should_fire) in [
        (" {}", true),
        ("\n        A: value", false),
        ("\n        A: !Ref AWS::NoValue\n        B: !Ref AWS::NoValue", true),
        ("\n        A: value\n        B: !Ref AWS::NoValue", false),
    ] {
        let diags = validate(&sv, &nested_cfg_template(resource_type, cfg));
        assert_eq!(
            mentions(&diags, "F3058", "One of"),
            should_fire,
            "unexpected requiredOr result for Cfg:{cfg}: {diags:?}"
        );
    }
}

#[test]
fn nested_required_xor_counts_only_concrete_members() {
    let resource_type = "AWS::Test::NestedReqXor";
    let sv = validator(vec![(resource_type, nested_group_schema("requiredXor"))]);
    for (cfg, should_fire) in [
        (" {}", true),
        ("\n        A: one\n        B: two", true),
        ("\n        A: one", false),
        ("\n        A: one\n        B: !Ref AWS::NoValue", false),
    ] {
        let diags = validate(&sv, &nested_cfg_template(resource_type, cfg));
        assert_eq!(
            mentions(&diags, "F3014", "Exactly one"),
            should_fire,
            "unexpected requiredXor result for Cfg:{cfg}: {diags:?}"
        );
    }
}

#[test]
fn required_xor_participates_in_one_of_branch_matching() {
    let resource_type = "AWS::Test::CompReqXor";
    let sv = validator(vec![(
        resource_type,
        json!({
            "properties": {
                "Cfg": {
                    "type": "object",
                    "properties": {
                        "A": { "type": "string" },
                        "B": { "type": "string" },
                        "C": { "type": "string" }
                    },
                    "oneOf": [{ "requiredXor": ["A", "B"] }, { "required": ["C"] }]
                }
            }
        }),
    )]);
    for (cfg, should_fire) in [("\n        A: value", false), ("\n        C: value", false), (" {}", true)] {
        let diags = validate(&sv, &nested_cfg_template(resource_type, cfg));
        assert_eq!(
            mentions(&diags, "F3018", "schema"),
            should_fire,
            "unexpected oneOf result for Cfg:{cfg}: {diags:?}"
        );
    }
}

#[test]
fn required_or_branch_rejects_an_aws_novalue_member() {
    let resource_type = "AWS::Test::CompReqOr";
    let sv = validator(vec![(
        resource_type,
        json!({
            "properties": {
                "Cfg": {
                    "type": "object",
                    "properties": {
                        "A": { "type": "string" },
                        "B": { "type": "string" },
                        "C": { "type": "string" }
                    },
                    "anyOf": [{ "requiredOr": ["A", "B"] }, { "required": ["C"] }]
                }
            }
        }),
    )]);
    for (cfg, should_fire) in
        [("\n        A: !Ref AWS::NoValue", true), ("\n        A: !Ref AWS::NoValue\n        C: value", false)]
    {
        let diags = validate(&sv, &nested_cfg_template(resource_type, cfg));
        assert_eq!(
            mentions(&diags, "F3017", "not valid under any"),
            should_fire,
            "unexpected anyOf result for Cfg:{cfg}: {diags:?}"
        );
    }
}

#[test]
fn required_or_one_of_is_decided_per_condition_scenario() {
    let resource_type = "AWS::Test::CompReqOrScenarios";
    let sv = validator(vec![(
        resource_type,
        json!({
            "properties": {
                "Cfg": {
                    "type": "object",
                    "properties": { "A": { "type": "string" }, "B": { "type": "string" } },
                    "oneOf": [{ "requiredOr": ["A"] }, { "requiredOr": ["B"] }]
                }
            }
        }),
    )]);
    let template = concat!(
        "Conditions:\n",
        "  UseA: !Equals [!Ref AWS::Region, us-east-1]\n",
        "Resources:\n",
        "  R:\n",
        "    Type: AWS::Test::CompReqOrScenarios\n",
        "    Properties:\n",
        "      Cfg:\n",
        "        A: !If [UseA, a, !Ref AWS::NoValue]\n",
        "        B: !If [UseA, !Ref AWS::NoValue, b]\n",
    );
    let diags = validate(&sv, template);
    assert!(
        !mentions(&diags, "F3018", "schema"),
        "each satisfiable condition scenario must match exactly one requiredOr branch: {diags:?}"
    );
}

// requiredOr reports a defect when every candidate resolves to AWS::NoValue.

#[test]
fn required_or_emits_f3058_when_all_candidates_resolve_to_novalue() {
    // All requiredOr members authored but every one resolves to AWS::NoValue
    // unconditionally - CloudFormation strips them, so none survive deployment.
    let sv = validator(vec![(
        "AWS::Test::ReqOrNoValue",
        json!({
            "properties": {
                "A": { "type": "string" },
                "B": { "type": "string" },
                "C": { "type": "string" }
            },
            "requiredOr": ["A", "B"],
            "additionalProperties": false
        }),
    )]);
    let template = concat!(
        "Resources:\n",
        "  R:\n",
        "    Type: AWS::Test::ReqOrNoValue\n",
        "    Properties:\n",
        "      A: !Ref AWS::NoValue\n",
        "      B: !Ref AWS::NoValue\n",
        "      C: hello\n",
    );
    let diags = validate(&sv, template);
    assert!(
        mentions(&diags, "F3058", "required property"),
        "expected F3058 when all requiredOr candidates are NoValue: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn required_or_conditional_f3058_only_in_novalue_scenario() {
    // One requiredOr member is conditionally NoValue: the scenario where
    // the condition is false (member A resolves to NoValue) and no other candidate is
    // present must produce a conditional required-property finding. The scenario where the
    // condition is true (member A has a value) must not produce that finding.
    let sv = validator(vec![(
        "AWS::Test::ReqOrCondNoValue",
        json!({
            "properties": {
                "A": { "type": "string" },
                "B": { "type": "string" }
            },
            "requiredOr": ["A", "B"],
            "additionalProperties": false
        }),
    )]);
    let template = concat!(
        "Conditions:\n",
        "  UseA: !Equals [!Ref AWS::Region, us-east-1]\n",
        "Resources:\n",
        "  R:\n",
        "    Type: AWS::Test::ReqOrCondNoValue\n",
        "    Properties:\n",
        "      A: !If [UseA, real-value, !Ref AWS::NoValue]\n",
    );
    let diags = validate(&sv, template);
    let f3058_diags: Vec<_> = diags.iter().filter(|d| d.rule_id == "F3058").collect();
    assert!(
        !f3058_diags.is_empty(),
        "expected conditional F3058 for the scenario where A is NoValue: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
    // The diagnostic must carry the condition scenario (UseA=false).
    assert!(
        f3058_diags.iter().any(|d| d.condition_scenario.is_some()),
        "F3058 must have condition_scenario set for conditional findings: {:?}",
        f3058_diags.iter().map(|d| (&d.condition_scenario,)).collect::<Vec<_>>()
    );
}

#[test]
fn required_or_no_diagnostic_when_one_candidate_has_value() {
    // At least one requiredOr candidate has a concrete (non-null) value in
    // every scenario, so no required-property finding should fire.
    let sv = validator(vec![(
        "AWS::Test::ReqOrOnePresent",
        json!({
            "properties": {
                "A": { "type": "string" },
                "B": { "type": "string" }
            },
            "requiredOr": ["A", "B"],
            "additionalProperties": false
        }),
    )]);
    let template = concat!(
        "Resources:\n",
        "  R:\n",
        "    Type: AWS::Test::ReqOrOnePresent\n",
        "    Properties:\n",
        "      A: hello\n",
        "      B: !Ref AWS::NoValue\n",
    );
    let diags = validate(&sv, template);
    assert!(
        !mentions(&diags, "F3058", ""),
        "no F3058 when at least one candidate is concrete: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn required_or_nested_in_composition_branch_evaluates_per_scenario() {
    // requiredOr inside a oneOf branch must still evaluate per condition
    // scenario when the member properties are conditional.
    let sv = validator(vec![(
        "AWS::Test::ReqOrNested",
        json!({
            "properties": {
                "A": { "type": "string" },
                "B": { "type": "string" },
                "C": { "type": "string" }
            },
            "oneOf": [
                { "requiredOr": ["A", "B"] },
                { "required": ["C"] }
            ],
            "additionalProperties": false
        }),
    )]);
    // A is conditionally NoValue, B absent, C absent - the first oneOf branch
    // has no surviving member in the UseA=false scenario, triggering a violation in
    // that branch's validate_sub call.
    let template = concat!(
        "Conditions:\n",
        "  UseA: !Equals [!Ref AWS::Region, us-east-1]\n",
        "Resources:\n",
        "  R:\n",
        "    Type: AWS::Test::ReqOrNested\n",
        "    Properties:\n",
        "      A: !If [UseA, value, !Ref AWS::NoValue]\n",
    );
    let diags = validate(&sv, template);
    // Either the requiredOr violation or a no-branch-matched finding must fire.
    let has_finding = mentions(&diags, "F3058", "") || mentions(&diags, "F3018", "");
    assert!(
        has_finding,
        "expected F3058 or F3018 when nested requiredOr has no surviving candidate: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

// requiredXor evaluates each condition scenario independently.

#[test]
fn required_xor_no_false_positive_for_mutually_exclusive_conditions() {
    // Two requiredXor members, each present only in its own condition branch.
    // In every deployable scenario exactly one is present, so no xor finding is expected.
    let sv = validator(vec![(
        "AWS::Test::ReqXorCond",
        json!({
            "properties": {
                "A": { "type": "string" },
                "B": { "type": "string" }
            },
            "requiredXor": ["A", "B"],
            "additionalProperties": false
        }),
    )]);
    let template = concat!(
        "Conditions:\n",
        "  UseA: !Equals [!Ref AWS::Region, us-east-1]\n",
        "Resources:\n",
        "  R:\n",
        "    Type: AWS::Test::ReqXorCond\n",
        "    Properties:\n",
        "      A: !If [UseA, a-value, !Ref AWS::NoValue]\n",
        "      B: !If [UseA, !Ref AWS::NoValue, b-value]\n",
    );
    let diags = validate(&sv, template);
    assert!(
        !mentions(&diags, "F3014", ""),
        "no F3014 when each scenario has exactly one member: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn required_xor_emits_f3014_when_zero_members_in_scenario() {
    // Both requiredXor members resolve to NoValue in the same scenario.
    let sv = validator(vec![(
        "AWS::Test::ReqXorZero",
        json!({
            "properties": {
                "A": { "type": "string" },
                "B": { "type": "string" }
            },
            "requiredXor": ["A", "B"],
            "additionalProperties": false
        }),
    )]);
    let template = concat!(
        "Resources:\n",
        "  R:\n",
        "    Type: AWS::Test::ReqXorZero\n",
        "    Properties:\n",
        "      A: !Ref AWS::NoValue\n",
        "      B: !Ref AWS::NoValue\n",
    );
    let diags = validate(&sv, template);
    assert!(
        mentions(&diags, "F3014", "Exactly one"),
        "expected F3014 when zero members survive deployment: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn required_xor_emits_f3014_when_two_members_in_every_scenario() {
    // Both requiredXor members are unconditionally concrete - always two present.
    let sv = validator(vec![(
        "AWS::Test::ReqXorTwo",
        json!({
            "properties": {
                "A": { "type": "string" },
                "B": { "type": "string" }
            },
            "requiredXor": ["A", "B"],
            "additionalProperties": false
        }),
    )]);
    let template = concat!(
        "Resources:\n",
        "  R:\n",
        "    Type: AWS::Test::ReqXorTwo\n",
        "    Properties:\n",
        "      A: hello\n",
        "      B: world\n",
    );
    let diags = validate(&sv, template);
    assert!(
        mentions(&diags, "F3014", "Exactly one"),
        "expected F3014 when two members are unconditionally present: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn required_xor_independent_conditions_evaluated_correctly() {
    // Two truly independent conditions (based on different parameters) control
    // two requiredXor members. The satisfiable scenarios include combinations
    // where zero or two are present, which violate the xor constraint.
    let sv = validator(vec![(
        "AWS::Test::ReqXorIndep",
        json!({
            "properties": {
                "A": { "type": "string" },
                "B": { "type": "string" }
            },
            "requiredXor": ["A", "B"],
            "additionalProperties": false
        }),
    )]);
    let template = concat!(
        "Parameters:\n",
        "  ParamA:\n",
        "    Type: String\n",
        "  ParamB:\n",
        "    Type: String\n",
        "Conditions:\n",
        "  CondA: !Equals [!Ref ParamA, yes]\n",
        "  CondB: !Equals [!Ref ParamB, yes]\n",
        "Resources:\n",
        "  R:\n",
        "    Type: AWS::Test::ReqXorIndep\n",
        "    Properties:\n",
        "      A: !If [CondA, a-value, !Ref AWS::NoValue]\n",
        "      B: !If [CondB, b-value, !Ref AWS::NoValue]\n",
    );
    let diags = validate(&sv, template);
    // With truly independent conditions, CondA=true/CondB=true gives two
    // present (violates xor) and CondA=false/CondB=false gives zero present
    // (also violates xor). The other two worlds are valid.
    let f3014_diags: Vec<_> = diags.iter().filter(|d| d.rule_id == "F3014").collect();
    assert_eq!(
        f3014_diags.len(),
        2,
        "expected exactly 2 F3014 diagnostics (one per violating world), got {}: {:?}",
        f3014_diags.len(),
        f3014_diags.iter().map(|d| (&d.condition_scenario, &d.message)).collect::<Vec<_>>()
    );
    // All xor findings must carry condition_scenario metadata.
    assert!(
        f3014_diags.iter().all(|d| d.condition_scenario.is_some()),
        "F3014 for conditional scenarios must have condition_scenario set: {:?}",
        f3014_diags.iter().map(|d| (&d.condition_scenario,)).collect::<Vec<_>>()
    );
    // Assert the two violating worlds are exactly:
    //   CondA=true, CondB=true (both present)
    //   CondA=false, CondB=false (neither present)
    let scenarios: Vec<&HashMap<String, bool>> =
        f3014_diags.iter().map(|d| d.condition_scenario.as_ref().unwrap()).collect();
    let both_true = scenarios.iter().any(|s| s.get("CondA") == Some(&true) && s.get("CondB") == Some(&true));
    let both_false = scenarios.iter().any(|s| s.get("CondA") == Some(&false) && s.get("CondB") == Some(&false));
    assert!(both_true, "expected a violation for CondA=true, CondB=true (two present): {:?}", scenarios);
    assert!(both_false, "expected a violation for CondA=false, CondB=false (zero present): {:?}", scenarios);
}

#[test]
fn required_xor_nested_in_composition_branch() {
    // requiredXor inside a oneOf branch must still evaluate per scenario.
    let sv = validator(vec![(
        "AWS::Test::ReqXorNested",
        json!({
            "properties": {
                "A": { "type": "string" },
                "B": { "type": "string" },
                "C": { "type": "string" }
            },
            "oneOf": [
                { "requiredXor": ["A", "B"] },
                { "required": ["C"] }
            ],
            "additionalProperties": false
        }),
    )]);
    // In every scenario exactly one of A/B is present (mutually exclusive via
    // condition) - the first oneOf branch should pass.
    let template = concat!(
        "Conditions:\n",
        "  UseA: !Equals [!Ref AWS::Region, us-east-1]\n",
        "Resources:\n",
        "  R:\n",
        "    Type: AWS::Test::ReqXorNested\n",
        "    Properties:\n",
        "      A: !If [UseA, a-val, !Ref AWS::NoValue]\n",
        "      B: !If [UseA, !Ref AWS::NoValue, b-val]\n",
    );
    let diags = validate(&sv, template);
    // The first oneOf branch should match in both scenarios (xor satisfied),
    // so no no-branch-matched finding should fire.
    assert!(
        !mentions(&diags, "F3018", "not valid under any"),
        "expected no F3018 when requiredXor is satisfied per scenario in nested branch: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn required_xor_dynamic_value_conservatively_present() {
    // When a requiredXor member has a dynamic value (e.g. Ref to a parameter),
    // it must be conservatively treated as present, with no false xor finding.
    let sv = validator(vec![(
        "AWS::Test::ReqXorDynamic",
        json!({
            "properties": {
                "A": { "type": "string" },
                "B": { "type": "string" }
            },
            "requiredXor": ["A", "B"],
            "additionalProperties": false
        }),
    )]);
    let template = concat!(
        "Parameters:\n",
        "  MyParam:\n",
        "    Type: String\n",
        "Resources:\n",
        "  R:\n",
        "    Type: AWS::Test::ReqXorDynamic\n",
        "    Properties:\n",
        "      A: !Ref MyParam\n",
    );
    let diags = validate(&sv, template);
    assert!(
        !mentions(&diags, "F3014", ""),
        "no F3014 when a dynamic member is conservatively present: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn required_xor_preserves_conditions_on_dynamic_members() {
    let sv = validator(vec![(
        "AWS::Test::ReqXorDynamicConditional",
        json!({
            "properties": {
                "A": { "type": "string" },
                "B": { "type": "string" }
            },
            "requiredXor": ["A", "B"],
            "additionalProperties": false
        }),
    )]);
    let template = r#"
Parameters:
  Target:
    Type: String
  Toggle:
    Type: String
    AllowedValues: ['true', 'false']
Conditions:
  DuplicateTarget: !Equals [!Ref Toggle, 'true']
Resources:
  R:
    Type: AWS::Test::ReqXorDynamicConditional
    Properties:
      A: !Ref Target
      B: !If [DuplicateTarget, !Ref Target, !Ref AWS::NoValue]
"#;

    let diags = validate(&sv, template);
    let findings: Vec<_> = diags.iter().filter(|diagnostic| diagnostic.rule_id == "F3014").collect();
    assert_eq!(findings.len(), 1, "the duplicate-present world must be diagnosed exactly once: {diags:?}");
    assert_eq!(
        findings[0].condition_scenario.as_ref().and_then(|scenario| scenario.get("DuplicateTarget")),
        Some(&true)
    );
}

#[test]
fn required_xor_respects_resource_condition_correlation() {
    let sv = validator(vec![(
        "AWS::Test::ReqXorResourceCondition",
        json!({
            "properties": {
                "A": { "type": "string" },
                "B": { "type": "string" }
            },
            "requiredXor": ["A", "B"],
            "additionalProperties": false
        }),
    )]);
    let template = r#"
Parameters:
  Target:
    Type: String
  Toggle:
    Type: String
    AllowedValues: ['true', 'false']
Conditions:
  DuplicateTarget: !Equals [!Ref Toggle, 'true']
  CreateWithoutDuplicate: !Not [!Condition DuplicateTarget]
Resources:
  R:
    Type: AWS::Test::ReqXorResourceCondition
    Condition: CreateWithoutDuplicate
    Properties:
      A: !Ref Target
      B: !If [DuplicateTarget, !Ref Target, !Ref AWS::NoValue]
"#;

    let diags = validate(&sv, template);
    assert!(!mentions(&diags, "F3014", ""), "the resource exists only in the single-present world: {diags:?}");
}

#[test]
fn required_or_dynamic_value_conservatively_present() {
    // When a requiredOr member has a dynamic value, it must be conservatively
    // treated as present, with no false required-property finding.
    let sv = validator(vec![(
        "AWS::Test::ReqOrDynamic",
        json!({
            "properties": {
                "A": { "type": "string" },
                "B": { "type": "string" }
            },
            "requiredOr": ["A", "B"],
            "additionalProperties": false
        }),
    )]);
    let template = concat!(
        "Parameters:\n",
        "  MyParam:\n",
        "    Type: String\n",
        "Resources:\n",
        "  R:\n",
        "    Type: AWS::Test::ReqOrDynamic\n",
        "    Properties:\n",
        "      A: !Ref MyParam\n",
    );
    let diags = validate(&sv, template);
    assert!(
        !mentions(&diags, "F3058", ""),
        "no F3058 when a dynamic member is conservatively present: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn outer_key_scenario_constrains_required_xor_evaluation() {
    // When Properties is wrapped in Fn::If, BOTH branches expose the same
    // requiredXor key names but with different values/NoValue. This proves
    // value scenarios are constrained by the outer key condition rather than
    // relying on actual_keys gating.
    let sv = validator(vec![(
        "AWS::Test::OuterKeyXor",
        json!({
            "properties": {
                "A": { "type": "string" },
                "B": { "type": "string" }
            },
            "requiredXor": ["A", "B"],
            "additionalProperties": false
        }),
    )]);
    // Both branches expose A and B keys. CondX=true gives A=val, B=NoValue;
    // CondX=false gives A=NoValue, B=val. Each branch has exactly one
    // non-null requiredXor member - no violation in either world.
    let template = r#"{
        "Conditions": { "CondX": { "Fn::Equals": [{ "Ref": "AWS::Region" }, "us-east-1"] } },
        "Resources": {
            "R": {
                "Type": "AWS::Test::OuterKeyXor",
                "Properties": { "Fn::If": ["CondX",
                    { "A": "val", "B": { "Ref": "AWS::NoValue" } },
                    { "A": { "Ref": "AWS::NoValue" }, "B": "val" }
                ] }
            }
        }
    }"#;
    let diags = validate(&sv, template);
    assert!(
        !mentions(&diags, "F3014", ""),
        "no F3014 when each outer key branch satisfies requiredXor independently: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn outer_key_scenario_constrains_required_or_evaluation() {
    // Both Fn::If branches expose the SAME requiredOr key names but with
    // different values/NoValue, proving value scenarios are constrained by
    // the outer key condition rather than relying on actual_keys gating.
    // Assert exactly one diagnostic tagged with the all-NoValue branch.
    let sv = validator(vec![(
        "AWS::Test::OuterKeyOr",
        json!({
            "properties": {
                "A": { "type": "string" },
                "B": { "type": "string" }
            },
            "requiredOr": ["A", "B"],
            "additionalProperties": false
        }),
    )]);
    // Both branches have A and B. CondX=true gives A=val, B=NoValue (at least
    // one present, valid). CondX=false gives A=NoValue, B=NoValue (none present,
    // violation). Exactly one finding should fire, tagged with the CondX=false
    // scenario.
    let template = r#"{
        "Conditions": { "CondX": { "Fn::Equals": [{ "Ref": "AWS::Region" }, "us-east-1"] } },
        "Resources": {
            "R": {
                "Type": "AWS::Test::OuterKeyOr",
                "Properties": { "Fn::If": ["CondX",
                    { "A": "val", "B": { "Ref": "AWS::NoValue" } },
                    { "A": { "Ref": "AWS::NoValue" }, "B": { "Ref": "AWS::NoValue" } }
                ] }
            }
        }
    }"#;
    let diags = validate(&sv, template);
    let f3058_diags: Vec<_> = diags.iter().filter(|d| d.rule_id == "F3058").collect();
    assert_eq!(
        f3058_diags.len(),
        1,
        "expected exactly 1 F3058 (the all-NoValue branch), got {}: {:?}",
        f3058_diags.len(),
        f3058_diags.iter().map(|d| (&d.condition_scenario, &d.message)).collect::<Vec<_>>()
    );
    let conds = f3058_diags[0]
        .condition_scenario
        .as_ref()
        .expect("the F3058 must carry the condition assignment for the all-NoValue branch");
    assert_eq!(conds.get("CondX"), Some(&false), "the all-NoValue branch is CondX=false: {conds:?}");
}

#[test]
fn nested_independent_conditions_inside_one_of_branch() {
    // requiredXor inside a oneOf branch with independent conditions.
    // The nested evaluation under the outer branch assignment must still
    // expand the independent conditions within that branch's world.
    let sv = validator(vec![(
        "AWS::Test::NestedIndep",
        json!({
            "properties": {
                "A": { "type": "string" },
                "B": { "type": "string" },
                "C": { "type": "string" }
            },
            "oneOf": [
                { "requiredXor": ["A", "B"] },
                { "required": ["C"] }
            ],
            "additionalProperties": false
        }),
    )]);
    // A and B are controlled by independent conditions. The satisfiable worlds:
    //   CondA=T, CondB=T: A present, B present (xor violated, 2 present)
    //   CondA=T, CondB=F: A present, B absent (xor satisfied)
    //   CondA=F, CondB=T: A absent, B present (xor satisfied)
    //   CondA=F, CondB=F: A absent, B absent (xor violated, 0 present)
    // In worlds where xor is violated AND C is absent, no oneOf branch is
    // satisfied, producing a no-branch-matched finding. The violating assignments are exactly
    // {CondA=T, CondB=T} and {CondA=F, CondB=F}.
    let template = concat!(
        "Parameters:\n",
        "  ParamA:\n",
        "    Type: String\n",
        "  ParamB:\n",
        "    Type: String\n",
        "Conditions:\n",
        "  CondA: !Equals [!Ref ParamA, yes]\n",
        "  CondB: !Equals [!Ref ParamB, yes]\n",
        "Resources:\n",
        "  R:\n",
        "    Type: AWS::Test::NestedIndep\n",
        "    Properties:\n",
        "      A: !If [CondA, a-val, !Ref AWS::NoValue]\n",
        "      B: !If [CondB, b-val, !Ref AWS::NoValue]\n",
    );
    let diags = validate(&sv, template);
    // Collect all oneOf branch-failure diagnostics.
    let f3018_diags: Vec<_> = diags.iter().filter(|d| d.rule_id == "F3018").collect();
    assert_eq!(
        f3018_diags.len(),
        2,
        "expected exactly 2 F3018 diagnostics (one per violating world), got {}: {:?}",
        f3018_diags.len(),
        f3018_diags.iter().map(|d| (&d.condition_scenario, &d.message)).collect::<Vec<_>>()
    );
    // Assert the two violating worlds are exactly:
    //   CondA=true, CondB=true (both present, xor violated)
    //   CondA=false, CondB=false (neither present, xor violated)
    let scenarios: Vec<&HashMap<String, bool>> =
        f3018_diags.iter().filter_map(|d| d.condition_scenario.as_ref()).collect();
    assert_eq!(scenarios.len(), 2, "both F3018 findings must carry condition_scenario: {:?}", f3018_diags);
    let both_true = scenarios.iter().any(|s| s.get("CondA") == Some(&true) && s.get("CondB") == Some(&true));
    let both_false = scenarios.iter().any(|s| s.get("CondA") == Some(&false) && s.get("CondB") == Some(&false));
    assert!(both_true, "expected a violation for CondA=true, CondB=true: {:?}", scenarios);
    assert!(both_false, "expected a violation for CondA=false, CondB=false: {:?}", scenarios);
}

#[test]
fn conditional_schema_branch_selection_respects_the_active_scenario() {
    let validator = validator(vec![(
        "AWS::Test::ScenarioConditional",
        json!({
            "properties": {
                "Mode": {"type": "string", "enum": ["X", "Y"]},
                "Target": {"type": "string", "enum": ["for-x", "for-y"]}
            },
            "anyOf": [{
                "properties": {
                    "Mode": {"type": "string"},
                    "Target": {"type": "string"}
                },
                "if": {
                    "properties": {"Mode": {"const": "X"}},
                    "required": ["Mode"]
                },
                "then": {"properties": {"Target": {"const": "for-x"}}},
                "else": {"properties": {"Target": {"const": "for-y"}}}
            }],
            "additionalProperties": false
        }),
    )]);
    let template = r#"
Conditions:
  UseX: !Equals [!Ref AWS::Region, us-east-1]
Resources:
  Resource:
    Type: AWS::Test::ScenarioConditional
    Properties:
      Mode: !If [UseX, X, Y]
      Target: !If [UseX, for-x, for-y]
"#;

    let diagnostics = validate(&validator, template);

    assert!(
        !mentions(&diagnostics, "F3017", ""),
        "each condition world satisfies its selected schema branch: {diagnostics:#?}"
    );
}

#[test]
fn independent_optional_conditionals_have_bounded_composition_work() {
    const PROPERTY_COUNT: usize = 14;

    let mut properties = serde_json::Map::new();
    let mut branch_properties = serde_json::Map::new();
    let mut template = String::from("Parameters:\n");
    for index in 0..PROPERTY_COUNT {
        let property_name = format!("Property{index:02}");
        let property_schema = json!({"type": "string", "enum": [format!("value-{index:02}")]});
        properties.insert(property_name.clone(), property_schema.clone());
        branch_properties.insert(property_name, property_schema);
        template.push_str(&format!(
            "  Parameter{index:02}:\n    Type: String\n    AllowedValues: [yes, no]\n    Default: no\n"
        ));
    }
    template.push_str("Conditions:\n");
    for index in 0..PROPERTY_COUNT {
        template.push_str(&format!("  Condition{index:02}: !Equals [!Ref Parameter{index:02}, yes]\n"));
    }
    template.push_str("Resources:\n  Resource:\n    Type: AWS::Test::ScenarioBound\n    Properties:\n");
    for index in 0..PROPERTY_COUNT {
        template.push_str(&format!(
            "      Property{index:02}: !If [Condition{index:02}, value-{index:02}, !Ref AWS::NoValue]\n"
        ));
    }
    let validator = validator(vec![(
        "AWS::Test::ScenarioBound",
        json!({
            "properties": properties,
            "anyOf": [{"properties": branch_properties}],
            "additionalProperties": false
        }),
    )]);

    let diagnostics = validate(&validator, &template);

    assert!(
        diagnostics.iter().all(|diagnostic| !diagnostic.rule_id.starts_with('F')),
        "bounded analysis must not turn uncertainty into a schema violation: {diagnostics:#?}"
    );
    // The budget-exhaustion warning is emitted by the validation engine, not the schema validator.
    // The schema validator records budget exhaustions to the model tracker.
    assert!(
        diagnostics.iter().all(|diagnostic| diagnostic.rule_id != "W9052"),
        "schema validator must not emit per-path budget diagnostics: {diagnostics:#?}"
    );
}

fn conditional_required_or_fixture(property_count: usize) -> (SchemaValidator, String) {
    let mut properties = serde_json::Map::new();
    let mut required_or = Vec::new();
    let mut template = String::from("Parameters:\n");
    for index in 0..property_count {
        let property_name = format!("Property{index:02}");
        properties.insert(property_name.clone(), json!({"type": "string"}));
        required_or.push(property_name);
        template.push_str(&format!(
            "  Parameter{index:02}:\n    Type: String\n    AllowedValues: [yes, no]\n    Default: no\n"
        ));
    }
    template.push_str("Conditions:\n");
    for index in 0..property_count {
        template.push_str(&format!("  Condition{index:02}: !Equals [!Ref Parameter{index:02}, yes]\n"));
    }
    template.push_str("Resources:\n  Resource:\n    Type: AWS::Test::RequiredOrScenarioBound\n    Properties:\n");
    for index in 0..property_count {
        template.push_str(&format!(
            "      Property{index:02}: !If [Condition{index:02}, value-{index:02}, !Ref AWS::NoValue]\n"
        ));
    }
    let validator = validator(vec![(
        "AWS::Test::RequiredOrScenarioBound",
        json!({
            "properties": properties,
            "requiredOr": required_or,
            "additionalProperties": false
        }),
    )]);
    (validator, template)
}

#[test]
fn required_or_scenario_budget_boundary_is_non_silent() {
    let (validator, template) = conditional_required_or_fixture(8);
    let diagnostics = validate(&validator, &template);
    let required_findings: Vec<_> = diagnostics.iter().filter(|diagnostic| diagnostic.rule_id == "F3058").collect();
    assert_eq!(
        required_findings.len(),
        1,
        "all 256 condition worlds must be analyzed, including the all-false world: {diagnostics:#?}"
    );
    assert!(
        diagnostics.iter().all(|diagnostic| diagnostic.rule_id != "W9052"),
        "the exact assignment limit must remain fully analyzable: {diagnostics:#?}"
    );

    let (validator, template) = conditional_required_or_fixture(9);
    let diagnostics = validate(&validator, &template);
    let required_findings: Vec<_> = diagnostics.iter().filter(|diagnostic| diagnostic.rule_id == "F3058").collect();
    assert_eq!(
        required_findings.len(),
        1,
        "targeted witness search must find the reachable all-false world beyond the exact-enumeration limit: {diagnostics:#?}"
    );
    // The budget-exhaustion warning is emitted by the validation engine at report level, not per-path.
    // Schema validator records the exhaustion to the model budget tracker.
    assert!(
        diagnostics.iter().all(|diagnostic| diagnostic.rule_id != "W9052"),
        "schema validator must not emit per-path budget diagnostics: {diagnostics:#?}"
    );
}

fn adversarial_no_value_tree(condition_names: &[String]) -> Value {
    condition_names.iter().rev().fold(
        json!({"Ref": "AWS::NoValue"}),
        |branch, condition| json!({"Fn::If": [condition, branch.clone(), branch]}),
    )
}

fn adversarial_required_xor_fixture(condition_count: usize) -> (SchemaValidator, String) {
    let mut parameters = serde_json::Map::new();
    parameters.insert("Split".to_string(), json!({"Type": "String", "AllowedValues": ["left", "right"]}));
    let mut conditions = serde_json::Map::new();
    conditions.insert("UseLeft".to_string(), json!({"Fn::Equals": [{"Ref": "Split"}, "left"]}));
    let mut flag_names = Vec::new();
    for index in 0..condition_count {
        let parameter_name = format!("FlagParameter{index:02}");
        let condition_name = format!("Flag{index:02}");
        parameters.insert(parameter_name.clone(), json!({"Type": "String", "AllowedValues": ["yes", "no"]}));
        conditions.insert(condition_name.clone(), json!({"Fn::Equals": [{"Ref": parameter_name}, "yes"]}));
        flag_names.push(condition_name);
    }
    let no_value_tree = adversarial_no_value_tree(&flag_names);
    let template = json!({
        "Parameters": parameters,
        "Conditions": conditions,
        "Resources": {
            "Example": {
                "Type": "AWS::Test::RequiredXorBudget",
                "Properties": {
                    "A": {"Fn::If": ["UseLeft", no_value_tree.clone(), "present-a"]},
                    "B": {"Fn::If": ["UseLeft", "present-b", no_value_tree]}
                }
            }
        }
    })
    .to_string();
    let validator = validator(vec![(
        "AWS::Test::RequiredXorBudget",
        json!({
            "properties": {"A": {"type": "string"}, "B": {"type": "string"}},
            "requiredXor": ["A", "B"],
            "additionalProperties": false
        }),
    )]);
    (validator, template)
}

#[test]
fn required_xor_fallback_bounds_adversarial_branch_expansion() {
    const CONDITION_COUNT: usize = 12;
    const MAX_ACCOUNTED_SCENARIOS: u64 = 2_000;

    let (validator, template) = adversarial_required_xor_fixture(CONDITION_COUNT);
    let semantic_model = model(&template);
    let diagnostics = validator.validate(&semantic_model, Some("us-east-1")).diagnostics;

    assert!(
        diagnostics.iter().all(|diagnostic| diagnostic.rule_id != "F3014"),
        "exactly one property is present in every reachable world: {diagnostics:#?}"
    );
    assert!(
        semantic_model.exhausted_budget_kinds().contains(&template_model::BudgetKind::SchemaScenarioAssignments),
        "bounded analysis must record its curtailment on the model: {diagnostics:#?}"
    );
    assert!(
        semantic_model.scenario_combinations_used() <= MAX_ACCOUNTED_SCENARIOS,
        "fallback scenario work must stay locally bounded, used {}",
        semantic_model.scenario_combinations_used()
    );
}

// ─── Budget fallback: targeted proof/witness search ────────────────────────

/// With 9+ conditions where all members resolve to AWS::NoValue in every world
/// (each member is conditional but maps to NoValue regardless), the budget
/// fallback must still emit F3058.
#[test]
fn required_or_budget_fallback_fires_when_all_members_absent() {
    // Use 9 conditions — each requiredOr member is conditional on its own
    // condition but always resolves to AWS::NoValue (both branches produce null).
    let condition_count = 9;
    let mut properties = serde_json::Map::new();
    let mut required_or: Vec<String> = Vec::new();
    let mut template = String::from("Parameters:\n");
    for index in 0..condition_count {
        let property_name = format!("Member{index:02}");
        properties.insert(property_name.clone(), json!({"type": "string"}));
        required_or.push(property_name);
        template.push_str(&format!(
            "  Param{index:02}:\n    Type: String\n    AllowedValues: [yes, no]\n    Default: no\n"
        ));
    }
    template.push_str("Conditions:\n");
    for index in 0..condition_count {
        template.push_str(&format!("  Cond{index:02}: !Equals [!Ref Param{index:02}, yes]\n"));
    }
    // Each member is present as a key but resolves to AWS::NoValue in EVERY
    // scenario — so it's provably absent in all worlds.
    template.push_str("Resources:\n  Res:\n    Type: AWS::Test::BudgetFallbackOr\n    Properties:\n");
    for index in 0..condition_count {
        template
            .push_str(&format!("      Member{index:02}: !If [Cond{index:02}, !Ref AWS::NoValue, !Ref AWS::NoValue]\n"));
    }
    let sv = validator(vec![(
        "AWS::Test::BudgetFallbackOr",
        json!({
            "properties": properties,
            "requiredOr": required_or,
            "additionalProperties": false
        }),
    )]);
    let diagnostics = validate(&sv, &template);
    let findings: Vec<_> = diagnostics.iter().filter(|d| d.rule_id == "F3058").collect();
    assert_eq!(findings.len(), 1, "budget fallback must detect provably absent requiredOr members: {diagnostics:#?}");
}

/// With 9+ conditions but one requiredOr member unconditionally present, the
/// budget fallback must NOT emit F3058.
#[test]
fn required_or_budget_fallback_no_false_positive_when_member_present() {
    // 9 requiredOr members with independent conditions. One member (Member00)
    // is unconditionally present (both branches non-null). The rest resolve to
    // NoValue. Since one member is possibly present, requiredOr is satisfied.
    let condition_count = 9;
    let mut properties = serde_json::Map::new();
    let mut required_or: Vec<String> = Vec::new();
    let mut template = String::from("Parameters:\n");
    for index in 0..condition_count {
        let property_name = format!("Member{index:02}");
        properties.insert(property_name.clone(), json!({"type": "string"}));
        required_or.push(property_name);
        template.push_str(&format!(
            "  Param{index:02}:\n    Type: String\n    AllowedValues: [yes, no]\n    Default: no\n"
        ));
    }
    template.push_str("Conditions:\n");
    for index in 0..condition_count {
        template.push_str(&format!("  Cond{index:02}: !Equals [!Ref Param{index:02}, yes]\n"));
    }
    // Member00 is unconditionally present (both branches produce a real value).
    // All other members always resolve to NoValue.
    template.push_str("Resources:\n  Res:\n    Type: AWS::Test::BudgetFallbackOrValid\n    Properties:\n");
    template.push_str("      Member00: !If [Cond00, val-a, val-b]\n");
    for index in 1..condition_count {
        template
            .push_str(&format!("      Member{index:02}: !If [Cond{index:02}, !Ref AWS::NoValue, !Ref AWS::NoValue]\n"));
    }
    let sv = validator(vec![(
        "AWS::Test::BudgetFallbackOrValid",
        json!({
            "properties": properties,
            "requiredOr": required_or,
            "additionalProperties": false
        }),
    )]);
    let diagnostics = validate(&sv, &template);
    assert!(
        diagnostics.iter().all(|d| d.rule_id != "F3058"),
        "budget fallback must not fire when a member is unconditionally present: {diagnostics:#?}"
    );
}

/// requiredXor budget fallback: all 9 members resolve to AWS::NoValue in every
/// scenario → zero-present is provable → F3014 fires.
#[test]
fn required_xor_budget_fallback_fires_when_all_members_absent() {
    let condition_count = 9;
    let mut properties = serde_json::Map::new();
    let mut required_xor: Vec<String> = Vec::new();
    let mut template = String::from("Parameters:\n");
    for index in 0..condition_count {
        let property_name = format!("Choice{index:02}");
        properties.insert(property_name.clone(), json!({"type": "string"}));
        required_xor.push(property_name);
        template.push_str(&format!(
            "  Param{index:02}:\n    Type: String\n    AllowedValues: [yes, no]\n    Default: no\n"
        ));
    }
    template.push_str("Conditions:\n");
    for index in 0..condition_count {
        template.push_str(&format!("  Cond{index:02}: !Equals [!Ref Param{index:02}, yes]\n"));
    }
    // Each member always resolves to NoValue regardless of condition state.
    template.push_str("Resources:\n  Res:\n    Type: AWS::Test::BudgetXorZero\n    Properties:\n");
    for index in 0..condition_count {
        template
            .push_str(&format!("      Choice{index:02}: !If [Cond{index:02}, !Ref AWS::NoValue, !Ref AWS::NoValue]\n"));
    }
    let sv = validator(vec![(
        "AWS::Test::BudgetXorZero",
        json!({
            "properties": properties,
            "requiredXor": required_xor,
            "additionalProperties": false
        }),
    )]);
    let diagnostics = validate(&sv, &template);
    let findings: Vec<_> = diagnostics.iter().filter(|d| d.rule_id == "F3014").collect();
    assert_eq!(findings.len(), 1, "budget fallback must detect zero-present requiredXor violation: {diagnostics:#?}");
}

/// requiredXor budget fallback: 9 members in the group, all unconditionally
/// present (each has a condition but both branches yield a real value).
/// Two or more are universally present → F3014 fires.
#[test]
fn required_xor_budget_fallback_fires_when_multiple_members_unconditional() {
    let condition_count = 9;
    let mut properties = serde_json::Map::new();
    let mut required_xor: Vec<String> = Vec::new();
    let mut template = String::from("Parameters:\n");
    for index in 0..condition_count {
        let property_name = format!("Choice{index:02}");
        properties.insert(property_name.clone(), json!({"type": "string"}));
        required_xor.push(property_name);
        template.push_str(&format!(
            "  Param{index:02}:\n    Type: String\n    AllowedValues: [yes, no]\n    Default: no\n"
        ));
    }
    template.push_str("Conditions:\n");
    for index in 0..condition_count {
        template.push_str(&format!("  Cond{index:02}: !Equals [!Ref Param{index:02}, yes]\n"));
    }
    // All members are unconditionally present (both branches of Fn::If yield
    // a real value, not NoValue) — at least 2 are universally present.
    template.push_str("Resources:\n  Res:\n    Type: AWS::Test::BudgetXorMultiple\n    Properties:\n");
    for index in 0..condition_count {
        template
            .push_str(&format!("      Choice{index:02}: !If [Cond{index:02}, val-a-{index:02}, val-b-{index:02}]\n"));
    }
    let sv = validator(vec![(
        "AWS::Test::BudgetXorMultiple",
        json!({
            "properties": properties,
            "requiredXor": required_xor,
            "additionalProperties": false
        }),
    )]);
    let diagnostics = validate(&sv, &template);
    let findings: Vec<_> = diagnostics.iter().filter(|d| d.rule_id == "F3014").collect();
    assert_eq!(
        findings.len(),
        1,
        "budget fallback must detect multiple unconditionally-present requiredXor members: {diagnostics:#?}"
    );
}

/// requiredXor budget fallback: 9 members, but only one is unconditionally
/// present (both Fn::If branches yield a real value). All others resolve to
/// NoValue unconditionally. Exactly one universally present → no violation.
#[test]
fn required_xor_budget_fallback_no_false_positive_one_unconditional() {
    let condition_count = 9;
    let mut properties = serde_json::Map::new();
    let mut required_xor: Vec<String> = Vec::new();
    let mut template = String::from("Parameters:\n");
    for index in 0..condition_count {
        let property_name = format!("Choice{index:02}");
        properties.insert(property_name.clone(), json!({"type": "string"}));
        required_xor.push(property_name);
        template.push_str(&format!(
            "  Param{index:02}:\n    Type: String\n    AllowedValues: [yes, no]\n    Default: no\n"
        ));
    }
    template.push_str("Conditions:\n");
    for index in 0..condition_count {
        template.push_str(&format!("  Cond{index:02}: !Equals [!Ref Param{index:02}, yes]\n"));
    }
    // Choice00 is unconditionally present (both branches non-null); all others
    // are unconditionally absent (both branches NoValue). Exactly one member
    // is universally present — no violation.
    template.push_str("Resources:\n  Res:\n    Type: AWS::Test::BudgetXorOk\n    Properties:\n");
    template.push_str("      Choice00: !If [Cond00, val-a, val-b]\n");
    for index in 1..condition_count {
        template
            .push_str(&format!("      Choice{index:02}: !If [Cond{index:02}, !Ref AWS::NoValue, !Ref AWS::NoValue]\n"));
    }
    let sv = validator(vec![(
        "AWS::Test::BudgetXorOk",
        json!({
            "properties": properties,
            "requiredXor": required_xor,
            "additionalProperties": false
        }),
    )]);
    let diagnostics = validate(&sv, &template);
    assert!(
        diagnostics.iter().all(|d| d.rule_id != "F3014"),
        "budget fallback must not fire when exactly one member is unconditionally present: {diagnostics:#?}"
    );
}

/// Nine independently conditional requiredXor members have both an all-false
/// world and worlds where two members are true. Targeted witness search must
/// prove the violation without enumerating all 512 combinations.
#[test]
fn required_xor_budget_fallback_finds_conditional_witnesses() {
    let condition_count = 9;
    let mut properties = serde_json::Map::new();
    let mut required_xor: Vec<String> = Vec::new();
    let mut template = String::from("Parameters:\n");
    for index in 0..condition_count {
        let property_name = format!("Choice{index:02}");
        properties.insert(property_name.clone(), json!({"type": "string"}));
        required_xor.push(property_name);
        template.push_str(&format!(
            "  Param{index:02}:\n    Type: String\n    AllowedValues: [yes, no]\n    Default: no\n"
        ));
    }
    template.push_str("Conditions:\n");
    for index in 0..condition_count {
        template.push_str(&format!("  Cond{index:02}: !Equals [!Ref Param{index:02}, yes]\n"));
    }
    template.push_str("Resources:\n  Res:\n    Type: AWS::Test::BudgetXorConditional\n    Properties:\n");
    for index in 0..condition_count {
        template.push_str(&format!("      Choice{index:02}: !If [Cond{index:02}, present, !Ref AWS::NoValue]\n"));
    }
    let sv = validator(vec![(
        "AWS::Test::BudgetXorConditional",
        json!({
            "properties": properties,
            "requiredXor": required_xor,
            "additionalProperties": false
        }),
    )]);
    let diagnostics = validate(&sv, &template);
    assert!(
        diagnostics.iter().any(|d| d.rule_id == "F3014"),
        "reachable zero- and multiple-present worlds must be diagnosed: {diagnostics:#?}"
    );
}

#[test]
fn required_xor_nine_mutually_exclusive_members_are_valid() {
    const VALUES: [&str; 9] = ["a", "b", "c", "d", "e", "f", "g", "h", "i"];
    let mut properties = serde_json::Map::new();
    let mut required_xor = Vec::new();
    let mut template = String::from(
        "Parameters:\n  Selector:\n    Type: String\n    AllowedValues: [a, b, c, d, e, f, g, h, i]\nConditions:\n",
    );
    for (index, value) in VALUES.iter().enumerate() {
        let property = format!("Choice{index:02}");
        properties.insert(property.clone(), json!({"type": "string"}));
        required_xor.push(property);
        template.push_str(&format!("  Is{value}: !Equals [!Ref Selector, {value}]\n"));
    }
    template.push_str("Resources:\n  Res:\n    Type: AWS::Test::BudgetXorExclusive\n    Properties:\n");
    for (index, value) in VALUES.iter().enumerate() {
        template.push_str(&format!("      Choice{index:02}: !If [Is{value}, present, !Ref AWS::NoValue]\n"));
    }
    let sv = validator(vec![(
        "AWS::Test::BudgetXorExclusive",
        json!({
            "properties": properties,
            "requiredXor": required_xor,
            "additionalProperties": false
        }),
    )]);
    let diagnostics = validate(&sv, &template);
    assert!(
        diagnostics.iter().all(|diagnostic| diagnostic.rule_id != "F3014"),
        "exactly one mutually exclusive member is present in every parameter world: {diagnostics:#?}"
    );
}

// ─── Customer-facing composition diagnostics ───────────────────────────────

fn composition_extra<'a>(diagnostic: &'a diagnostics::Diagnostic, key: &str) -> &'a Value {
    &diagnostic
        .context
        .as_ref()
        .expect("composition diagnostic must carry violation context")
        .extra
        .as_ref()
        .expect("composition diagnostic must carry structured extra context")
        .get(key)
        .unwrap_or_else(|| panic!("composition context must contain '{key}'"))
        .0
}

#[test]
fn any_of_zero_match_is_one_actionable_primary_diagnostic() {
    let sv = validator(vec![(
        "AWS::Test::ActionableAnyOf",
        json!({
            "properties": {
                "A": { "type": "string" },
                "B": { "type": "string" },
                "Other": { "type": "string" }
            },
            "anyOf": [{ "required": ["A"] }, { "required": ["B"] }],
            "additionalProperties": false
        }),
    )]);
    let template = concat!(
        "Resources:\n",
        "  R:\n",
        "    Type: AWS::Test::ActionableAnyOf\n",
        "    Properties:\n",
        "      Other: value\n",
    );
    let semantic_model = model(template);
    let diags = sv.validate(&semantic_model, Some("us-east-1")).diagnostics;
    let findings: Vec<_> = diags.iter().filter(|d| d.rule_id == "F3017").collect();
    assert_eq!(findings.len(), 1, "anyOf must emit one primary finding: {diags:#?}");
    assert!(
        diags.iter().all(|d| d.rule_id != "F3003"),
        "alternative-only requirements must not escape as standalone F3003 findings: {diags:#?}"
    );

    let finding = findings[0];
    assert!(finding.message.contains("0 branches matched"), "zero-match outcome must be explicit: {}", finding.message);
    assert!(
        finding.message.contains("'A'") && finding.message.contains("'B'"),
        "valid alternatives must be named: {}",
        finding.message
    );
    assert!(
        finding.message.contains("branch 1") && finding.message.contains("branch 2"),
        "each failed branch must be explained: {}",
        finding.message
    );
    assert_eq!(finding.property_path.as_deref(), Some("Properties"));
    assert_eq!(finding.location, Some(semantic_model.resource_span("R", "Properties")));
    assert_eq!(composition_extra(finding, "compositionKind"), &json!("anyOf"));
    assert_eq!(composition_extra(finding, "matchOutcome"), &json!("zeroMatches"));
    assert_eq!(composition_extra(finding, "validPropertyCombinations"), &json!([["A"], ["B"]]));

    let branch_failures =
        composition_extra(finding, "branchFailures").as_array().expect("branchFailures must be an array");
    assert_eq!(branch_failures.len(), 2, "each failed branch needs structured reasons: {branch_failures:#?}");
    assert_eq!(branch_failures[0]["branch"], json!(1));
    assert_eq!(branch_failures[1]["branch"], json!(2));
    assert_eq!(branch_failures[0]["reasons"].as_array().map(Vec::len), Some(1));
    assert_eq!(branch_failures[1]["reasons"].as_array().map(Vec::len), Some(1));
}

#[test]
fn one_of_zero_and_multiple_match_outcomes_are_distinct() {
    let sv = validator(vec![(
        "AWS::Test::ActionableOneOf",
        json!({
            "properties": {
                "A": { "type": "string" },
                "B": { "type": "string" },
                "Other": { "type": "string" }
            },
            "oneOf": [{ "required": ["A"] }, { "required": ["B"] }],
            "additionalProperties": false
        }),
    )]);

    let zero =
        validate(&sv, "Resources:\n  R:\n    Type: AWS::Test::ActionableOneOf\n    Properties:\n      Other: value\n");
    let zero_finding = zero.iter().find(|d| d.rule_id == "F3018").expect("zero-match finding");
    assert!(zero_finding.message.contains("0 branches matched"), "got: {}", zero_finding.message);
    assert_eq!(composition_extra(zero_finding, "matchOutcome"), &json!("zeroMatches"));
    assert!(zero.iter().all(|d| d.rule_id != "F3003"), "got: {zero:#?}");
    assert!(composition_extra(zero_finding, "branchFailures").as_array().is_some_and(|v| v.len() == 2));

    let multiple = validate(
        &sv,
        "Resources:\n  R:\n    Type: AWS::Test::ActionableOneOf\n    Properties:\n      A: one\n      B: two\n",
    );
    let multiple_finding = multiple.iter().find(|d| d.rule_id == "F3018").expect("multiple-match finding");
    assert!(multiple_finding.message.contains("2 branches matched"), "got: {}", multiple_finding.message);
    assert!(multiple_finding.message.contains("more than one"), "got: {}", multiple_finding.message);
    assert_eq!(composition_extra(multiple_finding, "matchOutcome"), &json!("multipleMatches"));
    assert_eq!(composition_extra(multiple_finding, "matchingBranches"), &json!([1, 2]));
    assert!(multiple.iter().all(|d| d.rule_id != "F3003"), "got: {multiple:#?}");
}

#[test]
fn scalar_any_of_reports_deduplicated_branch_reasons_at_property_location() {
    let sv = validator(vec![(
        "AWS::Test::ActionableScalarAnyOf",
        json!({
            "properties": {
                "Mode": {
                    "type": "string",
                    "anyOf": [
                        { "allOf": [{ "enum": ["A"] }, { "enum": ["A"] }] },
                        { "enum": ["B"] }
                    ]
                }
            },
            "additionalProperties": false
        }),
    )]);
    let template = concat!(
        "Resources:\n",
        "  R:\n",
        "    Type: AWS::Test::ActionableScalarAnyOf\n",
        "    Properties:\n",
        "      Mode: C\n",
    );
    let semantic_model = model(template);
    let diags = sv.validate(&semantic_model, Some("us-east-1")).diagnostics;
    let findings: Vec<_> = diags.iter().filter(|d| d.rule_id == "F3017").collect();
    assert_eq!(findings.len(), 1, "scalar anyOf must emit one primary finding: {diags:#?}");
    let finding = findings[0];
    assert!(finding.message.contains("branch 1") && finding.message.contains("branch 2"), "got: {}", finding.message);
    assert!(finding.message.contains("'A'") && finding.message.contains("'B'"), "got: {}", finding.message);
    assert_eq!(finding.property_path.as_deref(), Some("Properties.Mode"));
    assert_eq!(finding.location, Some(semantic_model.resource_span("R", "Properties.Mode")));

    let failures = composition_extra(finding, "branchFailures").as_array().expect("branchFailures array");
    assert_eq!(failures.len(), 2);
    assert_eq!(
        failures[0]["reasons"].as_array().map(Vec::len),
        Some(1),
        "identical reasons from nested constraints must be deduplicated: {failures:#?}"
    );
    assert_eq!(failures[0]["reasons"][0]["propertyPath"], json!("Properties.Mode"));
}

#[test]
fn actionable_any_of_preserves_the_invalid_condition_scenario() {
    let sv = validator(vec![(
        "AWS::Test::ActionableScenario",
        json!({
            "properties": { "Mode": { "type": "string" } },
            "anyOf": [
                { "properties": { "Mode": { "enum": ["A"] } }, "required": ["Mode"] },
                { "properties": { "Mode": { "enum": ["B"] } }, "required": ["Mode"] }
            ],
            "additionalProperties": false
        }),
    )]);
    let template = r#"{
        "Conditions": { "IsA": { "Fn::Equals": [{ "Ref": "AWS::Region" }, "us-east-1"] } },
        "Resources": {
            "R": {
                "Type": "AWS::Test::ActionableScenario",
                "Properties": { "Mode": { "Fn::If": ["IsA", "A", "C"] } }
            }
        }
    }"#;
    let diags = validate(&sv, template);
    let findings: Vec<_> = diags.iter().filter(|d| d.rule_id == "F3017").collect();
    assert_eq!(findings.len(), 1, "only the invalid condition world should fail: {findings:#?}");
    assert_eq!(findings[0].condition_scenario.as_ref().and_then(|c| c.get("IsA")), Some(&false));
    assert_eq!(composition_extra(findings[0], "matchOutcome"), &json!("zeroMatches"));
    assert!(composition_extra(findings[0], "branchFailures").as_array().is_some_and(|v| v.len() == 2));
}

// Nested list constraints need complete, condition-compatible worlds even when
// basic type and scalar checks can validate only the outer value.

#[test]
fn conditional_novalue_list_item_still_enforces_min_items() {
    let sv = validator(vec![(
        "AWS::Test::ConstrainedList",
        json!({
            "properties": {
                "Values": {
                    "type": "array",
                    "items": {"type": "string"},
                    "minItems": 2
                }
            },
            "required": ["Values"],
            "additionalProperties": false
        }),
    )]);
    let template = concat!(
        "Parameters:\n",
        "  Toggle:\n",
        "    Type: String\n",
        "Conditions:\n",
        "  UseBranch: !Equals [!Ref Toggle, 'true']\n",
        "Resources:\n",
        "  R:\n",
        "    Type: AWS::Test::ConstrainedList\n",
        "    Properties:\n",
        "      Values:\n",
        "        - fixed\n",
        "        - !If [UseBranch, !Ref AWS::NoValue, other]\n",
    );

    let diags = validate(&sv, template);
    let findings = diags.iter().filter(|d| d.rule_id == "F3032").count();

    assert_eq!(
        findings,
        1,
        "the reachable one-item world must violate minItems: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn conditional_list_item_still_enforces_unique_items() {
    let sv = validator(vec![(
        "AWS::Test::ConstrainedList",
        json!({
            "properties": {
                "Values": {
                    "type": "array",
                    "items": {"type": "string"},
                    "uniqueItems": true
                }
            },
            "required": ["Values"],
            "additionalProperties": false
        }),
    )]);
    let template = concat!(
        "Parameters:\n",
        "  Toggle:\n",
        "    Type: String\n",
        "Conditions:\n",
        "  UseBranch: !Equals [!Ref Toggle, 'true']\n",
        "Resources:\n",
        "  R:\n",
        "    Type: AWS::Test::ConstrainedList\n",
        "    Properties:\n",
        "      Values:\n",
        "        - fixed\n",
        "        - !If [UseBranch, fixed, other]\n",
    );

    let diags = validate(&sv, template);
    let findings = diags.iter().filter(|d| d.rule_id == "F3037").count();

    assert_eq!(
        findings,
        1,
        "the reachable duplicate world must violate uniqueItems: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

// ─── not_enum direct property enforcement ───────────────────────────────────

#[test]
fn not_enum_rejects_excluded_value_on_direct_property() {
    let sv = validator(vec![(
        "AWS::Test::NotEnum",
        json!({
            "properties": {
                "Username": {
                    "type": "string",
                    "not": { "enum": ["admin", "root", "system"] }
                }
            },
            "additionalProperties": false
        }),
    )]);
    let template = "Resources:\n  R:\n    Type: AWS::Test::NotEnum\n    Properties:\n      Username: admin\n";
    let diags = validate(&sv, template);
    assert!(
        mentions(&diags, "F3030", "must not be one of"),
        "excluded value 'admin' should fire F3030: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn not_enum_defers_overridable_parameter_default() {
    let sv = validator(vec![(
        "AWS::Test::NotEnum",
        json!({
            "properties": {
                "Username": {
                    "type": "string",
                    "not": { "enum": ["admin", "root", "system"] }
                }
            },
            "additionalProperties": false
        }),
    )]);
    let template = "Parameters:\n  UserName:\n    Type: String\n    Default: admin\nResources:\n  R:\n    Type: AWS::Test::NotEnum\n    Properties:\n      Username: !Ref UserName\n";

    let diags = validate(&sv, template);
    assert!(
        !mentions(&diags, "F3030", "must not be one of"),
        "a caller may override the prohibited default before deployment: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn not_enum_rejects_excluded_deterministic_join() {
    let sv = validator(vec![(
        "AWS::Test::NotEnum",
        json!({
            "properties": {
                "Username": {
                    "type": "string",
                    "not": { "enum": ["admin", "root", "system"] }
                }
            },
            "additionalProperties": false
        }),
    )]);
    let template =
        "Resources:\n  R:\n    Type: AWS::Test::NotEnum\n    Properties:\n      Username: !Join ['', [ad, min]]\n";

    let diags = validate(&sv, template);
    let findings: Vec<_> = diags.iter().filter(|diagnostic| diagnostic.rule_id == "F3030").collect();
    assert_eq!(findings.len(), 1, "a literal-only join deterministically produces an excluded value: {diags:?}");
}

#[test]
fn not_enum_checks_only_the_deterministic_conditional_branch() {
    let sv = validator(vec![(
        "AWS::Test::NotEnum",
        json!({
            "properties": {
                "Username": {
                    "type": "string",
                    "not": { "enum": ["admin", "root", "system"] }
                }
            },
            "additionalProperties": false
        }),
    )]);
    let template = r#"
Parameters:
  UserName:
    Type: String
    Default: admin
Conditions:
  UseLiteral: !Equals [!Ref AWS::Region, us-east-1]
Resources:
  R:
    Type: AWS::Test::NotEnum
    Properties:
      Username: !If
        - UseLiteral
        - !Join ['', [ad, min]]
        - !Join ['', [!Ref UserName]]
"#;

    let diags = validate(&sv, template);
    let findings: Vec<_> = diags.iter().filter(|diagnostic| diagnostic.rule_id == "F3030").collect();
    assert_eq!(findings.len(), 1, "only the parameter-independent branch proves a violation: {diags:?}");
    assert_eq!(findings[0].condition_scenario.as_ref().and_then(|scenario| scenario.get("UseLiteral")), Some(&true));
}

#[test]
fn not_enum_accepts_non_excluded_value() {
    let sv = validator(vec![(
        "AWS::Test::NotEnum",
        json!({
            "properties": {
                "Username": {
                    "type": "string",
                    "not": { "enum": ["admin", "root", "system"] }
                }
            },
            "additionalProperties": false
        }),
    )]);
    let template = "Resources:\n  R:\n    Type: AWS::Test::NotEnum\n    Properties:\n      Username: legitimate_user\n";
    let diags = validate(&sv, template);
    assert!(
        !mentions(&diags, "F3030", "must not be one of"),
        "non-excluded value should not fire F3030: {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

// ─── Unicode string length counting ─────────────────────────────────────────

#[test]
fn string_length_counts_unicode_scalar_values_not_bytes() {
    // Each emoji is 4 bytes in UTF-8 but 1 Unicode scalar value.
    // maxLength of 5 should accept 5 emoji characters (5 scalars, 20 bytes).
    let sv = validator(vec![(
        "AWS::Test::UniLength",
        json!({
            "properties": {
                "Label": {
                    "type": "string",
                    "minLength": 1,
                    "maxLength": 5
                }
            },
            "additionalProperties": false
        }),
    )]);

    // 5 emoji characters = 5 Unicode scalar values = 20 UTF-8 bytes
    let template_ok = "Resources:\n  R:\n    Type: AWS::Test::UniLength\n    Properties:\n      Label: '\u{1F600}\u{1F601}\u{1F602}\u{1F603}\u{1F604}'\n";
    let diags_ok = validate(&sv, template_ok);
    assert!(
        !diags_ok.iter().any(|d| d.rule_id == "F3033"),
        "5 emoji (5 scalars) within maxLength=5 must not fire F3033: {:?}",
        diags_ok.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );

    // 6 emoji characters = 6 Unicode scalar values > maxLength 5
    let template_bad = "Resources:\n  R:\n    Type: AWS::Test::UniLength\n    Properties:\n      Label: '\u{1F600}\u{1F601}\u{1F602}\u{1F603}\u{1F604}\u{1F605}'\n";
    let diags_bad = validate(&sv, template_bad);
    assert!(
        diags_bad.iter().any(|d| d.rule_id == "F3033" && d.message.contains("6")),
        "6 emoji (6 scalars) exceeding maxLength=5 must fire F3033 with length 6: {:?}",
        diags_bad.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn string_length_multibyte_characters_below_minimum() {
    // 2-byte characters (e.g. "ñ" is U+00F1, 2 bytes in UTF-8, 1 scalar)
    let sv = validator(vec![(
        "AWS::Test::UniLength",
        json!({
            "properties": {
                "Name": {
                    "type": "string",
                    "minLength": 5
                }
            },
            "additionalProperties": false
        }),
    )]);

    // "a\u{00F1}o" is 3 Unicode scalar values but 4 UTF-8 bytes
    let template = "Resources:\n  R:\n    Type: AWS::Test::UniLength\n    Properties:\n      Name: 'a\u{00F1}o'\n";
    let diags = validate(&sv, template);
    assert!(
        diags.iter().any(|d| d.rule_id == "F3033" && d.message.contains("3")),
        "'a\\u{{00F1}}o' has 3 Unicode scalars, should fire F3033 (below min 5): {:?}",
        diags.iter().map(|d| (&d.rule_id, &d.message)).collect::<Vec<_>>()
    );
}

#[test]
fn one_of_required_properties_are_decided_per_condition_scenario() {
    let resource_type = "AWS::Test::ConditionalRequired";
    let validator = validator(vec![(
        resource_type,
        json!({
            "properties": {
                "A": { "type": "string" },
                "B": { "type": "string" }
            },
            "oneOf": [
                {
                    "type": "object",
                    "properties": { "A": { "type": "string" } },
                    "required": ["A"],
                    "additionalProperties": false
                },
                {
                    "type": "object",
                    "properties": { "B": { "type": "string" } },
                    "required": ["B"],
                    "additionalProperties": false
                }
            ],
            "additionalProperties": false
        }),
    )]);
    let template = concat!(
        "Conditions:\n",
        "  UseA: !Equals [!Ref AWS::Region, us-east-1]\n",
        "Resources:\n",
        "  R:\n",
        "    Type: AWS::Test::ConditionalRequired\n",
        "    Properties:\n",
        "      A: !If [UseA, a, !Ref AWS::NoValue]\n",
        "      B: !If [UseA, !Ref AWS::NoValue, b]\n",
    );

    let diagnostics = validate(&validator, template);

    assert!(
        !mentions(&diagnostics, "F3018", ""),
        "each condition scenario satisfies exactly one required branch: {diagnostics:?}"
    );
}

#[test]
fn referenced_one_of_required_properties_are_decided_per_condition_scenario() {
    let resource_type = "AWS::Test::ReferencedConditionalRequired";
    let validator = validator(vec![(
        resource_type,
        json!({
            "properties": {
                "A": { "type": "string" },
                "B": { "type": "string" }
            },
            "definitions": {
                "RequiresA": { "required": ["A"] },
                "RequiresB": { "required": ["B"] }
            },
            "oneOf": [
                { "$ref": "#/definitions/RequiresA" },
                { "$ref": "#/definitions/RequiresB" }
            ],
            "additionalProperties": false
        }),
    )]);
    let template = concat!(
        "Conditions:\n",
        "  UseA: !Equals [!Ref AWS::Region, us-east-1]\n",
        "Resources:\n",
        "  R:\n",
        "    Type: AWS::Test::ReferencedConditionalRequired\n",
        "    Properties:\n",
        "      A: !If [UseA, a, !Ref AWS::NoValue]\n",
        "      B: !If [UseA, !Ref AWS::NoValue, b]\n",
    );

    let diagnostics = validate(&validator, template);

    assert!(
        !mentions(&diagnostics, "F3018", ""),
        "referenced required branches must preserve condition correlation: {diagnostics:?}"
    );
}

#[test]
fn one_of_required_properties_report_only_the_world_with_no_surviving_property() {
    let resource_type = "AWS::Test::ConditionalRequiredInvalid";
    let validator = validator(vec![(
        resource_type,
        json!({
            "properties": {
                "A": { "type": "string" },
                "B": { "type": "string" }
            },
            "oneOf": [{ "required": ["A"] }, { "required": ["B"] }],
            "additionalProperties": false
        }),
    )]);
    let template = concat!(
        "Conditions:\n",
        "  UseA: !Equals [!Ref AWS::Region, us-east-1]\n",
        "Resources:\n",
        "  R:\n",
        "    Type: AWS::Test::ConditionalRequiredInvalid\n",
        "    Properties:\n",
        "      A: !If [UseA, a, !Ref AWS::NoValue]\n",
        "      B: !Ref AWS::NoValue\n",
    );

    let diagnostics = validate(&validator, template);
    let one_of_diagnostics: Vec<_> = diagnostics.iter().filter(|diagnostic| diagnostic.rule_id == "F3018").collect();

    assert_eq!(one_of_diagnostics.len(), 1, "only one condition world violates oneOf: {diagnostics:?}");
    assert_eq!(
        one_of_diagnostics[0].condition_scenario.as_ref().and_then(|scenario| scenario.get("UseA")),
        Some(&false),
        "the finding must identify the world where both properties are removed"
    );
}

#[test]
fn composition_defers_unresolved_substitution_markers() {
    let validator = validator(vec![(
        "AWS::Test::ConditionalPattern",
        json!({
            "properties": {
                "Name": {
                    "type": "string",
                    "anyOf": [
                        { "pattern": "^foo-[a-z]+$" },
                        { "pattern": "^bar-[a-z]+$" }
                    ]
                }
            },
            "additionalProperties": false
        }),
    )]);
    let template = concat!(
        "Parameters:\n",
        "  Name:\n",
        "    Type: String\n",
        "Resources:\n",
        "  R:\n",
        "    Type: AWS::Test::ConditionalPattern\n",
        "    Properties:\n",
        "      Name: !Sub 'foo-${Name}'\n",
    );

    let diagnostics = validate(&validator, template);

    assert!(
        !mentions(&diagnostics, "F3017", ""),
        "an unresolved intrinsic substitution must remain deferred: {diagnostics:?}"
    );
}

#[test]
fn composition_validates_authored_substitution_markers_as_literals() {
    let validator = validator(vec![(
        "AWS::Test::LiteralPattern",
        json!({
            "properties": {
                "Name": {
                    "type": "string",
                    "anyOf": [
                        { "pattern": "^foo-[a-z]+$" },
                        { "pattern": "^bar-[a-z]+$" }
                    ]
                }
            },
            "additionalProperties": false
        }),
    )]);
    let template = concat!(
        "Resources:\n",
        "  R:\n",
        "    Type: AWS::Test::LiteralPattern\n",
        "    Properties:\n",
        "      Name: 'foo-${Name}'\n",
    );

    let diagnostics = validate(&validator, template);

    assert!(
        mentions(&diagnostics, "F3017", "not valid under any"),
        "authored dollar-brace text is a concrete literal and must be validated: {diagnostics:?}"
    );
}