cloudformation-validate-validation-engine 1.12.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
#[cfg(test)]
use data_source::AdditionalSchemaSource;
use data_source::embedded::{CFN_LINT_VERSION, RESOURCE_SCHEMA_VERSION};
use diagnostics::{
    BudgetExhaustionRecord, DetailLevel, Diagnostic, Entity, PerformanceMetrics, Phase, PhaseMetric,
    RegisteredDiagnostic, RelatedResource, ReportMetadata, ReportStatus, ResourceRef, Summary, ValidationReport,
    ViolationContext, apply_filters, diagnostic_from_parse_defect, phase_metric, resolve_section_span,
};
use rules::{
    FilterConfig, RuleInfo, RuleMetadataEntry, RuleOrigin, Severity, is_fatal_rule, is_valid_custom_rule_id,
    rule_number,
};
use schema_validator::{
    OverlayCatalog, SchemaValidationResult, SchemaValidator, SchemaValidatorConfig, build_overlay_catalog,
};
use serde::{Deserialize, Serialize};
use std::any::Any;
use std::collections::HashMap;
use std::error;
use std::fmt;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Arc;
use template_model::resolved_value::effective_path_from_scenario_source_path;
use template_model::{
    EntityType, JsonValue, ParseConfig, ParseError, ParseResult, PseudoParameterOverrides, SemanticModel, SourceSpan,
    UNKNOWN_SPAN, entity_identity, is_sam_transform_error_message, region_enums, span_to_option,
};
use web_time::Instant;

pub const DIAGNOSTIC_SOURCE_PATH_FIELD: &str = "source_path";

#[derive(Debug)]
pub enum ValidationError {
    Parse(ParseError),
    Engine(String),
}

impl fmt::Display for ValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ValidationError::Parse(e) => write!(f, "{}", e),
            ValidationError::Engine(msg) => write!(f, "{}", msg),
        }
    }
}

impl error::Error for ValidationError {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match self {
            ValidationError::Parse(e) => Some(e),
            ValidationError::Engine(_) => None,
        }
    }
}

impl From<ParseError> for ValidationError {
    fn from(e: ParseError) -> Self {
        ValidationError::Parse(e)
    }
}

impl From<String> for ValidationError {
    fn from(s: String) -> Self {
        ValidationError::Engine(s)
    }
}

impl From<&str> for ValidationError {
    fn from(s: &str) -> Self {
        ValidationError::Engine(s.to_string())
    }
}

/// Selects which validation engine evaluates rules.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "wasm-bindings", derive(tsify::Tsify))]
#[cfg_attr(feature = "uniffi-bindings", derive(uniffi::Enum))]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum EngineType {
    Rego,
    Cel,
    /// Evaluates the built-in rules with one engine and layers caller-supplied
    /// external CEL, Rego, and Guard rules on top. With no external rules it
    /// produces the same diagnostics as the standalone engines, which is why it is
    /// the default selector.
    #[default]
    Composite,
}

impl EngineType {
    pub const fn as_str(&self) -> &'static str {
        match self {
            EngineType::Rego => "Rego",
            EngineType::Cel => "CEL",
            EngineType::Composite => "Composite",
        }
    }

    /// Parses an engine selector, accepting `rego`/`cel`/`composite`
    /// case-insensitively. Returns an error describing the valid options rather
    /// than panicking, so a bad selector becomes a handleable failure instead of
    /// a process abort.
    pub fn parse(raw: &str) -> Result<Self, String> {
        match raw.to_lowercase().as_str() {
            "rego" => Ok(EngineType::Rego),
            "cel" => Ok(EngineType::Cel),
            "composite" => Ok(EngineType::Composite),
            other => Err(format!("Unknown engine type '{other}'; expected 'rego', 'cel', or 'composite'")),
        }
    }
}

impl fmt::Display for EngineType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// A pre-read rule file provided by the caller (custom Rego/CEL or Guard DSL).
///
/// `name` identifies the rule source in error messages and logging. For a
/// file-backed rule this is typically the filesystem path; otherwise it is
/// whatever label the caller provides.
///
/// `content` is the full source text of the rule file.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "wasm-bindings", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm-bindings", tsify(from_wasm_abi))]
#[cfg_attr(feature = "uniffi-bindings", derive(uniffi::Record))]
pub struct ExternalRuleSource {
    pub name: String,
    pub content: String,
}

#[derive(Default, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "wasm-bindings", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm-bindings", tsify(from_wasm_abi))]
#[cfg_attr(feature = "uniffi-bindings", derive(uniffi::Record))]
#[serde(rename_all = "camelCase")]
pub struct EngineConfig {
    /// Engine-native custom rules (Rego or CEL depending on engine).
    #[serde(default)]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub custom_rules: Vec<ExternalRuleSource>,
    /// Guard DSL rules as raw source text, usable regardless of the selected engine.
    #[serde(default)]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub guard_rules: Vec<ExternalRuleSource>,
    /// Optional schema validator configuration. A standalone engine derives its
    /// schema-aware rule metadata from this config. Language APIs also use it to
    /// construct the schema validator bundled with the engine, so both components
    /// observe the same additional schemas.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "wasm-bindings", tsify(optional))]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub schema_validator_config: Option<SchemaValidatorConfig>,
}

impl EngineConfig {
    /// Starts from the default configuration.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds engine-native custom rules (Rego or CEL, depending on the engine).
    pub fn with_custom_rules(mut self, rules: impl IntoIterator<Item = ExternalRuleSource>) -> Self {
        self.custom_rules.extend(rules);
        self
    }

    /// Adds Guard DSL rules, usable regardless of the selected engine.
    pub fn with_guard_rules(mut self, rules: impl IntoIterator<Item = ExternalRuleSource>) -> Self {
        self.guard_rules.extend(rules);
        self
    }

    /// Sets the nested schema validator configuration. When the engine is built
    /// standalone via `new(EngineConfig)`, it derives overlay-aware metadata from
    /// the configured additional schemas.
    pub fn with_schema_validator_config(mut self, config: SchemaValidatorConfig) -> Self {
        self.schema_validator_config = Some(config);
        self
    }

    /// Builds an [`OverlayCatalog`] from the nested schema validator config's
    /// additional schemas. Returns an empty catalog when no schema config is set
    /// or the config carries no overlays.
    ///
    /// This is an internal helper for standalone engine construction.
    #[doc(hidden)]
    pub fn build_overlay_catalog(&self) -> Result<OverlayCatalog, ValidationError> {
        let additional_schemas = match &self.schema_validator_config {
            Some(cfg) if !cfg.additional_schemas.is_empty() => &cfg.additional_schemas,
            _ => return Ok(OverlayCatalog::default()),
        };
        let overlays: Vec<(String, serde_json::Value)> = additional_schemas
            .iter()
            .map(|s| s.resolve().map_err(|e| ValidationError::Engine(e.0)))
            .collect::<Result<Vec<_>, _>>()?;
        build_overlay_catalog(overlays)
            .map_err(|e| ValidationError::Engine(format!("Failed to apply an additional schema: {e}")))
    }
}

/// Configuration for a composite engine that evaluates the built-in rules with
/// one engine and caller-supplied external rules with another.
///
/// The built-in rules are always evaluated, so this config only carries the
/// external rules layered on top plus the shared schema configuration. Custom
/// rules can be supplied in all three formats: Rego rules are evaluated by the
/// external engine, while CEL custom rules and Guard rules are evaluated by the
/// engine that owns the built-ins. It has no field for engine-native built-in
/// custom rules because the composite fixes which engine owns the built-ins.
#[derive(Default, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "wasm-bindings", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm-bindings", tsify(from_wasm_abi))]
#[cfg_attr(feature = "uniffi-bindings", derive(uniffi::Record))]
#[serde(rename_all = "camelCase")]
pub struct CompositeEngineConfig {
    /// Custom Rego rules layered on top of the built-in rules.
    #[serde(default)]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub rego_rules: Vec<ExternalRuleSource>,
    /// Custom CEL rules layered on top of the built-in rules. They are evaluated
    /// by the same engine that owns the built-ins, since CEL custom rules are a
    /// CEL-engine feature.
    #[serde(default)]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub cel_rules: Vec<ExternalRuleSource>,
    /// Guard DSL rules as raw source text, layered on top of the built-in rules.
    #[serde(default)]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub guard_rules: Vec<ExternalRuleSource>,
    /// Optional schema validator configuration. A standalone engine derives its
    /// schema-aware rule metadata from this config. Language APIs also use it to
    /// construct the schema validator bundled with the engine, so both components
    /// observe the same additional schemas.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "wasm-bindings", tsify(optional))]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub schema_validator_config: Option<SchemaValidatorConfig>,
}

impl CompositeEngineConfig {
    /// Starts from the default configuration.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds custom Rego rules layered on top of the built-in rules.
    pub fn with_rego_rules(mut self, rules: impl IntoIterator<Item = ExternalRuleSource>) -> Self {
        self.rego_rules.extend(rules);
        self
    }

    /// Adds custom CEL rules layered on top of the built-in rules. They are
    /// evaluated by the engine that owns the built-ins.
    pub fn with_cel_rules(mut self, rules: impl IntoIterator<Item = ExternalRuleSource>) -> Self {
        self.cel_rules.extend(rules);
        self
    }

    /// Adds Guard DSL rules layered on top of the built-in rules.
    pub fn with_guard_rules(mut self, rules: impl IntoIterator<Item = ExternalRuleSource>) -> Self {
        self.guard_rules.extend(rules);
        self
    }

    /// Sets the nested schema validator configuration so both the built-in and
    /// external evaluation observe the same additional schemas.
    pub fn with_schema_validator_config(mut self, config: SchemaValidatorConfig) -> Self {
        self.schema_validator_config = Some(config);
        self
    }
}

#[derive(Clone, Default)]
pub struct ValidateConfig {
    pub filters: FilterConfig,
    pub detail_level: DetailLevel,
    pub severity_level: Severity,
    pub parameter_overrides: HashMap<String, String>,
    pub pseudo_parameter_overrides: PseudoParameterOverrides,
    /// When true, Warn-severity diagnostics are upgraded to Error.
    pub strict: bool,
    /// When true, all built-in rules
    /// Only user-provided custom rules and guard rules are evaluated.
    pub disable_builtin_rules: bool,
}

pub trait ValidationEngine {
    fn engine_name(&self) -> &str;

    fn evaluate_rules(
        &self,
        model: &Arc<SemanticModel>,
        config: &ValidateConfig,
    ) -> Result<Vec<Diagnostic>, ValidationError>;

    fn list_rules(&self) -> Vec<RuleInfo>;

    /// Built-in rule metadata from the rules registry only.
    fn rule_metadata(&self) -> &HashMap<String, RuleMetadataEntry>;

    /// Metadata for rules not in the registry: custom user rules and Guard rules.
    fn external_rule_metadata(&self) -> HashMap<String, RuleMetadataEntry>;

    fn init_metric(&self) -> &PhaseMetric;
}

pub(crate) fn validate(
    engine: &dyn ValidationEngine,
    schema_validator: &SchemaValidator,
    result: ParseResult,
    config: ValidateConfig,
    file_path: String,
) -> Result<ValidationReport, ValidationError> {
    let model = Arc::new(result.model);
    let model_build = PhaseMetric { duration_ms: result.model_build_ms };
    log::info!(
        "Validating: {} resources, {} types (engine={})",
        model.resources.len(),
        model.resources_by_type.len(),
        engine.engine_name()
    );

    let schema_result = if config.disable_builtin_rules {
        SchemaValidationResult { diagnostics: Vec::new(), metric: phase_metric(Instant::now()) }
    } else {
        schema_validator.validate(&model, config.pseudo_parameter_overrides.region.as_deref())
    };
    let mut all_diagnostics = schema_result.diagnostics;

    if !config.disable_builtin_rules {
        let invalid = config.pseudo_parameter_overrides.invalid_overrides();
        if !invalid.is_empty() {
            let message = format!("Invalid pseudo-parameter override(s): {}", invalid.join("; "));
            all_diagnostics.push(RegisteredDiagnostic::new("W9012", message).build());
        }
    }

    let t_eval = Instant::now();
    let engine_diags = engine.evaluate_rules(&model, &config)?;
    all_diagnostics.extend(engine_diags);
    let eval_metric = phase_metric(t_eval);

    let t_post = Instant::now();
    if !config.disable_builtin_rules {
        all_diagnostics.extend(crate::step_functions::validate_all_state_machines(&model));
        all_diagnostics.extend(model.diagnostics.iter().map(diagnostic_from_parse_defect));

        // The satisfiability budget is consumed almost entirely by the rule
        // evaluation that just ran, so this is the earliest point the exhausted
        // queries are observable. Budget exhaustions are recorded into the
        // model-level tracker by the condition model as they occur.

        if config.pseudo_parameter_overrides.region.is_none() && region_enums::template_has_region_scoped_value(&model)
        {
            all_diagnostics.push(
                RegisteredDiagnostic::new(
                    "I9003",
                    "No region supplied; region-scoped instance/node types were validated against all regions. \
                     A value reported valid here may still be unavailable in your target region - pass a region to \
                     validate against it specifically.",
                )
                .build(),
            );
        }
    }

    gate_sam_transform_errors(&mut all_diagnostics);
    gate_cdk_suppressed_rules(&mut all_diagnostics, &model);

    backfill_locations(&mut all_diagnostics, &model);
    backfill_entities(&mut all_diagnostics, &model);

    let registry_metadata = engine.rule_metadata();
    let external_metadata = config.detail_level.needs_enrichment().then(|| engine.external_rule_metadata());
    if let Some(external_metadata) = external_metadata.as_ref() {
        enrich_diagnostics(&mut all_diagnostics, &model, registry_metadata, external_metadata, &config.detail_level);
    }

    if config.detail_level.needs_context() {
        schema_validator.enrich_context(&mut all_diagnostics, &model);
        for d in all_diagnostics.iter_mut() {
            if d.context.is_none() && d.phase != Some(Phase::Schema) {
                d.context = build_context(
                    &d.rule_id,
                    d.resource_logical_id(),
                    d.property_path.as_deref().unwrap_or(""),
                    &model,
                );
            }
        }
    }

    // Filtering may suppress the visible warning, so report metadata is captured
    // independently before finalization.
    let exhausted_kinds = model.exhausted_budget_kinds();
    let budget_exhaustion_records: Vec<BudgetExhaustionRecord> = exhausted_kinds
        .iter()
        .map(|kind| BudgetExhaustionRecord {
            kind: kind.as_str().to_string(),
            description: kind.description().to_string(),
            limit: kind.limit(),
            analysis_incomplete: kind.analysis_incomplete(),
        })
        .collect();
    let analysis_incomplete = model.budget_analysis_incomplete();

    if !config.disable_builtin_rules && !exhausted_kinds.is_empty() {
        let message = if analysis_incomplete {
            "Deterministic validation budgets were exhausted; analysis may be incomplete and some findings may be omitted"
        } else {
            "Deterministic validation budgets were exhausted; analysis completed but some detail was omitted"
        };
        let mut budget_warning = RegisteredDiagnostic::new("W9052", message).build();
        if config.detail_level.needs_context() {
            let budget_context = budget_exhaustion_records
                .iter()
                .map(|record| {
                    serde_json::json!({
                        "kind": record.kind.as_str(),
                        "description": record.description.as_str(),
                        "limit": record.limit,
                        "analysisIncomplete": record.analysis_incomplete,
                    })
                })
                .collect();
            let mut context_extra = HashMap::new();
            context_extra.insert("budgetExhaustions".to_string(), serde_json::Value::Array(budget_context).into());
            budget_warning.context = Some(ViolationContext {
                actual_value: None,
                expected_constraint: None,
                property: None,
                lifecycle: None,
                resolution_source: None,
                extra: Some(context_extra),
            });
        }

        let warning_index = all_diagnostics.len();
        all_diagnostics.push(budget_warning);
        let warning_slice = &mut all_diagnostics[warning_index..];
        backfill_locations(warning_slice, &model);
        backfill_entities(warning_slice, &model);
        if let Some(external_metadata) = external_metadata.as_ref() {
            enrich_diagnostics(warning_slice, &model, registry_metadata, external_metadata, &config.detail_level);
        }
    }

    let (total_before, suppressed) = finalize_diagnostics(&mut all_diagnostics, &config);

    if suppressed > 0 {
        log::info!("Filtered {} -> {} diagnostics ({} suppressed)", total_before, all_diagnostics.len(), suppressed);
    }

    let excluded_cats = config.filters.excluded_categories();
    let active_rule_count = registry_metadata
        .iter()
        .filter(|(_, entry)| !entry.category.as_deref().is_some_and(|c| excluded_cats.contains(c)))
        .count() as u32;

    let mut report = build_report(
        all_diagnostics,
        &model,
        suppressed,
        Some(active_rule_count),
        config.strict,
        config.severity_level,
        file_path,
    );
    if analysis_incomplete {
        report.status = ReportStatus::AnalysisIncomplete;
    }
    report.metadata.budget_exhaustions = (!budget_exhaustion_records.is_empty()).then_some(budget_exhaustion_records);
    let finalize_metric = phase_metric(t_post);

    report.performance.schema_init = schema_validator.init_metric().clone();
    report.performance.engine_init = engine.init_metric().clone();
    report.performance.model_build = model_build;
    report.performance.schema_validate = schema_result.metric;
    report.performance.rule_evaluation = eval_metric;
    report.performance.diagnostic_finalize = finalize_metric;

    Ok(report)
}

struct DataSourceVersions {
    cfn_lint_version: &'static str,
    resource_schema_version: &'static str,
}

static DATA_SOURCE_VERSIONS: DataSourceVersions =
    DataSourceVersions { cfn_lint_version: CFN_LINT_VERSION, resource_schema_version: RESOURCE_SCHEMA_VERSION };

#[cfg(any(test, feature = "test"))]
pub fn validate_bytes(
    engine: &dyn ValidationEngine,
    schema_validator: &SchemaValidator,
    bytes: &[u8],
    config: ValidateConfig,
) -> Result<ValidationReport, ValidationError> {
    validate_bytes_with_path(engine, schema_validator, bytes, config, String::new())
}

pub fn validate_bytes_with_path(
    engine: &dyn ValidationEngine,
    schema_validator: &SchemaValidator,
    bytes: &[u8],
    config: ValidateConfig,
    file_path: String,
) -> Result<ValidationReport, ValidationError> {
    let total_start = Instant::now();
    let result = match SemanticModel::parse(
        bytes,
        ParseConfig {
            parameters: config.parameter_overrides.clone(),
            pseudo_parameters: config.pseudo_parameter_overrides.clone(),
        },
    ) {
        Ok(r) => r,
        Err(e) => {
            let span = match (e.line, e.column) {
                (Some(l), Some(c)) => SourceSpan { start_line: l, start_column: c, end_line: l, end_column: c },
                _ => UNKNOWN_SPAN,
            };
            let diag = RegisteredDiagnostic::new("F1101", e.message).location(span).phase(Phase::Parse).build();
            let diags = vec![diag];
            let report = ValidationReport {
                file_path,
                status: ReportStatus::Error,
                version: env!("CARGO_PKG_VERSION").to_string(),
                diagnostics: diags,
                metadata: ReportMetadata {
                    rules_evaluated: 0,
                    cfn_lint_version: DATA_SOURCE_VERSIONS.cfn_lint_version.to_owned(),
                    resource_schema_version: DATA_SOURCE_VERSIONS.resource_schema_version.to_owned(),
                    resources_scanned: 0,
                    counts: Summary { fatal: 1, errors: 0, warnings: 0, informational: 0, debug: 0 },
                    suppressed: 0,
                    strict: config.strict,
                    severity_level: config.severity_level,
                    budget_exhaustions: None,
                },
                performance: PerformanceMetrics {
                    schema_init: PhaseMetric { duration_ms: 0.0 },
                    engine_init: PhaseMetric { duration_ms: 0.0 },
                    model_build: PhaseMetric { duration_ms: 0.0 },
                    schema_validate: PhaseMetric { duration_ms: 0.0 },
                    rule_evaluation: PhaseMetric { duration_ms: 0.0 },
                    diagnostic_finalize: PhaseMetric { duration_ms: 0.0 },
                    validate_total: phase_metric(total_start),
                },
            };
            return Ok(report);
        }
    };
    let mut report = validate(engine, schema_validator, result, config, file_path)?;
    report.performance.validate_total = phase_metric(total_start);
    Ok(report)
}

/// Runs `operation`, converting any unwinding panic into an error produced by
/// `on_panic` instead of letting it escape into the caller. Every embedding
/// boundary routes through this guard, so an internal invariant violation on
/// adversarial input becomes a structured, catchable error rather than crashing
/// or trapping the host.
///
/// `on_panic` receives the panic's message and maps it to the caller's own error
/// type (for example a [`ValidationError`] or a binding-specific error type),
/// keeping the guard reusable across every binding without coupling it to one
/// error type.
///
/// The guard only works under the `unwind` panic strategy - [`catch_unwind`]
/// intercepts unwinding panics, not aborts. The workspace pins `panic = "unwind"`
/// in both the dev and release profiles (`src/Cargo.toml`), so on native targets
/// a panic is caught here before it can unwind across an FFI boundary - which
/// would be undefined behavior.
///
/// On `wasm32-unknown-unknown` the standard library is compiled with
/// `panic = "abort"`: a panic traps the instance and `catch_unwind` cannot
/// intercept it, so the only recovery is to recreate the instance. There this
/// guard is a no-op that becomes effective only if the wasm build opts into the
/// unwind strategy. Wrapping the wasm path is therefore harmless and
/// forward-compatible rather than load-bearing today.
pub fn catch_panics<T, E>(
    operation: impl FnOnce() -> Result<T, E>,
    on_panic: impl FnOnce(String) -> E,
) -> Result<T, E> {
    match catch_unwind(AssertUnwindSafe(operation)) {
        Ok(result) => result,
        Err(payload) => Err(on_panic(panic_message(payload.as_ref()))),
    }
}

/// Convenience wrapper over [`catch_panics`] for the core validation flow: a
/// panic becomes a structured [`ValidationError::Engine`] carrying the message.
pub fn validate_catching_panics<F>(validate: F) -> Result<ValidationReport, ValidationError>
where
    F: FnOnce() -> Result<ValidationReport, ValidationError>,
{
    catch_panics(validate, |message| ValidationError::Engine(format!("Internal validation error: {message}")))
}

pub fn semantic_model_to_input_json(model: &SemanticModel) -> Result<serde_json::Value, ValidationError> {
    serde_json::to_value(model.to_diagnostic_json()).map_err(|e| {
        ValidationError::Engine(format!("Failed to serialize the semantic model for rule evaluation: {e}"))
    })
}

fn panic_message(payload: &(dyn Any + Send)) -> String {
    if let Some(message) = payload.downcast_ref::<&str>() {
        (*message).to_string()
    } else if let Some(message) = payload.downcast_ref::<String>() {
        message.clone()
    } else {
        "Panic payload was not a string".to_string()
    }
}

fn parse_span_coordinate(
    diagnostic: &serde_json::Value,
    field_name: &str,
    rule_id: &str,
) -> Result<Option<u32>, String> {
    let Some(value) = diagnostic.get(field_name) else {
        return Ok(None);
    };
    if value.is_null() {
        return Ok(None);
    }
    let coordinate = value
        .as_u64()
        .ok_or_else(|| format!("Diagnostic '{}' field '{}' must be a non-negative integer", rule_id, field_name))?;
    u32::try_from(coordinate)
        .map(Some)
        .map_err(|_| format!("Diagnostic '{}' field '{}' exceeds the supported coordinate range", rule_id, field_name))
}

fn resolve_model_diagnostic_span(
    rule_id: &str,
    model: &SemanticModel,
    resource_id: Option<&str>,
    property_path: Option<&str>,
    source_path: Option<&str>,
) -> Result<SourceSpan, String> {
    if let Some(source_path) = source_path {
        let resource_id = resource_id.ok_or_else(|| {
            format!("Diagnostic '{}' provides '{}' without a resource_id", rule_id, DIAGNOSTIC_SOURCE_PATH_FIELD)
        })?;
        let property_path = property_path.ok_or_else(|| {
            format!(
                "Diagnostic '{}' on resource '{}' provides '{}' without a resource_path",
                rule_id, resource_id, DIAGNOSTIC_SOURCE_PATH_FIELD
            )
        })?;
        let effective_source_path = effective_path_from_scenario_source_path(source_path)
            .ok_or_else(|| format!("Diagnostic '{}' has malformed scenario source path '{}'", rule_id, source_path))?;
        if effective_source_path != property_path {
            return Err(format!(
                "Diagnostic '{}' source path '{}' resolves to '{}' instead of resource path '{}'",
                rule_id, source_path, effective_source_path, property_path
            ));
        }
    }

    let location_path = source_path.or(property_path).unwrap_or("");
    Ok(if let Some(resource_id) = resource_id {
        model.resource_span(resource_id, location_path)
    } else {
        model.diagnostic_span(None, location_path).unwrap_or_else(|| resolve_section_span(rule_id, model))
    })
}

fn validate_explicit_diagnostic_span(
    diagnostic: &serde_json::Value,
    rule_id: &str,
    model_span: SourceSpan,
) -> Result<(), String> {
    let start_line = parse_span_coordinate(diagnostic, "start_line", rule_id)?;
    let start_column = parse_span_coordinate(diagnostic, "start_column", rule_id)?;
    let end_line = parse_span_coordinate(diagnostic, "end_line", rule_id)?;
    let end_column = parse_span_coordinate(diagnostic, "end_column", rule_id)?;

    if start_line.is_none() && start_column.is_none() && end_line.is_none() && end_column.is_none() {
        return Ok(());
    }
    let (Some(start_line), Some(start_column)) = (start_line, start_column) else {
        return Err(format!("Diagnostic '{}' explicit span must provide both start_line and start_column", rule_id));
    };
    let explicit_end = match (end_line, end_column) {
        (None, None) => None,
        (Some(line), Some(column)) => Some((line, column)),
        _ => {
            return Err(format!("Diagnostic '{}' explicit span must provide both end_line and end_column", rule_id));
        }
    };
    if model_span == UNKNOWN_SPAN {
        return Err(format!(
            "Diagnostic '{}' explicit span cannot be verified because its resource path has no model-derived location",
            rule_id
        ));
    }

    let start_matches = start_line == model_span.start_line && start_column == model_span.start_column;
    let end_matches =
        explicit_end.is_none_or(|(line, column)| line == model_span.end_line && column == model_span.end_column);
    if !start_matches || !end_matches {
        let (explicit_end_line, explicit_end_column) = explicit_end.unwrap_or((start_line, start_column));
        return Err(format!(
            "Diagnostic '{}' explicit span {}:{}-{}:{} does not match model-derived span {}:{}-{}:{}",
            rule_id,
            start_line,
            start_column,
            explicit_end_line,
            explicit_end_column,
            model_span.start_line,
            model_span.start_column,
            model_span.end_line,
            model_span.end_column
        ));
    }
    Ok(())
}

pub(crate) fn parse_diagnostic(
    val: &serde_json::Value,
    model: &SemanticModel,
    source_override: Option<&RuleOrigin>,
) -> Result<Diagnostic, String> {
    let rule_id =
        val.get("rule_id").and_then(|v| v.as_str()).ok_or("Diagnostic missing required field 'rule_id'")?.to_string();
    if rule_id.trim().is_empty() {
        return Err("Diagnostic has an empty 'rule_id'".to_string());
    }
    let message = val
        .get("message")
        .and_then(|v| v.as_str())
        .ok_or_else(|| format!("Diagnostic '{}' missing required field 'message'", rule_id))?
        .to_string();
    if message.trim().is_empty() {
        return Err(format!("Diagnostic '{}' has an empty 'message'", rule_id));
    }
    let resource_id = val.get("resource_id").and_then(|v| v.as_str()).filter(|s| !s.is_empty()).map(|s| s.to_string());
    let entity = resource_id
        .as_ref()
        .and_then(|rid| Entity::resource(rid, model.resources.get(rid.as_str()).map(|r| r.resource_type.clone())));
    let property_path =
        val.get("resource_path").and_then(|v| v.as_str()).filter(|s| !s.is_empty()).map(|s| s.to_string());

    let source_path = match val.get(DIAGNOSTIC_SOURCE_PATH_FIELD) {
        None | Some(serde_json::Value::Null) => None,
        Some(serde_json::Value::String(path)) if !path.is_empty() => Some(path.as_str()),
        Some(_) => {
            return Err(format!(
                "Diagnostic '{}' field '{}' must be a non-empty string",
                rule_id, DIAGNOSTIC_SOURCE_PATH_FIELD
            ));
        }
    };
    let span =
        resolve_model_diagnostic_span(&rule_id, model, resource_id.as_deref(), property_path.as_deref(), source_path)?;
    validate_explicit_diagnostic_span(val, &rule_id, span)?;

    let is_custom_or_guard = source_override.is_some_and(|o| matches!(o, RuleOrigin::Custom | RuleOrigin::Guard));

    let suggested_fix = val.get("suggested_fix").and_then(|v| v.as_str()).map(|s| s.to_string());
    let documentation_url = val.get("documentation_url").and_then(|v| v.as_str()).map(|s| s.to_string());
    let related_resources = val.get("related_locations").and_then(|v| v.as_array()).map(|arr| {
        arr.iter()
            .filter_map(|r| {
                let rel_rid = r.get("resource_id").and_then(|v| v.as_str()).map(|s| s.to_string());
                let rel_resource = rel_rid.as_ref().map(|rid| ResourceRef {
                    id: Some(rid.clone()),
                    resource_type: model.resources.get(rid.as_str()).map(|res| res.resource_type.clone()),
                });
                Some(RelatedResource {
                    resource: rel_resource,
                    location: Some(SourceSpan {
                        start_line: r.get("start_line")?.as_u64()? as u32,
                        start_column: r.get("start_column")?.as_u64()? as u32,
                        end_line: r.get("end_line")?.as_u64()? as u32,
                        end_column: r.get("end_column")?.as_u64()? as u32,
                    }),
                    message: r.get("message")?.as_str()?.to_string(),
                })
            })
            .collect()
    });
    let condition_scenario = val
        .get("condition_scenario")
        .and_then(|v| v.as_object())
        .map(|m| m.iter().filter_map(|(k, v)| v.as_bool().map(|b| (k.clone(), b))).collect());

    if is_custom_or_guard {
        if !is_valid_custom_rule_id(&rule_id) {
            return Err(format!(
                "Custom/Guard diagnostic '{}' has an invalid 'rule_id': only letters, digits, and the separators \
                 '_', '.', '-' are allowed",
                rule_id
            ));
        }
        let severity_str = val
            .get("severity")
            .and_then(|v| v.as_str())
            .ok_or_else(|| format!("Custom/Guard diagnostic '{}' missing required field 'severity'", rule_id))?;
        // The declared severity is authoritative. A custom/Guard rule ID is arbitrary,
        // so the built-in `F`-prefix→Fatal heuristic must NOT apply here
        let severity = severity_str.parse::<Severity>()?;
        let category = val.get("category").and_then(|v| v.as_str()).map(|c| c.to_string());
        let source = *source_override.expect("custom/guard branch is only reached with a source override");
        let rule_description = (source == RuleOrigin::Custom).then(|| message.clone());
        return Ok(Diagnostic {
            rule_id,
            severity,
            message,
            entity,
            property_path,
            suggested_fix,
            documentation_url,
            category,
            location: span_to_option(span),
            related_resources,
            condition_scenario,
            rule_description,
            phase: None,
            context: None,
            source,
        });
    }

    // The registry is the single source of truth for built-in severity,
    // category, origin, and description. Any `severity` field present in the
    // engine output is intentionally ignored, so it is not required here.
    let mut diagnostic = RegisteredDiagnostic::new(rule_id, message)
        .location(span)
        .suggested_fix(suggested_fix)
        .condition_scenario(condition_scenario)
        .related_resources(related_resources)
        .build();
    diagnostic.entity = entity;
    diagnostic.property_path = property_path;
    diagnostic.documentation_url = documentation_url;
    Ok(diagnostic)
}

/// Parses a JSON array of rule outputs, appending a [`Diagnostic`] for each
/// element. The array iteration and per-element parsing live in
/// [`extract_diagnostics_from_value`]; this entry point only turns the string
/// into a value first.
pub fn extract_diagnostics(
    json_str: &str,
    model: &SemanticModel,
    out: &mut Vec<Diagnostic>,
    source_override: Option<&RuleOrigin>,
) -> Result<(), String> {
    let json_val: serde_json::Value =
        serde_json::from_str(json_str).map_err(|e| format!("Failed to parse diagnostic JSON: {}", e))?;
    extract_diagnostics_from_value(&json_val, model, out, source_override)
}

/// Appends a [`Diagnostic`] for each element of an already-parsed JSON array of
/// rule outputs. A caller that already holds the structured value skips the JSON
/// string round-trip [`extract_diagnostics`] performs.
#[doc(hidden)]
pub fn extract_diagnostics_from_value(
    json_val: &serde_json::Value,
    model: &SemanticModel,
    out: &mut Vec<Diagnostic>,
    source_override: Option<&RuleOrigin>,
) -> Result<(), String> {
    let items = json_val.as_array().ok_or("Diagnostic output must be a JSON array")?;
    for item in items {
        out.push(parse_diagnostic(item, model, source_override)?);
    }
    Ok(())
}

pub(crate) fn build_report(
    diagnostics: Vec<Diagnostic>,
    model: &SemanticModel,
    suppressed: u32,
    rules_evaluated: Option<u32>,
    strict: bool,
    severity_level: Severity,
    file_path: String,
) -> ValidationReport {
    build_report_with_versions(
        diagnostics,
        model,
        suppressed,
        rules_evaluated,
        strict,
        severity_level,
        file_path,
        DATA_SOURCE_VERSIONS.cfn_lint_version.to_owned(),
        DATA_SOURCE_VERSIONS.resource_schema_version.to_owned(),
    )
}

fn build_report_with_versions(
    diagnostics: Vec<Diagnostic>,
    model: &SemanticModel,
    suppressed: u32,
    rules_evaluated: Option<u32>,
    strict: bool,
    severity_level: Severity,
    file_path: String,
    cfn_lint_version: String,
    resource_schema_version: String,
) -> ValidationReport {
    let fatal = diagnostics.iter().filter(|d| d.severity == Severity::Fatal).count() as u32;
    let errors = diagnostics.iter().filter(|d| d.severity == Severity::Error).count() as u32;
    let warnings = diagnostics.iter().filter(|d| d.severity == Severity::Warn).count() as u32;
    let debug = diagnostics.iter().filter(|d| d.severity == Severity::Debug).count() as u32;
    let informational = diagnostics.len() as u32 - fatal - errors - warnings - debug;
    ValidationReport {
        file_path,
        status: ReportStatus::Ok,
        version: env!("CARGO_PKG_VERSION").to_string(),
        diagnostics,
        metadata: ReportMetadata {
            rules_evaluated: rules_evaluated.unwrap_or(0),
            cfn_lint_version,
            resource_schema_version,
            resources_scanned: model.resources.len() as u32,
            counts: Summary { fatal, errors, warnings, informational, debug },
            suppressed,
            strict,
            severity_level,
            budget_exhaustions: None,
        },
        performance: PerformanceMetrics {
            schema_init: PhaseMetric { duration_ms: 0.0 },
            engine_init: PhaseMetric { duration_ms: 0.0 },
            model_build: PhaseMetric { duration_ms: 0.0 },
            schema_validate: PhaseMetric { duration_ms: 0.0 },
            rule_evaluation: PhaseMetric { duration_ms: 0.0 },
            diagnostic_finalize: PhaseMetric { duration_ms: 0.0 },
            validate_total: PhaseMetric { duration_ms: 0.0 },
        },
    }
}

pub(crate) fn finalize_diagnostics(diagnostics: &mut Vec<Diagnostic>, config: &ValidateConfig) -> (u32, u32) {
    let total_before = diagnostics.len() as u32;

    if config.disable_builtin_rules {
        diagnostics.retain(|d| matches!(d.source, RuleOrigin::Custom | RuleOrigin::Guard));
    }

    if config.strict {
        for d in diagnostics.iter_mut() {
            if d.severity == Severity::Warn {
                d.severity = Severity::Error;
            }
        }
    }

    apply_filters(diagnostics, &config.filters);

    // Filter by minimum severity. Debug is the lowest severity so it acts as "no filter".
    diagnostics.retain(|d| d.severity >= config.severity_level);

    // Order by severity first (Fatal, Error, Warn, Info, Debug), then by rule number,
    // then by location and the remaining fields. The severity and rule-number keys are
    // both functionally determined by `rule_id` (the prefix letter fixes the severity,
    // the digits fix the number), so they add grouping without ever splitting two
    // diagnostics that are otherwise identical.
    //
    // The sort key MUST stay a superset of the dedup key below. If two diagnostics share
    // the dedup key but are separated by a sibling that compares equal on the sort key,
    // stable sort leaves them non-adjacent and dedup_by silently misses them.
    // Seen in the wild: the same rule fired twice for the same parameter (two distinct usages)
    // with a sibling diagnostic for a different parameter at the same line/col in between -
    // native HashMap iteration order put them in [A, B, A] layout, dedup skipped.
    let line = |d: &Diagnostic| d.location.as_ref().map(|l| l.start_line).unwrap_or(0);
    let column = |d: &Diagnostic| d.location.as_ref().map(|l| l.start_column).unwrap_or(0);
    // The resource id is part of both keys: two findings on *different* resources
    // are distinct even when they share a span, message, and path. This happens
    // with `Fn::ForEach`-expanded resources, which are separate resources built
    // from one template body and therefore carry the same source span.
    //
    // An item fn (not a closure) is required to borrow the id: a closure cannot
    // express that its returned `&str` is tied to the borrowed argument.
    fn resource_id(d: &Diagnostic) -> &str {
        d.entity.as_ref().map(|e| e.logical_id.as_str()).unwrap_or_default()
    }
    diagnostics.sort_by(|a, b| {
        b.severity
            .cmp(&a.severity)
            .then_with(|| rule_number(&a.rule_id).cmp(&rule_number(&b.rule_id)))
            .then_with(|| a.rule_id.cmp(&b.rule_id))
            .then_with(|| line(a).cmp(&line(b)))
            .then_with(|| column(a).cmp(&column(b)))
            .then_with(|| resource_id(a).cmp(resource_id(b)))
            .then_with(|| a.property_path.cmp(&b.property_path))
            .then_with(|| a.message.cmp(&b.message))
    });
    diagnostics.dedup_by(|a, b| {
        a.location.as_ref().map(|l| l.start_line).unwrap_or(0) == b.location.as_ref().map(|l| l.start_line).unwrap_or(0)
            && a.location.as_ref().map(|l| l.start_column).unwrap_or(0)
                == b.location.as_ref().map(|l| l.start_column).unwrap_or(0)
            && a.rule_id == b.rule_id
            && resource_id(a) == resource_id(b)
            && a.message == b.message
            && a.property_path == b.property_path
    });

    let suppressed = total_before.saturating_sub(diagnostics.len() as u32);
    (total_before, suppressed)
}

pub(crate) fn build_context(
    rule_id: &str,
    resource_id: Option<&str>,
    property_path: &str,
    model: &SemanticModel,
) -> Option<ViolationContext> {
    let rid = resource_id?;

    let resolve_val = |path: &str| -> Option<serde_json::Value> {
        let scenarios = model.resolve_scenarios_json(rid, path);
        scenarios.into_iter().next().map(|(v, _)| v)
    };

    // Resolves a value only when every condition scenario agrees on it. A property
    // driven by `Fn::If` resolves to a different value per branch, and each branch
    // yields its own diagnostic (with a branch-specific message); attaching the
    // first branch's value to all of them would contradict the other messages. When
    // the branches disagree this returns `None`, leaving the message as the sole,
    // correct carrier of the offending value.
    let unambiguous_val = |path: &str| -> Option<serde_json::Value> {
        let mut scenarios = model.resolve_scenarios_json(rid, path).into_iter().map(|(v, _)| v);
        let first = scenarios.next()?;
        if scenarios.all(|v| v == first) { Some(first) } else { None }
    };

    let mut actual_value: Option<JsonValue> = None;
    let mut property = None;
    let mut lifecycle = None;
    let mut extra: HashMap<String, JsonValue> = HashMap::new();

    match rule_id {
        "F3012" | "E3012" => {
            if !property_path.is_empty() {
                actual_value = resolve_val(property_path).map(Into::into);
            }
        }
        "F3030" | "W3030" | "E3030" | "F3031" | "E3031" | "F3034" | "E3034" | "F3037" | "W3045" | "E1103" | "E1150"
        | "E1151" | "E1152" | "E1153" | "E1154" | "E1155" | "E1156" => {
            actual_value = resolve_val(property_path).map(Into::into);
        }
        "F3033" | "W9006" => {
            if let Some(v) = resolve_val(property_path) {
                if let Some(s) = v.as_str() {
                    extra.insert("actual_length".into(), serde_json::json!(s.chars().count()).into());
                }
                actual_value = Some(v.into());
            }
        }
        "F3032" | "E3032" => {
            if let Some(v) = resolve_val(property_path)
                && let Some(arr) = v.as_array()
            {
                extra.insert("actual_count".into(), serde_json::json!(arr.len()).into());
            }
        }
        "F3002" | "E3002" | "F3020" => {
            let prop = property_path.rsplit('.').next().unwrap_or("");
            if !prop.is_empty() {
                property = Some(prop.to_string());
            }
        }
        "F3003" | "F3021" | "F3014" | "F3058" => {}
        "E3047" => {
            if let Some(v) = resolve_val("Properties.Cpu") {
                extra.insert("cpu".into(), v.into());
            }
            if let Some(v) = resolve_val("Properties.Memory") {
                extra.insert("memory".into(), v.into());
            }
        }
        "E3060" => {
            if let Some(v) = resolve_val("Properties.CidrBlock") {
                extra.insert("cidr".into(), v.into());
            }
        }
        "E9002" => {
            actual_value = resolve_val("Properties.SecurityGroupIngress").map(Into::into);
        }
        "F3006" => {
            if let Some(res) = model.resources.get(rid) {
                extra.insert("resource_type".into(), serde_json::json!(res.resource_type).into());
            }
        }
        "E3501" => {
            if let Some(v) = resolve_val("Properties.QueueName") {
                extra.insert("queue_name".into(), v.into());
            }
        }
        "E3505" => {
            if let Some(v) = resolve_val("Properties.VisibilityTimeout") {
                extra.insert("visibility_timeout".into(), v.into());
            }
        }
        "E3044" => {
            if let Some(v) = resolve_val("Properties.LaunchType") {
                extra.insert("launch_type".into(), v.into());
            }
            if let Some(v) = resolve_val("Properties.SchedulingStrategy") {
                extra.insert("scheduling_strategy".into(), v.into());
            }
        }
        "E3053" => {
            if !property_path.is_empty() {
                actual_value = resolve_val(property_path).map(Into::into);
            }
        }
        "W9009" => {
            lifecycle = Some("deprecated".into());
        }
        "I9001" => {
            lifecycle = Some("create-only".into());
        }
        "W9054" => {
            lifecycle = Some("write-only".into());
        }
        // Lambda runtime lifecycle: surface the offending runtime string and the
        // stage of its lifecycle, mirroring how resource-type deprecation (W9009)
        // and property lifecycle (I9001/W9054) carry a lifecycle marker. The runtime
        // is emitted once per condition branch, so only attach the value when every
        // branch agrees - otherwise the message alone names the branch's runtime.
        "E2533" => {
            actual_value = unambiguous_val(property_path).map(Into::into);
            lifecycle = Some("end-of-life".into());
        }
        "E2531" => {
            actual_value = unambiguous_val(property_path).map(Into::into);
            lifecycle = Some("create-blocked".into());
        }
        "W2531" => {
            actual_value = unambiguous_val(property_path).map(Into::into);
            lifecycle = Some("deprecated".into());
        }
        // RDS instance exposed to the public internet: surface the offending
        // PubliclyAccessible value against the expected safe setting.
        "W9011" => {
            actual_value = unambiguous_val(property_path).map(Into::into);
        }
        "W2503" | "W2502" => {
            if let Some(res) = model.resources.get(rid)
                && let Some(ref c) = res.condition
            {
                extra.insert("source_condition".into(), serde_json::json!(c).into());
            }
        }
        _ => {}
    }

    if actual_value.is_none() && property.is_none() && lifecycle.is_none() && extra.is_empty() {
        return None;
    }

    Some(ViolationContext {
        actual_value,
        expected_constraint: None,
        property,
        lifecycle,
        resolution_source: None,
        extra: if extra.is_empty() { None } else { Some(extra) },
    })
}

/// Drops every non-transform diagnostic when a SAM transform error is present.
///
/// A failed SAM transform stops CloudFormation before resource validation, so
/// schema and lint findings on the untransformed template are noise. Retaining
/// only the transform errors mirrors that short-circuit.
fn gate_sam_transform_errors(diagnostics: &mut Vec<Diagnostic>) {
    let has_transform_error = diagnostics.iter().any(|d| is_sam_transform_error_message(&d.message));
    if has_transform_error {
        diagnostics.retain(|d| is_sam_transform_error_message(&d.message));
    }
}

/// Rules suppressed on CDK-generated templates. CDK synthesizes templates from
/// higher-level code, so findings about how the template itself is written are
/// not actionable for the developer and would only add noise.
const CDK_SUPPRESSED_RULE_IDS: [&str; 2] = ["I1022", "W3010"];

/// Suppresses non-actionable findings on CDK-generated templates (see
/// [`CDK_SUPPRESSED_RULE_IDS`]).
fn gate_cdk_suppressed_rules(diagnostics: &mut Vec<Diagnostic>, model: &SemanticModel) {
    if !model.is_cdk {
        return;
    }
    diagnostics.retain(|d| !CDK_SUPPRESSED_RULE_IDS.contains(&d.rule_id.as_str()));
}

/// Attaches a source span to any diagnostic still missing one. Location is part of
/// the report at every detail level, so this runs regardless of the configured
/// detail level and independently of the engine.
///
/// Most diagnostics are located at construction (via `resource_span` /
/// `resolve_section_span`), but some emission paths cannot reach a span there:
/// parse-time findings built before byte spans are assigned, findings anchored on
/// an output/parameter path that `resource_span` cannot resolve (it only roots at
/// `Resources/`), and template-model findings that never pass through
/// `parse_diagnostic`'s section fallback. This is the single place that repairs
/// them. The resolution is best-effort and monotonic - it only ever fills a `None`
/// location, never overrides an existing one - so it cannot move a diagnostic that
/// already points at the right place.
fn backfill_locations(diagnostics: &mut [Diagnostic], model: &SemanticModel) {
    for d in diagnostics.iter_mut() {
        if d.location.is_some() {
            continue;
        }
        let resource_id = d.resource_logical_id();
        let property_path = d.property_path.as_deref().unwrap_or("");
        let span = model
            .diagnostic_span(resource_id, property_path)
            .unwrap_or_else(|| resolve_section_span(&d.rule_id, model));
        d.location = span_to_option(span);
    }
}

/// Fills the targeted entity of every diagnostic on a named template entity
/// that did not attach one at emission time, by deriving the entity type and
/// logical ID from its section-absolute property path (`Parameters/MyParam/…`).
/// Resource entities emitted before the model existed (parse- and
/// transform-time) carry no CloudFormation type, so it is filled in from the
/// model here. Like `backfill_locations`, the resolution is monotonic - an
/// already-set entity or resource type is never overridden.
fn backfill_entities(diagnostics: &mut [Diagnostic], model: &SemanticModel) {
    for d in diagnostics.iter_mut() {
        if d.entity.is_none() {
            d.entity = d.property_path.as_deref().and_then(entity_identity).map(|(entity_type, logical_id)| Entity {
                logical_id: logical_id.to_string(),
                entity_type,
                resource_type: None,
            });
        }
        if let Some(entity) = d.entity.as_mut()
            && entity.entity_type == EntityType::Resource
            && entity.resource_type.is_none()
        {
            entity.resource_type = model.resources.get(entity.logical_id.as_str()).map(|r| r.resource_type.clone());
        }
    }
}

pub(crate) fn enrich_diagnostics(
    diagnostics: &mut [Diagnostic],
    model: &SemanticModel,
    registry_metadata: &HashMap<String, RuleMetadataEntry>,
    external_metadata: &HashMap<String, RuleMetadataEntry>,
    format: &DetailLevel,
) {
    if !format.needs_enrichment() {
        return;
    }
    let needs_context = format.needs_context();

    for d in diagnostics.iter_mut() {
        // Custom and Guard rules are user-supplied and have no built-in evaluation
        // phase, so leave their phase unset rather than forcing one. Built-in rules
        // are Schema-phase when fatal and Lint-phase otherwise.
        if d.phase.is_none() && !matches!(d.source, RuleOrigin::Custom | RuleOrigin::Guard) {
            d.phase = Some(if is_fatal_rule(&d.rule_id) { Phase::Schema } else { Phase::Lint });
        }
        if d.rule_description.is_none() {
            d.rule_description = registry_metadata
                .get(&d.rule_id)
                .or_else(|| external_metadata.get(&d.rule_id))
                .map(|entry| entry.description.clone());
        }
        if needs_context && d.context.is_none() {
            d.context =
                build_context(&d.rule_id, d.resource_logical_id(), d.property_path.as_deref().unwrap_or(""), model);
        }
    }
}

pub fn build_rule_list(
    registry: &HashMap<String, RuleMetadataEntry>,
    external: &HashMap<String, RuleMetadataEntry>,
) -> Vec<RuleInfo> {
    let mut rules: Vec<RuleInfo> = registry
        .iter()
        .chain(external.iter())
        .map(|(id, entry)| RuleInfo {
            id: id.clone(),
            severity: entry.severity,
            category: entry.category.clone(),
            description: entry.description.clone(),
            origin: entry.origin,
        })
        .collect();
    rules.sort_by(|a, b| a.id.cmp(&b.id));
    rules
}

pub fn make_resource_diagnostic(
    rule_id: &str,
    message: &str,
    model: &SemanticModel,
    resource_id: &str,
    prop_path: &str,
    suggested_fix: Option<&str>,
) -> Diagnostic {
    make_resource_diagnostic_at_source(rule_id, message, model, resource_id, prop_path, prop_path, suggested_fix)
}

/// Builds a resource diagnostic whose public property path and source-span anchor differ.
/// Scenario-aware rules use this when an effective path maps to an authored intrinsic branch.
pub fn make_resource_diagnostic_at_source(
    rule_id: &str,
    message: &str,
    model: &SemanticModel,
    resource_id: &str,
    prop_path: &str,
    source_path: &str,
    suggested_fix: Option<&str>,
) -> Diagnostic {
    // With no resource, a section-absolute path (`Parameters/MyParam/Type`)
    // anchors the finding at the named entity; without one the section span from
    // the rule-ID table is the closest known location.
    let span = if resource_id.is_empty() {
        match model.diagnostic_span(None, source_path) {
            Some(found) => found,
            None => resolve_section_span(rule_id, model),
        }
    } else {
        model.resource_span(resource_id, source_path)
    };
    RegisteredDiagnostic::new(rule_id, message)
        .property_path(prop_path)
        .location(span)
        .suggested_fix(suggested_fix)
        .resource(resource_id, model.resources.get(resource_id).map(|r| r.resource_type.clone()))
        .build()
}

#[cfg(test)]
mod tests {
    use super::*;
    use diagnostics::Phase;
    use rules::{Category, RuleFilterConfig, build_rule_metadata_map, lookup_rule};
    use std::sync::atomic::{AtomicUsize, Ordering};
    use template_model::{SAM_TRANSFORM_ERROR_PREFIX, SAM_TRANSFORM_ERROR_RULE_ID};

    const TEST_CFN_LINT_VERSION: &str = "https://github.com/aws-cloudformation/cfn-lint@1.54.0";
    const TEST_RESOURCE_SCHEMA_VERSION: &str =
        "https://github.com/aws-cloudformation/resource-provider-enhanced-schemas@2026-08-07T18:20:13Z";
    #[test]
    fn additional_schema_resolve_uses_explicit_type_name() {
        let src = AdditionalSchemaSource {
            type_name: Some("AWS::Lambda::Function".into()),
            schema: r#"{"properties":{"P":{"type":"string"}}}"#.into(),
        };
        let (type_name, schema) = src.resolve().expect("valid schema resolves");
        assert_eq!(type_name, "AWS::Lambda::Function", "an explicit type_name names the target type");
        assert!(schema.is_object());
    }

    #[test]
    fn additional_schema_resolve_accepts_matching_type_names() {
        let src = AdditionalSchemaSource {
            type_name: Some("AWS::Lambda::Function".into()),
            schema: r#"{"typeName":"AWS::Lambda::Function","properties":{"P":{"type":"string"}}}"#.into(),
        };
        let (type_name, _) = src.resolve().expect("agreeing type names resolve");
        assert_eq!(type_name, "AWS::Lambda::Function");
    }

    #[test]
    fn additional_schema_resolve_rejects_contradictory_type_names() {
        let src = AdditionalSchemaSource {
            type_name: Some("AWS::Lambda::Function".into()),
            schema: r#"{"typeName":"AWS::Other::Type","properties":{}}"#.into(),
        };
        let err = src.resolve().expect_err("contradictory type names must fail");
        assert!(
            err.0.contains("AWS::Lambda::Function") && err.0.contains("AWS::Other::Type"),
            "the error must name both types, got: {}",
            err.0
        );
    }

    #[test]
    fn additional_schema_resolve_falls_back_to_schema_type_name() {
        let src = AdditionalSchemaSource {
            type_name: None,
            schema: r#"{"typeName":"AWS::Lambda::Function","properties":{}}"#.into(),
        };
        let (type_name, _) = src.resolve().expect("valid schema resolves");
        assert_eq!(type_name, "AWS::Lambda::Function", "an absent type_name falls back to the schema's typeName");
    }

    #[test]
    fn additional_schema_resolve_rejects_invalid_json() {
        let src =
            AdditionalSchemaSource { type_name: Some("AWS::Lambda::Function".into()), schema: "{ not json ".into() };
        let err = src.resolve().expect_err("invalid JSON must fail");
        assert!(err.0.contains("Invalid additional schema"), "unexpected error: {}", err.0);
    }

    #[test]
    fn additional_schema_resolve_rejects_non_object() {
        let src = AdditionalSchemaSource { type_name: Some("AWS::Lambda::Function".into()), schema: "42".into() };
        let err = src.resolve().expect_err("non-object schema must fail");
        assert!(err.0.contains("expected a JSON object"), "unexpected error: {}", err.0);
    }

    #[test]
    fn additional_schema_resolve_rejects_missing_type_name() {
        let src = AdditionalSchemaSource { type_name: None, schema: r#"{"properties":{}}"#.into() };
        let err = src.resolve().expect_err("missing type name must fail");
        assert!(err.0.contains("missing a resource type name"), "unexpected error: {}", err.0);
    }

    #[test]
    fn additional_schema_resolve_error_names_an_unnamed_source() {
        let src = AdditionalSchemaSource { type_name: None, schema: "{ not json ".into() };
        let err = src.resolve().expect_err("invalid JSON must fail");
        assert!(err.0.contains("<unnamed>"), "unexpected error: {}", err.0);
    }

    #[test]
    fn engine_config_build_overlay_catalog_applies_schemas() {
        let config = EngineConfig::new().with_schema_validator_config(SchemaValidatorConfig {
            additional_schemas: vec![AdditionalSchemaSource {
                type_name: None,
                schema: r#"{"typeName":"AWS::Lambda::Function","properties":{"TestForOverride":{"type":"string"}}}"#
                    .into(),
            }],
        });
        let catalog = config.build_overlay_catalog().expect("valid overlay builds catalog");
        assert!(!catalog.is_empty());
        assert!(catalog.type_names.contains(&"AWS::Lambda::Function".to_string()));
    }

    #[test]
    fn engine_config_build_overlay_catalog_empty_is_noop() {
        let config = EngineConfig::default();
        let catalog = config.build_overlay_catalog().expect("empty config builds empty catalog");
        assert!(catalog.is_empty());
    }

    #[test]
    fn engine_config_builder_composes_without_a_struct_literal() {
        let config = EngineConfig::new()
            .with_custom_rules([ExternalRuleSource { name: "a.rego".into(), content: "package a".into() }])
            .with_guard_rules([ExternalRuleSource { name: "b.guard".into(), content: "rule x {}".into() }])
            .with_schema_validator_config(SchemaValidatorConfig {
                additional_schemas: vec![AdditionalSchemaSource {
                    type_name: Some("AWS::Test::One".into()),
                    schema: r#"{"properties":{"P":{"type":"string"}}}"#.into(),
                }],
            });
        assert_eq!(config.custom_rules.len(), 1);
        assert_eq!(config.guard_rules.len(), 1);
        let sv_config = config.schema_validator_config.as_ref().expect("schema_validator config must be set");
        assert_eq!(sv_config.additional_schemas.len(), 1);
        assert_eq!(sv_config.additional_schemas[0].type_name.as_deref(), Some("AWS::Test::One"));
    }

    #[test]
    fn default_engine_config_serializes_without_the_schema_validator_config_field() {
        let json = serde_json::to_value(EngineConfig::default()).expect("EngineConfig serializes");
        assert!(
            json.get("schemaValidatorConfig").is_none(),
            "an empty schema_validator_config must not change the serialized form, got: {json}"
        );
    }

    #[test]
    fn engine_config_nested_schema_validator_serialization_roundtrip() {
        let config = EngineConfig::new().with_schema_validator_config(SchemaValidatorConfig {
            additional_schemas: vec![AdditionalSchemaSource {
                type_name: Some("AWS::Test::RT".into()),
                schema: r#"{"properties":{}}"#.into(),
            }],
        });
        let json = serde_json::to_value(&config).expect("serializes");
        assert!(json.get("schemaValidatorConfig").is_some(), "nested config must appear in JSON: {json}");
        assert!(json.get("schemaValidator").is_none(), "the old config field must not be serialized: {json}");
        let deserialized: EngineConfig = serde_json::from_value(json).expect("deserializes");
        let sv = deserialized.schema_validator_config.expect("nested config must roundtrip");
        assert_eq!(sv.additional_schemas.len(), 1);
        assert_eq!(sv.additional_schemas[0].type_name.as_deref(), Some("AWS::Test::RT"));
    }

    #[test]
    fn standalone_engine_with_nested_schema_config_derives_metadata() {
        // A standalone engine built from EngineConfig with a nested
        // SchemaValidatorConfig derives overlay-aware metadata from it. This
        // verifies the internal build_overlay_catalog path is exercised.
        let config = EngineConfig::new().with_schema_validator_config(SchemaValidatorConfig {
            additional_schemas: vec![AdditionalSchemaSource {
                type_name: None,
                schema: r#"{"typeName":"AWS::Lambda::Function","properties":{"TestForOverride":{"type":"string"}}}"#
                    .into(),
            }],
        });
        // The engine builds successfully - the nested schema config was resolved.
        let catalog = config.build_overlay_catalog().expect("nested config builds");
        assert!(!catalog.is_empty(), "the catalog must be populated from nested config");
    }

    #[test]
    fn combined_wrapper_style_path_constructs_validator_and_engine_once() {
        // Simulates the binding/CLI pattern: build SchemaValidator once from the
        // nested config, then pass it to the engine via new_with_schema_validator.
        // This ensures the combined path does not re-resolve overlays.
        let schema_config = SchemaValidatorConfig {
            additional_schemas: vec![AdditionalSchemaSource {
                type_name: None,
                schema: r#"{"typeName":"AWS::Lambda::Function","properties":{"TestForOverride":{"type":"string"}}}"#
                    .into(),
            }],
        };
        let validator = schema_validator::SchemaValidator::new(schema_config).expect("validator builds");
        // Verify the catalog is populated from the validator
        assert!(!validator.overlay_catalog().is_empty());
        assert!(validator.overlay_catalog().type_names.contains(&"AWS::Lambda::Function".to_string()));
    }

    #[test]
    fn standalone_schema_validator_config() {
        // SchemaValidator can be built standalone from SchemaValidatorConfig.
        let config = SchemaValidatorConfig {
            additional_schemas: vec![AdditionalSchemaSource {
                type_name: None,
                schema: r#"{"typeName":"AWS::Test::Standalone","properties":{"Name":{"type":"string"}}}"#.into(),
            }],
        };
        let validator = schema_validator::SchemaValidator::new(config).expect("standalone validator builds");
        assert!(validator.overlay_catalog().type_names.contains(&"AWS::Test::Standalone".to_string()));
    }

    fn minimal_model() -> SemanticModel {
        let yaml = br#"
AWSTemplateFormatVersion: "2010-09-09"
Resources:
  Bucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: my-bucket
"#;
        SemanticModel::from_bytes(yaml).expect("minimal model should parse")
    }

    fn meta_map() -> HashMap<String, RuleMetadataEntry> {
        build_rule_metadata_map()
    }

    fn default_diag() -> Diagnostic {
        Diagnostic {
            rule_id: String::new(),
            severity: Severity::Info,
            message: String::new(),
            entity: None,
            property_path: None,
            suggested_fix: None,
            documentation_url: None,
            category: None,
            location: None,
            related_resources: None,
            condition_scenario: None,
            rule_description: None,
            phase: None,
            context: None,
            source: RuleOrigin::Engine,
        }
    }

    #[test]
    fn parse_diagnostic_minimal_valid() {
        let model = minimal_model();
        let val: serde_json::Value = serde_json::json!({
            "rule_id": "E3012",
            "severity": Severity::Error.as_str(),
            "message": "Type mismatch",
            "resource_id": "Bucket",
            "resource_path": "Properties.BucketName"
        });
        let diag = parse_diagnostic(&val, &model, None).expect("should parse");
        assert_eq!(diag.rule_id, "E3012");
        assert_eq!(diag.severity, Severity::Error);
        assert_eq!(diag.message, "Type mismatch");
        assert_eq!(diag.resource_logical_id(), Some("Bucket"));
        assert_eq!(diag.entity.as_ref().and_then(|e| e.resource_type.as_deref()), Some("AWS::S3::Bucket"));
    }

    #[test]
    fn parse_diagnostic_missing_rule_id_returns_error() {
        let model = minimal_model();
        let val = serde_json::json!({"severity": Severity::Error.as_str(), "message": "x"});
        parse_diagnostic(&val, &model, None).unwrap_err();
    }

    #[test]
    fn parse_diagnostic_missing_severity_for_builtin_is_accepted() {
        let model = minimal_model();
        let val = serde_json::json!({"rule_id": "E3012", "message": "x"});
        let diag = parse_diagnostic(&val, &model, None).expect("built-in diagnostic must not require severity in JSON");
        assert_eq!(diag.severity, Severity::Error, "registry-derived severity must win for built-in rules");
    }

    #[test]
    fn parse_diagnostic_missing_severity_for_custom_returns_error() {
        let model = minimal_model();
        let val = serde_json::json!({"rule_id": "XCUSTOM", "message": "x"});
        parse_diagnostic(&val, &model, Some(&RuleOrigin::Custom))
            .expect_err("custom/guard diagnostics without severity must error");
    }

    #[test]
    fn parse_diagnostic_builtin_ignores_json_severity() {
        let model = minimal_model();
        let val = serde_json::json!({
            "rule_id": "E3012",
            "severity": Severity::Warn.as_str(),
            "message": "x"
        });
        let diag = parse_diagnostic(&val, &model, None).unwrap();
        assert_eq!(
            diag.severity,
            Severity::Error,
            "the registry's Error severity for E3012 must override any JSON severity"
        );
    }

    #[test]
    fn parse_diagnostic_missing_message_returns_error() {
        let model = minimal_model();
        let val = serde_json::json!({"rule_id": "E3012", "severity": Severity::Error.as_str()});
        parse_diagnostic(&val, &model, None).unwrap_err();
    }

    #[test]
    fn parse_diagnostic_empty_rule_id_returns_error() {
        let model = minimal_model();
        let val = serde_json::json!({"rule_id": "", "severity": Severity::Error.as_str(), "message": "x"});
        let err = parse_diagnostic(&val, &model, Some(&RuleOrigin::Custom))
            .expect_err("an empty rule_id must be rejected, not accepted as a blank-ID diagnostic");
        assert!(err.contains("empty 'rule_id'"), "got: {err}");
    }

    #[test]
    fn parse_diagnostic_empty_message_returns_error() {
        let model = minimal_model();
        let val = serde_json::json!({"rule_id": "CUSTOM1", "severity": Severity::Error.as_str(), "message": "   "});
        let err =
            parse_diagnostic(&val, &model, Some(&RuleOrigin::Custom)).expect_err("a blank message must be rejected");
        assert!(err.contains("CUSTOM1") && err.contains("empty 'message'"), "got: {err}");
    }

    #[test]
    fn parse_diagnostic_custom_severity_is_authoritative_even_for_f_prefixed_id() {
        // A custom rule chooses its own ID freely, so the built-in `F`-prefix→Fatal
        // heuristic must NOT apply: the declared severity is preserved verbatim. This
        // also keeps the Rego/Guard boundary at parity with the CEL engine, which emits
        // the declared severity directly.
        let model = minimal_model();
        let val = serde_json::json!({
            "rule_id": "FCUSTOM",
            "severity": Severity::Error.as_str(),
            "message": "type mismatch"
        });
        let diag = parse_diagnostic(&val, &model, Some(&RuleOrigin::Custom)).unwrap();
        assert_eq!(diag.severity, Severity::Error, "declared severity must survive an F-prefixed custom ID");
    }

    #[test]
    fn parse_diagnostic_custom_rule_id_allows_separators_but_rejects_punctuation() {
        let model = minimal_model();
        let ok = serde_json::json!({
            "rule_id": "s3.encryption-required_1",
            "severity": Severity::Warn.as_str(),
            "message": "ok"
        });
        assert!(parse_diagnostic(&ok, &model, Some(&RuleOrigin::Custom)).is_ok());

        let bad = serde_json::json!({
            "rule_id": "bad id/with space",
            "severity": Severity::Warn.as_str(),
            "message": "bad"
        });
        let err = parse_diagnostic(&bad, &model, Some(&RuleOrigin::Custom))
            .expect_err("a rule_id with whitespace/punctuation must be rejected");
        assert!(err.contains("invalid 'rule_id'"), "got: {err}");
    }

    #[test]
    fn parse_diagnostic_warning_severity() {
        let model = minimal_model();
        let val = serde_json::json!({
            "rule_id": "W3045",
            "severity": Severity::Warn.as_str(),
            "message": "warn"
        });
        let diag = parse_diagnostic(&val, &model, None).unwrap();
        assert_eq!(diag.severity, Severity::Warn);
    }

    #[test]
    fn parse_diagnostic_with_suggested_fix_and_doc_url() {
        let model = minimal_model();
        let val = serde_json::json!({
            "rule_id": "E3012",
            "severity": Severity::Error.as_str(),
            "message": "bad",
            "suggested_fix": "fix it",
            "documentation_url": "https://example.com"
        });
        let diag = parse_diagnostic(&val, &model, None).unwrap();
        assert_eq!(diag.suggested_fix.as_deref(), Some("fix it"));
        assert_eq!(diag.documentation_url.as_deref(), Some("https://example.com"));
    }

    #[test]
    fn parse_diagnostic_empty_resource_id_treated_as_none() {
        let model = minimal_model();
        let val = serde_json::json!({
            "rule_id": "E3012",
            "severity": Severity::Error.as_str(),
            "message": "x",
            "resource_id": ""
        });
        let diag = parse_diagnostic(&val, &model, None).unwrap();
        assert!(diag.entity.is_none(), "diagnostic without resource_id should have no entity");
    }

    #[test]
    fn parse_diagnostic_accepts_model_matching_explicit_location() {
        let model = minimal_model();
        let expected = model.resource_span("Bucket", "Properties.BucketName");
        let val = serde_json::json!({
            "rule_id": "E3012",
            "severity": Severity::Error.as_str(),
            "message": "x",
            "resource_id": "Bucket",
            "resource_path": "Properties.BucketName",
            "start_line": expected.start_line,
            "start_column": expected.start_column,
            "end_line": expected.end_line,
            "end_column": expected.end_column
        });
        let diag = parse_diagnostic(&val, &model, None).expect("model-matching coordinates should be accepted");
        assert_eq!(diag.location, Some(expected));
    }

    #[test]
    fn parse_diagnostic_rejects_unverified_explicit_location() {
        let model = minimal_model();
        let val = serde_json::json!({
            "rule_id": "XCUSTOM",
            "severity": Severity::Error.as_str(),
            "message": "x",
            "resource_id": "Bucket",
            "resource_path": "Properties.BucketName",
            "start_line": 42,
            "start_column": 7,
            "end_line": 43,
            "end_column": 9
        });
        let error = parse_diagnostic(&val, &model, Some(&RuleOrigin::Custom))
            .expect_err("custom coordinates outside the declared property must be rejected");
        assert!(error.contains("does not match model-derived span"), "got: {error}");
    }

    #[test]
    fn parse_diagnostic_accepts_verified_conditional_source_path() {
        let model = SemanticModel::from_bytes(
            br#"
Parameters:
  Mode: {Type: String}
Conditions:
  UseFirst: !Equals [!Ref Mode, first]
Resources:
  Record:
    Type: Custom::Record
    Properties:
      Values: !If
        - UseFirst
        - [invalid]
        - [valid]
"#,
        )
        .expect("conditional model should parse");
        let source_path = "Properties.Values.Fn::If.1.0";
        let expected = model.resource_span("Record", source_path);
        let val = serde_json::json!({
            "rule_id": "E3012",
            "severity": Severity::Error.as_str(),
            "message": "x",
            "resource_id": "Record",
            "resource_path": "Properties.Values.0",
            (DIAGNOSTIC_SOURCE_PATH_FIELD): source_path,
            "start_line": expected.start_line,
            "start_column": expected.start_column,
            "end_line": expected.end_line,
            "end_column": expected.end_column
        });
        let diag = parse_diagnostic(&val, &model, None).expect("verified conditional source path should be accepted");
        assert_eq!(diag.location, Some(expected));
    }

    #[test]
    fn parse_diagnostic_rejects_source_path_for_another_property() {
        let model = minimal_model();
        let expected = model.resource_span("Bucket", "Properties.BucketName");
        let val = serde_json::json!({
            "rule_id": "E3012",
            "severity": Severity::Error.as_str(),
            "message": "x",
            "resource_id": "Bucket",
            "resource_path": "Properties.BucketName",
            (DIAGNOSTIC_SOURCE_PATH_FIELD): "Properties.Tags.Fn::If.1.0",
            "start_line": expected.start_line,
            "start_column": expected.start_column,
            "end_line": expected.end_line,
            "end_column": expected.end_column
        });
        let error = parse_diagnostic(&val, &model, None)
            .expect_err("a source path for another property must not relocate the diagnostic");
        assert!(error.contains("instead of resource path 'Properties.BucketName'"), "got: {error}");
    }

    #[test]
    fn parse_diagnostic_unknown_rule_uses_json_category() {
        let model = minimal_model();
        let val = serde_json::json!({
            "rule_id": "XUNKNOWN",
            "severity": Severity::Error.as_str(),
            "message": "x",
            "category": "my-category"
        });
        let diag = parse_diagnostic(&val, &model, Some(&RuleOrigin::Custom)).unwrap();
        assert_eq!(diag.category.as_deref(), Some("my-category"));
    }

    #[test]
    fn parse_diagnostic_builtin_rule_ignores_json_category_and_uses_registry() {
        let model = minimal_model();
        let val = serde_json::json!({
            "rule_id": "E3012",
            "severity": Severity::Error.as_str(),
            "message": "x",
            "category": "general"
        });
        let diag = parse_diagnostic(&val, &model, None).unwrap();
        let expected = lookup_rule("E3012").unwrap().category.as_str();
        assert_eq!(
            diag.category.as_deref(),
            Some(expected),
            "a built-in rule takes its category from the registry, ignoring any category in the engine JSON"
        );
    }

    #[test]
    fn parse_diagnostic_with_related_locations() {
        let model = minimal_model();
        let val = serde_json::json!({
            "rule_id": "E3012",
            "severity": Severity::Error.as_str(),
            "message": "x",
            "related_locations": [{
                "resource_id": "Bucket",
                "start_line": 1,
                "start_column": 2,
                "end_line": 3,
                "end_column": 4,
                "message": "related"
            }]
        });
        let diag = parse_diagnostic(&val, &model, None).unwrap();
        assert_eq!(diag.related_resources.as_ref().unwrap().len(), 1);
        assert_eq!(diag.related_resources.as_ref().unwrap()[0].message, "related");
    }

    #[test]
    fn parse_diagnostic_with_condition_scenario() {
        let model = minimal_model();
        let val = serde_json::json!({
            "rule_id": "E3012",
            "severity": Severity::Error.as_str(),
            "message": "x",
            "condition_scenario": {"IsProd": true}
        });
        let diag = parse_diagnostic(&val, &model, None).unwrap();
        let scenario = diag.condition_scenario.unwrap();
        assert_eq!(scenario.get("IsProd"), Some(&true));
    }

    #[test]
    fn extract_diagnostics_valid_array() {
        let model = minimal_model();
        let json = serde_json::json!([
            {"rule_id": "E3012", "severity": Severity::Error.as_str(), "message": "a"},
            {"rule_id": "W3045", "severity": Severity::Warn.as_str(), "message": "b"}
        ]);
        let mut out = Vec::new();
        extract_diagnostics(&json.to_string(), &model, &mut out, None).unwrap();
        assert_eq!(out.len(), 2);
        assert_eq!(out[0].rule_id, "E3012");
        assert_eq!(out[1].rule_id, "W3045");
    }

    #[test]
    fn extract_diagnostics_invalid_json_is_error() {
        let model = minimal_model();
        let mut out = Vec::new();
        let result = extract_diagnostics("not json", &model, &mut out, None);
        result.unwrap_err();
    }

    #[test]
    fn extract_diagnostics_non_array_json_is_error() {
        let model = minimal_model();
        let mut out = Vec::new();
        let result = extract_diagnostics(r#"{"key": "value"}"#, &model, &mut out, None);
        result.unwrap_err();
    }

    #[test]
    fn extract_diagnostics_fails_on_missing_required_fields() {
        let model = minimal_model();
        let json = serde_json::json!([
            {"rule_id": "E3012", "severity": Severity::Error.as_str(), "message": "ok"},
            {"bad": "item"},
            {"rule_id": "W3045", "severity": Severity::Warn.as_str(), "message": "ok2"}
        ]);
        let mut out = Vec::new();
        let result = extract_diagnostics(&json.to_string(), &model, &mut out, None);
        result.unwrap_err();
        assert_eq!(out.len(), 1, "first valid item should have been added before failure");
    }

    #[test]
    fn extract_diagnostics_from_value_matches_string_extraction() {
        let model = minimal_model();
        let json = serde_json::json!([
            {"rule_id": "E3012", "severity": Severity::Error.as_str(), "message": "a", "resource_id": "Bucket",
             "resource_path": "Properties.BucketName"},
            {"rule_id": "W3045", "severity": Severity::Warn.as_str(), "message": "b"}
        ]);

        let mut from_string = Vec::new();
        extract_diagnostics(&json.to_string(), &model, &mut from_string, None)
            .expect("string extraction should succeed");
        let mut from_value = Vec::new();
        extract_diagnostics_from_value(&json, &model, &mut from_value, None).expect("value extraction should succeed");

        assert_eq!(
            serde_json::to_value(&from_string).expect("serialize string-extracted diagnostics"),
            serde_json::to_value(&from_value).expect("serialize value-extracted diagnostics"),
            "value input and its serialized string form must yield identical diagnostics"
        );
    }

    #[test]
    fn extract_diagnostics_from_value_rejects_non_array() {
        let model = minimal_model();
        let mut out = Vec::new();
        extract_diagnostics_from_value(&serde_json::json!({"key": "value"}), &model, &mut out, None)
            .expect_err("a non-array value must be rejected the same as the string form");
    }

    #[test]
    fn build_report_counts_severities() {
        let model = minimal_model();
        let diags = vec![
            Diagnostic {
                rule_id: "F3012".into(),
                severity: Severity::Fatal,
                message: "fatal".into(),
                ..default_diag()
            },
            Diagnostic {
                rule_id: "E3012".into(),
                severity: Severity::Error,
                message: "error".into(),
                ..default_diag()
            },
            Diagnostic {
                rule_id: "E3013".into(),
                severity: Severity::Error,
                message: "error2".into(),
                ..default_diag()
            },
            Diagnostic { rule_id: "W3045".into(), severity: Severity::Warn, message: "warn".into(), ..default_diag() },
            Diagnostic { severity: Severity::Info, message: "info".into(), ..default_diag() },
        ];
        let report = build_report_with_versions(
            diags,
            &model,
            3,
            Some(50),
            false,
            Severity::Info,
            String::new(),
            TEST_CFN_LINT_VERSION.to_string(),
            TEST_RESOURCE_SCHEMA_VERSION.to_string(),
        );
        assert_eq!(report.metadata.counts.fatal, 1);
        assert_eq!(report.metadata.counts.errors, 2);
        assert_eq!(report.metadata.counts.warnings, 1);
        assert_eq!(report.metadata.counts.informational, 1);
        assert_eq!(report.metadata.suppressed, 3);
        assert_eq!(report.metadata.rules_evaluated, 50);
        assert_eq!(report.metadata.cfn_lint_version, TEST_CFN_LINT_VERSION);
        assert_eq!(report.metadata.resource_schema_version, TEST_RESOURCE_SCHEMA_VERSION);
        assert!(!report.metadata.strict, "default mode should not be strict");
        assert_eq!(report.metadata.severity_level, Severity::Info);
        assert_eq!(report.metadata.resources_scanned, 1);
        assert_eq!(report.diagnostics.len(), 5);
    }

    #[test]
    fn build_report_empty_diagnostics() {
        let model = minimal_model();
        let report = build_report_with_versions(
            vec![],
            &model,
            0,
            None,
            true,
            Severity::Error,
            String::new(),
            TEST_CFN_LINT_VERSION.to_string(),
            TEST_RESOURCE_SCHEMA_VERSION.to_string(),
        );
        assert_eq!(report.metadata.rules_evaluated, 0);
        assert_eq!(report.metadata.counts.fatal, 0);
        assert_eq!(report.metadata.counts.errors, 0);
        assert_eq!(report.metadata.counts.warnings, 0);
        assert!(report.metadata.strict, "strict mode should be enabled");
        assert_eq!(report.metadata.severity_level, Severity::Error);
        assert!(report.diagnostics.is_empty());
    }

    #[test]
    fn build_report_debug_severity_counted() {
        let model = minimal_model();
        let diags = vec![Diagnostic { severity: Severity::Debug, message: "dbg".into(), ..default_diag() }];
        let report = build_report_with_versions(
            diags,
            &model,
            0,
            None,
            false,
            Severity::Debug,
            String::new(),
            TEST_CFN_LINT_VERSION.to_string(),
            TEST_RESOURCE_SCHEMA_VERSION.to_string(),
        );
        assert_eq!(report.metadata.counts.debug, 1);
        assert_eq!(report.metadata.counts.informational, 0);
    }

    #[test]
    fn build_rule_list_sorted_by_id() {
        let mut meta = HashMap::new();
        meta.insert(
            "E3012".into(),
            RuleMetadataEntry {
                category: Some("schema".into()),
                description: "Type check".into(),
                severity: Severity::Error,
                origin: RuleOrigin::Engine,
            },
        );
        meta.insert(
            "E0001".into(),
            RuleMetadataEntry {
                category: Some("structure".into()),
                description: "Resources".into(),
                severity: Severity::Error,
                origin: RuleOrigin::Engine,
            },
        );
        meta.insert(
            "W3045".into(),
            RuleMetadataEntry {
                category: Some("schema".into()),
                description: "Enum".into(),
                severity: Severity::Warn,
                origin: RuleOrigin::Engine,
            },
        );
        let rules = build_rule_list(&meta, &HashMap::new());
        assert_eq!(rules.len(), 3);
        assert_eq!(rules[0].id, "E0001");
        assert_eq!(rules[1].id, "E3012");
        assert_eq!(rules[2].id, "W3045");
    }

    #[test]
    fn build_rule_list_uses_stored_severity() {
        let mut meta = HashMap::new();
        meta.insert(
            "F3012".into(),
            RuleMetadataEntry {
                category: Some("schema".into()),
                description: "desc".into(),
                severity: Severity::Fatal,
                origin: RuleOrigin::Engine,
            },
        );
        meta.insert(
            "E3012".into(),
            RuleMetadataEntry {
                category: Some("schema".into()),
                description: "desc".into(),
                severity: Severity::Error,
                origin: RuleOrigin::Engine,
            },
        );
        meta.insert(
            "W3045".into(),
            RuleMetadataEntry {
                category: Some("schema".into()),
                description: "desc".into(),
                severity: Severity::Warn,
                origin: RuleOrigin::Engine,
            },
        );
        meta.insert(
            "I9001".into(),
            RuleMetadataEntry {
                category: Some("best-practice".into()),
                description: "desc".into(),
                severity: Severity::Info,
                origin: RuleOrigin::Engine,
            },
        );
        let rules = build_rule_list(&meta, &HashMap::new());
        let find = |id: &str| rules.iter().find(|r| r.id == id).unwrap();
        assert_eq!(find("F3012").severity, Severity::Fatal);
        assert_eq!(find("E3012").severity, Severity::Error);
        assert_eq!(find("W3045").severity, Severity::Warn);
        assert_eq!(find("I9001").severity, Severity::Info);
    }

    #[test]
    fn build_rule_list_schema_category_gets_schema_origin() {
        let mut meta = HashMap::new();
        meta.insert(
            "E3012".into(),
            RuleMetadataEntry {
                category: Some("schema".into()),
                description: "desc".into(),
                severity: Severity::Error,
                origin: RuleOrigin::Schema,
            },
        );
        meta.insert(
            "E0001".into(),
            RuleMetadataEntry {
                category: Some("structure".into()),
                description: "desc".into(),
                severity: Severity::Error,
                origin: RuleOrigin::Engine,
            },
        );
        let rules = build_rule_list(&meta, &HashMap::new());
        let schema_rule = rules.iter().find(|r| r.id == "E3012").unwrap();
        assert!(matches!(schema_rule.origin, RuleOrigin::Schema));
        let struct_rule = rules.iter().find(|r| r.id == "E0001").unwrap();
        assert!(matches!(struct_rule.origin, RuleOrigin::Engine));
    }

    fn make_diag(rule_id: &str, severity: Severity, line: u32, col: u32) -> Diagnostic {
        Diagnostic {
            rule_id: rule_id.into(),
            severity,
            message: format!("msg for {}", rule_id),
            location: Some(SourceSpan { start_line: line, start_column: col, end_line: line, end_column: col }),
            ..default_diag()
        }
    }

    fn make_transform_error_diag() -> Diagnostic {
        Diagnostic {
            message: format!(
                "{} Resource with id [Fn] is invalid. 'AutoPublishAlias' must be a string or a Ref to a template parameter",
                SAM_TRANSFORM_ERROR_PREFIX
            ),
            ..make_diag(SAM_TRANSFORM_ERROR_RULE_ID, Severity::Error, 1, 1)
        }
    }

    #[test]
    fn gate_drops_non_transform_diagnostics_when_transform_error_present() {
        let mut diags = vec![
            make_diag("E3012", Severity::Error, 5, 1),
            make_transform_error_diag(),
            make_diag("I9040", Severity::Info, 7, 1),
        ];
        gate_sam_transform_errors(&mut diags);
        assert_eq!(diags.len(), 1);
        assert!(is_sam_transform_error_message(&diags[0].message));
    }

    #[test]
    fn gate_keeps_all_diagnostics_when_no_transform_error() {
        let mut diags = vec![make_diag("E3012", Severity::Error, 5, 1), make_diag("I9040", Severity::Info, 7, 1)];
        gate_sam_transform_errors(&mut diags);
        assert_eq!(diags.len(), 2);
    }

    #[test]
    fn finalize_sorts_by_severity_then_rule_number_then_location() {
        let config = ValidateConfig::default();
        let mut diags = vec![
            make_diag("W3045", Severity::Warn, 10, 1),
            make_diag("E3012", Severity::Error, 5, 1),
            make_diag("F3012", Severity::Fatal, 5, 1),
        ];
        finalize_diagnostics(&mut diags, &config);
        assert_eq!(diags.len(), 3);
        // Severity orders first: Fatal, then Error, then Warn - regardless of location.
        assert_eq!(diags[0].rule_id, "F3012");
        assert_eq!(diags[1].rule_id, "E3012");
        assert_eq!(diags[2].rule_id, "W3045");
    }

    #[test]
    fn finalize_orders_same_severity_by_rule_number() {
        let config = ValidateConfig::default();
        // Higher-numbered rule appears earlier in the file; rule number must still win.
        let mut diags = vec![make_diag("E3999", Severity::Error, 1, 1), make_diag("E3012", Severity::Error, 50, 1)];
        finalize_diagnostics(&mut diags, &config);
        assert_eq!(diags[0].rule_id, "E3012", "lower rule number sorts first within a severity");
        assert_eq!(diags[1].rule_id, "E3999");
    }

    #[test]
    fn finalize_deduplicates_same_span_rule_message() {
        let config = ValidateConfig::default();
        let d = make_diag("E3012", Severity::Error, 5, 1);
        let mut diags = vec![d.clone(), d];
        let (total_before, suppressed) = finalize_diagnostics(&mut diags, &config);
        assert_eq!(total_before, 2);
        assert_eq!(suppressed, 1);
        assert_eq!(diags.len(), 1);
    }

    #[test]
    fn finalize_keeps_f_and_e_as_separate_diagnostics() {
        let config = ValidateConfig::default();
        let mut diags = vec![make_diag("F3012", Severity::Fatal, 5, 1), make_diag("E3012", Severity::Error, 5, 1)];
        let (_, suppressed) = finalize_diagnostics(&mut diags, &config);
        assert_eq!(suppressed, 0);
        assert_eq!(diags.len(), 2);
        assert_eq!(diags[0].rule_id, "F3012");
        assert_eq!(diags[1].rule_id, "E3012");
    }

    #[test]
    fn finalize_severity_filter_retains_fatal_always() {
        let config = ValidateConfig { severity_level: Severity::Error, strict: false, ..Default::default() };
        let mut diags = vec![
            make_diag("F3012", Severity::Fatal, 1, 1),
            make_diag("E3012", Severity::Error, 2, 1),
            make_diag("W3045", Severity::Warn, 3, 1),
            Diagnostic { severity: Severity::Info, message: "info".into(), location: None, ..default_diag() },
        ];
        finalize_diagnostics(&mut diags, &config);
        assert!(
            diags.iter().all(|d| d.severity >= Severity::Error),
            "all diagnostics should be Error or above after filtering"
        );
        assert_eq!(diags.len(), 2);
    }

    #[test]
    fn finalize_different_messages_not_deduped() {
        let config = ValidateConfig::default();
        let mut d1 = make_diag("E3012", Severity::Error, 5, 1);
        let mut d2 = make_diag("E3012", Severity::Error, 5, 1);
        d1.message = "message A".into();
        d2.message = "message B".into();
        let mut diags = vec![d1, d2];
        finalize_diagnostics(&mut diags, &config);
        assert_eq!(diags.len(), 2);
    }

    /// Regression for a dedup bug where the same rule/message/line was duplicated
    /// across native and WASM builds, separated by a sibling diagnostic.
    ///
    /// Two diagnostics for rule X message M at the same line/col, separated by a sibling
    /// for the same rule but a different message M', must still be deduped. Before the fix
    /// the sort key was (line, col, severity, rule_id) which treated all three as equal;
    /// stable sort preserved insertion order [M, M', M] and `dedup_by` (consecutive-only)
    /// skipped the outer pair. HashMap iteration order means insertion order is random,
    /// so the dedup worked or failed per-process - native fired twice, WASM once.
    #[test]
    fn finalize_dedups_same_rule_message_across_sibling_with_different_message() {
        let config = ValidateConfig::default();
        let mut a1 = make_diag("W2506", Severity::Warn, 125, 1);
        let mut sib = make_diag("W2506", Severity::Warn, 125, 1);
        let mut a2 = make_diag("W2506", Severity::Warn, 125, 1);
        a1.message = "param pWebServerAMI".into();
        sib.message = "param pAppAmi".into();
        a2.message = "param pWebServerAMI".into();
        let mut diags = vec![a1, sib, a2];
        finalize_diagnostics(&mut diags, &config);
        assert_eq!(diags.len(), 2, "W2506 pWebServerAMI must dedup across sibling");
        let msgs: Vec<&str> = diags.iter().map(|d| d.message.as_str()).collect();
        assert!(msgs.contains(&"param pAppAmi"));
        assert!(msgs.contains(&"param pWebServerAMI"));
    }

    #[test]
    fn finalize_strict_upgrades_warnings_to_errors() {
        let config = ValidateConfig { strict: true, ..Default::default() };
        let mut diags = vec![
            make_diag("W3045", Severity::Warn, 1, 1),
            make_diag("E3012", Severity::Error, 2, 1),
            make_diag("F3012", Severity::Fatal, 3, 1),
        ];
        finalize_diagnostics(&mut diags, &config);
        let severity_of = |id: &str| diags.iter().find(|d| d.rule_id == id).map(|d| d.severity);
        assert_eq!(severity_of("W3045"), Some(Severity::Error), "Warn should be upgraded to Error");
        assert_eq!(severity_of("E3012"), Some(Severity::Error), "Error should stay Error");
        assert_eq!(severity_of("F3012"), Some(Severity::Fatal), "Fatal should stay Fatal");
    }

    #[test]
    fn finalize_non_strict_preserves_warning_severity() {
        let config = ValidateConfig { strict: false, ..Default::default() };
        let mut diags = vec![make_diag("W3045", Severity::Warn, 1, 1), make_diag("E3012", Severity::Error, 2, 1)];
        finalize_diagnostics(&mut diags, &config);
        let severity_of = |id: &str| diags.iter().find(|d| d.rule_id == id).map(|d| d.severity);
        assert_eq!(severity_of("W3045"), Some(Severity::Warn), "Warn should be preserved");
        assert_eq!(severity_of("E3012"), Some(Severity::Error), "Error should stay Error");
    }

    #[test]
    fn finalize_disable_builtin_rules_keeps_only_custom_and_guard() {
        let config = ValidateConfig { disable_builtin_rules: true, ..Default::default() };
        let mut diags = vec![
            make_diag("F3006", Severity::Fatal, 1, 1),
            Diagnostic { source: RuleOrigin::Custom, ..make_diag("CUSTOM001", Severity::Warn, 2, 1) },
            Diagnostic { source: RuleOrigin::Guard, ..make_diag("GUARD001", Severity::Warn, 3, 1) },
            make_diag("E3012", Severity::Error, 4, 1),
        ];
        finalize_diagnostics(&mut diags, &config);
        assert_eq!(diags.len(), 2);
        assert_eq!(diags[0].rule_id, "CUSTOM001");
        assert_eq!(diags[1].rule_id, "GUARD001");
    }

    #[test]
    fn finalize_default_config_keeps_all_origins() {
        let config = ValidateConfig::default();
        let mut diags = vec![
            make_diag("F3006", Severity::Fatal, 1, 1),
            Diagnostic { source: RuleOrigin::Custom, ..make_diag("CUSTOM001", Severity::Warn, 2, 1) },
        ];
        finalize_diagnostics(&mut diags, &config);
        assert_eq!(diags.len(), 2);
    }

    #[test]
    fn enrich_adds_phase_and_description() {
        let model = minimal_model();
        let meta = meta_map();
        let mut diags = vec![Diagnostic {
            rule_id: "E3012".into(),
            severity: Severity::Error,
            message: "x".into(),
            entity: Entity::resource("Bucket", Some("AWS::S3::Bucket".into())),
            category: Some(Category::Schema.as_str().into()),
            ..default_diag()
        }];
        enrich_diagnostics(&mut diags, &model, &meta, &HashMap::new(), &DetailLevel::Detailed);
        assert_eq!(diags[0].phase, Some(Phase::Lint));
        assert!(diags[0].rule_description.is_some(), "enriched diagnostic should have rule_description");
    }

    #[test]
    fn enrich_parse_category_gets_parse_phase() {
        let model = minimal_model();
        let meta = meta_map();
        let mut diags = vec![Diagnostic {
            rule_id: "F0000".into(),
            severity: Severity::Fatal,
            message: "dup".into(),
            category: Some(Category::Structure.as_str().into()),
            phase: Some(Phase::Parse),
            ..default_diag()
        }];
        enrich_diagnostics(&mut diags, &model, &meta, &HashMap::new(), &DetailLevel::Detailed);
        assert_eq!(diags[0].phase, Some(Phase::Parse));
    }

    #[test]
    fn enrich_fatal_rule_gets_schema_phase() {
        let model = minimal_model();
        let meta = meta_map();
        let mut diags = vec![Diagnostic {
            rule_id: "F3012".into(),
            severity: Severity::Fatal,
            message: "x".into(),
            ..default_diag()
        }];
        enrich_diagnostics(&mut diags, &model, &meta, &HashMap::new(), &DetailLevel::Detailed);
        assert_eq!(diags[0].phase, Some(Phase::Schema));
    }

    #[test]
    fn enrich_custom_rule_gets_no_phase() {
        let model = minimal_model();
        let meta = meta_map();
        let mut diags = vec![Diagnostic {
            rule_id: "Firewall".into(),
            severity: Severity::Error,
            message: "x".into(),
            source: RuleOrigin::Custom,
            ..default_diag()
        }];
        enrich_diagnostics(&mut diags, &model, &meta, &HashMap::new(), &DetailLevel::Detailed);
        assert_eq!(diags[0].phase, None, "custom rules must not be assigned a phase");
    }

    #[test]
    fn enrich_full_format_builds_context() {
        let model = minimal_model();
        let meta = meta_map();
        let mut diags = vec![Diagnostic {
            rule_id: "E3012".into(),
            severity: Severity::Error,
            message: "x".into(),
            entity: Entity::resource("Bucket", Some("AWS::S3::Bucket".into())),
            property_path: Some("Properties.BucketName".into()),
            ..default_diag()
        }];
        enrich_diagnostics(&mut diags, &model, &meta, &HashMap::new(), &DetailLevel::Detailed);
        assert!(diags[0].context.is_some(), "enriched diagnostic should have context");
    }

    #[test]
    fn enrich_standard_format_skips_enrichment() {
        let model = minimal_model();
        let meta = meta_map();
        let mut diags = vec![Diagnostic {
            rule_id: "E3012".into(),
            severity: Severity::Error,
            message: "x".into(),
            entity: Entity::resource("Bucket", Some("AWS::S3::Bucket".into())),
            property_path: Some("Properties.BucketName".into()),
            ..default_diag()
        }];
        enrich_diagnostics(&mut diags, &model, &meta, &HashMap::new(), &DetailLevel::Standard);
        assert!(diags[0].phase.is_none(), "unenriched diagnostic should have no phase");
        assert!(diags[0].rule_description.is_none(), "unenriched diagnostic should have no rule_description");
        assert!(diags[0].context.is_none(), "unenriched diagnostic should have no context");
    }

    #[test]
    fn make_resource_diagnostic_known_rule() {
        let model = minimal_model();
        let diag = make_resource_diagnostic(
            "E3012",
            "Type mismatch on BucketName",
            &model,
            "Bucket",
            "Properties.BucketName",
            Some("Use a string"),
        );
        assert_eq!(diag.rule_id, "E3012");
        assert_eq!(diag.severity, Severity::Error);
        assert_eq!(diag.resource_logical_id(), Some("Bucket"));
        assert_eq!(diag.suggested_fix.as_deref(), Some("Use a string"));
    }

    #[test]
    #[should_panic(expected = "Rule 'XBOGUS' not found in RULE_REGISTRY")]
    fn make_resource_diagnostic_unknown_rule_panics() {
        let model = minimal_model();
        make_resource_diagnostic("XBOGUS", "msg", &model, "Bucket", "", None);
    }

    #[test]
    fn make_resource_diagnostic_empty_resource_id() {
        let model = minimal_model();
        let diag = make_resource_diagnostic("E3012", "msg", &model, "", "", None);
        assert!(diag.entity.is_none(), "diagnostic without resource_id should have no entity");
    }

    #[test]
    fn build_context_no_resource_returns_none() {
        let model = minimal_model();
        assert!(build_context("E3012", None, "Properties.X", &model).is_none(), "no resource should return None");
    }

    #[test]
    fn build_context_unknown_rule_returns_none() {
        let model = minimal_model();
        assert!(
            build_context("XUNKNOWN", Some("Bucket"), "Properties.X", &model).is_none(),
            "unknown rule should return None"
        );
    }

    #[test]
    fn build_context_e3012_with_property_path() {
        let model = minimal_model();
        let ctx = build_context("E3012", Some("Bucket"), "Properties.BucketName", &model)
            .expect("E3012 with property path should return context");
        assert!(ctx.actual_value.is_some(), "context should have actual_value");
    }

    #[test]
    fn build_context_runtime_rules_carry_actual_value_and_lifecycle() {
        let yaml = br#"
Resources:
  Fn:
    Type: AWS::Lambda::Function
    Properties:
      Runtime: nodejs4.3
"#;
        let model = SemanticModel::from_bytes(yaml).expect("model with lambda runtime");
        for (rule_id, expected_lifecycle) in
            [("E2533", "end-of-life"), ("E2531", "create-blocked"), ("W2531", "deprecated")]
        {
            let ctx = build_context(rule_id, Some("Fn"), "Properties.Runtime", &model)
                .unwrap_or_else(|| panic!("{rule_id} should return context"));
            assert_eq!(
                ctx.actual_value.as_ref().and_then(|v| v.as_str()),
                Some("nodejs4.3"),
                "{rule_id} context should carry the offending runtime string"
            );
            assert_eq!(ctx.lifecycle.as_deref(), Some(expected_lifecycle), "{rule_id} lifecycle marker");
        }
    }

    #[test]
    fn build_context_runtime_omits_actual_value_when_branches_disagree() {
        // Runtime driven by Fn::If resolves to a different value per branch, and the
        // emitter produces one diagnostic per branch. Attaching one branch's value to
        // all would contradict the sibling messages, so no actual_value is set; the
        // lifecycle marker is still safe to attach.
        let yaml = br#"
Parameters:
  Env:
    Type: String
Conditions:
  IsProd: !Equals [!Ref Env, prod]
Resources:
  Fn:
    Type: AWS::Lambda::Function
    Properties:
      Runtime: !If [IsProd, dotnetcore2.1, nodejs4.3]
"#;
        let model = SemanticModel::from_bytes(yaml).expect("model with conditional runtime");
        let ctx = build_context("E2533", Some("Fn"), "Properties.Runtime", &model)
            .expect("E2533 should still return context (lifecycle)");
        assert_eq!(ctx.lifecycle.as_deref(), Some("end-of-life"), "lifecycle is unconditionally safe");
        assert!(
            ctx.actual_value.is_none(),
            "actual_value must be omitted when branches resolve to different runtimes, got {:?}",
            ctx.actual_value
        );
    }

    #[test]
    fn backfill_locations_only_fills_missing_and_resolves_resource_property() {
        let yaml = br#"
Resources:
  Bucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: my-bucket
"#;
        let model = SemanticModel::from_bytes(yaml).expect("model");
        let existing = SourceSpan { start_line: 999, start_column: 1, end_line: 999, end_column: 2 };
        let mut diags = vec![
            // Missing location: should be backfilled from the resource property span.
            Diagnostic {
                rule_id: "E3012".into(),
                severity: Severity::Error,
                message: "x".into(),
                entity: Entity::resource("Bucket", None),
                property_path: Some("Properties.BucketName".into()),
                ..default_diag()
            },
            // Already located: must be left untouched.
            Diagnostic {
                rule_id: "E3013".into(),
                severity: Severity::Error,
                message: "y".into(),
                location: Some(existing),
                ..default_diag()
            },
        ];
        backfill_locations(&mut diags, &model);
        assert!(diags[0].location.is_some(), "missing location should be backfilled");
        assert_ne!(diags[0].location, Some(UNKNOWN_SPAN), "backfilled location must be a real span");
        assert_eq!(diags[1].location, Some(existing), "existing location must be preserved");
    }

    #[test]
    fn backfill_entities_derives_from_entity_paths_without_overriding() {
        let model = minimal_model();
        let mut diags = vec![
            // Resource finding: entity was attached at emission and must be kept.
            Diagnostic {
                rule_id: "E3012".into(),
                severity: Severity::Error,
                message: "x".into(),
                entity: Entity::resource("Bucket", None),
                ..default_diag()
            },
            // Non-resource entity finding: derived from the section-absolute path.
            Diagnostic {
                rule_id: "W2001".into(),
                severity: Severity::Warn,
                message: "y".into(),
                property_path: Some("Parameters/MyParam".into()),
                ..default_diag()
            },
            // Template-level finding: no entity.
            Diagnostic { rule_id: "F0001".into(), severity: Severity::Fatal, message: "z".into(), ..default_diag() },
        ];
        backfill_entities(&mut diags, &model);
        let resource = diags[0].entity.as_ref().expect("resource entity preserved");
        assert_eq!(resource.logical_id, "Bucket");
        assert_eq!(resource.entity_type, EntityType::Resource);
        assert_eq!(
            resource.resource_type.as_deref(),
            Some("AWS::S3::Bucket"),
            "missing resource type is filled from the model"
        );
        let parameter = diags[1].entity.as_ref().expect("parameter entity derived from path");
        assert_eq!(parameter.logical_id, "MyParam");
        assert_eq!(parameter.entity_type, EntityType::Parameter);
        assert_eq!(parameter.resource_type, None);
        assert!(diags[2].entity.is_none(), "template-level finding has no entity");
    }

    #[test]
    fn build_context_e3012_empty_path_returns_none() {
        let model = minimal_model();
        let ctx = build_context("E3012", Some("Bucket"), "", &model);
        assert!(ctx.is_none(), "E3012 with empty path should return None");
    }

    #[test]
    fn build_context_f3002_extracts_property_name() {
        let model = minimal_model();
        let ctx = build_context("F3002", Some("Bucket"), "Properties.BucketName", &model)
            .expect("F3002 should return context");
        assert_eq!(ctx.property.as_deref(), Some("BucketName"));
    }

    #[test]
    fn build_context_w3042_sets_deprecated_lifecycle() {
        let model = minimal_model();
        let ctx = build_context("W9009", Some("Bucket"), "", &model).expect("W9009 should return context");
        assert_eq!(ctx.lifecycle.as_deref(), Some("deprecated"));
    }

    #[test]
    fn build_context_i3043_sets_create_only_lifecycle() {
        let model = minimal_model();
        let ctx = build_context("I9001", Some("Bucket"), "", &model).expect("I9001 should return context");
        assert_eq!(ctx.lifecycle.as_deref(), Some("create-only"));
    }

    #[test]
    fn build_context_w9054_sets_write_only_lifecycle() {
        let model = minimal_model();
        let ctx = build_context("W9054", Some("Bucket"), "", &model).expect("W9054 should return context");
        assert_eq!(ctx.lifecycle.as_deref(), Some("write-only"));
    }

    #[test]
    fn parse_diagnostic_debug_severity() {
        let model = minimal_model();
        let val = serde_json::json!({
            "rule_id": "D9999",
            "severity": Severity::Debug.as_str(),
            "message": "dbg"
        });
        let diag = parse_diagnostic(&val, &model, Some(&RuleOrigin::Custom)).unwrap();
        assert_eq!(diag.severity, Severity::Debug);
    }

    #[test]
    fn parse_diagnostic_no_resource_no_location_resolves_via_section_span() {
        let model = minimal_model();
        let val = serde_json::json!({
            "rule_id": "F0001",
            "severity": Severity::Fatal.as_str(),
            "message": "no resources"
        });
        let diag = parse_diagnostic(&val, &model, None).unwrap();
        assert_eq!(diag.rule_id, "F0001");
    }

    #[test]
    fn parse_diagnostic_builtin_rule_category_comes_from_registry() {
        let model = minimal_model();
        let val = serde_json::json!({
            "rule_id": "E3012",
            "severity": Severity::Error.as_str(),
            "message": "x"
        });
        let diag = parse_diagnostic(&val, &model, None).unwrap();
        let expected = lookup_rule("E3012").unwrap().category.as_str();
        assert_eq!(diag.category.as_deref(), Some(expected));
    }

    #[test]
    fn build_context_e3030_resolves_actual_value() {
        let model = minimal_model();
        let ctx = build_context("E3030", Some("Bucket"), "Properties.BucketName", &model)
            .expect("E3030 should return context");
        assert!(ctx.actual_value.is_some(), "E3030 context should have actual_value");
    }

    #[test]
    fn build_context_f3006_adds_resource_type() {
        let model = minimal_model();
        let ctx = build_context("F3006", Some("Bucket"), "", &model).expect("F3006 should return context");
        let extra = ctx.extra.unwrap();
        assert_eq!(extra.get("resource_type").and_then(|v| v.as_str()), Some("AWS::S3::Bucket"));
    }

    #[test]
    fn build_context_f3003_noop_returns_none() {
        let model = minimal_model();
        assert!(build_context("F3003", Some("Bucket"), "", &model).is_none(), "F3003 should return None");
    }

    #[test]
    fn build_context_e3053_with_property_path() {
        let model = minimal_model();
        let ctx = build_context("E3053", Some("Bucket"), "Properties.BucketName", &model)
            .expect("E3053 should return context");
        assert!(ctx.actual_value.is_some(), "E3053 context should have actual_value");
    }

    #[test]
    fn build_context_e3053_empty_path_returns_none() {
        let model = minimal_model();
        assert!(
            build_context("E3053", Some("Bucket"), "", &model).is_none(),
            "E3053 with empty path should return None"
        );
    }

    #[test]
    fn build_context_e2501_with_condition() {
        let yaml = br#"
AWSTemplateFormatVersion: "2010-09-09"
Conditions:
  IsProd:
    !Equals [!Ref "AWS::Region", "us-east-1"]
Resources:
  Bucket:
    Type: AWS::S3::Bucket
    Condition: IsProd
"#;
        let model = SemanticModel::from_bytes(yaml).expect("model with condition");
        let ctx =
            build_context("W2503", Some("Bucket"), "", &model).expect("W2503 with condition should return context");
        let extra = ctx.extra.unwrap();
        assert!(extra.contains_key("source_condition"));
    }

    #[test]
    fn build_context_e2501_without_condition_returns_none() {
        let model = minimal_model();
        assert!(
            build_context("W2503", Some("Bucket"), "", &model).is_none(),
            "W2503 without condition should return None"
        );
    }

    #[test]
    fn enrich_preserves_existing_phase_and_description() {
        let model = minimal_model();
        let meta = meta_map();
        let mut diags = vec![Diagnostic {
            rule_id: "E3012".into(),
            severity: Severity::Error,
            message: "x".into(),
            phase: Some(Phase::Lint),
            rule_description: Some("custom desc".into()),
            ..default_diag()
        }];
        enrich_diagnostics(&mut diags, &model, &meta, &HashMap::new(), &DetailLevel::Standard);
        assert_eq!(diags[0].phase, Some(Phase::Lint));
        assert_eq!(diags[0].rule_description.as_deref(), Some("custom desc"));
    }

    #[test]
    fn finalize_warning_level_filters_info() {
        let config = ValidateConfig { severity_level: Severity::Warn, ..Default::default() };
        let mut diags = vec![
            make_diag("F3012", Severity::Fatal, 1, 1),
            make_diag("E3012", Severity::Error, 2, 1),
            make_diag("W3045", Severity::Warn, 3, 1),
            Diagnostic { severity: Severity::Info, message: "info".into(), location: None, ..default_diag() },
        ];
        finalize_diagnostics(&mut diags, &config);
        assert!(
            diags.iter().all(|d| d.severity >= Severity::Warn),
            "all diagnostics should be Warn or above after filtering"
        );
        assert_eq!(diags.len(), 3);
    }

    #[test]
    fn finalize_different_property_paths_not_deduped() {
        let config = ValidateConfig::default();
        let mut d1 = make_diag("E3012", Severity::Error, 5, 1);
        let mut d2 = make_diag("E3012", Severity::Error, 5, 1);
        d1.property_path = Some("Properties.A".into());
        d2.property_path = Some("Properties.B".into());
        let mut diags = vec![d1, d2];
        finalize_diagnostics(&mut diags, &config);
        assert_eq!(diags.len(), 2);
    }

    #[test]
    fn build_rule_list_uses_stored_severity_for_any_rule_id() {
        let mut meta = HashMap::new();
        meta.insert(
            "X9999".into(),
            RuleMetadataEntry {
                category: Some("custom".into()),
                description: "desc".into(),
                severity: Severity::Error,
                origin: RuleOrigin::Engine,
            },
        );
        let rules = build_rule_list(&meta, &HashMap::new());
        assert_eq!(rules[0].severity, Severity::Error);
    }

    #[test]
    fn engine_type_default_is_composite() {
        assert_eq!(EngineType::default(), EngineType::Composite);
    }

    #[test]
    fn engine_type_as_str_and_display_name_every_variant() {
        for (engine, expected) in
            [(EngineType::Rego, "Rego"), (EngineType::Cel, "CEL"), (EngineType::Composite, "Composite")]
        {
            assert_eq!(engine.as_str(), expected);
            assert_eq!(engine.to_string(), expected, "Display must match as_str");
        }
    }

    #[test]
    fn engine_type_parse_accepts_case_insensitive_input() {
        assert_eq!(EngineType::parse("rego"), Ok(EngineType::Rego));
        assert_eq!(EngineType::parse("REGO"), Ok(EngineType::Rego));
        assert_eq!(EngineType::parse("Cel"), Ok(EngineType::Cel));
        assert_eq!(EngineType::parse("CEL"), Ok(EngineType::Cel));
        assert_eq!(EngineType::parse("composite"), Ok(EngineType::Composite));
        assert_eq!(EngineType::parse("COMPOSITE"), Ok(EngineType::Composite));
    }

    #[test]
    fn engine_type_parse_returns_error_for_unknown_value() {
        let error =
            EngineType::parse("unknown").expect_err("an unknown engine selector must return an error, not a default");
        assert!(
            error.contains("Unknown engine type 'unknown'")
                && error.contains("rego")
                && error.contains("cel")
                && error.contains("composite"),
            "the error must name the bad selector and all three valid options, got: {error}"
        );
    }

    #[test]
    fn catch_panics_maps_panic_to_caller_error_type() {
        // The bindings rely on this to keep a panic during engine construction from
        // unwinding across the FFI boundary: it must become the caller's own error type.
        #[derive(Debug, PartialEq)]
        struct BindingError(String);
        let result: Result<(), BindingError> = catch_panics(|| panic!("engine init blew up"), BindingError);
        let error = result.expect_err("a panic must be converted to the caller's error type");
        assert!(error.0.contains("engine init blew up"), "the panic payload must be carried, got: {}", error.0);
    }

    #[test]
    fn catch_panics_passes_through_ok_and_err_without_wrapping() {
        let ok: Result<i32, String> = catch_panics(|| Ok(7), |m| m);
        assert_eq!(ok, Ok(7), "a non-panicking Ok must pass through unchanged");
        let err: Result<i32, String> = catch_panics(|| Err("plain error".to_string()), |_| "panic".to_string());
        assert_eq!(err, Err("plain error".to_string()), "a returned Err must pass through, not be treated as a panic");
    }

    #[test]
    fn validate_catching_panics_converts_panic_to_structured_error() {
        let error = validate_catching_panics(|| panic!("simulated invariant violation"))
            .expect_err("a panic must be converted into a structured error, not propagated");
        match error {
            ValidationError::Engine(message) => assert!(
                message.contains("Internal validation error") && message.contains("simulated invariant violation"),
                "error must wrap the panic payload as a structured engine error, got: {message}"
            ),
            other => panic!("expected ValidationError::Engine, got {other:?}"),
        }
    }

    #[test]
    fn validate_catching_panics_passes_success_through_unchanged() {
        let model = minimal_model();
        let report = validate_catching_panics(|| {
            Ok(build_report_with_versions(
                vec![],
                &model,
                0,
                Some(7),
                false,
                Severity::Info,
                "inline".to_string(),
                TEST_CFN_LINT_VERSION.to_string(),
                TEST_RESOURCE_SCHEMA_VERSION.to_string(),
            ))
        })
        .expect("a non-panicking Ok result must pass through the guard unchanged");
        assert_eq!(report.metadata.rules_evaluated, 7, "the guard must return the closure's report verbatim");
    }

    /// A test engine that fails on demand, to prove that engine failures surface
    /// as errors (exceptions) and are never absorbed into the diagnostics list.
    enum Explosion {
        Panic,
        ReturnErr,
    }

    struct ExplodingEngine {
        mode: Explosion,
        metadata: HashMap<String, RuleMetadataEntry>,
        metric: PhaseMetric,
    }

    impl ExplodingEngine {
        fn new(mode: Explosion) -> Self {
            Self { mode, metadata: HashMap::new(), metric: PhaseMetric { duration_ms: 0.0 } }
        }
    }

    impl ValidationEngine for ExplodingEngine {
        fn engine_name(&self) -> &str {
            "exploding-test-engine"
        }

        fn evaluate_rules(
            &self,
            _model: &Arc<SemanticModel>,
            _config: &ValidateConfig,
        ) -> Result<Vec<Diagnostic>, ValidationError> {
            match self.mode {
                Explosion::Panic => panic!("simulated engine invariant violation"),
                Explosion::ReturnErr => Err(ValidationError::Engine("Simulated engine evaluation failure".to_string())),
            }
        }

        fn list_rules(&self) -> Vec<RuleInfo> {
            Vec::new()
        }

        fn rule_metadata(&self) -> &HashMap<String, RuleMetadataEntry> {
            &self.metadata
        }

        fn external_rule_metadata(&self) -> HashMap<String, RuleMetadataEntry> {
            HashMap::new()
        }

        fn init_metric(&self) -> &PhaseMetric {
            &self.metric
        }
    }

    const WELL_FORMED_TEMPLATE: &[u8] = b"Resources:\n  Bucket:\n    Type: AWS::S3::Bucket\n";

    struct EnrichmentTrackingEngine {
        external_metadata_requests: AtomicUsize,
        metadata: HashMap<String, RuleMetadataEntry>,
        metric: PhaseMetric,
    }

    impl EnrichmentTrackingEngine {
        fn new() -> Self {
            Self {
                external_metadata_requests: AtomicUsize::new(0),
                metadata: build_rule_metadata_map(),
                metric: PhaseMetric { duration_ms: 0.0 },
            }
        }
    }

    impl ValidationEngine for EnrichmentTrackingEngine {
        fn engine_name(&self) -> &str {
            "enrichment-tracking-engine"
        }

        fn evaluate_rules(
            &self,
            _model: &Arc<SemanticModel>,
            _config: &ValidateConfig,
        ) -> Result<Vec<Diagnostic>, ValidationError> {
            Ok(vec![Diagnostic {
                rule_id: "E3012".into(),
                severity: Severity::Error,
                message: "tracking diagnostic".into(),
                ..default_diag()
            }])
        }

        fn list_rules(&self) -> Vec<RuleInfo> {
            Vec::new()
        }

        fn rule_metadata(&self) -> &HashMap<String, RuleMetadataEntry> {
            &self.metadata
        }

        fn external_rule_metadata(&self) -> HashMap<String, RuleMetadataEntry> {
            self.external_metadata_requests.fetch_add(1, Ordering::SeqCst);
            HashMap::new()
        }

        fn init_metric(&self) -> &PhaseMetric {
            &self.metric
        }
    }

    #[test]
    fn standard_detail_level_bypasses_enrichment_metadata_lookup() {
        let schema_validator = SchemaValidator::default();
        let standard_engine = EnrichmentTrackingEngine::new();
        let standard_report = validate_bytes(
            &standard_engine,
            &schema_validator,
            WELL_FORMED_TEMPLATE,
            ValidateConfig { detail_level: DetailLevel::Standard, ..Default::default() },
        )
        .expect("STANDARD validation must succeed");

        assert_eq!(
            standard_engine.external_metadata_requests.load(Ordering::SeqCst),
            0,
            "STANDARD must not request metadata used only by diagnostic enrichment"
        );
        let standard_diagnostic = standard_report
            .diagnostics
            .iter()
            .find(|diagnostic| diagnostic.message == "tracking diagnostic")
            .expect("the tracking diagnostic must be present");
        assert!(standard_diagnostic.phase.is_none());
        assert!(standard_diagnostic.rule_description.is_none());
        assert!(standard_diagnostic.context.is_none());

        let detailed_engine = EnrichmentTrackingEngine::new();
        let detailed_report = validate_bytes(
            &detailed_engine,
            &schema_validator,
            WELL_FORMED_TEMPLATE,
            ValidateConfig { detail_level: DetailLevel::Detailed, ..Default::default() },
        )
        .expect("DETAILED validation must succeed");

        assert_eq!(
            detailed_engine.external_metadata_requests.load(Ordering::SeqCst),
            1,
            "DETAILED must request external metadata for diagnostic enrichment"
        );
        let detailed_diagnostic = detailed_report
            .diagnostics
            .iter()
            .find(|diagnostic| diagnostic.message == "tracking diagnostic")
            .expect("the tracking diagnostic must be present");
        assert_eq!(detailed_diagnostic.phase, Some(Phase::Lint));
        assert!(detailed_diagnostic.rule_description.is_some());
    }

    /// A test engine that records specified budget kinds during evaluation.
    struct BudgetExhaustingEngine {
        kinds: Vec<template_model::BudgetKind>,
        metadata: HashMap<String, RuleMetadataEntry>,
        metric: PhaseMetric,
    }

    impl BudgetExhaustingEngine {
        fn new(kinds: Vec<template_model::BudgetKind>) -> Self {
            Self { kinds, metadata: build_rule_metadata_map(), metric: PhaseMetric { duration_ms: 0.0 } }
        }
    }

    impl ValidationEngine for BudgetExhaustingEngine {
        fn engine_name(&self) -> &str {
            "budget-test-engine"
        }

        fn evaluate_rules(
            &self,
            model: &Arc<SemanticModel>,
            _config: &ValidateConfig,
        ) -> Result<Vec<Diagnostic>, ValidationError> {
            for kind in &self.kinds {
                model.record_budget_exhaustion(*kind);
            }
            Ok(Vec::new())
        }

        fn list_rules(&self) -> Vec<RuleInfo> {
            Vec::new()
        }

        fn rule_metadata(&self) -> &HashMap<String, RuleMetadataEntry> {
            &self.metadata
        }

        fn external_rule_metadata(&self) -> HashMap<String, RuleMetadataEntry> {
            HashMap::new()
        }

        fn init_metric(&self) -> &PhaseMetric {
            &self.metric
        }
    }

    #[test]
    fn budget_exhaustion_emits_one_warning_with_metadata() {
        use template_model::BudgetKind;
        let engine = BudgetExhaustingEngine::new(vec![
            BudgetKind::ResolverDepth,
            BudgetKind::EnumExpansion,
            BudgetKind::ResolverDepth, // duplicate — must not create a second entry
        ]);
        let schema_validator = SchemaValidator::default();
        let report = validate_bytes(
            &engine,
            &schema_validator,
            WELL_FORMED_TEMPLATE,
            ValidateConfig { detail_level: DetailLevel::Detailed, ..Default::default() },
        )
        .expect("validation must succeed");

        let budget_warnings: Vec<_> = report.diagnostics.iter().filter(|d| d.rule_id == "W9052").collect();
        assert_eq!(budget_warnings.len(), 1, "exactly one aggregate budget warning must be emitted");
        let w = budget_warnings[0];
        assert_eq!(w.severity, Severity::Warn);
        assert_eq!(
            w.rule_description.as_deref(),
            Some("Deterministic validation budgets were exhausted; see report metadata for completeness impact")
        );
        assert_eq!(w.category.as_deref(), Some(Category::Structure.as_str()));
        assert_eq!(w.source, RuleOrigin::Engine);
        assert_eq!(w.phase, Some(Phase::Lint));

        assert_eq!(report.status, ReportStatus::AnalysisIncomplete);
        let budget_exhaustions =
            report.metadata.budget_exhaustions.as_deref().expect("exhausted budgets must be present in metadata");
        assert_eq!(budget_exhaustions.len(), 2, "two distinct kinds, not three");
        // Deterministic order (BTreeSet)
        assert_eq!(budget_exhaustions[0].kind, "resolverDepth");
        assert_eq!(budget_exhaustions[0].description, BudgetKind::ResolverDepth.description());
        assert_eq!(budget_exhaustions[0].limit, BudgetKind::ResolverDepth.limit());
        assert_eq!(budget_exhaustions[1].kind, "enumExpansion");
        assert_eq!(budget_exhaustions[1].description, BudgetKind::EnumExpansion.description());

        // Context must be present at the DETAILED detail level.
        assert!(w.context.is_some(), "budget warning context must be attached at the DETAILED detail level");
        let ctx = w.context.as_ref().unwrap();
        let extra = ctx.extra.as_ref().expect("context.extra must be populated");
        assert!(extra.contains_key("budgetExhaustions"));
    }

    #[test]
    fn standard_detail_level_skips_budget_warning_enrichment() {
        use template_model::BudgetKind;

        let engine = BudgetExhaustingEngine::new(vec![BudgetKind::ResolverDepth]);
        let schema_validator = SchemaValidator::default();
        let report = validate_bytes(
            &engine,
            &schema_validator,
            WELL_FORMED_TEMPLATE,
            ValidateConfig { detail_level: DetailLevel::Standard, ..Default::default() },
        )
        .expect("STANDARD validation must succeed");

        let warning = report
            .diagnostics
            .iter()
            .find(|diagnostic| diagnostic.rule_id == "W9052")
            .expect("budget exhaustion must still emit its aggregate warning");
        assert!(warning.phase.is_none());
        assert!(warning.context.is_none());

        let budget_exhaustions = report
            .metadata
            .budget_exhaustions
            .as_deref()
            .expect("budget metadata must remain available without diagnostic enrichment");
        assert_eq!(budget_exhaustions.len(), 1);
        assert_eq!(budget_exhaustions[0].kind, "resolverDepth");
    }

    #[test]
    fn context_only_required_property_combinations_keeps_report_status_ok() {
        use template_model::BudgetKind;

        let choice_count = BudgetKind::RequiredPropertyCombinations.limit() as usize + 1;
        let choices: Vec<String> = (0..choice_count).map(|index| format!("Choice{index:03}")).collect();
        let properties: serde_json::Map<String, serde_json::Value> =
            choices.iter().map(|choice| (choice.clone(), serde_json::json!({"type": "string"}))).collect();
        let schema_validator = SchemaValidator::try_with_additional_schemas(vec![(
            "AWS::Test::RequiredCombinationBudget",
            serde_json::json!({
                "properties": properties,
                "anyOf": [{"requiredOr": choices}],
                "additionalProperties": false
            }),
        )])
        .expect("test schema must compile");
        let template = b"Resources:\n  R:\n    Type: AWS::Test::RequiredCombinationBudget\n    Properties: {}\n";
        let engine = BudgetExhaustingEngine::new(Vec::new());

        let report = validate_bytes(&engine, &schema_validator, template, ValidateConfig::default())
            .expect("validation must succeed");

        let budget_warnings: Vec<_> =
            report.diagnostics.iter().filter(|diagnostic| diagnostic.rule_id == "W9052").collect();
        assert_eq!(budget_warnings.len(), 1);
        assert_eq!(report.status, ReportStatus::Ok);
        let budget_exhaustions =
            report.metadata.budget_exhaustions.as_deref().expect("context-only exhaustion must be present in metadata");
        assert_eq!(budget_exhaustions.len(), 1);
        assert_eq!(budget_exhaustions[0].kind, "requiredPropertyCombinations");
        assert_eq!(budget_exhaustions[0].description, BudgetKind::RequiredPropertyCombinations.description());
        assert_eq!(budget_exhaustions[0].limit, BudgetKind::RequiredPropertyCombinations.limit());
        assert!(!budget_exhaustions[0].analysis_incomplete);
    }

    #[test]
    fn severity_filtering_removes_warning_but_metadata_persists() {
        use template_model::BudgetKind;
        let engine = BudgetExhaustingEngine::new(vec![BudgetKind::ResolverDepth]);
        let schema_validator = SchemaValidator::default();
        let report = validate_bytes(
            &engine,
            &schema_validator,
            WELL_FORMED_TEMPLATE,
            ValidateConfig { severity_level: Severity::Error, ..Default::default() },
        )
        .expect("validation must succeed");

        let budget_warnings: Vec<_> = report.diagnostics.iter().filter(|d| d.rule_id == "W9052").collect();
        assert!(budget_warnings.is_empty(), "severity filter must remove the warning");
        assert_eq!(
            report.status,
            ReportStatus::AnalysisIncomplete,
            "status reflects correctness-affecting exhaustion regardless of filter"
        );
        assert!(report.metadata.budget_exhaustions.is_some());
    }

    #[test]
    fn parse_error_sets_error_status_without_budget_warning() {
        let schema_validator = SchemaValidator::default();
        let engine = BudgetExhaustingEngine::new(vec![]);
        let report = validate_bytes_with_path(
            &engine,
            &schema_validator,
            b"{ not valid yaml or json <<<",
            ValidateConfig::default(),
            "bad.yaml".to_string(),
        )
        .expect("parse errors return Ok with error diagnostics");

        assert_eq!(report.status, ReportStatus::Error);
        assert!(report.metadata.budget_exhaustions.is_none());
        let budget_warnings: Vec<_> = report.diagnostics.iter().filter(|d| d.rule_id == "W9052").collect();
        assert!(budget_warnings.is_empty(), "parse errors must not emit a budget warning");
    }

    #[test]
    fn category_filtering_removes_warning_but_metadata_persists() {
        use template_model::BudgetKind;
        let engine = BudgetExhaustingEngine::new(vec![BudgetKind::ResolverDepth]);
        let schema_validator = SchemaValidator::default();
        let filters = FilterConfig::new(
            RuleFilterConfig::default(),
            RuleFilterConfig {
                categories: vec![Category::Structure.as_str().to_string()],
                ..RuleFilterConfig::default()
            },
        );
        let report = validate_bytes(
            &engine,
            &schema_validator,
            WELL_FORMED_TEMPLATE,
            ValidateConfig { filters, ..ValidateConfig::default() },
        )
        .expect("validation must succeed");

        assert!(report.diagnostics.iter().all(|diagnostic| diagnostic.rule_id != "W9052"));
        assert_eq!(report.status, ReportStatus::AnalysisIncomplete);
        let budget_exhaustions = report
            .metadata
            .budget_exhaustions
            .as_deref()
            .expect("exhausted budget must be present despite warning suppression");
        assert_eq!(budget_exhaustions.len(), 1);
        assert_eq!(budget_exhaustions[0].kind, "resolverDepth");
    }

    #[test]
    fn disabling_builtins_suppresses_warning_but_metadata_persists() {
        use template_model::BudgetKind;
        let engine = BudgetExhaustingEngine::new(vec![BudgetKind::ResolverDepth]);
        let schema_validator = SchemaValidator::default();
        let report = validate_bytes(
            &engine,
            &schema_validator,
            WELL_FORMED_TEMPLATE,
            ValidateConfig { disable_builtin_rules: true, ..ValidateConfig::default() },
        )
        .expect("validation must succeed");

        assert!(report.diagnostics.iter().all(|diagnostic| diagnostic.rule_id != "W9052"));
        assert_eq!(report.status, ReportStatus::AnalysisIncomplete);
        let budget_exhaustions = report
            .metadata
            .budget_exhaustions
            .as_deref()
            .expect("exhausted budget must be present despite warning suppression");
        assert_eq!(budget_exhaustions.len(), 1);
        assert_eq!(budget_exhaustions[0].kind, "resolverDepth");
    }

    #[test]
    fn non_curtailed_fixture_omits_exhaustions_and_has_ok_status() {
        let engine = BudgetExhaustingEngine::new(vec![]); // no exhaustions
        let schema_validator = SchemaValidator::default();
        let report = validate_bytes(&engine, &schema_validator, WELL_FORMED_TEMPLATE, ValidateConfig::default())
            .expect("validation must succeed");

        assert_eq!(report.status, ReportStatus::Ok);
        assert!(report.metadata.budget_exhaustions.is_none());
        let budget_warnings: Vec<_> = report.diagnostics.iter().filter(|d| d.rule_id == "W9052").collect();
        assert!(budget_warnings.is_empty());
    }

    #[test]
    fn engine_exception_surfaces_as_error_never_as_diagnostic() {
        let schema_validator = SchemaValidator::default();
        let engine = ExplodingEngine::new(Explosion::ReturnErr);
        let result = validate_bytes_with_path(
            &engine,
            &schema_validator,
            WELL_FORMED_TEMPLATE,
            ValidateConfig::default(),
            "inline".to_string(),
        );
        match result {
            Err(ValidationError::Engine(message)) => assert!(
                message.contains("Simulated engine evaluation failure"),
                "an engine exception must surface verbatim as an error, got: {message}"
            ),
            Ok(report) => panic!(
                "an engine exception must surface as Err, never as an Ok report with \
                 diagnostics; got {} diagnostics",
                report.diagnostics.len()
            ),
            Err(other) => panic!("expected ValidationError::Engine, got {other:?}"),
        }
    }

    #[test]
    fn engine_panic_is_caught_as_error_never_as_diagnostic() {
        let schema_validator = SchemaValidator::default();
        let engine = ExplodingEngine::new(Explosion::Panic);
        let result = validate_catching_panics(|| {
            validate_bytes_with_path(
                &engine,
                &schema_validator,
                WELL_FORMED_TEMPLATE,
                ValidateConfig::default(),
                "inline".to_string(),
            )
        });
        match result {
            Err(ValidationError::Engine(message)) => assert!(
                message.contains("Internal validation error")
                    && message.contains("simulated engine invariant violation"),
                "a panic must surface as a structured internal error, got: {message}"
            ),
            Ok(report) => panic!(
                "a panic must surface as Err, never as an Ok report with diagnostics; got {} \
                 diagnostics",
                report.diagnostics.len()
            ),
            Err(other) => panic!("expected ValidationError::Engine, got {other:?}"),
        }
    }
}