semver-analyzer-ts 0.0.4

TypeScript/JavaScript support for the semver-analyzer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
//! v2 Konveyor rule generation from SD pipeline results.
//!
//! Generates flat, precise rules from:
//! - Composition changes (new required wrappers, family restructuring)
//! - Composition trees (conformance: parent-child validation)
//! - Context dependency changes (provider/consumer changes)
//! - Prop↔child migration (TD removed props × SD new children)
//!
//! Rules are designed to be consumed by a fix-engine that aggregates
//! related incidents per component and builds LLM prompts. Each rule
//! fires on exactly one thing (a specific prop, component, or import)
//! and carries machine-readable fix_strategy metadata.

use crate::sd_types::{
    ChildRelationship, CompositionChangeType, CompositionTree, ConformanceCheck,
    ConformanceCheckType, SdPipelineResult, SourceLevelCategory, SourceLevelChange,
};
use semver_analyzer_core::types::MigrationTarget;
use semver_analyzer_core::{AnalysisReport, ApiChangeType};
use semver_analyzer_konveyor_core::{
    FixStrategyEntry, FrontendPatternFields, FrontendReferencedFields, KonveyorCondition,
    KonveyorRule,
};

use crate::TypeScript;
use semver_analyzer_konveyor_core::resolve_npm_package;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};

/// Generate v2 rules from SD pipeline results + TD structural data.
///
/// Returns rules that are appended to the v1 TD-generated rules.
/// The v1 rules handle renamed/removed props, type changes, CSS prefixes,
/// manifests, and dependency updates. The v2 rules add:
/// - Composition migration rules
/// - Conformance rules
/// - Context dependency rules
/// - Prop↔child migration rules (cross-referencing TD + SD)
pub fn generate_sd_rules(
    report: &AnalysisReport<TypeScript>,
    sd: &SdPipelineResult,
    pkg_cache: &HashMap<String, String>,
) -> Vec<KonveyorRule> {
    let mut rules = Vec::new();

    // Build component → package lookup from SD profiles
    let component_packages = build_component_package_map(sd, pkg_cache);

    // ── Composition change rules ────────────────────────────────────
    rules.extend(generate_composition_change_rules(sd, &component_packages));

    // ── Conformance rules ───────────────────────────────────────────
    rules.extend(generate_conformance_rules(
        &sd.composition_trees,
        &sd.conformance_checks,
        &component_packages,
    ));

    // ── Context dependency rules ────────────────────────────────────
    rules.extend(generate_context_rules(
        &sd.source_level_changes,
        &component_packages,
    ));

    // ── Prop↔child migration rules ──────────────────────────────────
    rules.extend(generate_prop_child_migration_rules(
        report,
        sd,
        &component_packages,
    ));

    // ── Cross-family child→prop migration rules ───────────────────────
    rules.extend(generate_cross_family_child_to_prop_rules(
        report,
        sd,
        &component_packages,
    ));

    // ── Deprecated↔main migration rules ─────────────────────────────
    rules.extend(generate_deprecated_migration_rules(sd, &component_packages));

    // ── Prop value conformance rules ────────────────────────────────
    rules.extend(generate_prop_value_conformance_rules(
        report,
        sd,
        &component_packages,
    ));

    // ── Required prop added rules ───────────────────────────────────
    rules.extend(generate_required_prop_added_rules(sd, &component_packages));

    // ── Test impact rules ───────────────────────────────────────────
    rules.extend(generate_test_impact_rules(
        &sd.source_level_changes,
        &component_packages,
    ));

    // ── Composition inversion rules (internal → render prop) ──────
    rules.extend(generate_composition_inversion_rules(
        sd,
        &component_packages,
    ));

    // ── Prop attribute override rules ──────────────────────────────
    rules.extend(generate_prop_attribute_override_rules(
        &sd.source_level_changes,
        sd,
        &component_packages,
    ));

    // ── CSS class removal rules ─────────────────────────────────────
    rules.extend(generate_css_class_removal_rules(&sd.removed_css_blocks));

    // ── Dead CSS class rules (prefix swap produces non-existent class) ──
    rules.extend(generate_dead_css_class_rules(
        &sd.dead_css_classes_after_swap,
    ));

    rules
}

/// Build a map from component name → npm package name.
///
/// Priority:
/// 1. Pre-computed `sd.component_packages` (available in saved reports)
/// 2. SD profiles' `file` field resolved via `pkg_cache` (available during pipeline run)
/// 3. Source-level change `component` field matched to file changes in the report
fn build_component_package_map(
    sd: &SdPipelineResult,
    pkg_cache: &HashMap<String, String>,
) -> HashMap<String, String> {
    // If the SD result already has the map (from a saved report), use it
    if !sd.component_packages.is_empty() {
        return sd.component_packages.clone();
    }

    // Build from profiles + pkg_cache
    let mut map = HashMap::new();
    for (name, profile) in &sd.new_profiles {
        if let Some(pkg) = resolve_npm_package(&profile.file, pkg_cache) {
            map.insert(name.clone(), pkg);
        }
    }
    for (name, profile) in &sd.old_profiles {
        if !map.contains_key(name) {
            if let Some(pkg) = resolve_npm_package(&profile.file, pkg_cache) {
                map.insert(name.clone(), pkg);
            }
        }
    }
    map
}

/// Look up the package for a component, with fallback.
fn pkg_for(component: &str, map: &HashMap<String, String>) -> String {
    map.get(component)
        .cloned()
        .unwrap_or_else(|| "@patternfly/react-core".to_string())
}

/// Look up the package for a component in a potentially deprecated family.
/// If the family root starts with "deprecated/" and the resolved package
/// doesn't already contain "/deprecated", appends "/deprecated" to scope
/// the rule to the deprecated import path.
fn pkg_for_deprecated(component: &str, family_root: &str, map: &HashMap<String, String>) -> String {
    let base = pkg_for(component, map);
    if family_root.starts_with("deprecated/") && !base.contains("/deprecated") {
        format!("{}/deprecated", base)
    } else {
        base
    }
}

/// Resolve the deprecated import package from a `migration_from` path.
///
/// Example: `"packages/react-core/src/deprecated/components/Select/Select.tsx"`
///        → `"@patternfly/react-core/deprecated"`
fn deprecated_pkg_from_migration_path(path: &str) -> String {
    // Extract the package directory name (e.g., "react-core" from "packages/react-core/...")
    if let Some(pkg_dir) = path
        .strip_prefix("packages/")
        .and_then(|s| s.split('/').next())
    {
        format!("@patternfly/{}/deprecated", pkg_dir)
    } else {
        "@patternfly/react-core/deprecated".to_string()
    }
}

/// Return a rule ID prefix based on whether this is a migration change.
/// Migration changes use "sd-migration-" to avoid colliding with
/// same-component evolution rules.
fn rule_prefix(migration_from: &Option<String>) -> &'static str {
    if migration_from.is_some() {
        "sd-migration"
    } else {
        "sd"
    }
}

// ── Composition change rules ────────────────────────────────────────────

fn generate_composition_change_rules(
    sd: &SdPipelineResult,
    component_packages: &HashMap<String, String>,
) -> Vec<KonveyorRule> {
    let mut rules = Vec::new();

    // Build a lookup of family members that are prop-passed on the root.
    // These should NOT be restructured as children by the LLM.
    // A member is prop-passed when:
    //   - It's a family member with no edge in the composition tree
    //   - The root has a ReactNode/ComponentType prop whose name matches
    let mut prop_passed_members: HashMap<String, Vec<String>> = HashMap::new();
    for tree in &sd.composition_trees {
        let root = &tree.root;
        let children_in_edges: HashSet<&str> =
            tree.edges.iter().map(|e| e.child.as_str()).collect();

        let root_prop_types = sd.new_component_prop_types.get(root);

        for member in &tree.family_members {
            if member == root {
                continue;
            }
            // Member has no edge — it's not a direct child or internal
            if children_in_edges.contains(member.as_str()) {
                continue;
            }
            // Check if a ReactNode prop on root matches this member
            if let Some(prop_types) = root_prop_types {
                let suffix = member.strip_prefix(root.as_str()).unwrap_or("");
                if !suffix.is_empty() {
                    let suffix_lower = suffix.to_lowercase();
                    for (prop_name, prop_type) in prop_types {
                        if prop_name == "children" {
                            continue;
                        }
                        if !prop_type.contains("ReactNode") && !prop_type.contains("ComponentType")
                        {
                            continue;
                        }
                        let prop_lower = prop_name.to_lowercase();
                        if suffix_lower.starts_with(&prop_lower)
                            || prop_lower.starts_with(&suffix_lower)
                        {
                            prop_passed_members
                                .entry(root.clone())
                                .or_default()
                                .push(format!("{} (via `{}` prop)", member, prop_name));
                        }
                    }
                }
            }
        }
    }

    for change in &sd.composition_changes {
        match &change.change_type {
            CompositionChangeType::NewRequiredChild { .. } => {
                // Skip — conformance rules already validate parent-child
                // relationships from the child's perspective (notParent).
                // Generating a "requires" rule from the parent's perspective
                // is redundant and produces false positives on code where the
                // child component is already present.
            }
            CompositionChangeType::FamilyMemberAdded { .. } => {
                // Skip — the migration rule (component-import-deprecated)
                // already lists new child components in its message with
                // guidance on how to use them. Generating a new-member rule
                // fires on every parent usage regardless of whether the new
                // component is already in use, adding noise. If the new
                // component is required, conformance rules handle it.
            }
            CompositionChangeType::FamilyMemberRemoved { member } => {
                let pkg = pkg_for(member, component_packages);
                let rule_id = format!(
                    "sd-composition-{}-removed-member-{}",
                    sanitize(&change.family),
                    sanitize(member)
                );

                rules.push(KonveyorRule {
                    rule_id,
                    labels: vec![
                        "source=semver-analyzer".into(),
                        "change-type=composition".into(),
                        format!("package={}", pkg),
                        format!("family={}", change.family),
                    ],
                    effort: 3,
                    category: "mandatory".into(),
                    description: change.description.clone(),
                    message: format!(
                        "<{}> has been removed from the {} family.\n\
                         Remove usages or replace with the recommended alternative.",
                        member, change.family
                    ),
                    links: vec![],
                    when: KonveyorCondition::FrontendReferenced {
                        referenced: FrontendReferencedFields {
                            pattern: format!("^{}$", member),
                            location: "JSX_COMPONENT".into(),
                            component: None,
                            parent: None,
                            parent_from: None,
                            not_parent: None,
                            child: None,
                            not_child: None,
                            requires_child: None,
                            value: None,
                            from: Some(pkg.to_string()),
                            file_pattern: None,
                        },
                    },
                    fix_strategy: Some(FixStrategyEntry {
                        strategy: "Manual".into(),
                        from: Some(member.clone()),
                        ..Default::default()
                    }),
                });
            }
            _ => {}
        }
    }

    rules
}

// ── Conformance rules ───────────────────────────────────────────────────
//
// Conformance rule IDs use abbreviated segments to keep IDs short.
// Component names are shortened by stripping the family root prefix
// (e.g., `DualListSelectorControl` → `control` in the `DualListSelector` family).
// When stripping would produce an empty string (component == family root),
// the full name is kept.
//
// Abbreviation scheme:
//   conformance → cf
//   must-be-in  → in
//   requires    → req
//   requires-wrapper → req-wrap
//
// Rule ID formats:
//   notParent:         sd-cf-{family}-{child}-in-{parent1-or-parent2}
//   invalidDirectChild: sd-cf-{family}-{child}-not-in-{grandparent}-use-{parent1-or-parent2}
//   requiresChild:     sd-cf-{family}-{parent}-req-{child1-and-child2}
//   exclusiveWrapper:  sd-cf-{family}-{parent}-req-wrap
//
// Examples:
//   sd-cf-duallistselector-control-in-list-or-tree
//   sd-cf-table-td-not-in-table-use-tr
//   sd-cf-tabs-tabs-req-tab
//   sd-cf-deprecated-duallistselector-control-in-list-or-tree

fn generate_conformance_rules(
    trees: &[CompositionTree],
    conformance_checks: &[ConformanceCheck],
    component_packages: &HashMap<String, String>,
) -> Vec<KonveyorRule> {
    let mut rules = Vec::new();

    for tree in trees {
        // ── Step 1: Build children needing notParent rules.
        //
        // Children with at least one incoming edge that has
        // child_requires_parent (CHP) — i.e., Required or Structural edges.
        // These children MUST be placed inside their parent when used.
        //
        // PropPassed edges are included for notParent (the scanner correctly
        // tracks parent_name through prop expressions).
        let mut children_needing_not_parent: HashSet<&str> = HashSet::new();
        for edge in &tree.edges {
            if edge.relationship != ChildRelationship::Internal
                && edge.strength.child_requires_parent()
            {
                children_needing_not_parent.insert(edge.child.as_str());
            }
        }

        // ── Step 2: Build parent → PMC children map.
        //
        // Edges where parent_requires_child (PMC) — i.e., Required or Wrapper.
        // These parents MUST contain these children.
        //
        // PropPassed edges are excluded because the requiresChild scanner
        // only checks direct JSX children (el.children), not prop value
        // expressions. A prop-passed child like <Tab actions={<TabAction/>}/>
        // is invisible to the scanner and would cause guaranteed FPs.
        let mut parent_to_req_children: HashMap<&str, Vec<&str>> = HashMap::new();
        for edge in &tree.edges {
            if edge.strength.parent_requires_child()
                && edge.relationship != ChildRelationship::Internal
                && edge.relationship != ChildRelationship::PropPassed
            {
                parent_to_req_children
                    .entry(edge.parent.as_str())
                    .or_default()
                    .push(edge.child.as_str());
            }
        }

        // ── Step 3: Build child → all parents map.
        //
        // ALL non-internal edges (all strengths). Used for the notParent
        // regex so valid-but-not-required placements don't trigger false
        // positives, and for InvalidDirectChild grandparent lookup.
        let mut child_to_all_parents: HashMap<&str, Vec<&str>> = HashMap::new();
        for edge in &tree.edges {
            if edge.relationship != ChildRelationship::Internal {
                child_to_all_parents
                    .entry(edge.child.as_str())
                    .or_default()
                    .push(edge.parent.as_str());
            }
        }

        // ── Step 3b: Build parent → all children map (all strengths).
        //
        // Used for the requiresChild scanner regex. Including non-PMC children
        // prevents false positives when a parent has valid-but-not-required
        // children (e.g., ToolbarContent with ToolbarGroup/ToolbarItem).
        // The `parent_to_req_children` map still determines WHICH parents get
        // requiresChild rules — this map only expands the scanner regex.
        //
        // PropPassed edges are excluded (same reason as Step 2 — the scanner
        // can only see direct JSX children, not prop values).
        let mut parent_to_all_children: HashMap<&str, Vec<&str>> = HashMap::new();
        for edge in &tree.edges {
            if edge.relationship != ChildRelationship::Internal
                && edge.relationship != ChildRelationship::PropPassed
            {
                parent_to_all_children
                    .entry(edge.parent.as_str())
                    .or_default()
                    .push(edge.child.as_str());
            }
        }

        // ── Step 4: Generate rules.
        //
        // Two independent rule types based on the two dimensions:
        //
        //   notParent rule on child:
        //     Generated for children in children_needing_not_parent.
        //     "Td must be inside Tr" — child has CHP edge.
        //     Scanner: pattern=Td, notParent=^(Tr)$
        //
        //   requiresChild rule on parent:
        //     Generated for parents in parent_to_req_children.
        //     "ToggleGroup must contain ToggleGroupItem" — parent has PMC edge.
        //     Scanner: pattern=ToggleGroup, requiresChild=^(ToggleGroupItem)$

        // Extract the base family name for root comparison.
        // "deprecated/DualListSelector" → "DualListSelector", "Alert" → "Alert"
        let base_root = tree.root.rsplit('/').next().unwrap_or(&tree.root);

        // For deprecated families, scope the `from` field to the deprecated
        // import path (e.g., "@patternfly/react-core/deprecated"). Without
        // this, deprecated conformance rules share identical `when` clauses
        // with v6 rules because both families use the same component names
        // from the same base package.
        let family_root = &tree.root;
        let pkg_for_family = |component: &str| -> String {
            pkg_for_deprecated(component, family_root, component_packages)
        };

        // 4b: Generate notParent rules (child must be inside parent).
        for child in &children_needing_not_parent {
            // Skip notParent rules for the family root component. A family root
            // is standalone by definition — it can exist outside any parent.
            // Examples: Alert does not require AlertGroup, ChartDonutUtilization
            // does not require ChartDonutThreshold.
            if *child == base_root {
                continue;
            }

            let pkg = pkg_for_family(child);

            // Use ALL parents (Required + Allowed) for the notParent regex
            // so valid-but-not-required placements don't trigger false positives.
            let all_parents = child_to_all_parents
                .get(child)
                .map(|v| v.as_slice())
                .unwrap_or(&[]);

            let mut sorted_parents: Vec<&str> = all_parents.to_vec();
            sorted_parents.sort();
            sorted_parents.dedup();

            let not_parent_pattern = if sorted_parents.len() == 1 {
                format!("^{}$", sorted_parents[0])
            } else {
                format!("^({})$", sorted_parents.join("|"))
            };

            let rule_id_suffix = sorted_parents
                .iter()
                .map(|p| short_component_id(p, &tree.root))
                .collect::<Vec<_>>()
                .join("-or-");
            let rule_id = format!(
                "sd-cf-{}-{}-in-{}",
                sanitize(&tree.root),
                short_component_id(child, &tree.root),
                rule_id_suffix,
            );

            let parent_list = sorted_parents.join(" or ");

            let message = if sorted_parents.len() == 1 {
                format!(
                    "<{}> must be used inside <{}>.\n\n\
                     Correct usage:\n  <{}>\n    <{} />\n  </{}>",
                    child, sorted_parents[0], sorted_parents[0], child, sorted_parents[0],
                )
            } else {
                let examples: Vec<String> = sorted_parents
                    .iter()
                    .map(|p| format!("  <{}>\n    <{} />\n  </{}>", p, child, p))
                    .collect();
                format!(
                    "<{}> must be used inside {}.\n\n\
                     Correct usage (either):\n{}",
                    child,
                    parent_list,
                    examples.join("\n  or\n"),
                )
            };

            rules.push(KonveyorRule {
                rule_id,
                labels: vec![
                    "source=semver-analyzer".into(),
                    "change-type=conformance".into(),
                    format!("package={}", pkg),
                    format!("family={}", tree.root),
                ],
                effort: 1,
                category: "mandatory".into(),
                description: format!("<{}> must be a child of {}", child, parent_list),
                message,
                links: vec![],
                when: KonveyorCondition::FrontendReferenced {
                    referenced: FrontendReferencedFields {
                        pattern: format!("^{}$", child),
                        location: "JSX_COMPONENT".into(),
                        component: None,
                        parent: None,
                        not_parent: Some(not_parent_pattern),
                        child: None,
                        not_child: None,
                        requires_child: None,
                        parent_from: None,
                        value: None,
                        from: Some(pkg.to_string()),
                        file_pattern: None,
                    },
                },
                fix_strategy: Some(FixStrategyEntry {
                    strategy: "LlmAssisted".into(),
                    component: Some(child.to_string()),
                    replacement: Some(sorted_parents[0].to_string()),
                    ..Default::default()
                }),
            });

            // Build set of CHP parents for this child — parents where the child
            // has a Required or Structural edge (child_requires_parent = true).
            //
            // Used for two purposes:
            // 1. The grandparent walk only follows CHP parents in the first
            //    hop. Allowed parents (CSS descendant matches between peer
            //    components) create false intermediate paths and generate
            //    noise rules like "DLDescription not-in DLTermHelpText, use
            //    DLTerm" when Term and TermHelpText are actually peers.
            // 2. If the grandparent is already a CHP parent, the child IS a
            //    valid direct child of that grandparent — the invalidDirectChild
            //    rule would contradict the notParent rule.
            let chp_parents: HashSet<&str> = tree
                .edges
                .iter()
                .filter(|e| {
                    e.child == *child
                        && e.relationship != ChildRelationship::Internal
                        && e.strength.child_requires_parent()
                })
                .map(|e| e.parent.as_str())
                .collect();

            // ── InvalidDirectChild: child inside grandparent, skipping parent.
            //
            // For each CHP parent of this child, look up that parent's own
            // parents (grandparents of the child). Group by grandparent to
            // merge when multiple parents share the same grandparent (e.g.,
            // Tr in Table needs either Thead or Tbody).
            //
            // Only CHP parents are walked (first hop) because Allowed parents
            // represent weak CSS descendant signals between peer components,
            // not real parent-child API constraints. The second hop (parent →
            // grandparent) uses ALL parents to find all valid ancestors.
            let mut grandparent_to_expected: HashMap<&str, Vec<&str>> = HashMap::new();
            for parent in &sorted_parents {
                // First hop: only follow CHP parents
                if !chp_parents.contains(parent) {
                    continue;
                }
                if let Some(grandparents) = child_to_all_parents.get(parent) {
                    for grandparent in grandparents {
                        grandparent_to_expected
                            .entry(grandparent)
                            .or_default()
                            .push(parent);
                    }
                }
            }

            for (grandparent, expected_parents) in &grandparent_to_expected {
                // Suppress when the child already has a CHP edge to the
                // grandparent. The child is a valid direct child there, so
                // "X should not be directly in G" is wrong.
                if chp_parents.contains(grandparent) {
                    continue;
                }
                let mut unique_parents: Vec<&str> = expected_parents.clone();
                unique_parents.sort();
                unique_parents.dedup();

                let parent_list = unique_parents.join(" or ");
                let rule_id_suffix = unique_parents
                    .iter()
                    .map(|p| short_component_id(p, &tree.root))
                    .collect::<Vec<_>>()
                    .join("-or-");
                let rule_id = format!(
                    "sd-cf-{}-{}-not-in-{}-use-{}",
                    sanitize(&tree.root),
                    short_component_id(child, &tree.root),
                    short_component_id(grandparent, &tree.root),
                    rule_id_suffix,
                );

                let message = if unique_parents.len() == 1 {
                    format!(
                        "<{}> should be wrapped in <{}> inside <{}>.\n\n\
                         Replace:\n  <{}>\n    <{} />\n  </{}>\n\n\
                         With:\n  <{}>\n    <{}>\n      <{} />\n    </{}>\n  </{}>",
                        child,
                        unique_parents[0],
                        grandparent,
                        grandparent,
                        child,
                        grandparent,
                        grandparent,
                        unique_parents[0],
                        child,
                        unique_parents[0],
                        grandparent,
                    )
                } else {
                    let examples: Vec<String> = unique_parents
                        .iter()
                        .map(|p| {
                            format!(
                                "  <{}>\n    <{}>\n      <{} />\n    </{}>\n  </{}>",
                                grandparent, p, child, p, grandparent,
                            )
                        })
                        .collect();
                    format!(
                        "<{}> should be wrapped in {} inside <{}>.\n\n\
                         Replace:\n  <{}>\n    <{} />\n  </{}>\n\n\
                         With (either):\n{}",
                        child,
                        parent_list,
                        grandparent,
                        grandparent,
                        child,
                        grandparent,
                        examples.join("\n  or\n"),
                    )
                };

                rules.push(KonveyorRule {
                    rule_id,
                    labels: vec![
                        "source=semver-analyzer".into(),
                        "change-type=conformance".into(),
                        format!("package={}", pkg),
                        format!("family={}", tree.root),
                    ],
                    effort: 3,
                    category: "mandatory".into(),
                    description: format!(
                        "<{}> must be inside {}, not directly in <{}>",
                        child, parent_list, grandparent
                    ),
                    message,
                    links: vec![],
                    when: KonveyorCondition::FrontendReferenced {
                        referenced: FrontendReferencedFields {
                            pattern: format!("^{}$", child),
                            location: "JSX_COMPONENT".into(),
                            component: None,
                            parent: Some(format!("^{}$", grandparent)),
                            parent_from: Some(pkg.to_string()),
                            not_parent: None,
                            child: None,
                            not_child: None,
                            requires_child: None,
                            value: None,
                            from: Some(pkg.to_string()),
                            file_pattern: None,
                        },
                    },
                    fix_strategy: Some(FixStrategyEntry {
                        strategy: "CompositionChange".into(),
                        component: Some(child.to_string()),
                        replacement: Some(unique_parents[0].to_string()),
                        ..Default::default()
                    }),
                });
            }
        }

        // 4c: Generate requiresChild rules (parent must contain children).
        //
        // For parents with PMC edges (Required or Wrapper), the constraint
        // is "if you use this component, it must contain these children."
        //
        // The scanner regex uses ALL children (all strengths) so that
        // valid-but-optional children don't trigger false positives. The rule
        // still only fires on parents that have PMC children (from
        // parent_to_req_children), and the description lists the PMC ones.
        for (parent, children) in &parent_to_req_children {
            let pkg = pkg_for_family(parent);
            let mut sorted_children: Vec<&str> = children.clone();
            sorted_children.sort();
            sorted_children.dedup();

            // Use ALL children (Required + Allowed) for the scanner regex to
            // avoid false positives when valid-but-Allowed children are present.
            let all_children = parent_to_all_children
                .get(parent)
                .map(|v| v.as_slice())
                .unwrap_or(&[]);
            let mut sorted_all: Vec<&str> = all_children.to_vec();
            sorted_all.sort();
            sorted_all.dedup();
            let children_pattern = format!("^({})$", sorted_all.join("|"));
            let children_list = sorted_all.join(" or ");

            let rule_id_suffix = sorted_all
                .iter()
                .map(|c| short_component_id(c, &tree.root))
                .collect::<Vec<_>>()
                .join("-and-");
            let rule_id = format!(
                "sd-cf-{}-{}-req-{}",
                sanitize(&tree.root),
                short_component_id(parent, &tree.root),
                rule_id_suffix,
            );

            let message = format!(
                "<{}> must contain at least one {} child component.\n\n\
                 Correct usage:\n  <{}>\n    <{} />\n  </{}>",
                parent, children_list, parent, sorted_all[0], parent,
            );

            rules.push(KonveyorRule {
                rule_id,
                labels: vec![
                    "source=semver-analyzer".into(),
                    "change-type=conformance".into(),
                    format!("package={}", pkg),
                    format!("family={}", tree.root),
                ],
                effort: 1,
                category: "mandatory".into(),
                description: format!("<{}> must contain {} children", parent, children_list),
                message,
                links: vec![],
                when: KonveyorCondition::FrontendReferenced {
                    referenced: FrontendReferencedFields {
                        pattern: format!("^{}$", parent),
                        location: "JSX_COMPONENT".into(),
                        component: None,
                        parent: None,
                        not_parent: None,
                        child: None,
                        not_child: None,
                        requires_child: Some(children_pattern),
                        parent_from: None,
                        value: None,
                        from: Some(pkg.to_string()),
                        file_pattern: None,
                    },
                },
                fix_strategy: Some(FixStrategyEntry {
                    strategy: "LlmAssisted".into(),
                    component: Some(parent.to_string()),
                    replacement: Some(sorted_all.join(", ")),
                    ..Default::default()
                }),
            });
        }
    }

    // ── ExclusiveWrapper: all children must be a specific wrapper
    for check in conformance_checks {
        if let ConformanceCheckType::ExclusiveWrapper {
            parent,
            allowed_children,
        } = &check.check_type
        {
            let pkg = pkg_for_deprecated(parent, &check.family, component_packages);
            let allowed_pattern = format!("^({})$", allowed_children.join("|"));
            let allowed_list = allowed_children.join(" or ");

            let rule_id = format!(
                "sd-cf-{}-{}-req-wrap",
                sanitize(&check.family),
                short_component_id(parent, &check.family),
            );

            rules.push(KonveyorRule {
                rule_id,
                labels: vec![
                    "source=semver-analyzer".into(),
                    "change-type=conformance".into(),
                    format!("package={}", pkg),
                    format!("family={}", check.family),
                ],
                effort: 3,
                category: "mandatory".into(),
                description: format!(
                    "All children of <{}> must be wrapped in {}",
                    parent, allowed_list
                ),
                message: format!(
                    "Components placed directly inside <{}> must be wrapped in <{}>.\n\n\
                     Replace:\n  <{}>\n    <SomeComponent />\n  </{}>\n\n\
                     With:\n  <{}>\n    <{}>\n      <SomeComponent />\n    </{}>\n  </{}>",
                    parent,
                    allowed_children.first().unwrap_or(&parent.clone()),
                    parent,
                    parent,
                    parent,
                    allowed_children.first().unwrap_or(&parent.clone()),
                    allowed_children.first().unwrap_or(&parent.clone()),
                    parent,
                ),
                links: vec![],
                when: KonveyorCondition::FrontendReferenced {
                    referenced: FrontendReferencedFields {
                        pattern: format!("^{}$", parent),
                        location: "JSX_COMPONENT".into(),
                        component: None,
                        parent: None,
                        not_parent: None,
                        child: None,
                        not_child: Some(allowed_pattern),
                        requires_child: None,
                        parent_from: None,
                        value: None,
                        from: Some(pkg.to_string()),
                        file_pattern: None,
                    },
                },
                fix_strategy: Some(FixStrategyEntry {
                    strategy: "LlmAssisted".into(),
                    component: Some(parent.clone()),
                    replacement: Some(allowed_children.first().unwrap_or(&parent.clone()).clone()),
                    ..Default::default()
                }),
            });
        }
    }

    rules
}

// ── Context dependency rules ────────────────────────────────────────────

fn generate_context_rules(
    changes: &[SourceLevelChange],
    component_packages: &HashMap<String, String>,
) -> Vec<KonveyorRule> {
    let mut rules = Vec::new();

    for change in changes {
        if change.category != SourceLevelCategory::ContextDependency {
            continue;
        }

        // Extract context name from old_value or new_value
        let context_name = change
            .new_value
            .as_ref()
            .or(change.old_value.as_ref())
            .and_then(|v| {
                // Values are like "useContext(MenuContext)" or "<MenuContext.Provider>"
                v.strip_prefix("useContext(")
                    .and_then(|s| s.strip_suffix(')'))
                    .or_else(|| {
                        v.strip_prefix('<')
                            .and_then(|s| s.strip_suffix(".Provider>"))
                    })
            });

        let Some(ctx_name) = context_name else {
            continue;
        };

        let pkg = pkg_for(&change.component, component_packages);
        let prefix = rule_prefix(&change.migration_from);
        let rule_id = format!(
            "{}-context-{}-{}",
            prefix,
            sanitize(&change.component),
            sanitize(ctx_name),
        );

        // For migration changes, match imports from the deprecated path.
        // For evolution changes, match imports from the current package.
        let from_pkg = if let Some(ref mf) = change.migration_from {
            deprecated_pkg_from_migration_path(mf)
        } else {
            pkg.clone()
        };

        // Fire on import of the context — consumers who directly import
        // and use the context are affected.
        rules.push(KonveyorRule {
            rule_id,
            labels: vec![
                "source=semver-analyzer".into(),
                "change-type=context-dependency".into(),
                format!("package={}", from_pkg),
                format!("component={}", change.component),
            ],
            effort: 3,
            category: "mandatory".into(),
            description: change.description.clone(),
            message: format!(
                "{}\n\n\
                 If you import and use {} directly, review your usage.\n\
                 The context shape or provider location may have changed.",
                change.description, ctx_name,
            ),
            links: vec![],
            when: KonveyorCondition::FrontendReferenced {
                referenced: FrontendReferencedFields {
                    pattern: format!("^{}$", ctx_name),
                    location: "IMPORT".into(),
                    component: None,
                    parent: None,
                    parent_from: None,
                    not_parent: None,
                    child: None,
                    not_child: None,
                    requires_child: None,
                    value: None,
                    from: Some(from_pkg),
                    file_pattern: None,
                },
            },
            fix_strategy: Some(FixStrategyEntry {
                strategy: "Manual".into(),
                component: Some(change.component.clone()),
                from: change.old_value.clone(),
                to: change.new_value.clone(),
                ..Default::default()
            }),
        });
    }

    rules
}

// ── Prop↔Child migration rules ─────────────────────────────────────────

/// Detect props that migrated between parent and child components.
///
/// Cross-references TD structural data (removed/added props) with
/// SD composition data (new/removed children) to find:
/// - Prop→child: parent lost a prop, new child gained it
/// - Child→prop: child removed, parent gained a prop of same name
fn generate_prop_child_migration_rules(
    report: &AnalysisReport<TypeScript>,
    sd: &SdPipelineResult,
    component_packages: &HashMap<String, String>,
) -> Vec<KonveyorRule> {
    let mut rules = Vec::new();

    // Build lookup: component name → removed props
    let mut removed_props: HashMap<String, Vec<RemovedProp>> = HashMap::new();
    // Build lookup: component name → added props
    let mut added_props: HashMap<String, HashSet<String>> = HashMap::new();

    for file_changes in &report.changes {
        for change in &file_changes.breaking_api_changes {
            if let Some(component) = extract_component_name_from_symbol(&change.symbol) {
                if let Some(prop) = extract_prop_name_from_symbol(&change.symbol) {
                    if change.change == ApiChangeType::Removed {
                        let is_reactnode = change
                            .before
                            .as_ref()
                            .map(|b| is_react_node_type(b))
                            .unwrap_or(false);

                        removed_props
                            .entry(component.clone())
                            .or_default()
                            .push(RemovedProp {
                                name: prop,
                                component,
                                is_reactnode,
                                before_type: change.before.clone(),
                            });
                    }
                }
            }
        }

        // Track added props from the new surface (non-breaking additions)
        // We need to check the new API surface for child component props
    }

    // For added props, scan all file changes for new symbols too
    // (TD reports additions as well as removals in some cases)
    // Also check the new API surface directly
    if let Some(_new_surface) = report.changes.first() {
        // Build added props from the new surface
        for file_changes in &report.changes {
            for change in &file_changes.breaking_api_changes {
                if change.change == ApiChangeType::Renamed {
                    // If renamed, the new name is an "added" prop
                    if let Some(component) = extract_component_name_from_symbol(&change.symbol) {
                        if let Some(after) = &change.after {
                            added_props
                                .entry(component)
                                .or_default()
                                .insert(after.clone());
                        }
                    }
                }
            }
        }
    }

    // For each composition tree, find prop→child migrations
    for tree in &sd.composition_trees {
        let new_children: HashSet<&str> = tree
            .edges
            .iter()
            .filter(|e| e.parent == tree.root)
            .map(|e| e.child.as_str())
            .collect();

        // Get removed props from the root component
        let root_removed = removed_props.get(&tree.root);
        let Some(root_removed) = root_removed else {
            continue;
        };

        // For each new child, check the new API surface for its props
        // We need to get the child's prop names from the new surface
        let child_props = get_child_props_from_report(report, sd, &new_children);

        let pkg = pkg_for(&tree.root, component_packages);

        for removed in root_removed {
            // Phase 1: Exact prop name match
            for (child_name, child_prop_set) in &child_props {
                if child_prop_set.contains(&removed.name) {
                    // Prop→Prop migration: same name on new child
                    let rule_id = format!(
                        "sd-prop-to-child-{}-{}-to-{}",
                        sanitize(&tree.root),
                        sanitize(&removed.name),
                        sanitize(child_name),
                    );

                    rules.push(KonveyorRule {
                        rule_id,
                        labels: vec![
                            "source=semver-analyzer".into(),
                            "change-type=prop-to-child".into(),
                            format!("package={}", pkg),
                            format!("family={}", tree.root),
                            format!("target-component={}", child_name),
                        ],
                        effort: 3,
                        category: "mandatory".into(),
                        description: format!(
                            "The `{}` prop moved from <{}> to <{}>",
                            removed.name, tree.root, child_name
                        ),
                        message: {
                            let mut msg = format!(
                                "The `{}` prop has been removed from <{}>.\n\
                                 Use <{} {}={{...}} /> as a child of <{}> instead.\n\n\
                                 Before:\n  <{} {}={{value}}>\n    ...\n  </{}>\n\n\
                                 After:\n  <{}>\n    <{} {}={{value}} />\n    ...\n  </{}>",
                                removed.name,
                                tree.root,
                                child_name,
                                removed.name,
                                tree.root,
                                tree.root,
                                removed.name,
                                tree.root,
                                tree.root,
                                child_name,
                                removed.name,
                                tree.root,
                            );
                            // List props that STAY on the parent component so the
                            // LLM doesn't accidentally move them to the child.
                            if let Some(parent_props) = sd.new_component_props.get(&tree.root) {
                                let staying: Vec<&String> = parent_props
                                    .iter()
                                    .filter(|p| {
                                        p.as_str() != "children" && p.as_str() != "className"
                                    })
                                    .take(10)
                                    .collect();
                                if !staying.is_empty() {
                                    msg.push_str(&format!(
                                        "\n\nIMPORTANT: These props stay on <{}>: {}.\n\
                                         Do NOT move them to <{}>.",
                                        tree.root,
                                        staying
                                            .iter()
                                            .map(|p| format!("`{}`", p))
                                            .collect::<Vec<_>>()
                                            .join(", "),
                                        child_name,
                                    ));
                                }
                            }
                            msg
                        },
                        links: vec![],
                        when: KonveyorCondition::FrontendReferenced {
                            referenced: FrontendReferencedFields {
                                pattern: format!("^{}$", removed.name),
                                location: "JSX_PROP".into(),
                                component: Some(format!("^{}$", tree.root)),
                                parent: None,
                                parent_from: None,
                                not_parent: None,
                                child: None,
                                not_child: None,
                                requires_child: None,
                                value: None,
                                from: Some(pkg.to_string()),
                                file_pattern: None,
                            },
                        },
                        fix_strategy: Some(FixStrategyEntry {
                            strategy: "PropToChild".into(),
                            from: Some(removed.name.clone()),
                            component: Some(tree.root.clone()),
                            replacement: Some(child_name.clone()),
                            prop: Some(removed.name.clone()),
                            ..Default::default()
                        }),
                    });
                    break; // Found match, stop checking other children
                }
            }

            // Phase 2: Name containment for ReactNode props
            if removed.is_reactnode {
                let matched_in_phase1 = rules.iter().any(|r| {
                    r.labels.iter().any(|l| l == "change-type=prop-to-child")
                        && r.fix_strategy
                            .as_ref()
                            .map(|fs| fs.from.as_deref() == Some(removed.name.as_str()))
                            .unwrap_or(false)
                });

                if !matched_in_phase1 {
                    // Check if prop name appears in any child component name
                    for child_name in &new_children {
                        if child_name
                            .to_lowercase()
                            .contains(&removed.name.to_lowercase())
                        {
                            let rule_id = format!(
                                "sd-prop-to-children-{}-{}-to-{}",
                                sanitize(&tree.root),
                                sanitize(&removed.name),
                                sanitize(child_name),
                            );

                            rules.push(KonveyorRule {
                                rule_id,
                                labels: vec![
                                    "source=semver-analyzer".into(),
                                    "change-type=prop-to-child".into(),
                                    format!("package={}", pkg),
                                    format!("family={}", tree.root),
                                    format!("target-component={}", child_name),
                                ],
                                effort: 3,
                                category: "mandatory".into(),
                                description: format!(
                                    "The `{}` prop (ReactNode) moved from <{}> to <{}> children",
                                    removed.name, tree.root, child_name
                                ),
                                message: format!(
                                    "The `{}` prop has been removed from <{}>.\n\
                                     Pass this content as children of <{}> instead.\n\n\
                                     Before:\n  <{} {}={{content}}>\n    ...\n  </{}>\n\n\
                                     After:\n  <{}>\n    <{}>{{content}}</{}>\n    ...\n  </{}>",
                                    removed.name,
                                    tree.root,
                                    child_name,
                                    tree.root,
                                    removed.name,
                                    tree.root,
                                    tree.root,
                                    child_name,
                                    child_name,
                                    tree.root,
                                ),
                                links: vec![],
                                when: KonveyorCondition::FrontendReferenced {
                                    referenced: FrontendReferencedFields {
                                        pattern: format!("^{}$", removed.name),
                                        location: "JSX_PROP".into(),
                                        component: Some(format!("^{}$", tree.root)),
                                        parent: None,
                                        not_parent: None,
                                        child: None,
                                        not_child: None,
                                        requires_child: None,
                                        parent_from: None,
                                        value: None,
                                        from: Some(pkg.to_string()),
                                        file_pattern: None,
                                    },
                                },
                                fix_strategy: Some(FixStrategyEntry {
                                    strategy: "PropToChildren".into(),
                                    from: Some(removed.name.clone()),
                                    component: Some(tree.root.clone()),
                                    replacement: Some(child_name.to_string()),
                                    ..Default::default()
                                }),
                            });
                            break;
                        }
                    }
                }
            }
        }
    }

    // ── Child→prop migration (reverse direction) ─────────────────
    //
    // Detect when a child component was removed from a family and the
    // parent gained a new prop that serves the same purpose.
    //
    // Algorithm:
    // 1. Find family members in old profiles but not in new profiles
    //    (removed children)
    // 2. Find props on the parent that exist in the new version but
    //    not the old version (added props)
    // 3. Match: removed child name ↔ added prop name

    for tree in &sd.composition_trees {
        let root = &tree.root;
        let pkg = pkg_for(root, component_packages);

        // Get old and new props for the root component
        let old_root_props = sd
            .old_component_props
            .get(root)
            .cloned()
            .unwrap_or_default();
        let new_root_props = sd
            .new_component_props
            .get(root)
            .cloned()
            .unwrap_or_default();

        // Added props = in new but not in old
        let added_props: BTreeSet<String> = new_root_props
            .difference(&old_root_props)
            .cloned()
            .collect();

        if added_props.is_empty() {
            continue;
        }

        // Get the prop types from the new version
        let new_prop_types = sd
            .new_component_prop_types
            .get(root)
            .cloned()
            .unwrap_or_default();

        // Find removed family members (in old component props but not in new tree)
        let old_members: HashSet<&str> = sd
            .old_component_props
            .keys()
            .filter(|name| {
                // Only consider members of this family (name starts with root)
                name.starts_with(root.as_str()) && *name != root
            })
            .map(|s| s.as_str())
            .collect();
        let new_members: HashSet<&str> = tree.family_members.iter().map(|s| s.as_str()).collect();

        let removed_children: Vec<&str> = old_members.difference(&new_members).copied().collect();

        for removed_child in &removed_children {
            let child_lower = removed_child.to_lowercase();
            // Strip the root prefix to get the child suffix
            // e.g., "ModalIcon" with root "Modal" → suffix "icon"
            let child_suffix = child_lower
                .strip_prefix(&root.to_lowercase())
                .unwrap_or(&child_lower)
                .to_lowercase();

            if child_suffix.is_empty() {
                continue;
            }

            // Check if any added prop matches the child suffix
            for added_prop in &added_props {
                if added_prop.to_lowercase() == child_suffix {
                    // Check if the prop type is ReactNode-ish
                    let is_reactnode = new_prop_types
                        .get(added_prop)
                        .map(|t| is_react_node_type(t))
                        .unwrap_or(false);

                    let rule_id = format!(
                        "sd-child-to-prop-{}-{}-to-{}",
                        sanitize(root),
                        sanitize(removed_child),
                        sanitize(added_prop),
                    );

                    let message = if is_reactnode {
                        format!(
                            "<{}> has been removed. Pass its content via the `{}` prop on <{}> instead.\n\n\
                             Before:\n  <{}>\n    <{}>{{}}</{}>\n  </{}>\n\n\
                             After:\n  <{} {}={{content}} />",
                            removed_child, added_prop, root,
                            root, removed_child, removed_child, root,
                            root, added_prop,
                        )
                    } else {
                        format!(
                            "<{}> has been removed. Use the `{}` prop on <{}> instead.\n\n\
                             Before:\n  <{}>\n    <{} />\n  </{}>\n\n\
                             After:\n  <{} {}={{...}} />",
                            removed_child,
                            added_prop,
                            root,
                            root,
                            removed_child,
                            root,
                            root,
                            added_prop,
                        )
                    };

                    rules.push(KonveyorRule {
                        rule_id,
                        labels: vec![
                            "source=semver-analyzer".into(),
                            "change-type=child-to-prop".into(),
                            format!("package={}", pkg),
                            format!("family={}", root),
                        ],
                        effort: 3,
                        category: "mandatory".into(),
                        description: format!(
                            "<{}> removed — use `{}` prop on <{}> instead",
                            removed_child, added_prop, root
                        ),
                        message,
                        links: vec![],
                        when: KonveyorCondition::FrontendReferenced {
                            referenced: FrontendReferencedFields {
                                pattern: format!("^{}$", removed_child),
                                location: "JSX_COMPONENT".into(),
                                component: None,
                                parent: Some(format!("^{}$", root)),
                                parent_from: Some(pkg.clone()),
                                not_parent: None,
                                child: None,
                                not_child: None,
                                requires_child: None,
                                value: None,
                                from: Some(pkg.clone()),
                                file_pattern: None,
                            },
                        },
                        fix_strategy: Some(FixStrategyEntry {
                            strategy: "ChildToProp".into(),
                            from: Some(removed_child.to_string()),
                            to: Some(added_prop.clone()),
                            component: Some(root.clone()),
                            prop: Some(added_prop.clone()),
                            ..Default::default()
                        }),
                    });
                    break;
                }
            }
        }
    }

    rules
}

// ── Cross-family child→prop migration rules ─────────────────────────────

/// Detect non-family components that should be replaced by a new prop on the parent.
///
/// Tier 1 heuristic using three converging signals:
///
/// 1. **BEM evidence** from the old composition tree: a removed family member's
///    edge carries `bem_evidence` naming a prop (e.g., `"EmptyStateHeader is BEM
///    element 'titleText' of emptyState block"`).
///
/// 2. **Migration target**: the removed member's Props interface has a
///    `matching_members` entry mapping that prop to the root's new prop
///    (e.g., `EmptyStateHeaderProps.titleText → EmptyStateProps.titleText`).
///
/// 3. **Component name match**: a standalone PF component's name (case-insensitive)
///    is a prefix of the added prop name (e.g., `Title` → `titleText`), AND the
///    component is NOT a family member.
///
/// When all three signals align, we generate a rule that detects the standalone
/// component used as a child of the root and recommends using the prop instead.
///
/// Example: `<Title>` inside `<EmptyState>` → use `titleText` prop.
fn generate_cross_family_child_to_prop_rules(
    report: &AnalysisReport<TypeScript>,
    sd: &SdPipelineResult,
    component_packages: &HashMap<String, String>,
) -> Vec<KonveyorRule> {
    let mut rules = Vec::new();

    // Build a set of all known PF component names (old + new)
    let all_component_names: HashSet<&str> = sd
        .component_packages
        .keys()
        .chain(sd.old_component_packages.keys())
        .map(|s| s.as_str())
        .collect();

    // Build migration target lookup: "EmptyStateHeaderProps" → MigrationTarget
    let mut migration_targets: HashMap<String, &semver_analyzer_core::MigrationTarget> =
        HashMap::new();
    for file_changes in &report.changes {
        for change in &file_changes.breaking_api_changes {
            if let Some(ref mt) = change.migration_target {
                migration_targets.insert(mt.removed_symbol.clone(), mt);
            }
        }
    }

    // For each new composition tree, look at the OLD tree for removed members
    // with BEM evidence that names a prop.
    for new_tree in &sd.composition_trees {
        let root = &new_tree.root;
        let pkg = pkg_for(root, component_packages);

        // Find the old tree for this family
        let old_tree = match sd.old_composition_trees.iter().find(|t| t.root == *root) {
            Some(t) => t,
            None => continue,
        };

        // Compute added props on the root
        let old_root_props: BTreeSet<&str> = sd
            .old_component_props
            .get(root)
            .map(|s| s.iter().map(|p| p.as_str()).collect())
            .unwrap_or_default();
        let new_root_props: BTreeSet<&str> = sd
            .new_component_props
            .get(root)
            .map(|s| s.iter().map(|p| p.as_str()).collect())
            .unwrap_or_default();
        let added_props: BTreeSet<&str> = new_root_props
            .difference(&old_root_props)
            .copied()
            .collect();

        if added_props.is_empty() {
            continue;
        }

        // New tree family members (for dedup — skip components already in the family)
        let new_family: HashSet<&str> =
            new_tree.family_members.iter().map(|s| s.as_str()).collect();

        // Find removed family members with BEM evidence
        let new_members: HashSet<&str> =
            new_tree.family_members.iter().map(|s| s.as_str()).collect();

        for edge in &old_tree.edges {
            // Only consider edges to members that were removed
            if new_members.contains(edge.child.as_str()) {
                continue;
            }

            // Signal 1: BEM evidence must name a prop
            let bem_prop = match &edge.bem_evidence {
                Some(evidence) => {
                    // Parse "EmptyStateHeader is BEM element 'titleText' of emptyState block"
                    // Extract the quoted prop name
                    extract_bem_prop_name(evidence)
                }
                None => continue,
            };

            let bem_prop = match bem_prop {
                Some(p) => p,
                None => continue,
            };

            // The BEM prop must be an added prop on the root
            if !added_props.contains(bem_prop.as_str()) {
                continue;
            }

            // Signal 2: migration_target confirms the prop mapping
            let removed_props_iface = format!("{}Props", edge.child);
            let has_migration_match = migration_targets
                .get(&removed_props_iface)
                .map(|mt| {
                    mt.matching_members
                        .iter()
                        .any(|mm| mm.old_name == bem_prop && mm.new_name == bem_prop)
                })
                .unwrap_or(false);

            if !has_migration_match {
                continue;
            }

            // Signal 3: find a standalone PF component whose name is a prefix
            // of the prop name (case-insensitive) and is NOT a family member
            let prop_lower = bem_prop.to_lowercase();

            for comp_name in &all_component_names {
                let comp_lower = comp_name.to_lowercase();

                // Component name must be a prefix of the prop name
                if !prop_lower.starts_with(&comp_lower) {
                    continue;
                }

                // Must not be a family member of this root
                if new_family.contains(comp_name) {
                    continue;
                }

                // Must not be the removed family member itself (that's
                // already handled by the family-based child→prop detection)
                if *comp_name == edge.child.as_str() {
                    continue;
                }

                let comp_pkg = pkg_for(comp_name, component_packages);

                let rule_id = format!(
                    "sd-cross-family-child-to-prop-{}-{}-to-{}",
                    sanitize(root),
                    sanitize(comp_name),
                    sanitize(&bem_prop),
                );

                let message = format!(
                    "<{comp}> should no longer be used as a child of <{root}>.\n\
                     Use the `{prop}` prop on <{root}> instead.\n\n\
                     Before:\n\
                     \x20 <{root}>\n\
                     \x20   <{comp} ...>...</{comp}>\n\
                     \x20 </{root}>\n\n\
                     After:\n\
                     \x20 <{root} {prop}={{...}}>\n\
                     \x20   ...\n\
                     \x20 </{root}>\n\n\
                     The <{removed}> component that previously wrapped this content \
                     has been removed. Its `{prop}` prop has moved to <{root}>.",
                    comp = comp_name,
                    root = root,
                    prop = bem_prop,
                    removed = edge.child,
                );

                rules.push(KonveyorRule {
                    rule_id,
                    labels: vec![
                        "source=semver-analyzer".into(),
                        "change-type=child-to-prop".into(),
                        format!("package={}", pkg),
                        format!("family={}", root),
                    ],
                    effort: 3,
                    category: "mandatory".into(),
                    description: format!(
                        "<{}> inside <{}> — use `{}` prop instead",
                        comp_name, root, bem_prop
                    ),
                    message,
                    links: vec![],
                    when: KonveyorCondition::FrontendReferenced {
                        referenced: FrontendReferencedFields {
                            pattern: format!("^{}$", comp_name),
                            location: "JSX_COMPONENT".into(),
                            component: None,
                            parent: Some(format!("^{}$", root)),
                            parent_from: Some(pkg.clone()),
                            not_parent: None,
                            child: None,
                            not_child: None,
                            requires_child: None,
                            value: None,
                            from: Some(comp_pkg),
                            file_pattern: None,
                        },
                    },
                    fix_strategy: Some(FixStrategyEntry {
                        strategy: "ChildToProp".into(),
                        from: Some(comp_name.to_string()),
                        to: Some(bem_prop.clone()),
                        component: Some(root.clone()),
                        prop: Some(bem_prop.clone()),
                        ..Default::default()
                    }),
                });
            }
        }
    }

    if !rules.is_empty() {
        tracing::info!(
            count = rules.len(),
            "Generated cross-family child→prop migration rules"
        );
    }

    rules
}

/// Extract the prop name from a BEM evidence string.
///
/// Parses strings like:
///   "EmptyStateHeader is BEM element 'titleText' of emptyState block"
/// Returns `Some("titleText")`.
fn extract_bem_prop_name(evidence: &str) -> Option<String> {
    let start = evidence.find('\'')?;
    let rest = &evidence[start + 1..];
    let end = rest.find('\'')?;
    Some(rest[..end].to_string())
}

// ── Deprecated↔main migration rules ─────────────────────────────────────

/// Generate rules for components that moved between deprecated and main.
///
/// Detects two cases:
/// 1. Component was in /deprecated in old version, removed in new → must migrate to main
/// 2. Component was in main in old version, moved to /deprecated in new → should migrate to new API
///
/// For both cases, includes the new component's composition tree in the
/// migration guidance.
fn generate_deprecated_migration_rules(
    sd: &SdPipelineResult,
    _component_packages: &HashMap<String, String>,
) -> Vec<KonveyorRule> {
    let mut rules = Vec::new();

    // Compare old vs new package assignments to find moves
    for (component, old_pkg) in &sd.old_component_packages {
        let new_pkg = sd.component_packages.get(component);

        let old_is_deprecated = old_pkg.contains("/deprecated");
        let new_pkg_val = new_pkg.cloned().unwrap_or_default();
        let new_is_deprecated = new_pkg_val.contains("/deprecated");
        let new_is_main = !new_pkg_val.is_empty()
            && !new_pkg_val.contains("/deprecated")
            && !new_pkg_val.contains("/next");

        // Case 1: Was in /deprecated, now either:
        //   a) removed entirely, or
        //   b) the deprecated version is gone but a main version exists
        // Both mean: consumer using /deprecated must migrate to main.
        if old_is_deprecated && !new_is_deprecated {
            // Check if a same-named component exists in main
            let main_pkg_name = if new_is_main {
                Some(new_pkg_val.clone())
            } else {
                sd.component_packages
                    .iter()
                    .find(|(name, pkg)| {
                        *name == component && !pkg.contains("/deprecated") && !pkg.contains("/next")
                    })
                    .map(|(_, pkg)| pkg.clone())
            };

            if let Some(main_pkg) = main_pkg_name {
                let composition = find_composition_tree_for(component, &sd.composition_trees);
                let rule_id = format!(
                    "sd-deprecated-removed-{}-migrate-to-main",
                    sanitize(component),
                );

                let mut message = format!(
                    "The deprecated `<{}>` from `{}` has been removed.\n\
                     Migrate to the new `<{}>` from `{}`.\n",
                    component, old_pkg, component, main_pkg,
                );
                if let Some(tree) = composition {
                    message.push_str(&format!(
                        "\nNew composition structure:\n{}",
                        format_tree_as_jsx(tree),
                    ));
                }

                rules.push(KonveyorRule {
                    rule_id,
                    labels: vec![
                        "source=semver-analyzer".into(),
                        "change-type=deprecated-migration".into(),
                        format!("package={}", old_pkg),
                        format!("target-package={}", main_pkg),
                    ],
                    effort: 5,
                    category: "mandatory".into(),
                    description: format!(
                        "Deprecated <{}> removed — migrate to new API in {}",
                        component, main_pkg
                    ),
                    message,
                    links: vec![],
                    when: KonveyorCondition::FrontendReferenced {
                        referenced: FrontendReferencedFields {
                            pattern: format!("^{}$", component),
                            location: "IMPORT".into(),
                            component: None,
                            parent: None,
                            parent_from: None,
                            not_parent: None,
                            child: None,
                            not_child: None,
                            requires_child: None,
                            value: None,
                            from: Some(old_pkg.clone()),
                            file_pattern: None,
                        },
                    },
                    fix_strategy: Some(FixStrategyEntry {
                        strategy: "DeprecatedMigration".into(),
                        from: Some(old_pkg.clone()),
                        to: Some(main_pkg.clone()),
                        component: Some(component.clone()),
                        ..Default::default()
                    }),
                });
            }
            continue;
        }

        // Case 2: Was in main, now in /deprecated → new API in main.
        // Fire on consumers importing from /deprecated (they're using the
        // old API explicitly). Consumers importing from main already have
        // the new API — they might need prop→child rules but not this one.
        if !old_is_deprecated && new_is_deprecated {
            let base_pkg = old_pkg.clone();
            let deprecated_pkg = format!("{}/deprecated", base_pkg);

            let composition = find_composition_tree_for(component, &sd.composition_trees);
            let rule_id = format!("sd-deprecated-moved-{}-to-deprecated", sanitize(component));

            let mut message = format!(
                "`<{}>` from `{}` uses the old API.\n\
                 Migrate to the new `<{}>` from `{}`.\n",
                component, deprecated_pkg, component, base_pkg,
            );
            if let Some(tree) = composition {
                message.push_str(&format!(
                    "\nNew composition structure:\n{}",
                    format_tree_as_jsx(tree),
                ));
            }

            rules.push(KonveyorRule {
                rule_id,
                labels: vec![
                    "source=semver-analyzer".into(),
                    "change-type=deprecated-migration".into(),
                    format!("package={}", deprecated_pkg),
                    format!("target-package={}", base_pkg),
                ],
                effort: 5,
                category: "mandatory".into(),
                description: format!(
                    "<{}> from /deprecated — migrate to new API in {}",
                    component, base_pkg
                ),
                message,
                links: vec![],
                when: KonveyorCondition::FrontendReferenced {
                    referenced: FrontendReferencedFields {
                        pattern: format!("^{}$", component),
                        location: "IMPORT".into(),
                        component: None,
                        parent: None,
                        parent_from: None,
                        not_parent: None,
                        child: None,
                        not_child: None,
                        requires_child: None,
                        value: None,
                        from: Some(deprecated_pkg.clone()),
                        file_pattern: None,
                    },
                },
                fix_strategy: Some(FixStrategyEntry {
                    strategy: "DeprecatedMigration".into(),
                    from: Some(deprecated_pkg),
                    to: Some(base_pkg),
                    component: Some(component.clone()),
                    ..Default::default()
                }),
            });
        }
    }

    rules
}

/// Find the composition tree for a component (as root).
fn find_composition_tree_for<'a>(
    component: &str,
    trees: &'a [CompositionTree],
) -> Option<&'a CompositionTree> {
    trees.iter().find(|t| t.root == component)
}

/// Format a composition tree as a JSX code example.
fn format_tree_as_jsx(tree: &CompositionTree) -> String {
    let mut lines = Vec::new();

    // Build children lookup: parent → [child]
    let mut parent_children: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
    for edge in &tree.edges {
        if edge.relationship != ChildRelationship::Internal {
            parent_children
                .entry(edge.parent.as_str())
                .or_default()
                .push(edge.child.as_str());
        }
    }

    fn render(
        component: &str,
        parent_children: &BTreeMap<&str, Vec<&str>>,
        indent: usize,
        lines: &mut Vec<String>,
        visited: &mut HashSet<String>,
    ) {
        let pad = "  ".repeat(indent);
        if !visited.insert(component.to_string()) || indent > 5 {
            lines.push(format!("{}<{} />", pad, component));
            return;
        }
        if let Some(children) = parent_children.get(component) {
            lines.push(format!("{}<{}>", pad, component));
            for child in children {
                render(child, parent_children, indent + 1, lines, visited);
            }
            lines.push(format!("{}</{}>", pad, component));
        } else {
            lines.push(format!("{}<{} />", pad, component));
        }
        visited.remove(component);
    }

    let mut visited = HashSet::new();
    render(&tree.root, &parent_children, 1, &mut lines, &mut visited);
    lines.join("\n")
}

// ── Family-level strategy generation ────────────────────────────────────
//
// Generates one `FixStrategyEntry` per family that has structural composition
// changes. These entries describe the complete target v6 component structure
// so the frontend-analyzer-provider can build a single coherent LLM prompt
// per (file, family) instead of N overlapping rule-level prompts.

/// Generate family-level fix strategy entries for families with structural changes.
///
/// Returns a map of `"family:<Name>"` → `FixStrategyEntry` with the complete
/// target structure, prop assignments, and import changes.
pub fn generate_family_strategies(
    report: &AnalysisReport<TypeScript>,
    sd: &SdPipelineResult,
) -> HashMap<String, FixStrategyEntry> {
    let mut family_strats = HashMap::new();

    // Build lookup: component name → removed props (from TD pipeline)
    let mut removed_props_by_component: HashMap<String, Vec<String>> = HashMap::new();
    for file_changes in &report.changes {
        for change in &file_changes.breaking_api_changes {
            if change.change == ApiChangeType::Removed {
                if let Some(component) = extract_component_name_from_symbol(&change.symbol) {
                    if let Some(prop) = extract_prop_name_from_symbol(&change.symbol) {
                        removed_props_by_component
                            .entry(component)
                            .or_default()
                            .push(prop);
                    }
                }
            }
        }
    }

    for tree in &sd.composition_trees {
        // Skip single-component families and deprecated families
        if tree.family_members.len() <= 1 || tree.root.starts_with("deprecated/") {
            continue;
        }

        // Only generate for families that have composition changes
        let has_changes = sd.composition_changes.iter().any(|c| c.family == tree.root);
        if !has_changes {
            continue;
        }

        // 1. Render target structure with props
        let target_jsx = render_family_target_with_props(tree, &sd.new_component_props);

        // 2. Retained props (props on root in new version)
        let retained_props: Vec<String> = sd
            .new_component_props
            .get(&tree.root)
            .map(|props| {
                props
                    .iter()
                    .filter(|p| p.as_str() != "children" && p.as_str() != "className")
                    .cloned()
                    .collect()
            })
            .unwrap_or_default();

        // 3. Prop-to-child map: removed root props that appear on new children
        let mut prop_to_child: BTreeMap<String, String> = BTreeMap::new();
        let new_children: HashSet<&str> = tree
            .edges
            .iter()
            .filter(|e| e.parent == tree.root && e.relationship != ChildRelationship::Internal)
            .map(|e| e.child.as_str())
            .collect();

        if let Some(removed) = removed_props_by_component.get(&tree.root) {
            for prop_name in removed {
                for &child_name in &new_children {
                    if let Some(child_props) = sd.new_component_props.get(child_name) {
                        if child_props.contains(prop_name) {
                            prop_to_child.insert(prop_name.clone(), child_name.to_string());
                            break;
                        }
                    }
                }
            }
        }

        // 4. Child-to-parent map: props named after removed children
        let mut child_props_to_parent: BTreeMap<String, String> = BTreeMap::new();
        let old_members: HashSet<&str> = sd
            .old_composition_trees
            .iter()
            .find(|t| t.root == tree.root)
            .map(|t| t.family_members.iter().map(|m| m.as_str()).collect())
            .unwrap_or_default();
        let new_members: HashSet<&str> = tree.family_members.iter().map(|m| m.as_str()).collect();
        let removed_members: Vec<&str> = old_members.difference(&new_members).copied().collect();

        for removed_member in &removed_members {
            // Check if root gained a prop matching the child suffix
            if let Some(root_props) = sd.new_component_props.get(&tree.root) {
                let suffix = removed_member
                    .strip_prefix(&tree.root)
                    .unwrap_or(removed_member)
                    .to_lowercase();
                for prop in root_props {
                    if !suffix.is_empty() && prop.to_lowercase() == suffix {
                        child_props_to_parent.insert(
                            format!("{}.props", removed_member),
                            format!("{}.{}", tree.root, prop),
                        );
                    }
                }
            }
        }

        // 5. Removed children (in old tree but not new)
        let removed_children: Vec<String> = removed_members.iter().map(|m| m.to_string()).collect();

        // 6. New imports: ALL consumer-facing family members that need importing
        // (at any depth, not just direct children of root). Consumers must
        // import MastheadLogo even though it's a grandchild of the root
        // (MastheadBrand -> MastheadLogo).
        //
        // Excludes:
        //  - Context providers (e.g., AlertContext, FormContext) — consumers
        //    get context implicitly from the parent, not via direct import.
        //  - Members with only Internal edges — these are rendered by the
        //    parent component, not placed by the consumer.
        let consumer_facing_members: HashSet<&str> = {
            let mut members = HashSet::new();
            for edge in &tree.edges {
                if edge.relationship != ChildRelationship::Internal {
                    members.insert(edge.parent.as_str());
                    members.insert(edge.child.as_str());
                }
            }
            members
        };
        let new_imports: Vec<String> = tree
            .family_members
            .iter()
            .filter(|member| {
                let name = member.as_str();
                name != tree.root
                    && !old_members.contains(name)
                    && !name.ends_with("Context")
                    && consumer_facing_members.contains(name)
            })
            .cloned()
            .collect();

        // 7. Removed imports: old children no longer in the family
        let removed_imports: Vec<String> = removed_children.clone();

        // 8. Import source package
        let import_source = sd.component_packages.get(&tree.root).cloned();

        // 9. Prop value changes from composition changes
        let prop_value_changes: BTreeMap<String, Vec<semver_analyzer_konveyor_core::MappingEntry>> =
            BTreeMap::new();
        for change in &sd.composition_changes {
            if change.family != tree.root {
                continue;
            }
            if let CompositionChangeType::PropToChild { props, child, .. } = &change.change_type {
                for prop in props {
                    prop_to_child.insert(prop.clone(), child.clone());
                }
            }
            if let CompositionChangeType::ChildToProp { props, child, .. } = &change.change_type {
                for prop in props {
                    child_props_to_parent.insert(
                        format!("{}.content", child),
                        format!("{}.{}", tree.root, prop),
                    );
                }
            }
        }

        // 10. Deprecated migration context: cross-reference MigrationTarget
        //     with prop type maps to build a complete old→new mapping.
        //
        //     Look for a MigrationTarget whose replacement matches this family's
        //     root Props interface (e.g., "SelectProps" → "SelectProps"). This
        //     means a deprecated component was removed and detected as having a
        //     migration path to this family's root.
        let deprecated_migration = build_deprecated_migration_context(&tree.root, report, sd);

        // 11. Unmapped removed props: props removed from the root that don't
        //     have an exact prop-name match on any child (not in prop_to_child).
        //     Uses the shared classifier to determine where each prop should go.
        let unmapped_removed_props = {
            use crate::konveyor::classify_removed_props;
            let mut unmapped = BTreeMap::new();

            // Find the TypeSummary for this family root to get
            // removed_members and child_components.
            let type_summary = report
                .packages
                .iter()
                .flat_map(|pkg| &pkg.type_summaries)
                .find(|comp| comp.name == tree.root);

            if let Some(comp) = type_summary {
                let classifications = classify_removed_props(
                    &comp.removed_members,
                    &comp.language_data.child_components,
                );
                for c in &classifications {
                    // Skip props already in prop_to_child (exact match)
                    if prop_to_child.contains_key(&c.name) {
                        continue;
                    }
                    // Skip retained props
                    if retained_props.contains(&c.name) {
                        continue;
                    }
                    let type_hint = c.old_type.as_deref().unwrap_or("unknown type");
                    match (c.target_child.as_deref(), c.mechanism.as_str()) {
                        (Some(child), "prop") => {
                            unmapped.insert(
                                c.name.clone(),
                                format!("{} (as prop, {})", child, type_hint),
                            );
                        }
                        (Some(child), "children") => {
                            unmapped.insert(
                                c.name.clone(),
                                format!("{} (as children, {})", child, type_hint),
                            );
                        }
                        (_, "removed") => {
                            unmapped.insert(c.name.clone(), format!("removed ({})", type_hint));
                        }
                        _ => {
                            unmapped.insert(
                                c.name.clone(),
                                format!("map to appropriate child component ({})", type_hint),
                            );
                        }
                    }
                }
            }
            unmapped
        };

        // Only emit if we have meaningful data
        if target_jsx.is_empty()
            && retained_props.is_empty()
            && prop_to_child.is_empty()
            && child_props_to_parent.is_empty()
            && removed_children.is_empty()
            && deprecated_migration.is_none()
        {
            continue;
        }

        let entry = FixStrategyEntry {
            strategy: "FamilyMigration".into(),
            component: Some(tree.root.clone()),
            target_structure: Some(target_jsx),
            retained_props,
            prop_to_child,
            unmapped_removed_props,
            child_props_to_parent,
            removed_children,
            prop_value_changes,
            new_imports,
            removed_imports,
            import_source,
            deprecated_migration,
            ..Default::default()
        };

        family_strats.insert(format!("family:{}", tree.root), entry);
    }

    family_strats
}

/// Build a `DeprecatedMigrationContext` for a family root by finding
/// `MigrationTarget` entries where the replacement matches this family's
/// Props interface, then cross-referencing with prop type maps.
fn build_deprecated_migration_context(
    family_root: &str,
    report: &AnalysisReport<TypeScript>,
    sd: &SdPipelineResult,
) -> Option<semver_analyzer_konveyor_core::DeprecatedMigrationContext> {
    let root_props_name = format!("{}Props", family_root);

    // Find the MigrationTarget where replacement_symbol matches our root Props.
    // This means a deprecated interface was detected as migrating TO this family.
    let mut best_mt: Option<&MigrationTarget> = None;
    let mut best_change_file: Option<String> = None;

    for file_changes in &report.changes {
        let file_str = file_changes.file.to_string_lossy();
        for change in &file_changes.breaking_api_changes {
            if let Some(ref mt) = change.migration_target {
                if mt.replacement_symbol == root_props_name && mt.removed_symbol != root_props_name
                {
                    // Prefer higher overlap ratio
                    let dominated = best_mt
                        .map(|prev| mt.overlap_ratio > prev.overlap_ratio)
                        .unwrap_or(true);
                    if dominated {
                        best_mt = Some(mt);
                        best_change_file = Some(file_str.to_string());
                    }
                }
                // Also check deprecated→promoted same-name migration
                // (e.g., deprecated SelectProps → promoted SelectProps)
                if mt.replacement_symbol == root_props_name && mt.removed_symbol == root_props_name
                {
                    // Same-name migration (deprecated → promoted version)
                    let is_deprecated = change.qualified_name.contains("deprecated")
                        || file_str.contains("deprecated");
                    if is_deprecated {
                        let dominated = best_mt
                            .map(|prev| mt.overlap_ratio > prev.overlap_ratio)
                            .unwrap_or(true);
                        if dominated {
                            best_mt = Some(mt);
                            best_change_file = Some(file_str.to_string());
                        }
                    }
                }
            }
        }
    }

    let mt = best_mt?;

    // Determine old/new package from component_packages or the file path.
    let old_package = mt
        .removed_package
        .clone()
        .or_else(|| {
            best_change_file.as_deref().and_then(|f| {
                if f.contains("deprecated") {
                    sd.old_component_packages
                        .get(family_root)
                        .cloned()
                        .map(|p| {
                            if p.contains("/deprecated") {
                                p
                            } else {
                                format!("{}/deprecated", p)
                            }
                        })
                } else {
                    sd.old_component_packages.get(family_root).cloned()
                }
            })
        })
        .unwrap_or_else(|| "@patternfly/react-core/deprecated".to_string());

    let new_package = mt
        .replacement_package
        .clone()
        .or_else(|| sd.component_packages.get(family_root).cloned())
        .unwrap_or_else(|| "@patternfly/react-core".to_string());

    // Cross-reference matching members with prop type maps.
    let old_types = sd.old_component_prop_types.get(family_root);
    let new_types = sd.new_component_prop_types.get(family_root);

    let matching_props: Vec<semver_analyzer_konveyor_core::PropMigrationEntry> = mt
        .matching_members
        .iter()
        .map(|m| {
            let ot = old_types.and_then(|t| t.get(&m.old_name)).cloned();
            let nt = new_types.and_then(|t| t.get(&m.new_name)).cloned();
            let type_changed = match (&ot, &nt) {
                (Some(a), Some(b)) => a != b,
                _ => false,
            };
            semver_analyzer_konveyor_core::PropMigrationEntry {
                old_name: m.old_name.clone(),
                new_name: m.new_name.clone(),
                old_type: ot,
                new_type: nt,
                type_changed,
            }
        })
        .collect();

    // Compute new-only props: props on the v6 component that have NO match
    // in the deprecated component's matching or removed lists.
    let matching_new_names: HashSet<&str> = mt
        .matching_members
        .iter()
        .map(|m| m.new_name.as_str())
        .collect();
    let new_props: BTreeMap<String, String> = new_types
        .map(|types| {
            types
                .iter()
                .filter(|(name, _)| {
                    !matching_new_names.contains(name.as_str())
                        && name.as_str() != "children"
                        && name.as_str() != "className"
                })
                .map(|(name, typ)| (name.clone(), typ.clone()))
                .collect()
        })
        .unwrap_or_default();

    let removed_props = mt.removed_only_members.clone();

    // Only return if we have meaningful data
    if matching_props.is_empty() && new_props.is_empty() && removed_props.is_empty() {
        return None;
    }

    Some(semver_analyzer_konveyor_core::DeprecatedMigrationContext {
        old_package,
        new_package,
        matching_props,
        new_props,
        removed_props,
    })
}

/// Render a family's target JSX structure with prop names on each component.
fn render_family_target_with_props(
    tree: &CompositionTree,
    new_props: &HashMap<String, BTreeSet<String>>,
) -> String {
    let mut lines = Vec::new();

    // Build children lookup: parent → [child]
    let mut parent_children: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
    for edge in &tree.edges {
        if edge.relationship != ChildRelationship::Internal {
            parent_children
                .entry(edge.parent.as_str())
                .or_default()
                .push(edge.child.as_str());
        }
    }

    fn render(
        component: &str,
        parent_children: &BTreeMap<&str, Vec<&str>>,
        new_props: &HashMap<String, BTreeSet<String>>,
        indent: usize,
        lines: &mut Vec<String>,
        visited: &mut HashSet<String>,
    ) {
        let pad = "  ".repeat(indent);
        if !visited.insert(component.to_string()) || indent > 5 {
            lines.push(format!("{}<{} />", pad, component));
            return;
        }

        // Format props for this component (show most important ones)
        let props_str = if let Some(props) = new_props.get(component) {
            let display_props: Vec<String> = props
                .iter()
                .filter(|p| p.as_str() != "children" && p.as_str() != "className")
                .take(8) // limit to avoid overly long lines
                .map(|p| format!("{}={{...}}", p))
                .collect();
            if display_props.is_empty() {
                String::new()
            } else {
                format!(" {}", display_props.join(" "))
            }
        } else {
            String::new()
        };

        if let Some(children) = parent_children.get(component) {
            lines.push(format!("{}<{}{}>", pad, component, props_str));
            for child in children {
                render(
                    child,
                    parent_children,
                    new_props,
                    indent + 1,
                    lines,
                    visited,
                );
            }
            lines.push(format!("{}</{}>", pad, component));
        } else {
            lines.push(format!("{}<{}{} />", pad, component, props_str));
        }
        visited.remove(component);
    }

    let mut visited = HashSet::new();
    render(
        &tree.root,
        &parent_children,
        new_props,
        1,
        &mut lines,
        &mut visited,
    );
    lines.join("\n")
}

// ── Helper types ────────────────────────────────────────────────────────

struct RemovedProp {
    name: String,
    #[allow(dead_code)]
    component: String,
    is_reactnode: bool,
    #[allow(dead_code)]
    before_type: Option<String>,
}

// ── Prop value conformance rules ────────────────────────────────────────
//
// When a prop's string union type narrows (values removed), generate a rule
// that fires on the removed value. E.g., if PageSection.variant lost "dark",
// fire on `<PageSection variant="dark">`.

fn generate_prop_value_conformance_rules(
    report: &AnalysisReport<crate::language::TypeScript>,
    sd: &SdPipelineResult,
    component_packages: &HashMap<String, String>,
) -> Vec<KonveyorRule> {
    let mut rules = Vec::new();

    for fc in &report.changes {
        for api in &fc.breaking_api_changes {
            if api.change != ApiChangeType::TypeChanged {
                continue;
            }
            let symbol = &api.symbol;
            if !symbol.contains('.') {
                continue;
            }

            let component = match extract_component_name_from_symbol(symbol) {
                Some(c) => c,
                None => continue,
            };
            let prop = match extract_prop_name_from_symbol(symbol) {
                Some(p) => p,
                None => continue,
            };

            let before = match &api.before {
                Some(b) => b,
                None => continue,
            };
            let after = match &api.after {
                Some(a) => a,
                None => continue,
            };

            // Extract string literal values from union types
            let old_values: HashSet<String> = extract_union_values(before);
            let new_values: HashSet<String> = extract_union_values(after);

            if old_values.is_empty() {
                continue;
            }

            let removed: Vec<&String> = old_values.difference(&new_values).collect();
            if removed.is_empty() {
                continue;
            }

            let pkg = pkg_for(&component, component_packages);

            // Generate one rule per removed value for precise matching
            for value in &removed {
                let rule_id = format!(
                    "sd-prop-value-{}-{}-{}",
                    sanitize(&component),
                    sanitize(&prop),
                    sanitize(value),
                );

                // Find replacement suggestion if there's a close match in new values
                let replacement_hint = find_replacement_value(value, &new_values);
                let message = if let Some(ref replacement) = replacement_hint {
                    format!(
                        "The value \"{}\" is no longer valid for the `{}` prop on <{}>.\n\
                         Use \"{}\" instead.\n\n\
                         Old: <{component} {prop}=\"{value}\" />\n\
                         New: <{component} {prop}=\"{replacement}\" />",
                        value,
                        prop,
                        component,
                        replacement,
                        component = component,
                        prop = prop,
                        value = value,
                        replacement = replacement,
                    )
                } else {
                    format!(
                        "The value \"{}\" is no longer valid for the `{}` prop on <{}>.\n\
                         Valid values: {}",
                        value,
                        prop,
                        component,
                        new_values
                            .iter()
                            .map(|v| format!("\"{}\"", v))
                            .collect::<Vec<_>>()
                            .join(", "),
                    )
                };

                rules.push(KonveyorRule {
                    rule_id,
                    labels: vec![
                        "source=semver-analyzer".into(),
                        "change-type=prop-value-removed".into(),
                        format!("package={}", pkg),
                    ],
                    effort: 1,
                    category: "mandatory".into(),
                    description: format!(
                        "Value \"{}\" removed from `{}` prop on <{}>",
                        value, prop, component,
                    ),
                    message,
                    links: vec![],
                    when: KonveyorCondition::FrontendReferenced {
                        referenced: FrontendReferencedFields {
                            pattern: format!("^{}$", prop),
                            location: "JSX_PROP".into(),
                            component: Some(format!("^{}$", component)),
                            parent: None,
                            not_parent: None,
                            child: None,
                            not_child: None,
                            requires_child: None,
                            parent_from: None,
                            value: Some(format!("^{}$", regex::escape(value))),
                            from: Some(pkg.to_string()),
                            file_pattern: None,
                        },
                    },
                    fix_strategy: Some(FixStrategyEntry {
                        strategy: "PropValueChange".into(),
                        component: Some(component.clone()),
                        prop: Some(prop.clone()),
                        from: Some(value.to_string()),
                        replacement: replacement_hint,
                        ..Default::default()
                    }),
                });
            }
        }
    }

    // ── Phase 2: Renamed props with value changes ────────────────────
    //
    // When a prop is renamed (e.g., spacer → gap), the values may also
    // change (e.g., spacerNone → gapNone). Detect these by comparing
    // old prop type (from old_component_prop_types) with new prop type
    // (from new_component_prop_types). Generate per-value rules that
    // trigger on the old value in EITHER the old or new prop name.
    for fc in &report.changes {
        for api in &fc.breaking_api_changes {
            if api.change != ApiChangeType::Renamed {
                continue;
            }
            let symbol = &api.symbol;
            if !symbol.contains('.') {
                continue;
            }

            let component = match extract_component_name_from_symbol(symbol) {
                Some(c) => c,
                None => continue,
            };
            let old_prop = match extract_prop_name_from_symbol(symbol) {
                Some(p) => p,
                None => continue,
            };
            let new_prop = match &api.after {
                Some(a) => a.clone(),
                None => continue,
            };

            // Look up old and new types from SD prop type data
            let old_type = sd
                .old_component_prop_types
                .get(&component)
                .and_then(|m| m.get(&old_prop));
            let new_type = sd
                .new_component_prop_types
                .get(&component)
                .and_then(|m| m.get(&new_prop));

            let (old_type, new_type) = match (old_type, new_type) {
                (Some(o), Some(n)) => (o, n),
                _ => continue,
            };

            let old_values = extract_union_values(old_type);
            let new_values = extract_union_values(new_type);

            if old_values.is_empty() || new_values.is_empty() {
                continue;
            }

            let removed: Vec<&String> = old_values.difference(&new_values).collect();
            if removed.is_empty() {
                continue;
            }

            let pkg = pkg_for(&component, component_packages);

            for value in &removed {
                let replacement_hint = find_replacement_value(value, &new_values);

                // Generate rules for BOTH old and new prop names, since the
                // rename fix may or may not have been applied yet.
                for prop in &[&old_prop, &new_prop] {
                    let rule_id = format!(
                        "sd-prop-value-{}-{}-{}",
                        sanitize(&component),
                        sanitize(prop),
                        sanitize(value),
                    );

                    let message = if let Some(ref replacement) = replacement_hint {
                        format!(
                            "The value \"{value}\" is no longer valid for the `{prop}` prop on <{component}>.\n\
                             Use \"{replacement}\" instead.\n\n\
                             Old: <{component} {prop}=\"{value}\" />\n\
                             New: <{component} {prop}=\"{replacement}\" />\n\n\
                             Note: `{old_prop}` was renamed to `{new_prop}`.",
                            value = value,
                            prop = prop,
                            component = component,
                            replacement = replacement,
                            old_prop = old_prop,
                            new_prop = new_prop,
                        )
                    } else {
                        let valid = new_values
                            .iter()
                            .map(|v| format!("\"{}\"", v))
                            .collect::<Vec<_>>()
                            .join(", ");
                        format!(
                            "The value \"{value}\" is no longer valid for the `{prop}` prop on <{component}>.\n\
                             Note: `{old_prop}` was renamed to `{new_prop}`.\n\
                             Valid values: {valid}",
                            value = value,
                            prop = prop,
                            component = component,
                            old_prop = old_prop,
                            new_prop = new_prop,
                            valid = valid,
                        )
                    };

                    rules.push(KonveyorRule {
                        rule_id,
                        labels: vec![
                            "source=semver-analyzer".into(),
                            "change-type=prop-value-removed".into(),
                            format!("package={}", pkg),
                        ],
                        effort: 1,
                        category: "mandatory".into(),
                        description: format!(
                            "Value \"{}\" removed from `{}` prop on <{}> (renamed from `{}`)",
                            value, prop, component, old_prop,
                        ),
                        message,
                        links: vec![],
                        when: KonveyorCondition::FrontendReferenced {
                            referenced: FrontendReferencedFields {
                                pattern: format!("^{}$", prop),
                                location: "JSX_PROP".into(),
                                component: Some(format!("^{}$", component)),
                                parent: None,
                                not_parent: None,
                                child: None,
                                not_child: None,
                                requires_child: None,
                                parent_from: None,
                                value: Some(format!("^{}$", regex::escape(value))),
                                from: Some(pkg.to_string()),
                                file_pattern: None,
                            },
                        },
                        fix_strategy: Some(FixStrategyEntry {
                            strategy: "PropValueChange".into(),
                            component: Some(component.clone()),
                            prop: Some(prop.to_string()),
                            from: Some(value.to_string()),
                            replacement: replacement_hint.clone(),
                            ..Default::default()
                        }),
                    });
                }
            }
        }
    }

    rules
}

/// Extract string literal values from a TypeScript union type string.
/// E.g., "'dark' | 'light' | 'default'" → {"dark", "light", "default"}
fn extract_union_values(type_str: &str) -> HashSet<String> {
    let re = regex::Regex::new(r"'([^']+)'").unwrap();
    re.captures_iter(type_str)
        .map(|c| c[1].to_string())
        .collect()
}

/// Try to find a replacement value in the new set for a removed value.
/// Heuristic: looks for common PF rename patterns.
fn find_replacement_value(removed: &str, new_values: &HashSet<String>) -> Option<String> {
    // Common PF v5→v6 renames
    let mappings = [
        ("light", "secondary"),
        ("dark", "secondary"),
        ("darker", "secondary"),
        ("light-200", "secondary"),
        ("light300", "secondary"),
        ("tertiary", "secondary"),
        ("cyan", "teal"),
        ("gold", "yellow"),
        ("alignLeft", "start"),
        ("alignRight", "end"),
        ("button-group", "action-group"),
        ("icon-button-group", "action-group-plain"),
        ("chip-group", "label-group"),
        ("TableComposable", "default"),
    ];

    for (old, new) in &mappings {
        if removed == *old && new_values.contains(*new) {
            return Some(new.to_string());
        }
    }

    None
}

// ── Required prop added rules ───────────────────────────────────────────
//
// When a component gains a new REQUIRED prop (not optional, no default),
// fire on every usage of that component to warn that the prop must be provided.

fn generate_required_prop_added_rules(
    sd: &SdPipelineResult,
    component_packages: &HashMap<String, String>,
) -> Vec<KonveyorRule> {
    let mut rules = Vec::new();

    for (component, required) in &sd.new_required_props {
        let old_props = sd.old_component_props.get(component);
        let old_required = old_props.cloned().unwrap_or_default();

        // Find required props that are NEW (not in old version)
        let newly_required: Vec<&String> = required
            .iter()
            .filter(|p| !old_required.contains(*p))
            // Skip children — it's always "required" but passed as JSX children
            .filter(|p| p.as_str() != "children")
            .collect();

        if newly_required.is_empty() {
            continue;
        }

        let pkg = pkg_for(component, component_packages);

        for prop in &newly_required {
            let rule_id = format!(
                "sd-required-prop-{}-{}",
                sanitize(component),
                sanitize(prop),
            );

            // Look up the type for context
            let type_hint = sd
                .new_component_prop_types
                .get(component)
                .and_then(|types| types.get(*prop))
                .map(|t| format!(" (type: `{}`)", t))
                .unwrap_or_default();

            rules.push(KonveyorRule {
                rule_id,
                labels: vec![
                    "source=semver-analyzer".into(),
                    "change-type=required-prop-added".into(),
                    format!("package={}", pkg),
                ],
                effort: 1,
                category: "mandatory".into(),
                description: format!(
                    "<{}> now requires the `{}` prop{}",
                    component, prop, type_hint,
                ),
                message: format!(
                    "<{}> has a new required prop `{}`{}.\n\
                     This prop must be provided — omitting it will cause a TypeScript error.\n\n\
                     Add the prop: <{} {}={{...}} />",
                    component, prop, type_hint, component, prop,
                ),
                links: vec![],
                when: KonveyorCondition::FrontendReferenced {
                    referenced: FrontendReferencedFields {
                        pattern: format!("^{}$", component),
                        location: "JSX_COMPONENT".into(),
                        component: None,
                        parent: None,
                        not_parent: None,
                        child: None,
                        not_child: None,
                        requires_child: None,
                        parent_from: None,
                        value: None,
                        from: Some(pkg.to_string()),
                        file_pattern: None,
                    },
                },
                fix_strategy: Some(FixStrategyEntry {
                    strategy: "LlmAssisted".into(),
                    component: Some(component.clone()),
                    prop: Some(prop.to_string()),
                    ..Default::default()
                }),
            });
        }
    }

    rules
}

// ── Test impact rules ───────────────────────────────────────────────────
//
// Generate rules that match testing-library function calls in test files
// when a component's rendered ARIA roles, aria-label values, or DOM
// structure has changed between versions.

/// Testing Library query function pattern (all variants).
const ROLE_QUERY_PATTERN: &str =
    "^(getByRole|queryByRole|findByRole|getAllByRole|queryAllByRole|findAllByRole)$";
const LABEL_QUERY_PATTERN: &str =
    "^(getByLabelText|queryByLabelText|findByLabelText|getAllByLabelText|queryAllByLabelText|findAllByLabelText)$";
const DATA_ATTR_QUERY_PATTERN: &str =
    "^(querySelector|querySelectorAll|getByAttribute|queryByAttribute|findByAttribute)$";
const TEST_FILE_PATTERN: &str = ".*\\.(test|spec)\\.(ts|tsx|js|jsx)$";

/// Map HTML element names to their implicit ARIA roles.
fn implicit_aria_role(element: &str) -> Option<&'static str> {
    match element {
        "button" => Some("button"),
        "input" => Some("textbox"),
        "a" => Some("link"),
        "img" => Some("img"),
        "select" => Some("combobox"),
        "textarea" => Some("textbox"),
        "table" => Some("table"),
        "tr" => Some("row"),
        "td" => Some("cell"),
        "th" => Some("columnheader"),
        "ul" | "ol" => Some("list"),
        "li" => Some("listitem"),
        "nav" => Some("navigation"),
        "main" => Some("main"),
        "header" => Some("banner"),
        "footer" => Some("contentinfo"),
        "form" => Some("form"),
        "dialog" => Some("dialog"),
        "article" => Some("article"),
        "section" => Some("region"),
        "aside" => Some("complementary"),
        "progress" => Some("progressbar"),
        _ => None,
    }
}

/// Check if a value is a concrete string literal (not a JSX expression).
fn is_concrete_value(value: &str) -> bool {
    !value.starts_with('{') && value != "true" && value != "false"
}

fn generate_test_impact_rules(
    changes: &[SourceLevelChange],
    component_packages: &HashMap<String, String>,
) -> Vec<KonveyorRule> {
    let mut rules = Vec::new();

    for change in changes {
        if !change.has_test_implications {
            continue;
        }

        let pkg = pkg_for(&change.component, component_packages);

        match change.category {
            // ── Role changes: match getByRole('oldValue') ───────────
            SourceLevelCategory::RoleChange => {
                // Role removed — tests using getByRole('X') will break
                if let Some(ref old_val) = change.old_value {
                    if !is_concrete_value(old_val) {
                        continue;
                    }

                    let prefix = rule_prefix(&change.migration_from);
                    let elem_part = change
                        .element
                        .as_deref()
                        .map(|e| format!("-{}", sanitize(e)))
                        .unwrap_or_default();
                    let rule_id = format!(
                        "{}-test-{}-role-{}{}-{}",
                        prefix,
                        sanitize(&change.component),
                        sanitize(old_val),
                        elem_part,
                        if change.new_value.is_some() {
                            "changed"
                        } else {
                            "removed"
                        },
                    );

                    let message = if let Some(ref new_val) = change.new_value {
                        if is_concrete_value(new_val) {
                            format!(
                                "{} role changed from '{}' to '{}'.\n\n\
                                 Update test queries:\n  \
                                 getByRole('{}') → getByRole('{}')",
                                change.component, old_val, new_val, old_val, new_val
                            )
                        } else {
                            format!(
                                "{} role '{}' changed to a dynamic value.\n\n\
                                 Tests using getByRole('{}') may need updating.\n\n\
                                 {}",
                                change.component, old_val, old_val, change.description
                            )
                        }
                    } else {
                        format!(
                            "{} no longer has role='{}'.\n\n\
                             Tests using getByRole('{}') to find this component will fail.\n\n\
                             {}",
                            change.component, old_val, old_val, change.description
                        )
                    };

                    rules.push(KonveyorRule {
                        rule_id,
                        labels: vec![
                            "source=semver-analyzer".into(),
                            "change-type=test-impact".into(),
                            "impact=frontend-testing".into(),
                            format!("package={}", pkg),
                        ],
                        effort: 1,
                        category: "optional".into(),
                        description: format!(
                            "Test impact: {} role '{}' {}",
                            change.component,
                            old_val,
                            if change.new_value.is_some() {
                                "changed"
                            } else {
                                "removed"
                            }
                        ),
                        message,
                        links: vec![],
                        when: KonveyorCondition::FrontendReferenced {
                            referenced: FrontendReferencedFields {
                                pattern: ROLE_QUERY_PATTERN.into(),
                                location: "FUNCTION_CALL".into(),
                                component: None,
                                parent: None,
                                not_parent: None,
                                child: None,
                                not_child: None,
                                requires_child: None,
                                parent_from: None,
                                value: Some(format!("^{}$", old_val)),
                                from: None,
                                file_pattern: Some(TEST_FILE_PATTERN.into()),
                            },
                        },
                        fix_strategy: None,
                    });
                }
            }

            // ── ARIA label changes: match getByLabelText('oldValue') ─
            SourceLevelCategory::AriaChange => {
                // Only generate rules for aria-label changes (not aria-hidden, etc.)
                if !change.description.contains("aria-label") {
                    continue;
                }

                if let Some(ref old_val) = change.old_value {
                    if !is_concrete_value(old_val) {
                        continue;
                    }

                    let prefix = rule_prefix(&change.migration_from);
                    let elem_part = change
                        .element
                        .as_deref()
                        .map(|e| format!("-{}", sanitize(e)))
                        .unwrap_or_default();
                    let rule_id = format!(
                        "{}-test-{}-aria-label-{}{}-{}",
                        prefix,
                        sanitize(&change.component),
                        sanitize(old_val),
                        elem_part,
                        if change.new_value.is_some() {
                            "changed"
                        } else {
                            "removed"
                        },
                    );

                    let message = if let Some(ref new_val) = change.new_value {
                        if is_concrete_value(new_val) {
                            format!(
                                "{} aria-label changed from '{}' to '{}'.\n\n\
                                 Update test queries:\n  \
                                 getByLabelText('{}') → getByLabelText('{}')",
                                change.component, old_val, new_val, old_val, new_val
                            )
                        } else {
                            format!(
                                "{} aria-label '{}' changed to a dynamic value.\n\n\
                                 Tests using getByLabelText('{}') may need updating.\n\n\
                                 {}",
                                change.component, old_val, old_val, change.description
                            )
                        }
                    } else {
                        format!(
                            "{} no longer has aria-label='{}'.\n\n\
                             Tests using getByLabelText('{}') to find this component will fail.\n\n\
                             {}",
                            change.component, old_val, old_val, change.description
                        )
                    };

                    rules.push(KonveyorRule {
                        rule_id,
                        labels: vec![
                            "source=semver-analyzer".into(),
                            "change-type=test-impact".into(),
                            "impact=frontend-testing".into(),
                            format!("package={}", pkg),
                        ],
                        effort: 1,
                        category: "optional".into(),
                        description: format!(
                            "Test impact: {} aria-label '{}' {}",
                            change.component,
                            old_val,
                            if change.new_value.is_some() {
                                "changed"
                            } else {
                                "removed"
                            }
                        ),
                        message,
                        links: vec![],
                        when: KonveyorCondition::FrontendReferenced {
                            referenced: FrontendReferencedFields {
                                pattern: LABEL_QUERY_PATTERN.into(),
                                location: "FUNCTION_CALL".into(),
                                component: None,
                                parent: None,
                                not_parent: None,
                                child: None,
                                not_child: None,
                                requires_child: None,
                                parent_from: None,
                                value: Some(format!("^{}$", old_val)),
                                from: None,
                                file_pattern: Some(TEST_FILE_PATTERN.into()),
                            },
                        },
                        fix_strategy: None,
                    });
                }
            }

            // ── DOM structure changes: match getByRole(implicit_role) ─
            SourceLevelCategory::DomStructure => {
                // Element removed — tests using getByRole for its implicit
                // role may break (e.g., <button> removed → getByRole('button'))
                if let Some(ref old_val) = change.old_value {
                    // Extract element name from values like "<button>" or "<button> (×2)"
                    let element = old_val
                        .trim_start_matches('<')
                        .split('>')
                        .next()
                        .unwrap_or("")
                        .trim();

                    if let Some(role) = implicit_aria_role(element) {
                        let prefix = rule_prefix(&change.migration_from);
                        let rule_id = format!(
                            "{}-test-{}-dom-{}-removed",
                            prefix,
                            sanitize(&change.component),
                            sanitize(element),
                        );

                        rules.push(KonveyorRule {
                            rule_id,
                            labels: vec![
                                "source=semver-analyzer".into(),
                                "change-type=test-impact".into(),
                                "impact=frontend-testing".into(),
                                format!("package={}", pkg),
                            ],
                            effort: 1,
                            category: "optional".into(),
                            description: format!(
                                "Test impact: {} no longer renders <{}>",
                                change.component, element
                            ),
                            message: format!(
                                "{} no longer renders a <{}> element (implicit role='{}').\n\n\
                                 Tests using getByRole('{}') inside {} may fail.\n\n\
                                 {}",
                                change.component,
                                element,
                                role,
                                role,
                                change.component,
                                change.description,
                            ),
                            links: vec![],
                            when: KonveyorCondition::FrontendReferenced {
                                referenced: FrontendReferencedFields {
                                    pattern: ROLE_QUERY_PATTERN.into(),
                                    location: "FUNCTION_CALL".into(),
                                    component: None,
                                    parent: None,
                                    not_parent: None,
                                    child: None,
                                    not_child: None,
                                    requires_child: None,
                                    parent_from: None,
                                    value: Some(format!("^{}$", role)),
                                    from: None,
                                    file_pattern: Some(TEST_FILE_PATTERN.into()),
                                },
                            },
                            fix_strategy: None,
                        });
                    }
                }
            }

            // ── Data attribute changes: match querySelector/getByAttribute ─
            SourceLevelCategory::DataAttribute => {
                // Only generate rules for transitive changes (via dependency chain)
                if change.dependency_chain.is_none() {
                    continue;
                }

                // Skip rules for fully-removed components (not in component_packages).
                // If the component doesn't exist in v6, the OUIA value change is moot —
                // the entire component needs migration, which TD rules already cover.
                if !component_packages.contains_key(&change.component) {
                    continue;
                }

                if let Some(ref old_val) = change.old_value {
                    // Parse the old_value format: `attr_name="value"`
                    // Example: `data-ouia-component-type="PF5/${componentType}"`
                    let (attr_name, raw_old_value) = if let Some(idx) = old_val.find("=\"") {
                        let attr = &old_val[..idx];
                        let val = old_val[idx + 2..].trim_end_matches('"');
                        (attr.to_string(), val.to_string())
                    } else if let Some(idx) = old_val.find(": ") {
                        // Fallback: `attr: value` format
                        (old_val[..idx].to_string(), old_val[idx + 2..].to_string())
                    } else {
                        continue;
                    };

                    // Parse new_value with same format
                    let raw_new_value = change.new_value.as_ref().and_then(|nv| {
                        if let Some(idx) = nv.find("=\"") {
                            Some(nv[idx + 2..].trim_end_matches('"').to_string())
                        } else {
                            nv.find(": ").map(|idx| nv[idx + 2..].to_string())
                        }
                    });

                    // Substitute template variables (e.g., `${componentType}`)
                    // with the component name. PatternFly convention: the OUIA
                    // component type matches the React component name.
                    let component = &change.component;
                    let old_value = raw_old_value.replace("${componentType}", component);
                    let new_value = raw_new_value
                        .as_ref()
                        .map(|v| v.replace("${componentType}", component));

                    if !is_concrete_value(&old_value) {
                        continue;
                    }

                    let prefix = rule_prefix(&change.migration_from);
                    let rule_id = format!(
                        "{}-test-{}-data-attr-{}-changed",
                        prefix,
                        sanitize(component),
                        sanitize(&attr_name),
                    );

                    let message = if let Some(ref new_val) = new_value {
                        if is_concrete_value(new_val) {
                            format!(
                                "{component} `{attr}` value changed from `{old}` to `{new}`.\n\n\
                                 Update test selectors:\n  \
                                 `querySelector('[{attr}=\"{old}\"]')` → `querySelector('[{attr}=\"{new}\"]')`",
                                attr = attr_name,
                                old = old_value,
                                new = new_val,
                            )
                        } else {
                            format!(
                                "{component} `{attr}` value changed from `{old}` to a dynamic value.\n\n\
                                 Tests using `querySelector('[{attr}=\"{old}\"]')` may need updating.\n\n\
                                 {desc}",
                                attr = attr_name,
                                old = old_value,
                                desc = change.description,
                            )
                        }
                    } else {
                        format!(
                            "{component} `{attr}` value `{old}` was removed.\n\n\
                             Tests using `querySelector('[{attr}=\"{old}\"]')` will fail.\n\n\
                             {desc}",
                            attr = attr_name,
                            old = old_value,
                            desc = change.description,
                        )
                    };

                    let fix =
                        new_value
                            .as_ref()
                            .filter(|nv| is_concrete_value(nv))
                            .map(|new_val| {
                                use semver_analyzer_konveyor_core::FixStrategyEntry;
                                FixStrategyEntry {
                                    strategy: "PropValueChange".into(),
                                    from: Some(old_value.clone()),
                                    to: Some(new_val.clone()),
                                    component: Some(component.clone()),
                                    prop: Some(attr_name.clone()),
                                    ..Default::default()
                                }
                            });

                    rules.push(KonveyorRule {
                        rule_id,
                        labels: vec![
                            "source=semver-analyzer".into(),
                            "change-type=test-impact".into(),
                            "impact=frontend-testing".into(),
                            format!("package={}", pkg),
                        ],
                        effort: 1,
                        category: "optional".into(),
                        description: format!(
                            "Test impact: {} `{}` value changed",
                            component, attr_name,
                        ),
                        message,
                        links: vec![],
                        when: KonveyorCondition::FrontendReferenced {
                            referenced: FrontendReferencedFields {
                                pattern: DATA_ATTR_QUERY_PATTERN.into(),
                                location: "FUNCTION_CALL".into(),
                                component: None,
                                parent: None,
                                not_parent: None,
                                child: None,
                                not_child: None,
                                requires_child: None,
                                parent_from: None,
                                value: Some(format!(".*{}.*", regex_escape(&old_value))),
                                from: None,
                                file_pattern: Some(TEST_FILE_PATTERN.into()),
                            },
                        },
                        fix_strategy: fix,
                    });
                }
            }

            _ => {}
        }
    }

    rules
}

// ── CSS class removal rules ─────────────────────────────────────────────
//
// When entire CSS component blocks are removed between PF versions (e.g.,
// Select CSS removed because Select now uses Menu's CSS), generate rules
// that flag consumer CSS files referencing the removed class prefixes.

// ── Composition inversion rules ─────────────────────────────────────────
// Detect when an internal subcomponent was removed from a family and the
// parent gained a render-function prop instead. The consumer must now provide
// the subcomponent via a render prop rather than having it managed internally.
//
// Example: deprecated Select rendered <SelectToggle> internally. Next-gen
// Select exposes `toggle: (toggleRef) => ReactNode` — the consumer provides
// <MenuToggle> via the render prop.

/// Returns true if the type string looks like a render function — a function
/// that returns a React element. Matches patterns like:
/// - `(toggleRef: React.Ref<...>) => React.ReactNode`
/// - `((toggleRef: React.RefObject<any>) => React.ReactNode) | SelectToggleProps`
fn is_render_prop_type(type_str: &str) -> bool {
    type_str.contains("=>") && {
        let lower = type_str.to_lowercase();
        lower.contains("reactnode")
            || lower.contains("react.reactnode")
            || lower.contains("reactelement")
            || lower.contains("jsx.element")
    }
}

fn generate_composition_inversion_rules(
    sd: &SdPipelineResult,
    component_packages: &HashMap<String, String>,
) -> Vec<KonveyorRule> {
    let mut rules = Vec::new();

    for new_tree in &sd.composition_trees {
        let root = &new_tree.root;
        let pkg = pkg_for(root, component_packages);

        // Find the old tree for this family
        let old_tree = match sd.old_composition_trees.iter().find(|t| t.root == *root) {
            Some(t) => t,
            None => continue,
        };

        // Find removed family members (in old tree but not in new tree)
        let new_members: HashSet<&str> =
            new_tree.family_members.iter().map(|s| s.as_str()).collect();

        // Compute added props on the root
        let old_root_props: BTreeSet<&str> = sd
            .old_component_props
            .get(root)
            .map(|s| s.iter().map(|p| p.as_str()).collect())
            .unwrap_or_default();
        let new_root_props: BTreeSet<&str> = sd
            .new_component_props
            .get(root)
            .map(|s| s.iter().map(|p| p.as_str()).collect())
            .unwrap_or_default();
        let added_props: BTreeSet<&str> = new_root_props
            .difference(&old_root_props)
            .copied()
            .collect();

        // Get prop types for the root
        let new_prop_types = sd.new_component_prop_types.get(root);

        for old_member in &old_tree.family_members {
            // Only consider removed members
            if new_members.contains(old_member.as_str()) || old_member == root {
                continue;
            }

            // Check if any added prop on the root is a render function whose
            // name matches the removed member. We check several patterns:
            // - "SelectToggle" removed, "toggle" prop added
            // - Strip the root prefix: "Select" + "Toggle" → "toggle"
            let member_lower = old_member.to_lowercase();
            let root_lower = root.to_lowercase();
            let stripped = member_lower
                .strip_prefix(&root_lower)
                .unwrap_or(&member_lower);

            for prop_name in &added_props {
                let prop_lower = prop_name.to_lowercase();

                // Check name match: prop matches the stripped member name
                if prop_lower != stripped
                    && !stripped.contains(&prop_lower)
                    && !prop_lower.contains(stripped)
                {
                    continue;
                }

                // Check if the prop type is a render function
                let is_render = new_prop_types
                    .and_then(|types| types.get(*prop_name))
                    .map(|t| is_render_prop_type(t))
                    .unwrap_or(false);

                if !is_render {
                    continue;
                }

                // Composition inversion detected!
                let prop_type = new_prop_types
                    .and_then(|types| types.get(*prop_name))
                    .cloned()
                    .unwrap_or_default();

                let rule_id = format!(
                    "sd-composition-inversion-{}-{}-to-{}",
                    sanitize(root),
                    sanitize(old_member),
                    sanitize(prop_name),
                );

                let message = format!(
                    "<{root}> no longer internally renders <{old_member}>.\n\
                     Instead, provide a render function via the `{prop}` prop.\n\n\
                     The `{prop}` prop accepts: `{prop_type}`\n\n\
                     Before (v5):\n\
                     \x20 <{root}>\n\
                     \x20   {{/* {old_member} was rendered internally */}}\n\
                     \x20 </{root}>\n\n\
                     After (v6):\n\
                     \x20 <{root} {prop}={{(ref) => <MenuToggle ref={{ref}}>...</MenuToggle>}}>\n\
                     \x20   ...\n\
                     \x20 </{root}>\n\n\
                     Any props previously passed to <{root}> that controlled {old_member}\n\
                     (e.g., onToggle, toggleRef, toggleAriaLabel) should now be set\n\
                     directly on the component you provide via the `{prop}` render function.",
                    root = root,
                    old_member = old_member,
                    prop = prop_name,
                    prop_type = prop_type,
                );

                rules.push(KonveyorRule {
                    rule_id,
                    labels: vec![
                        "source=semver-analyzer".into(),
                        "change-type=composition-inversion".into(),
                        format!("package={}", pkg),
                        format!("family={}", root),
                    ],
                    effort: 5,
                    category: "mandatory".into(),
                    description: format!(
                        "<{}> internal <{}> replaced by `{}` render prop",
                        root, old_member, prop_name,
                    ),
                    message,
                    links: vec![],
                    when: KonveyorCondition::FrontendReferenced {
                        referenced: FrontendReferencedFields {
                            pattern: format!("^{}$", regex_escape(root)),
                            location: "IMPORT".into(),
                            component: None,
                            parent: None,
                            not_parent: None,
                            child: None,
                            not_child: None,
                            requires_child: None,
                            parent_from: None,
                            value: None,
                            from: Some(pkg.clone()),
                            file_pattern: None,
                        },
                    },
                    fix_strategy: Some(FixStrategyEntry {
                        strategy: "CompositionInversion".into(),
                        from: Some(old_member.clone()),
                        to: Some(prop_name.to_string()),
                        component: Some(root.clone()),
                        prop: Some(prop_name.to_string()),
                        ..Default::default()
                    }),
                });

                break; // Only one rule per removed member
            }
        }
    }

    rules
}

// ── Prop attribute override rules ───────────────────────────────────────
// When a component extracts a prop, transforms it via a helper, and spreads
// the result after rest props — overriding any consumer-provided HTML attribute.

fn generate_prop_attribute_override_rules(
    changes: &[SourceLevelChange],
    _sd: &SdPipelineResult,
    component_packages: &HashMap<String, String>,
) -> Vec<KonveyorRule> {
    let mut rules = Vec::new();

    for change in changes {
        if change.category != SourceLevelCategory::PropAttributeOverride {
            continue;
        }

        // Only generate rules for "new managed attribute" (not "removed")
        if change.old_value.is_some() && change.new_value.is_none() {
            continue;
        }

        let pkg = pkg_for(&change.component, component_packages);
        let prefix = rule_prefix(&change.migration_from);

        // For migration changes, match imports from the deprecated path.
        let from_pkg = if let Some(ref mf) = change.migration_from {
            deprecated_pkg_from_migration_path(mf)
        } else {
            pkg.clone()
        };

        // Parse the new_value to extract overridden attribute names.
        // Format is "propName → attr1, attr2, attr3"
        let (prop_name, overridden_attrs) = match &change.new_value {
            Some(val) => {
                let parts: Vec<&str> = val.splitn(2, " → ").collect();
                if parts.len() == 2 {
                    let attrs: Vec<String> = parts[1]
                        .split(", ")
                        .map(|s| s.trim().to_string())
                        .filter(|s| !s.is_empty())
                        .collect();
                    (parts[0].to_string(), attrs)
                } else {
                    continue;
                }
            }
            None => continue,
        };

        // Skip when we don't know which attributes are overridden.
        // This happens when managed_attrs detected the helper spread but
        // couldn't correlate it with specific data-* attributes (e.g.,
        // useOUIAProps produces attributes at runtime, not as JSX literals).
        if overridden_attrs.is_empty() {
            continue;
        }

        // Generate one rule per overridden attribute
        for attr in &overridden_attrs {
            let rule_id = format!(
                "{}-prop-override-{}-{}-{}",
                prefix,
                sanitize(&change.component),
                sanitize(&prop_name),
                sanitize(attr),
            );

            let message = format!(
                "The <{component}> component internally generates the `{attr}` HTML \
                 attribute from the `{prop}` prop via its internal helper. If you pass \
                 `{attr}` as an HTML attribute, it will be silently overridden.\n\n\
                 Use the `{prop}` prop instead:\n\n\
                 Before: <{component} {attr}=\"value\" />\n\
                 After:  <{component} {prop}=\"value\" />",
                component = change.component,
                attr = attr,
                prop = prop_name,
            );

            rules.push(KonveyorRule {
                rule_id,
                labels: vec![
                    "source=semver-analyzer".into(),
                    "change-type=prop-attribute-override".into(),
                    "has-codemod=false".into(),
                    format!("package={}", pkg),
                ],
                effort: 3,
                category: "mandatory".into(),
                description: format!(
                    "{} manages `{}` internally via the `{}` prop",
                    change.component, attr, prop_name,
                ),
                message,
                links: vec![],
                when: KonveyorCondition::FrontendReferenced {
                    referenced: FrontendReferencedFields {
                        pattern: format!("^{}$", regex_escape(attr)),
                        location: "JSX_PROP".into(),
                        component: Some(format!("^{}$", regex_escape(&change.component))),
                        parent: None,
                        not_parent: None,
                        child: None,
                        not_child: None,
                        requires_child: None,
                        parent_from: None,
                        value: None,
                        from: if from_pkg != "unknown" {
                            Some(from_pkg.clone())
                        } else {
                            None
                        },
                        file_pattern: None,
                    },
                },
                fix_strategy: Some(FixStrategyEntry::new("LlmAssisted")),
            });
        }
    }

    rules
}

/// Escape special regex characters in a string.
fn regex_escape(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '.' | '*' | '+' | '?' | '(' | ')' | '[' | ']' | '{' | '}' | '\\' | '^' | '$' | '|' => {
                result.push('\\');
                result.push(c);
            }
            _ => result.push(c),
        }
    }
    result
}

const CSS_FILE_PATTERN: &str = ".*\\.css$";

fn generate_css_class_removal_rules(removed_blocks: &[String]) -> Vec<KonveyorRule> {
    let mut rules = Vec::new();

    for block in removed_blocks {
        // Match both v5 and v6 prefixed versions of the class, plus any
        // BEM element or modifier suffixes.
        // e.g., block "select" → matches:
        //   .pf-v5-c-select, .pf-v6-c-select
        //   .pf-v5-c-select__menu, .pf-v6-c-select__menu
        //   .pf-v5-c-select.pf-m-scrollable
        let pattern = format!("pf-(v5|v6)-c-{}", block);

        let rule_id = format!("sd-css-removed-{}", block);

        rules.push(KonveyorRule {
            rule_id,
            labels: vec![
                "source=semver-analyzer".into(),
                "change-type=css-removal".into(),
                "impact=visual-regression".into(),
            ],
            effort: 3,
            category: "mandatory".into(),
            description: format!("CSS component class 'pf-c-{}' was removed in PF v6", block),
            message: format!(
                "This CSS references the 'pf-c-{}' component class which was removed \
                 in PatternFly v6.\n\n\
                 The {} component was rebuilt and no longer uses this CSS class. \
                 This CSS override is dead and should be removed.\n\n\
                 Check if the behavior you were overriding is now available via a \
                 component prop instead.",
                block,
                block_to_component_name(block),
            ),
            links: vec![],
            when: KonveyorCondition::FrontendCssClass {
                cssclass: FrontendPatternFields {
                    pattern,
                    file_pattern: Some(CSS_FILE_PATTERN.into()),
                },
            },
            fix_strategy: None,
        });
    }

    rules
}

/// Convert a kebab-case BEM block name to a likely PascalCase component name.
/// e.g., "select" → "Select", "app-launcher" → "AppLauncher"
fn block_to_component_name(block: &str) -> String {
    block
        .split('-')
        .map(|part| {
            let mut chars = part.chars();
            match chars.next() {
                Some(c) => c.to_uppercase().to_string() + chars.as_str(),
                None => String::new(),
            }
        })
        .collect()
}

/// Generate rules for CSS classes where a version prefix swap produces a
/// class name that does not exist in the target CSS distribution.
///
/// These rules catch two scenarios:
/// 1. Consumer code still using the old class (e.g., `pf-v5-c-form__actions--right`)
/// 2. Consumer code where a blind prefix swap was already applied, producing
///    a dead class (e.g., `pf-v6-c-form__actions--right` doesn't exist in PFv6)
///
/// Both versions are matched by a single rule using regex alternation.
/// The fix strategy is `None` (manual), since there's no valid v6 replacement.
fn generate_dead_css_class_rules(dead_classes: &[(String, String)]) -> Vec<KonveyorRule> {
    use semver_analyzer_konveyor_core::sanitize_id;

    let mut rules = Vec::new();

    for (old_class, dead_v6_class) in dead_classes {
        // Build a regex that matches both the old and the dead-swapped version.
        // Escape regex metacharacters in the class names.
        let old_escaped = regex::escape(old_class);
        let dead_escaped = regex::escape(dead_v6_class);
        let pattern = format!("({}|{})", old_escaped, dead_escaped);

        let rule_id = format!("sd-css-dead-class-{}", sanitize_id(old_class));

        rules.push(KonveyorRule {
            rule_id,
            labels: vec![
                "source=semver-analyzer".into(),
                "change-type=css-dead-class".into(),
                "impact=visual-regression".into(),
                "suppresses-prefix-swap=true".into(),
            ],
            effort: 3,
            category: "mandatory".into(),
            description: format!(
                "CSS class '{}' was removed — prefix swap to '{}' is invalid",
                old_class, dead_v6_class
            ),
            message: format!(
                "The CSS class '{}' was removed in the new version. \
                 A simple version prefix swap to '{}' does NOT produce a valid class — \
                 this class does not exist in the target CSS distribution.\n\n\
                 Remove this class reference or replace it with appropriate custom CSS \
                 or a PatternFly component prop.",
                old_class, dead_v6_class
            ),
            links: vec![],
            when: KonveyorCondition::FrontendCssClass {
                cssclass: FrontendPatternFields {
                    pattern,
                    // Scan all file types — these appear in JSX className strings too
                    file_pattern: None,
                },
            },
            // No automated fix — manual intervention required since the class
            // was removed, not just renamed.
            fix_strategy: None,
        });
    }

    if !rules.is_empty() {
        tracing::info!(
            count = rules.len(),
            "Generated dead CSS class rules (prefix swap produces non-existent class)"
        );
    }

    rules
}

// ── Helper functions ────────────────────────────────────────────────────

/// Extract component name from a dotted symbol like "ModalProps.title".
fn extract_component_name_from_symbol(symbol: &str) -> Option<String> {
    let parts: Vec<&str> = symbol.split('.').collect();
    if parts.len() >= 2 {
        let iface = parts[0];
        // Strip "Props" suffix: "ModalProps" → "Modal"
        Some(iface.strip_suffix("Props").unwrap_or(iface).to_string())
    } else {
        None
    }
}

/// Extract prop name from a dotted symbol like "ModalProps.title".
fn extract_prop_name_from_symbol(symbol: &str) -> Option<String> {
    let parts: Vec<&str> = symbol.split('.').collect();
    if parts.len() >= 2 {
        Some(parts[1..].join("."))
    } else {
        None
    }
}

/// Check if a type string represents a ReactNode-ish type.
fn is_react_node_type(type_str: &str) -> bool {
    let t = type_str.trim();
    t.contains("ReactNode")
        || t.contains("ReactElement")
        || t.contains("JSX.Element")
        || t.contains("React.ReactNode")
        || t.contains("React.ReactElement")
}

/// Get the props for child components from TD report + SD profiles.
///
/// Uses two sources:
/// 1. TD structural changes — symbols like "ModalHeaderProps.title" tell us
///    ModalHeader has a `title` prop.
/// 2. SD profiles — `prop_defaults` keys are prop names on the component.
fn get_child_props_from_report(
    report: &AnalysisReport<TypeScript>,
    sd: &SdPipelineResult,
    new_children: &HashSet<&str>,
) -> HashMap<String, HashSet<String>> {
    let mut child_props: HashMap<String, HashSet<String>> = HashMap::new();

    // Initialize entries for all children
    for child in new_children {
        child_props.insert(child.to_string(), HashSet::new());
    }

    // Source 1: TD structural changes — prop symbols on child components
    for file_changes in &report.changes {
        for change in &file_changes.breaking_api_changes {
            if let Some(component) = extract_component_name_from_symbol(&change.symbol) {
                if new_children.contains(component.as_str()) {
                    if let Some(prop) = extract_prop_name_from_symbol(&change.symbol) {
                        child_props.entry(component).or_default().insert(prop);
                    }
                }
            }
        }
    }

    // Source 2: TD packages — component type summaries
    for pkg in &report.packages {
        for comp in &pkg.type_summaries {
            if new_children.contains(comp.name.as_str()) {
                // Type changes include added/modified members
                for tc in &comp.type_changes {
                    child_props
                        .entry(comp.name.clone())
                        .or_default()
                        .insert(tc.property.clone());
                }
            }
        }
    }

    // Source 3: SD profiles — prop_defaults keys are prop names
    for (name, profile) in &sd.new_profiles {
        if new_children.contains(name.as_str()) {
            for prop_name in profile.prop_defaults.keys() {
                child_props
                    .entry(name.clone())
                    .or_default()
                    .insert(prop_name.clone());
            }
        }
    }

    // Source 4: SD new_component_props — full prop list from AST extraction.
    // This is the most complete source and catches props like ModalHeader.title
    // that don't appear in TD breaking changes or prop defaults.
    for (name, props) in &sd.new_component_props {
        if new_children.contains(name.as_str()) {
            for prop_name in props {
                child_props
                    .entry(name.clone())
                    .or_default()
                    .insert(prop_name.clone());
            }
        }
    }

    child_props
}

/// Sanitize a string for use in rule IDs.
fn sanitize(s: &str) -> String {
    s.chars()
        .map(|c| {
            if c.is_alphanumeric() || c == '-' {
                c.to_lowercase().next().unwrap_or(c)
            } else {
                '-'
            }
        })
        .collect()
}

/// Shorten a component name for use in conformance rule IDs by stripping the
/// family root prefix. For example, in the `DualListSelector` family,
/// `DualListSelectorControl` becomes `control`.
///
/// If `family` contains a modifier prefix (e.g., `deprecated/DualListSelector`),
/// only the base name (`DualListSelector`) is used for prefix matching.
///
/// Returns the full sanitized name when:
/// - The component name doesn't start with the family base name
/// - Stripping would produce an empty string (component == family root)
fn short_component_id(component: &str, family: &str) -> String {
    // Extract the base family name: "deprecated/DualListSelector" → "DualListSelector"
    let base_family = family.rsplit('/').next().unwrap_or(family);

    if component.len() > base_family.len() && component.starts_with(base_family) {
        sanitize(&component[base_family.len()..])
    } else {
        sanitize(component)
    }
}

// ── Tests ───────────────────────────────────────────────────────────────

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

    #[test]
    fn test_extract_component_name() {
        assert_eq!(
            extract_component_name_from_symbol("ModalProps.title"),
            Some("Modal".into())
        );
        assert_eq!(
            extract_component_name_from_symbol("ButtonProps.variant"),
            Some("Button".into())
        );
        assert_eq!(extract_component_name_from_symbol("Button"), None);
    }

    #[test]
    fn test_extract_prop_name() {
        assert_eq!(
            extract_prop_name_from_symbol("ModalProps.title"),
            Some("title".into())
        );
        assert_eq!(extract_prop_name_from_symbol("Button"), None);
    }

    #[test]
    fn test_is_react_node_type() {
        assert!(is_react_node_type("React.ReactNode"));
        assert!(is_react_node_type("ReactElement<any>"));
        assert!(is_react_node_type("JSX.Element"));
        assert!(!is_react_node_type("string"));
        assert!(!is_react_node_type("boolean"));
    }

    #[test]
    fn test_sanitize() {
        assert_eq!(sanitize("ModalHeader"), "modalheader");
        assert_eq!(sanitize("Dropdown.Item"), "dropdown-item");
    }

    #[test]
    fn test_short_component_id() {
        // Strips family prefix when component starts with it
        assert_eq!(
            short_component_id("DualListSelectorControl", "DualListSelector"),
            "control"
        );
        assert_eq!(
            short_component_id("DualListSelectorList", "DualListSelector"),
            "list"
        );
        assert_eq!(short_component_id("CardBody", "Card"), "body");
        assert_eq!(short_component_id("AlertGroup", "Alert"), "group");

        // Keeps full name when component == family root (stripping would be empty)
        assert_eq!(
            short_component_id("DualListSelector", "DualListSelector"),
            "duallistselector"
        );
        assert_eq!(short_component_id("Card", "Card"), "card");

        // Keeps full name when component doesn't start with family
        assert_eq!(short_component_id("Tr", "Table"), "tr");
        assert_eq!(short_component_id("Thead", "Table"), "thead");
        assert_eq!(short_component_id("Tab", "Tabs"), "tab");
        assert_eq!(short_component_id("ActionGroup", "Form"), "actiongroup");

        // Handles deprecated/ prefix — strips the base family name
        assert_eq!(
            short_component_id("DualListSelectorControl", "deprecated/DualListSelector"),
            "control"
        );
        assert_eq!(
            short_component_id("DualListSelector", "deprecated/DualListSelector"),
            "duallistselector"
        );
    }

    #[test]
    fn test_extract_bem_prop_name() {
        assert_eq!(
            extract_bem_prop_name(
                "EmptyStateHeader is BEM element 'titleText' of emptyState block"
            ),
            Some("titleText".into())
        );
        assert_eq!(
            extract_bem_prop_name("FooBar is BEM element 'icon' of foo block"),
            Some("icon".into())
        );
        assert_eq!(extract_bem_prop_name("no quotes here"), None);
    }

    fn test_pkg_map() -> HashMap<String, String> {
        let mut m = HashMap::new();
        m.insert("Dropdown".into(), "@patternfly/react-core".into());
        m.insert("DropdownList".into(), "@patternfly/react-core".into());
        m.insert("DropdownItem".into(), "@patternfly/react-core".into());
        m.insert("AccordionContent".into(), "@patternfly/react-core".into());
        m.insert("AccordionItem".into(), "@patternfly/react-core".into());
        m
    }

    #[test]
    fn test_conformance_invalid_direct_child() {
        let tree = CompositionTree {
            root: "Dropdown".into(),
            family_members: vec![
                "Dropdown".into(),
                "DropdownList".into(),
                "DropdownItem".into(),
            ],
            edges: vec![
                crate::sd_types::CompositionEdge {
                    parent: "Dropdown".into(),
                    child: "DropdownList".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: true,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Required,
                    prop_name: None,
                },
                crate::sd_types::CompositionEdge {
                    parent: "DropdownList".into(),
                    child: "DropdownItem".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Required,
                    prop_name: None,
                },
            ],
        };

        let rules = generate_conformance_rules(&[tree], &[], &test_pkg_map());

        // Should have an InvalidDirectChild rule: DropdownItem in Dropdown
        let invalid_rule = rules
            .iter()
            .find(|r| r.rule_id.contains("item-not-in-dropdown"));
        assert!(
            invalid_rule.is_some(),
            "Expected InvalidDirectChild rule for DropdownItem in Dropdown, got rules: {:?}",
            rules.iter().map(|r| &r.rule_id).collect::<Vec<_>>()
        );

        // The condition should use parent: ^Dropdown$
        if let KonveyorCondition::FrontendReferenced { referenced } = &invalid_rule.unwrap().when {
            assert_eq!(referenced.pattern, "^DropdownItem$");
            assert_eq!(referenced.parent.as_deref(), Some("^Dropdown$"));
        } else {
            panic!("Expected FrontendReferenced condition");
        }
    }

    /// Recursive nesting edges (e.g., Tab → Tabs for nested tabs) should
    /// use Allowed strength, not Required. When both directions are Required
    /// (a tree accuracy bug), the rule generator produces contradictory
    /// notParent rules for both directions. This test verifies the correct
    /// behavior when the back-edge is properly marked as Allowed.
    #[test]
    fn test_conformance_rules_skip_allowed_back_edges() {
        let mut pkgs = test_pkg_map();
        pkgs.insert("Tabs".into(), "@patternfly/react-core".into());
        pkgs.insert("Tab".into(), "@patternfly/react-core".into());

        let tree = CompositionTree {
            root: "Tabs".into(),
            family_members: vec!["Tabs".into(), "Tab".into()],
            edges: vec![
                crate::sd_types::CompositionEdge {
                    parent: "Tabs".into(),
                    child: "Tab".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Required,
                    prop_name: None,
                },
                // Recursive nesting: nested tabs inside a tab (Allowed, not Required)
                crate::sd_types::CompositionEdge {
                    parent: "Tab".into(),
                    child: "Tabs".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Allowed,
                    prop_name: None,
                },
            ],
        };

        let rules = generate_conformance_rules(&[tree], &[], &pkgs);

        // Tabs is no_incoming (root), so it should get a requiresChild rule
        assert!(
            rules.iter().any(|r| r.rule_id.contains("tabs-req-tab")),
            "Expected requiresChild rule for Tabs. Got rules: {:?}",
            rules.iter().map(|r| &r.rule_id).collect::<Vec<_>>()
        );

        // "Tabs must be in Tab" should NOT exist — the Allowed back-edge
        // doesn't trigger Required conformance, and Tabs is no_incoming
        assert!(
            !rules.iter().any(|r| r.rule_id == "sd-cf-tabs-tabs-in-tab"),
            "Back-edge 'tabs-in-tab' should not exist. Got rules: {:?}",
            rules.iter().map(|r| &r.rule_id).collect::<Vec<_>>()
        );
    }

    /// When a child has multiple valid direct parents (e.g., Tr can be in
    /// Thead OR Tbody), the generator should produce ONE merged rule with
    /// a combined notParent regex instead of separate per-parent rules that
    /// false-positive against each other.
    #[test]
    fn test_multi_parent_must_be_in_merged() {
        let mut pkgs = test_pkg_map();
        pkgs.insert("Table".into(), "@patternfly/react-table".into());
        pkgs.insert("Thead".into(), "@patternfly/react-table".into());
        pkgs.insert("Tbody".into(), "@patternfly/react-table".into());
        pkgs.insert("Tr".into(), "@patternfly/react-table".into());
        pkgs.insert("Td".into(), "@patternfly/react-table".into());
        pkgs.insert("Th".into(), "@patternfly/react-table".into());

        let tree = CompositionTree {
            root: "Table".into(),
            family_members: vec![
                "Table".into(),
                "Thead".into(),
                "Tbody".into(),
                "Tr".into(),
                "Td".into(),
                "Th".into(),
            ],
            edges: vec![
                crate::sd_types::CompositionEdge {
                    parent: "Table".into(),
                    child: "Thead".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Required,
                    prop_name: None,
                },
                crate::sd_types::CompositionEdge {
                    parent: "Table".into(),
                    child: "Tbody".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Required,
                    prop_name: None,
                },
                crate::sd_types::CompositionEdge {
                    parent: "Thead".into(),
                    child: "Tr".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Required,
                    prop_name: None,
                },
                crate::sd_types::CompositionEdge {
                    parent: "Tbody".into(),
                    child: "Tr".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Required,
                    prop_name: None,
                },
                crate::sd_types::CompositionEdge {
                    parent: "Tr".into(),
                    child: "Td".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Required,
                    prop_name: None,
                },
                crate::sd_types::CompositionEdge {
                    parent: "Tr".into(),
                    child: "Th".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Required,
                    prop_name: None,
                },
            ],
        };

        let rules = generate_conformance_rules(&[tree], &[], &pkgs);

        // Tr should have ONE in- rule with combined notParent
        let tr_must_be_in: Vec<&KonveyorRule> = rules
            .iter()
            .filter(|r| r.rule_id.contains("tr-in-"))
            .collect();
        assert_eq!(
            tr_must_be_in.len(),
            1,
            "Expected exactly 1 merged in- rule for Tr, got {}: {:?}",
            tr_must_be_in.len(),
            tr_must_be_in.iter().map(|r| &r.rule_id).collect::<Vec<_>>()
        );

        let rule = tr_must_be_in[0];
        // Rule ID should contain both parents
        assert!(
            rule.rule_id.contains("tbody") && rule.rule_id.contains("thead"),
            "Rule ID should mention both parents: {}",
            rule.rule_id
        );

        // notParent should be a combined regex
        if let KonveyorCondition::FrontendReferenced { referenced } = &rule.when {
            let not_parent = referenced.not_parent.as_deref().unwrap();
            assert!(
                not_parent.contains("Thead") && not_parent.contains("Tbody"),
                "notParent should combine both parents: {}",
                not_parent
            );
            assert!(
                not_parent.contains('|'),
                "notParent should use alternation: {}",
                not_parent
            );
        } else {
            panic!("Expected FrontendReferenced condition");
        }

        // Description should mention both parents
        assert!(
            rule.description.contains("Tbody") && rule.description.contains("Thead"),
            "Description should mention both parents: {}",
            rule.description
        );

        // There should be NO separate tr-in-thead or tr-in-tbody
        assert!(
            !rules.iter().any(|r| r.rule_id == "sd-cf-table-tr-in-thead"),
            "Should not have separate tr-in-thead rule"
        );
        assert!(
            !rules.iter().any(|r| r.rule_id == "sd-cf-table-tr-in-tbody"),
            "Should not have separate tr-in-tbody rule"
        );
    }

    /// InvalidDirectChild rules should also be merged when a child has
    /// multiple valid parents under the same grandparent.
    #[test]
    fn test_multi_parent_invalid_direct_child_merged() {
        let mut pkgs = test_pkg_map();
        pkgs.insert("Table".into(), "@patternfly/react-table".into());
        pkgs.insert("Thead".into(), "@patternfly/react-table".into());
        pkgs.insert("Tbody".into(), "@patternfly/react-table".into());
        pkgs.insert("Tr".into(), "@patternfly/react-table".into());

        let tree = CompositionTree {
            root: "Table".into(),
            family_members: vec!["Table".into(), "Thead".into(), "Tbody".into(), "Tr".into()],
            edges: vec![
                crate::sd_types::CompositionEdge {
                    parent: "Table".into(),
                    child: "Thead".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Required,
                    prop_name: None,
                },
                crate::sd_types::CompositionEdge {
                    parent: "Table".into(),
                    child: "Tbody".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Required,
                    prop_name: None,
                },
                crate::sd_types::CompositionEdge {
                    parent: "Thead".into(),
                    child: "Tr".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Required,
                    prop_name: None,
                },
                crate::sd_types::CompositionEdge {
                    parent: "Tbody".into(),
                    child: "Tr".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Required,
                    prop_name: None,
                },
            ],
        };

        let rules = generate_conformance_rules(&[tree], &[], &pkgs);

        // Tr-not-in-Table should be ONE merged rule mentioning both Thead and Tbody
        let tr_not_in_table: Vec<&KonveyorRule> = rules
            .iter()
            .filter(|r| r.rule_id.contains("tr-not-in-table"))
            .collect();
        assert_eq!(
            tr_not_in_table.len(),
            1,
            "Expected 1 merged not-in-table rule for Tr, got {}: {:?}",
            tr_not_in_table.len(),
            tr_not_in_table
                .iter()
                .map(|r| &r.rule_id)
                .collect::<Vec<_>>()
        );

        // Description should mention both valid parents
        let rule = tr_not_in_table[0];
        assert!(
            rule.description.contains("Tbody") && rule.description.contains("Thead"),
            "Description should mention both valid parents: {}",
            rule.description
        );
    }

    /// Root components (no incoming edges) get requiresChild rules, not
    /// notParent rules. Children of non-root parents get notParent rules.
    #[test]
    fn test_root_gets_requires_child_children_get_not_parent() {
        // Four-strength model test:
        // Dropdown→DropdownList: Wrapper (parent renders child internally)
        //   → generates requiresChild on Dropdown
        //   → does NOT generate notParent on DropdownList (CHP=NO for Wrapper)
        // DropdownList→DropdownItem: Required (DOM nesting <ul>→<li>)
        //   → generates both requiresChild on DropdownList AND notParent on DropdownItem
        let tree = CompositionTree {
            root: "Dropdown".into(),
            family_members: vec![
                "Dropdown".into(),
                "DropdownList".into(),
                "DropdownItem".into(),
            ],
            edges: vec![
                crate::sd_types::CompositionEdge {
                    parent: "Dropdown".into(),
                    child: "DropdownList".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Wrapper,
                    prop_name: None,
                },
                crate::sd_types::CompositionEdge {
                    parent: "DropdownList".into(),
                    child: "DropdownItem".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Required,
                    prop_name: None,
                },
            ],
        };

        let rules = generate_conformance_rules(&[tree], &[], &test_pkg_map());

        // Dropdown→DropdownList is Wrapper (PMC=YES) → requiresChild rule on Dropdown
        let dropdown_rule = rules
            .iter()
            .find(|r| r.rule_id.contains("dropdown-req-list"));
        assert!(
            dropdown_rule.is_some(),
            "Expected requiresChild rule for Dropdown. Got rules: {:?}",
            rules.iter().map(|r| &r.rule_id).collect::<Vec<_>>()
        );
        if let KonveyorCondition::FrontendReferenced { referenced } = &dropdown_rule.unwrap().when {
            assert_eq!(referenced.pattern, "^Dropdown$");
            assert!(referenced.requires_child.is_some());
            assert!(referenced.not_parent.is_none());
        } else {
            panic!("Expected FrontendReferenced condition");
        }

        // DropdownItem has Required incoming edge (CHP=YES) → notParent rule
        let di_rule = rules.iter().find(|r| r.rule_id.contains("item-in-list"));
        assert!(
            di_rule.is_some(),
            "Expected notParent rule for DropdownItem. Got rules: {:?}",
            rules.iter().map(|r| &r.rule_id).collect::<Vec<_>>()
        );
        if let KonveyorCondition::FrontendReferenced { referenced } = &di_rule.unwrap().when {
            assert_eq!(referenced.pattern, "^DropdownItem$");
            assert!(referenced.not_parent.is_some());
        } else {
            panic!("Expected FrontendReferenced condition");
        }

        // NO notParent for DropdownList — its parent Dropdown has Wrapper (CHP=NO)
        assert!(
            !rules.iter().any(|r| r.rule_id.contains("list-in")),
            "DropdownList should not have a notParent rule (Wrapper edge has CHP=NO)"
        );
    }

    #[test]
    fn test_context_rule_generation() {
        let changes = vec![SourceLevelChange {
            component: "AccordionItem".into(),
            category: SourceLevelCategory::ContextDependency,
            description: "AccordionItem now provides AccordionItemContext".into(),
            old_value: None,
            new_value: Some("<AccordionItemContext.Provider>".into()),
            has_test_implications: true,
            test_description: None,
            element: None,
            migration_from: None,
            dependency_chain: None,
        }];

        let rules = generate_context_rules(&changes, &test_pkg_map());

        assert_eq!(rules.len(), 1);
        assert!(rules[0].rule_id.contains("accordionitemcontext"));

        if let KonveyorCondition::FrontendReferenced { referenced } = &rules[0].when {
            assert_eq!(referenced.pattern, "^AccordionItemContext$");
            assert_eq!(referenced.location, "IMPORT");
        } else {
            panic!("Expected FrontendReferenced condition");
        }
    }

    // ── Migration-aware rule generation tests ───────────────────────

    #[test]
    fn test_migration_test_impact_rules_have_distinct_ids() {
        // Simulate: deprecated SelectOption had role='presentation' on 3 elements,
        // new SelectOption has none. This produces 3 migration-tagged changes.
        // They should all produce rules with "sd-migration-" prefix and
        // NOT collide with each other or with evolution rules.
        // The `element` field disambiguates rule IDs for same-role different-element.
        let changes = vec![
            SourceLevelChange {
                component: "SelectOption".into(),
                category: SourceLevelCategory::RoleChange,
                description: "role='presentation' removed from <button> in SelectOption".into(),
                old_value: Some("presentation".into()),
                new_value: None,
                has_test_implications: true,
                test_description: None,
                element: Some("button".into()),
                migration_from: Some(
                    "packages/react-core/src/deprecated/components/Select/SelectOption.tsx".into(),
                ),
                dependency_chain: None,
            },
            SourceLevelChange {
                component: "SelectOption".into(),
                category: SourceLevelCategory::RoleChange,
                description: "role='presentation' removed from <div> in SelectOption".into(),
                old_value: Some("presentation".into()),
                new_value: None,
                has_test_implications: true,
                test_description: None,
                element: Some("div".into()),
                migration_from: Some(
                    "packages/react-core/src/deprecated/components/Select/SelectOption.tsx".into(),
                ),
                dependency_chain: None,
            },
            // Also add a non-migration change for the same component
            SourceLevelChange {
                component: "SelectOption".into(),
                category: SourceLevelCategory::RoleChange,
                description: "role='option' removed from <li> in SelectOption".into(),
                old_value: Some("option".into()),
                new_value: None,
                has_test_implications: true,
                test_description: None,
                element: Some("li".into()),
                migration_from: None, // evolution change
                dependency_chain: None,
            },
        ];

        let mut pkgs = test_pkg_map();
        pkgs.insert("SelectOption".into(), "@patternfly/react-core".into());

        let rules = generate_test_impact_rules(&changes, &pkgs);

        // Migration rules should have "sd-migration-" prefix
        let migration_rules: Vec<_> = rules
            .iter()
            .filter(|r| r.rule_id.starts_with("sd-migration-"))
            .collect();
        assert!(
            !migration_rules.is_empty(),
            "Should produce migration-prefixed rules"
        );

        // Evolution rules should have "sd-" prefix (not "sd-migration-")
        let evolution_rules: Vec<_> = rules
            .iter()
            .filter(|r| r.rule_id.starts_with("sd-test-"))
            .collect();
        assert!(
            !evolution_rules.is_empty(),
            "Should produce evolution-prefixed rules"
        );

        // All rule IDs should be unique
        let mut seen = std::collections::HashSet::new();
        for r in &rules {
            assert!(seen.insert(&r.rule_id), "Duplicate rule ID: {}", r.rule_id);
        }
    }

    #[test]
    fn test_migration_context_rules_use_deprecated_from_path() {
        let changes = vec![SourceLevelChange {
            component: "Select".into(),
            category: SourceLevelCategory::ContextDependency,
            description: "Select no longer uses useContext(SelectContext)".into(),
            old_value: Some("useContext(SelectContext)".into()),
            new_value: None,
            has_test_implications: false,
            test_description: None,
            element: None,
            migration_from: Some(
                "packages/react-core/src/deprecated/components/Select/Select.tsx".into(),
            ),
            dependency_chain: None,
        }];

        let mut pkgs = test_pkg_map();
        pkgs.insert("Select".into(), "@patternfly/react-core".into());

        let rules = generate_context_rules(&changes, &pkgs);

        assert_eq!(rules.len(), 1);

        // Rule ID should have migration prefix
        assert!(
            rules[0].rule_id.starts_with("sd-migration-context-"),
            "Expected migration prefix, got: {}",
            rules[0].rule_id
        );

        // from should be the deprecated package path
        if let KonveyorCondition::FrontendReferenced { referenced } = &rules[0].when {
            assert_eq!(
                referenced.from.as_deref(),
                Some("@patternfly/react-core/deprecated"),
                "Migration context rule should match deprecated import path"
            );
        } else {
            panic!("Expected FrontendReferenced condition");
        }
    }

    #[test]
    fn test_migration_prop_override_rules_use_deprecated_from_path() {
        let changes = vec![SourceLevelChange {
            component: "Dropdown".into(),
            category: SourceLevelCategory::PropAttributeOverride,
            description: "Dropdown's `ouiaId` prop overrides HTML attributes".into(),
            old_value: None,
            new_value: Some("ouiaId → data-ouia-component-id".into()),
            has_test_implications: false,
            test_description: None,
            element: None,
            migration_from: Some(
                "packages/react-core/src/deprecated/components/Dropdown/Dropdown.tsx".into(),
            ),
            dependency_chain: None,
        }];

        let pkgs = test_pkg_map();

        let rules =
            generate_prop_attribute_override_rules(&changes, &SdPipelineResult::default(), &pkgs);

        assert_eq!(rules.len(), 1);

        // Rule ID should have migration prefix
        assert!(
            rules[0].rule_id.starts_with("sd-migration-prop-override-"),
            "Expected migration prefix, got: {}",
            rules[0].rule_id
        );

        // from should be the deprecated package path
        if let KonveyorCondition::FrontendReferenced { referenced } = &rules[0].when {
            assert_eq!(
                referenced.from.as_deref(),
                Some("@patternfly/react-core/deprecated"),
                "Migration prop-override rule should match deprecated import path"
            );
        } else {
            panic!("Expected FrontendReferenced condition");
        }
    }

    #[test]
    fn test_evolution_rules_unchanged_by_migration_support() {
        // Verify that non-migration changes still produce "sd-" prefixed rules
        // with the normal package in `from`.
        let changes = vec![SourceLevelChange {
            component: "Dropdown".into(),
            category: SourceLevelCategory::PropAttributeOverride,
            description: "Dropdown's `ouiaId` prop overrides HTML attributes".into(),
            old_value: None,
            new_value: Some("ouiaId → data-ouia-component-id".into()),
            has_test_implications: false,
            test_description: None,
            element: None,
            migration_from: None, // evolution, not migration
            dependency_chain: None,
        }];

        let rules = generate_prop_attribute_override_rules(
            &changes,
            &SdPipelineResult::default(),
            &test_pkg_map(),
        );

        assert_eq!(rules.len(), 1);

        // Rule ID should NOT have migration prefix
        assert!(
            rules[0].rule_id.starts_with("sd-prop-override-"),
            "Expected sd- prefix, got: {}",
            rules[0].rule_id
        );

        // from should be the normal package
        if let KonveyorCondition::FrontendReferenced { referenced } = &rules[0].when {
            assert_eq!(
                referenced.from.as_deref(),
                Some("@patternfly/react-core"),
                "Evolution prop-override rule should match normal import path"
            );
        } else {
            panic!("Expected FrontendReferenced condition");
        }
    }

    #[test]
    fn test_deprecated_pkg_from_migration_path() {
        assert_eq!(
            deprecated_pkg_from_migration_path(
                "packages/react-core/src/deprecated/components/Select/Select.tsx"
            ),
            "@patternfly/react-core/deprecated"
        );
        assert_eq!(
            deprecated_pkg_from_migration_path(
                "packages/react-table/src/deprecated/components/Table/Table.tsx"
            ),
            "@patternfly/react-table/deprecated"
        );
        // Fallback for unexpected format
        assert_eq!(
            deprecated_pkg_from_migration_path("some/random/path.tsx"),
            "@patternfly/react-core/deprecated"
        );
    }

    /// When a child has one Required parent and one Allowed parent, the
    /// notParent regex should include BOTH parents so that placement inside
    /// the Allowed parent doesn't trigger a false positive.
    #[test]
    fn test_allowed_parent_included_in_not_parent_regex() {
        let mut pkgs = test_pkg_map();
        pkgs.insert("Table".into(), "@patternfly/react-table".into());
        pkgs.insert("Thead".into(), "@patternfly/react-table".into());
        pkgs.insert("Tbody".into(), "@patternfly/react-table".into());
        pkgs.insert("Tr".into(), "@patternfly/react-table".into());

        let tree = CompositionTree {
            root: "Table".into(),
            family_members: vec!["Table".into(), "Thead".into(), "Tbody".into(), "Tr".into()],
            edges: vec![
                crate::sd_types::CompositionEdge {
                    parent: "Table".into(),
                    child: "Thead".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Required,
                    prop_name: None,
                },
                crate::sd_types::CompositionEdge {
                    parent: "Table".into(),
                    child: "Tbody".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Required,
                    prop_name: None,
                },
                // Tbody→Tr is Required (e.g., CSS direct-child selector)
                crate::sd_types::CompositionEdge {
                    parent: "Tbody".into(),
                    child: "Tr".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Required,
                    prop_name: None,
                },
                // Thead→Tr is Allowed (e.g., CSS descendant selector)
                crate::sd_types::CompositionEdge {
                    parent: "Thead".into(),
                    child: "Tr".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Allowed,
                    prop_name: None,
                },
            ],
        };

        let rules = generate_conformance_rules(&[tree], &[], &pkgs);

        // A conformance rule SHOULD be generated (because Tbody→Tr is Required)
        let tr_must_be_in = rules.iter().find(|r| r.rule_id.contains("tr-in-"));
        assert!(tr_must_be_in.is_some(), "Expected an in- rule for Tr");

        let rule = tr_must_be_in.unwrap();

        // The rule ID should include both parents
        assert!(
            rule.rule_id.contains("tbody") && rule.rule_id.contains("thead"),
            "Rule ID should include both parents: {}",
            rule.rule_id
        );

        // The notParent regex should include both parents
        if let KonveyorCondition::FrontendReferenced { referenced } = &rule.when {
            let not_parent = referenced.not_parent.as_deref().unwrap();
            assert!(
                not_parent.contains("Tbody") && not_parent.contains("Thead"),
                "notParent regex should include both Required and Allowed parents: {}",
                not_parent
            );
        } else {
            panic!("Expected FrontendReferenced condition");
        }

        // Description should mention both parents
        assert!(
            rule.description.contains("Tbody") && rule.description.contains("Thead"),
            "Description should mention both parents: {}",
            rule.description
        );

        // InvalidDirectChild rule should mention only CHP parents.
        // Thead→Tr is Allowed (not CHP), so the grandparent walk skips it.
        // Only Tbody (Required/CHP) appears as the suggested intermediate.
        let tr_not_in_table = rules.iter().find(|r| r.rule_id.contains("tr-not-in-table"));
        if let Some(idc_rule) = tr_not_in_table {
            assert!(
                idc_rule.description.contains("Tbody"),
                "InvalidDirectChild should mention CHP parent Tbody: {}",
                idc_rule.description
            );
            // Thead is NOT mentioned — it's only an Allowed parent,
            // excluded from the first-hop grandparent walk.
            assert!(
                !idc_rule.description.contains("Thead"),
                "InvalidDirectChild should NOT mention Allowed parent Thead: {}",
                idc_rule.description
            );
        }
    }

    /// When a child has ONLY Allowed parents (no Required edges), no
    /// conformance rule should be generated.
    #[test]
    fn test_only_allowed_parents_no_rule_generated() {
        let tree = CompositionTree {
            root: "Menu".into(),
            family_members: vec!["Menu".into(), "MenuContent".into()],
            edges: vec![crate::sd_types::CompositionEdge {
                parent: "Menu".into(),
                child: "MenuContent".into(),
                relationship: ChildRelationship::DirectChild,
                required: false,
                bem_evidence: None,
                strength: crate::sd_types::EdgeStrength::Allowed,
                prop_name: None,
            }],
        };

        let rules = generate_conformance_rules(&[tree], &[], &test_pkg_map());

        // No in- rule should be generated for MenuContent
        let mc_rule = rules.iter().find(|r| r.rule_id.contains("content-in"));
        assert!(
            mc_rule.is_none(),
            "No conformance rule should be generated when child only has Allowed parents"
        );
    }

    /// Secondary roots (no incoming Required edges, not the tree root) should
    /// get requiresChild rules for their Required children. The tree root
    /// itself is also no_incoming and gets requiresChild.
    #[test]
    fn test_secondary_root_gets_requires_child() {
        let mut pkgs = test_pkg_map();
        pkgs.insert("Alert".into(), "@patternfly/react-core".into());
        pkgs.insert("AlertGroup".into(), "@patternfly/react-core".into());
        pkgs.insert(
            "AlertActionCloseButton".into(),
            "@patternfly/react-core".into(),
        );

        // Four-strength model: AlertGroup wraps Alert/AlertActionCloseButton
        // via Wrapper edges (parent requires child, child can exist standalone).
        let tree = CompositionTree {
            root: "Alert".into(),
            family_members: vec![
                "Alert".into(),
                "AlertGroup".into(),
                "AlertActionCloseButton".into(),
            ],
            edges: vec![
                // AlertGroup is a secondary root — no incoming edges
                // Wrapper: AlertGroup must contain Alert, Alert can exist standalone
                crate::sd_types::CompositionEdge {
                    parent: "AlertGroup".into(),
                    child: "Alert".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Wrapper,
                    prop_name: None,
                },
                crate::sd_types::CompositionEdge {
                    parent: "AlertGroup".into(),
                    child: "AlertActionCloseButton".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Wrapper,
                    prop_name: None,
                },
            ],
        };

        let rules = generate_conformance_rules(&[tree], &[], &pkgs);

        // AlertGroup should get a requiresChild rule (Wrapper = PMC=YES)
        let ag_rule = rules.iter().find(|r| r.rule_id.contains("group-req-"));
        assert!(
            ag_rule.is_some(),
            "Expected requiresChild rule for AlertGroup. Got: {:?}",
            rules.iter().map(|r| &r.rule_id).collect::<Vec<_>>()
        );

        if let KonveyorCondition::FrontendReferenced { referenced } = &ag_rule.unwrap().when {
            assert_eq!(referenced.pattern, "^AlertGroup$");
            assert!(
                referenced.requires_child.is_some(),
                "Should use requiresChild field"
            );
            let req = referenced.requires_child.as_deref().unwrap();
            assert!(req.contains("Alert"), "requiresChild should include Alert");
            assert!(
                req.contains("AlertActionCloseButton"),
                "requiresChild should include AlertActionCloseButton"
            );
        } else {
            panic!("Expected FrontendReferenced condition");
        }

        // Alert should NOT get a notParent rule — Wrapper edges have CHP=NO
        assert!(
            !rules.iter().any(|r| r.rule_id.contains("alert-in")),
            "Alert should NOT have a notParent rule (Wrapper has CHP=NO). Got: {:?}",
            rules.iter().map(|r| &r.rule_id).collect::<Vec<_>>()
        );
    }

    /// Family root should never get a notParent rule, even when edges have
    /// CHP=YES (Structural). The root is standalone by definition. This tests
    /// the rule-gen filter for the case where the composition builder produces
    /// Structural edges TO the root (e.g., cloneElement in AlertGroup→Alert).
    #[test]
    fn test_family_root_never_gets_not_parent_even_with_structural_edge() {
        let mut pkgs = test_pkg_map();
        pkgs.insert("Alert".into(), "@patternfly/react-core".into());
        pkgs.insert("AlertGroup".into(), "@patternfly/react-core".into());

        let tree = CompositionTree {
            root: "Alert".into(),
            family_members: vec!["Alert".into(), "AlertGroup".into()],
            edges: vec![
                // Structural edge TO the root: CHP=YES in the edge, but the
                // root is standalone — the rule-gen filter must suppress this.
                crate::sd_types::CompositionEdge {
                    parent: "AlertGroup".into(),
                    child: "Alert".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Structural,
                    prop_name: None,
                },
            ],
        };

        let rules = generate_conformance_rules(&[tree], &[], &pkgs);

        // Alert (the family root) must NOT get a notParent rule, even though
        // the Structural edge has CHP=YES. The root is standalone.
        assert!(
            !rules.iter().any(|r| r.rule_id.contains("alert-in")),
            "Family root Alert should NOT have a notParent rule even with Structural edge. Got: {:?}",
            rules.iter().map(|r| &r.rule_id).collect::<Vec<_>>()
        );

        // AlertGroup should NOT get a requiresChild rule either (Structural = PMC=NO).
        assert!(
            !rules.iter().any(|r| r.rule_id.contains("req-")),
            "AlertGroup should NOT get requiresChild (Structural = PMC=NO). Got: {:?}",
            rules.iter().map(|r| &r.rule_id).collect::<Vec<_>>()
        );
    }

    /// Same test for deprecated families: the deprecated/ prefix in tree.root
    /// should not prevent the root filter from matching edge.child.
    #[test]
    fn test_family_root_not_parent_filter_handles_deprecated_prefix() {
        let mut pkgs = test_pkg_map();
        pkgs.insert("DualListSelector".into(), "@patternfly/react-core".into());
        pkgs.insert(
            "DualListSelectorPane".into(),
            "@patternfly/react-core".into(),
        );

        let tree = CompositionTree {
            root: "deprecated/DualListSelector".into(),
            family_members: vec!["DualListSelector".into(), "DualListSelectorPane".into()],
            edges: vec![crate::sd_types::CompositionEdge {
                parent: "DualListSelectorPane".into(),
                child: "DualListSelector".into(),
                relationship: ChildRelationship::DirectChild,
                required: false,
                bem_evidence: None,
                strength: crate::sd_types::EdgeStrength::Structural,
                prop_name: None,
            }],
        };

        let rules = generate_conformance_rules(&[tree], &[], &pkgs);

        // DualListSelector is the root (deprecated/DualListSelector) —
        // must not get notParent rule.
        assert!(
            !rules.iter().any(|r| {
                r.rule_id.contains("duallistselector-in-") && !r.rule_id.contains("pane-in-")
            }),
            "Deprecated family root should NOT get notParent rule. Got: {:?}",
            rules.iter().map(|r| &r.rule_id).collect::<Vec<_>>()
        );
    }

    /// Deprecated families should use the deprecated import path in their
    /// `from` field so they don't produce identical `when` clauses with v6
    /// rules for the same component names.
    #[test]
    fn test_deprecated_conformance_rules_use_deprecated_from_path() {
        let mut pkgs = test_pkg_map();
        // Both v6 and deprecated WizardNav resolve to @patternfly/react-core
        // in the component_packages map (name collision)
        pkgs.insert("WizardNav".into(), "@patternfly/react-core".into());
        pkgs.insert("WizardNavItem".into(), "@patternfly/react-core".into());

        let deprecated_tree = CompositionTree {
            root: "deprecated/Wizard".into(),
            family_members: vec!["WizardNav".into(), "WizardNavItem".into()],
            edges: vec![crate::sd_types::CompositionEdge {
                parent: "WizardNav".into(),
                child: "WizardNavItem".into(),
                relationship: ChildRelationship::DirectChild,
                required: true,
                bem_evidence: None,
                strength: crate::sd_types::EdgeStrength::Required,
                prop_name: None,
            }],
        };

        let rules = generate_conformance_rules(&[deprecated_tree], &[], &pkgs);

        // All rules should use @patternfly/react-core/deprecated, not @patternfly/react-core
        for rule in &rules {
            if let KonveyorCondition::FrontendReferenced { referenced } = &rule.when {
                let from = referenced.from.as_deref().unwrap_or("");
                assert!(
                    from.contains("/deprecated"),
                    "Rule {} should use deprecated from path, got: {}",
                    rule.rule_id,
                    from
                );
            }
        }

        // Verify at least one rule was generated
        assert!(
            !rules.is_empty(),
            "Expected at least one conformance rule for deprecated/Wizard"
        );
    }

    /// V6 families should NOT have /deprecated in their from path.
    #[test]
    fn test_v6_conformance_rules_use_normal_from_path() {
        let mut pkgs = test_pkg_map();
        pkgs.insert("WizardNav".into(), "@patternfly/react-core".into());
        pkgs.insert("WizardNavItem".into(), "@patternfly/react-core".into());

        let v6_tree = CompositionTree {
            root: "Wizard".into(),
            family_members: vec!["WizardNav".into(), "WizardNavItem".into()],
            edges: vec![crate::sd_types::CompositionEdge {
                parent: "WizardNav".into(),
                child: "WizardNavItem".into(),
                relationship: ChildRelationship::DirectChild,
                required: true,
                bem_evidence: None,
                strength: crate::sd_types::EdgeStrength::Required,
                prop_name: None,
            }],
        };

        let rules = generate_conformance_rules(&[v6_tree], &[], &pkgs);

        // All rules should use @patternfly/react-core (no /deprecated)
        for rule in &rules {
            if let KonveyorCondition::FrontendReferenced { referenced } = &rule.when {
                let from = referenced.from.as_deref().unwrap_or("");
                assert!(
                    !from.contains("/deprecated"),
                    "v6 rule {} should NOT use deprecated from path, got: {}",
                    rule.rule_id,
                    from
                );
            }
        }
    }

    /// When the component_packages map already resolves to a deprecated path
    /// (e.g., Body → @patternfly/react-table/deprecated), don't double-append.
    #[test]
    fn test_deprecated_from_path_no_double_append() {
        let mut pkgs = test_pkg_map();
        // Body already resolves to the deprecated path in the map
        pkgs.insert("Body".into(), "@patternfly/react-table/deprecated".into());
        pkgs.insert("Header".into(), "@patternfly/react-table/deprecated".into());

        let tree = CompositionTree {
            root: "deprecated/Table".into(),
            family_members: vec!["Body".into(), "Header".into()],
            edges: vec![crate::sd_types::CompositionEdge {
                parent: "Header".into(),
                child: "Body".into(),
                relationship: ChildRelationship::DirectChild,
                required: false,
                bem_evidence: None,
                strength: crate::sd_types::EdgeStrength::Structural,
                prop_name: None,
            }],
        };

        let rules = generate_conformance_rules(&[tree], &[], &pkgs);

        for rule in &rules {
            if let KonveyorCondition::FrontendReferenced { referenced } = &rule.when {
                let from = referenced.from.as_deref().unwrap_or("");
                assert!(
                    !from.contains("/deprecated/deprecated"),
                    "Rule {} has double /deprecated in from path: {}",
                    rule.rule_id,
                    from
                );
                assert!(
                    from.contains("/deprecated"),
                    "Rule {} should use deprecated from path: {}",
                    rule.rule_id,
                    from
                );
            }
        }
    }

    /// Table-like deep trees: root gets requiresChild, intermediate nodes
    /// get notParent, and invalidDirectChild rules fire for skip-level.
    #[test]
    fn test_deep_tree_requires_child_and_not_parent() {
        let mut pkgs = test_pkg_map();
        pkgs.insert("Table".into(), "@patternfly/react-table".into());
        pkgs.insert("Tbody".into(), "@patternfly/react-table".into());
        pkgs.insert("Tr".into(), "@patternfly/react-table".into());
        pkgs.insert("Td".into(), "@patternfly/react-table".into());

        let tree = CompositionTree {
            root: "Table".into(),
            family_members: vec!["Table".into(), "Tbody".into(), "Tr".into(), "Td".into()],
            edges: vec![
                crate::sd_types::CompositionEdge {
                    parent: "Table".into(),
                    child: "Tbody".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Required,
                    prop_name: None,
                },
                crate::sd_types::CompositionEdge {
                    parent: "Tbody".into(),
                    child: "Tr".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Required,
                    prop_name: None,
                },
                crate::sd_types::CompositionEdge {
                    parent: "Tr".into(),
                    child: "Td".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Required,
                    prop_name: None,
                },
            ],
        };

        let rules = generate_conformance_rules(&[tree], &[], &pkgs);

        // Table (root, no_incoming) → requiresChild
        assert!(
            rules.iter().any(|r| r.rule_id.contains("table-req-tbody")),
            "Expected requiresChild on Table. Got: {:?}",
            rules.iter().map(|r| &r.rule_id).collect::<Vec<_>>()
        );

        // Tr (has incoming from Tbody) → notParent
        assert!(
            rules.iter().any(|r| r.rule_id.contains("tr-in-tbody")),
            "Expected notParent on Tr. Got: {:?}",
            rules.iter().map(|r| &r.rule_id).collect::<Vec<_>>()
        );

        // Td (has incoming from Tr) → notParent
        assert!(
            rules.iter().any(|r| r.rule_id.contains("td-in-tr")),
            "Expected notParent on Td. Got: {:?}",
            rules.iter().map(|r| &r.rule_id).collect::<Vec<_>>()
        );

        // InvalidDirectChild: Tr in Table should use Tbody
        assert!(
            rules.iter().any(|r| r.rule_id.contains("tr-not-in-table")),
            "Expected InvalidDirectChild for Tr in Table. Got: {:?}",
            rules.iter().map(|r| &r.rule_id).collect::<Vec<_>>()
        );

        // InvalidDirectChild: Td in Tbody should use Tr
        assert!(
            rules.iter().any(|r| r.rule_id.contains("td-not-in-tbody")),
            "Expected InvalidDirectChild for Td in Tbody. Got: {:?}",
            rules.iter().map(|r| &r.rule_id).collect::<Vec<_>>()
        );

        // Tbody SHOULD have a notParent rule — Required edges have CHP=YES,
        // so Tbody must be inside Table regardless of Table being a root.
        assert!(
            rules.iter().any(|r| r.rule_id.contains("tbody-in")),
            "Tbody should have notParent (Required edge has CHP=YES). Got: {:?}",
            rules.iter().map(|r| &r.rule_id).collect::<Vec<_>>()
        );
    }

    /// When a child has a CHP edge (Required or Structural) directly to the
    /// grandparent, no invalidDirectChild rule should be generated for that
    /// grandparent because the child IS a valid direct child there. The
    /// notParent rule already lists the grandparent as a valid parent.
    ///
    /// Example: Card family has Card→CardBody (Structural) and
    /// Card→CardHeader (Structural), plus CardHeader→CardBody (Allowed from
    /// CSS layout). Without CHP suppression, the grandparent walk would
    /// generate "CardBody not-in Card, use CardHeader" — but CardBody IS a
    /// valid direct child of Card.
    #[test]
    fn test_invalid_direct_child_suppressed_when_child_has_chp_to_grandparent() {
        let mut pkgs = test_pkg_map();
        pkgs.insert("Card".into(), "@patternfly/react-core".into());
        pkgs.insert("CardHeader".into(), "@patternfly/react-core".into());
        pkgs.insert("CardBody".into(), "@patternfly/react-core".into());
        pkgs.insert("CardFooter".into(), "@patternfly/react-core".into());

        let tree = CompositionTree {
            root: "Card".into(),
            family_members: vec![
                "Card".into(),
                "CardHeader".into(),
                "CardBody".into(),
                "CardFooter".into(),
            ],
            edges: vec![
                // Card → CardHeader: Structural (CHP=YES)
                crate::sd_types::CompositionEdge {
                    parent: "Card".into(),
                    child: "CardHeader".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Structural,
                    prop_name: None,
                },
                // Card → CardBody: Structural (CHP=YES)
                crate::sd_types::CompositionEdge {
                    parent: "Card".into(),
                    child: "CardBody".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Structural,
                    prop_name: None,
                },
                // Card → CardFooter: Structural (CHP=YES)
                crate::sd_types::CompositionEdge {
                    parent: "Card".into(),
                    child: "CardFooter".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Structural,
                    prop_name: None,
                },
                // CardHeader → CardBody: Allowed (CSS layout signal)
                crate::sd_types::CompositionEdge {
                    parent: "CardHeader".into(),
                    child: "CardBody".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Allowed,
                    prop_name: None,
                },
                // CardHeader → CardFooter: Allowed (CSS layout signal)
                crate::sd_types::CompositionEdge {
                    parent: "CardHeader".into(),
                    child: "CardFooter".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Allowed,
                    prop_name: None,
                },
            ],
        };

        let rules = generate_conformance_rules(&[tree], &[], &pkgs);

        // notParent rules should exist for CardBody, CardFooter, CardHeader
        // (they all have CHP edges to Card and/or CardHeader).
        assert!(
            rules.iter().any(|r| r.rule_id.contains("body-in-")),
            "Expected notParent for CardBody. Got: {:?}",
            rules.iter().map(|r| &r.rule_id).collect::<Vec<_>>()
        );
        assert!(
            rules.iter().any(|r| r.rule_id.contains("footer-in-")),
            "Expected notParent for CardFooter. Got: {:?}",
            rules.iter().map(|r| &r.rule_id).collect::<Vec<_>>()
        );

        // invalidDirectChild rules should NOT exist for CardBody/CardFooter
        // in Card, because they have direct Structural (CHP=YES) edges to
        // Card. The grandparent walk goes CardBody→CardHeader→Card, but
        // Card→CardBody is Structural, so it should be suppressed.
        let invalid_rules: Vec<&KonveyorRule> = rules
            .iter()
            .filter(|r| r.rule_id.contains("not-in-card"))
            .collect();
        assert!(
            invalid_rules.is_empty(),
            "CardBody/CardFooter should NOT get invalidDirectChild for Card \
             (they have CHP edges to Card). Got: {:?}",
            invalid_rules.iter().map(|r| &r.rule_id).collect::<Vec<_>>()
        );
    }

    /// The invalidDirectChild grandparent walk should only follow CHP=YES
    /// parents (Required or Structural) in the first hop. Allowed parents
    /// (CSS descendant matches between peer components) should NOT be walked
    /// because they create false intermediate paths.
    ///
    /// Example: DescriptionList has Group→Term [Allowed] and Group→Description
    /// [Structural]. Term→Description [Allowed] from CSS `.term .text`. Without
    /// CHP filtering, the walk goes Description→Term(Allowed)→TermHelpText
    /// (Allowed), generating "Description not-in TermHelpText, use Term" — but
    /// Term and Description are peers, not parent-child.
    #[test]
    fn test_invalid_direct_child_skips_allowed_first_hop() {
        let mut pkgs = test_pkg_map();
        pkgs.insert("DL".into(), "@patternfly/react-core".into());
        pkgs.insert("DLGroup".into(), "@patternfly/react-core".into());
        pkgs.insert("DLTerm".into(), "@patternfly/react-core".into());
        pkgs.insert("DLTermHelp".into(), "@patternfly/react-core".into());
        pkgs.insert("DLDesc".into(), "@patternfly/react-core".into());

        let tree = CompositionTree {
            root: "DL".into(),
            family_members: vec![
                "DL".into(),
                "DLGroup".into(),
                "DLTerm".into(),
                "DLTermHelp".into(),
                "DLDesc".into(),
            ],
            edges: vec![
                // DL → DLGroup: Required
                crate::sd_types::CompositionEdge {
                    parent: "DL".into(),
                    child: "DLGroup".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: true,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Required,
                    prop_name: None,
                },
                // DLGroup → DLDesc: Structural (CHP=YES — real parent)
                crate::sd_types::CompositionEdge {
                    parent: "DLGroup".into(),
                    child: "DLDesc".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Structural,
                    prop_name: None,
                },
                // DLGroup → DLTerm: Allowed (CSS noise — peer)
                crate::sd_types::CompositionEdge {
                    parent: "DLGroup".into(),
                    child: "DLTerm".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Allowed,
                    prop_name: None,
                },
                // DLGroup → DLTermHelp: Allowed (CSS noise — peer)
                crate::sd_types::CompositionEdge {
                    parent: "DLGroup".into(),
                    child: "DLTermHelp".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Allowed,
                    prop_name: None,
                },
                // DLTerm → DLDesc: Allowed (CSS descendant noise — peers!)
                crate::sd_types::CompositionEdge {
                    parent: "DLTerm".into(),
                    child: "DLDesc".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Allowed,
                    prop_name: None,
                },
                // DLTermHelp → DLDesc: Allowed (CSS descendant noise — peers!)
                crate::sd_types::CompositionEdge {
                    parent: "DLTermHelp".into(),
                    child: "DLDesc".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Allowed,
                    prop_name: None,
                },
                // DLTermHelp → DLTerm: Allowed (CSS descendant noise — peers!)
                crate::sd_types::CompositionEdge {
                    parent: "DLTermHelp".into(),
                    child: "DLTerm".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Allowed,
                    prop_name: None,
                },
            ],
        };

        let rules = generate_conformance_rules(&[tree], &[], &pkgs);

        // Should have "DLDesc not-in DL, use DLGroup" (valid — CHP first hop
        // through DLGroup, then DL as grandparent)
        assert!(
            rules.iter().any(|r| r.rule_id.contains("desc-not-in-dl")),
            "Expected valid invalidDirectChild for DLDesc in DL. Got: {:?}",
            rules.iter().map(|r| &r.rule_id).collect::<Vec<_>>()
        );

        // Should NOT have "DLDesc not-in DLTermHelp, use DLTerm" — the first
        // hop DLTerm→DLDesc is Allowed (CSS noise between peers), so the
        // grandparent walk should skip it.
        let false_rule = rules.iter().any(|r| {
            r.rule_id.contains("desc-not-in-dlterm") || r.rule_id.contains("desc-not-in-termhelp")
        });
        assert!(
            !false_rule,
            "Should NOT generate invalidDirectChild between peer components \
             (DLDesc not-in DLTermHelp via Allowed first hop). Got: {:?}",
            rules
                .iter()
                .filter(|r| r.rule_id.contains("not-in"))
                .map(|r| &r.rule_id)
                .collect::<Vec<_>>()
        );
    }

    /// Internal edges should not affect conformance rules at all.
    #[test]
    fn test_internal_edges_ignored() {
        let tree = CompositionTree {
            root: "Accordion".into(),
            family_members: vec![
                "Accordion".into(),
                "AccordionItem".into(),
                "AccordionContent".into(),
            ],
            edges: vec![
                crate::sd_types::CompositionEdge {
                    parent: "Accordion".into(),
                    child: "AccordionItem".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Required,
                    prop_name: None,
                },
                // Internal rendering: AccordionItem renders AccordionContent
                crate::sd_types::CompositionEdge {
                    parent: "AccordionItem".into(),
                    child: "AccordionContent".into(),
                    relationship: ChildRelationship::Internal,
                    required: false,
                    bem_evidence: None,
                    strength: crate::sd_types::EdgeStrength::Required,
                    prop_name: None,
                },
            ],
        };

        let rules = generate_conformance_rules(&[tree], &[], &test_pkg_map());

        // AccordionContent should NOT get any rule — the internal edge
        // doesn't count for no_incoming or parent_to_req_children
        assert!(
            !rules.iter().any(|r| r.rule_id.contains("content")),
            "Internal edges should not generate conformance rules. Got: {:?}",
            rules.iter().map(|r| &r.rule_id).collect::<Vec<_>>()
        );
    }

    // ── Fix B: requiresChild includes all valid children ────────────────

    /// Helper: create a Required non-internal edge.
    fn req_edge(parent: &str, child: &str) -> crate::sd_types::CompositionEdge {
        crate::sd_types::CompositionEdge {
            parent: parent.into(),
            child: child.into(),
            relationship: ChildRelationship::DirectChild,
            required: true,
            bem_evidence: None,
            strength: crate::sd_types::EdgeStrength::Required,
            prop_name: None,
        }
    }

    /// Helper: create an Allowed non-internal edge.
    fn allowed_edge(parent: &str, child: &str) -> crate::sd_types::CompositionEdge {
        crate::sd_types::CompositionEdge {
            parent: parent.into(),
            child: child.into(),
            relationship: ChildRelationship::DirectChild,
            required: false,
            bem_evidence: None,
            strength: crate::sd_types::EdgeStrength::Allowed,
            prop_name: None,
        }
    }

    /// requiresChild scanner regex should include Allowed children so
    /// they don't trigger false positives. For example, ToolbarContent
    /// has Required edges to ToolbarFilter/ToolbarToggleGroup but also
    /// Allowed edges to ToolbarGroup/ToolbarItem. The scanner regex
    /// should match ALL of them.
    #[test]
    fn test_requires_child_includes_allowed_children() {
        let mut pkgs = test_pkg_map();
        pkgs.insert("ToolbarContent".into(), "@patternfly/react-core".into());
        pkgs.insert("ToolbarFilter".into(), "@patternfly/react-core".into());
        pkgs.insert("ToolbarToggleGroup".into(), "@patternfly/react-core".into());
        pkgs.insert("ToolbarGroup".into(), "@patternfly/react-core".into());
        pkgs.insert("ToolbarItem".into(), "@patternfly/react-core".into());

        let tree = CompositionTree {
            root: "Toolbar".into(),
            family_members: vec![
                "Toolbar".into(),
                "ToolbarContent".into(),
                "ToolbarFilter".into(),
                "ToolbarToggleGroup".into(),
                "ToolbarGroup".into(),
                "ToolbarItem".into(),
            ],
            edges: vec![
                // Required context edges
                req_edge("ToolbarContent", "ToolbarFilter"),
                req_edge("ToolbarContent", "ToolbarToggleGroup"),
                // Allowed CSS descendant edges
                allowed_edge("ToolbarContent", "ToolbarGroup"),
                allowed_edge("ToolbarContent", "ToolbarItem"),
                // ToolbarContent itself hangs off Toolbar (Allowed)
                allowed_edge("Toolbar", "ToolbarContent"),
            ],
        };

        let rules = generate_conformance_rules(&[tree], &[], &pkgs);

        // ToolbarContent has no Required incoming → gets requiresChild
        let req_rule = rules.iter().find(|r| r.rule_id.contains("content-req-"));
        assert!(
            req_rule.is_some(),
            "Expected requiresChild rule for ToolbarContent. Got: {:?}",
            rules.iter().map(|r| &r.rule_id).collect::<Vec<_>>()
        );

        // The scanner regex should include ALL children (Required + Allowed)
        if let KonveyorCondition::FrontendReferenced { referenced } = &req_rule.unwrap().when {
            let pattern = referenced.requires_child.as_deref().unwrap();
            assert!(
                pattern.contains("ToolbarFilter"),
                "requiresChild should include Required child ToolbarFilter: {}",
                pattern
            );
            assert!(
                pattern.contains("ToolbarGroup"),
                "requiresChild should include Allowed child ToolbarGroup: {}",
                pattern
            );
            assert!(
                pattern.contains("ToolbarItem"),
                "requiresChild should include Allowed child ToolbarItem: {}",
                pattern
            );
        } else {
            panic!("Expected FrontendReferenced condition");
        }

        // The message should mention all valid children
        let msg = &req_rule.unwrap().message;
        assert!(
            msg.contains("ToolbarGroup"),
            "Message should mention Allowed child ToolbarGroup: {}",
            msg
        );
    }

    /// When a parent has only Required children and no Allowed ones,
    /// requiresChild should still work identically (no regression).
    #[test]
    fn test_requires_child_only_required_children_unchanged() {
        let mut pkgs = test_pkg_map();
        pkgs.insert("List".into(), "@patternfly/react-core".into());
        pkgs.insert("ListItem".into(), "@patternfly/react-core".into());

        let tree = CompositionTree {
            root: "List".into(),
            family_members: vec!["List".into(), "ListItem".into()],
            edges: vec![req_edge("List", "ListItem")],
        };

        let rules = generate_conformance_rules(&[tree], &[], &pkgs);

        let req_rule = rules.iter().find(|r| r.rule_id.contains("list-req-"));
        assert!(req_rule.is_some(), "Expected requiresChild rule for List");

        if let KonveyorCondition::FrontendReferenced { referenced } = &req_rule.unwrap().when {
            let pattern = referenced.requires_child.as_deref().unwrap();
            assert_eq!(
                pattern, "^(ListItem)$",
                "With only Required children, regex should be unchanged"
            );
        } else {
            panic!("Expected FrontendReferenced condition");
        }
    }

    /// The fix strategy replacement field should list all valid children,
    /// not just the first one.
    #[test]
    fn test_requires_child_fix_strategy_lists_all_children() {
        let mut pkgs = test_pkg_map();
        pkgs.insert("Menu".into(), "@patternfly/react-core".into());
        pkgs.insert("MenuItem".into(), "@patternfly/react-core".into());
        pkgs.insert("MenuContent".into(), "@patternfly/react-core".into());
        pkgs.insert("MenuList".into(), "@patternfly/react-core".into());

        let tree = CompositionTree {
            root: "Menu".into(),
            family_members: vec![
                "Menu".into(),
                "MenuItem".into(),
                "MenuContent".into(),
                "MenuList".into(),
            ],
            edges: vec![
                req_edge("Menu", "MenuItem"),
                allowed_edge("Menu", "MenuContent"),
                allowed_edge("Menu", "MenuList"),
            ],
        };

        let rules = generate_conformance_rules(&[tree], &[], &pkgs);

        let req_rule = rules.iter().find(|r| r.rule_id.contains("menu-req-"));
        assert!(req_rule.is_some(), "Expected requiresChild rule for Menu");

        let fix = req_rule.unwrap().fix_strategy.as_ref().unwrap();
        let replacement = fix.replacement.as_deref().unwrap();
        assert!(
            replacement.contains("MenuContent") && replacement.contains("MenuItem"),
            "Fix strategy replacement should list all valid children: {}",
            replacement
        );
    }

    // ── Fix C: prop-passed children excluded from requiresChild ─────────

    /// Helper: create a PropPassed edge (child passed via a named prop).
    fn prop_passed_edge(
        parent: &str,
        child: &str,
        prop_name: &str,
    ) -> crate::sd_types::CompositionEdge {
        crate::sd_types::CompositionEdge {
            parent: parent.into(),
            child: child.into(),
            relationship: ChildRelationship::PropPassed,
            required: true,
            bem_evidence: None,
            strength: crate::sd_types::EdgeStrength::Required,
            prop_name: Some(prop_name.into()),
        }
    }

    /// When ALL Required children of a parent are prop-passed, no
    /// requiresChild rule should be generated — the scanner only sees
    /// direct JSX children and would always report a false positive.
    #[test]
    fn test_requires_child_skipped_when_all_prop_passed() {
        let mut pkgs = test_pkg_map();
        pkgs.insert("ChartBullet".into(), "@patternfly/react-charts".into());
        pkgs.insert("ChartBulletTitle".into(), "@patternfly/react-charts".into());
        pkgs.insert(
            "ChartBulletQualitativeRange".into(),
            "@patternfly/react-charts".into(),
        );

        let tree = CompositionTree {
            root: "ChartBullet".into(),
            family_members: vec![
                "ChartBullet".into(),
                "ChartBulletTitle".into(),
                "ChartBulletQualitativeRange".into(),
            ],
            edges: vec![
                prop_passed_edge("ChartBullet", "ChartBulletTitle", "titleComponent"),
                prop_passed_edge(
                    "ChartBullet",
                    "ChartBulletQualitativeRange",
                    "qualitativeRangeComponent",
                ),
            ],
        };

        let rules = generate_conformance_rules(&[tree], &[], &pkgs);

        assert!(
            !rules.iter().any(|r| r.rule_id.contains("req-")),
            "All-prop-passed parent should not get requiresChild rule. Got: {:?}",
            rules.iter().map(|r| &r.rule_id).collect::<Vec<_>>()
        );
    }

    /// When a parent has a mix of direct and prop-passed Required children,
    /// only the direct children should appear in the requiresChild regex.
    /// The prop-passed children are invisible to the scanner.
    #[test]
    fn test_requires_child_excludes_prop_passed_children() {
        let mut pkgs = test_pkg_map();
        pkgs.insert("Tab".into(), "@patternfly/react-core".into());
        pkgs.insert("TabAction".into(), "@patternfly/react-core".into());
        pkgs.insert("TabContent".into(), "@patternfly/react-core".into());

        let tree = CompositionTree {
            root: "Tabs".into(),
            family_members: vec![
                "Tabs".into(),
                "Tab".into(),
                "TabAction".into(),
                "TabContent".into(),
            ],
            edges: vec![
                // Direct child — scanner CAN see this
                req_edge("Tab", "TabContent"),
                // Prop-passed — scanner CANNOT see this
                prop_passed_edge("Tab", "TabAction", "actions"),
            ],
        };

        let rules = generate_conformance_rules(&[tree], &[], &pkgs);

        let req_rule = rules.iter().find(|r| r.rule_id.contains("tab-req-"));
        assert!(
            req_rule.is_some(),
            "Tab should still get requiresChild for its direct child. Got: {:?}",
            rules.iter().map(|r| &r.rule_id).collect::<Vec<_>>()
        );

        if let KonveyorCondition::FrontendReferenced { referenced } = &req_rule.unwrap().when {
            let pattern = referenced.requires_child.as_deref().unwrap();
            assert!(
                pattern.contains("TabContent"),
                "requiresChild should include direct child TabContent: {}",
                pattern
            );
            assert!(
                !pattern.contains("TabAction"),
                "requiresChild should NOT include prop-passed child TabAction: {}",
                pattern
            );
        } else {
            panic!("Expected FrontendReferenced condition");
        }
    }

    // ── Insta snapshot tests for v2 YAML output safety ─────────────────
    //
    // These snapshots capture the exact YAML serialization of v2 rules
    // (composition, conformance, CSS removal, deprecated migration).
    // Any change to serde field names, condition shapes, or rule
    // structure will show as a snapshot diff.

    /// Wrapper that captures both the serialized rule and its fix_strategy
    /// (which is normally skipped by serde on KonveyorRule).
    #[derive(Debug, serde::Serialize)]
    struct RuleSnapshot {
        rule: KonveyorRule,
        fix_strategy: Option<FixStrategyEntry>,
    }

    impl RuleSnapshot {
        fn from_rule(mut rule: KonveyorRule) -> Self {
            let fix_strategy = rule.fix_strategy.take();
            Self { rule, fix_strategy }
        }
    }

    fn snapshot_rules(mut rules: Vec<KonveyorRule>) -> Vec<RuleSnapshot> {
        // Sort by rule_id for deterministic snapshot ordering — the generator
        // iterates over HashSet/HashMap which has non-deterministic order.
        rules.sort_by(|a, b| a.rule_id.cmp(&b.rule_id));
        rules.into_iter().map(RuleSnapshot::from_rule).collect()
    }

    fn make_edge(
        parent: &str,
        child: &str,
        strength: crate::sd_types::EdgeStrength,
    ) -> crate::sd_types::CompositionEdge {
        crate::sd_types::CompositionEdge {
            parent: parent.into(),
            child: child.into(),
            relationship: ChildRelationship::DirectChild,
            required: false,
            bem_evidence: None,
            strength,
            prop_name: None,
        }
    }

    #[test]
    fn snapshot_conformance_not_parent_rules() {
        let mut pkgs = test_pkg_map();
        pkgs.insert("Table".into(), "@patternfly/react-table".into());
        pkgs.insert("Thead".into(), "@patternfly/react-table".into());
        pkgs.insert("Tbody".into(), "@patternfly/react-table".into());
        pkgs.insert("Tr".into(), "@patternfly/react-table".into());
        pkgs.insert("Td".into(), "@patternfly/react-table".into());

        use crate::sd_types::EdgeStrength;

        let tree = CompositionTree {
            root: "Table".into(),
            family_members: vec![
                "Table".into(),
                "Thead".into(),
                "Tbody".into(),
                "Tr".into(),
                "Td".into(),
            ],
            edges: vec![
                make_edge("Table", "Thead", EdgeStrength::Required),
                make_edge("Table", "Tbody", EdgeStrength::Required),
                make_edge("Thead", "Tr", EdgeStrength::Required),
                make_edge("Tbody", "Tr", EdgeStrength::Required),
                make_edge("Tr", "Td", EdgeStrength::Required),
            ],
        };

        let rules = generate_conformance_rules(&[tree], &[], &pkgs);
        insta::assert_yaml_snapshot!(snapshot_rules(rules));
    }

    #[test]
    fn snapshot_conformance_requires_child_rule() {
        let mut pkgs = test_pkg_map();
        pkgs.insert("Tabs".into(), "@patternfly/react-core".into());
        pkgs.insert("Tab".into(), "@patternfly/react-core".into());
        pkgs.insert("TabContent".into(), "@patternfly/react-core".into());

        use crate::sd_types::EdgeStrength;

        let tree = CompositionTree {
            root: "Tabs".into(),
            family_members: vec!["Tabs".into(), "Tab".into(), "TabContent".into()],
            edges: vec![
                make_edge("Tabs", "Tab", EdgeStrength::Required),
                make_edge("Tabs", "TabContent", EdgeStrength::Required),
            ],
        };

        let rules = generate_conformance_rules(&[tree], &[], &pkgs);
        insta::assert_yaml_snapshot!(snapshot_rules(rules));
    }

    #[test]
    fn snapshot_css_class_removal_rules() {
        let removed_blocks = vec!["select".to_string(), "options-menu".to_string()];
        let rules = generate_css_class_removal_rules(&removed_blocks);
        insta::assert_yaml_snapshot!(snapshot_rules(rules));
    }

    #[test]
    fn snapshot_composition_removed_member_rule() {
        let sd = SdPipelineResult {
            composition_changes: vec![crate::sd_types::CompositionChange {
                family: "EmptyState".into(),
                change_type: CompositionChangeType::FamilyMemberRemoved {
                    member: "EmptyStateHeader".into(),
                },
                description: "EmptyStateHeader was removed from EmptyState family".into(),
                before_pattern: None,
                after_pattern: None,
            }],
            component_packages: {
                let mut m = HashMap::new();
                m.insert("EmptyState".into(), "@patternfly/react-core".into());
                m.insert("EmptyStateHeader".into(), "@patternfly/react-core".into());
                m
            },
            ..SdPipelineResult::default()
        };

        let pkg_map = sd.component_packages.clone();
        let rules = generate_composition_change_rules(&sd, &pkg_map);
        insta::assert_yaml_snapshot!(snapshot_rules(rules));
    }

    #[test]
    fn snapshot_conformance_invalid_direct_child_rule() {
        use crate::sd_types::EdgeStrength;

        let mut pkgs = test_pkg_map();
        pkgs.insert("Nav".into(), "@patternfly/react-core".into());
        pkgs.insert("NavList".into(), "@patternfly/react-core".into());
        pkgs.insert("NavItem".into(), "@patternfly/react-core".into());

        let tree = CompositionTree {
            root: "Nav".into(),
            family_members: vec!["Nav".into(), "NavList".into(), "NavItem".into()],
            edges: vec![
                make_edge("Nav", "NavList", EdgeStrength::Required),
                make_edge("NavList", "NavItem", EdgeStrength::Required),
            ],
        };

        let rules = generate_conformance_rules(&[tree], &[], &pkgs);
        insta::assert_yaml_snapshot!(snapshot_rules(rules));
    }
}