semver-analyzer-ts 0.0.3

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
//! 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 semver_analyzer_core::types::sd::{
    ChildRelationship, CompositionChangeType, CompositionTree, ConformanceCheck,
    ConformanceCheckType, SdPipelineResult, SourceLevelCategory, SourceLevelChange,
};
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,
    ));

    // ── 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));

    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())
}

// ── 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 {
                parent,
                new_child,
                wraps,
            } => {
                let rule_id = format!(
                    "sd-composition-{}-requires-{}",
                    sanitize(parent),
                    sanitize(new_child)
                );

                let mut message = format!(
                    "<{}> now requires <{}> as a child component.\n",
                    parent, new_child
                );
                if let Some(ref after) = change.after_pattern {
                    message.push_str(&format!("\nExpected pattern:\n{}\n", after));
                }
                if !wraps.is_empty() {
                    message.push_str(&format!("\n<{}> wraps: {}\n", new_child, wraps.join(", ")));
                }

                // Add warning about prop-passed family members
                if let Some(prop_members) = prop_passed_members.get(parent) {
                    message.push_str(&format!(
                        "\nIMPORTANT: The following components are passed via props on <{}>, \
                         NOT as JSX children. Do not move them into the children:\n",
                        parent
                    ));
                    for pm in prop_members {
                        message.push_str(&format!("  - {}\n", pm));
                    }
                }

                let pkg = pkg_for(parent, component_packages);
                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,
                    links: vec![],
                    when: KonveyorCondition::FrontendReferenced {
                        referenced: FrontendReferencedFields {
                            pattern: format!("^{}$", parent),
                            location: "JSX_COMPONENT".into(),
                            component: None,
                            parent: None,
                            parent_from: None,
                            not_parent: None,
                            not_child: None,
                            value: None,
                            from: Some(pkg.clone()),
                            file_pattern: None,
                        },
                    },
                    fix_strategy: Some(FixStrategyEntry {
                        strategy: "CompositionChange".into(),
                        component: Some(parent.clone()),
                        replacement: Some(new_child.clone()),
                        ..Default::default()
                    }),
                });
            }
            CompositionChangeType::FamilyMemberAdded { member } => {
                let pkg = pkg_for(member, component_packages);
                let rule_id = format!(
                    "sd-composition-{}-new-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: 1,
                    category: "optional".into(),
                    description: change.description.clone(),
                    message: format!(
                        "<{}> is a new component in the {} family.\n\
                         Consider using it for better structure and semantics.",
                        member, change.family
                    ),
                    links: vec![],
                    when: KonveyorCondition::FrontendReferenced {
                        referenced: FrontendReferencedFields {
                            pattern: format!("^{}$", change.family),
                            location: "JSX_COMPONENT".into(),
                            component: None,
                            parent: None,
                            parent_from: None,
                            not_parent: None,
                            not_child: None,
                            value: None,
                            from: Some(pkg.to_string()),
                            file_pattern: None,
                        },
                    },
                    fix_strategy: None,
                });
            }
            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,
                            not_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 ───────────────────────────────────────────────────

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 {
        // Build parent lookup for InvalidDirectChild detection
        let mut child_to_parents: HashMap<&str, Vec<&str>> = HashMap::new();
        for edge in &tree.edges {
            child_to_parents
                .entry(edge.child.as_str())
                .or_default()
                .push(edge.parent.as_str());
        }

        for edge in &tree.edges {
            // Skip internal rendering edges — not consumer-facing
            if edge.relationship == ChildRelationship::Internal {
                continue;
            }

            let pkg = pkg_for(&edge.child, component_packages);

            // ── InvalidDirectChild: child inside grandparent, skipping parent
            if let Some(grandparents) = child_to_parents.get(edge.parent.as_str()) {
                for grandparent in grandparents {
                    let rule_id = format!(
                        "sd-conformance-{}-not-in-{}-use-{}",
                        sanitize(&edge.child),
                        sanitize(grandparent),
                        sanitize(&edge.parent),
                    );

                    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 <{}>",
                            edge.child, edge.parent, grandparent
                        ),
                        message: format!(
                            "<{}> should be wrapped in <{}> inside <{}>.\n\n\
                             Replace:\n  <{}>\n    <{} />\n  </{}>\n\n\
                             With:\n  <{}>\n    <{}>\n      <{} />\n    </{}>\n  </{}>",
                            edge.child,
                            edge.parent,
                            grandparent,
                            grandparent,
                            edge.child,
                            grandparent,
                            grandparent,
                            edge.parent,
                            edge.child,
                            edge.parent,
                            grandparent,
                        ),
                        links: vec![],
                        when: KonveyorCondition::FrontendReferenced {
                            referenced: FrontendReferencedFields {
                                pattern: format!("^{}$", edge.child),
                                location: "JSX_COMPONENT".into(),
                                component: None,
                                parent: Some(format!("^{}$", grandparent)),
                                parent_from: Some(pkg.to_string()),
                                not_parent: None,
                                not_child: None,
                                value: None,
                                from: Some(pkg.to_string()),
                                file_pattern: None,
                            },
                        },
                        fix_strategy: Some(FixStrategyEntry {
                            strategy: "CompositionChange".into(),
                            component: Some(edge.child.clone()),
                            replacement: Some(edge.parent.clone()),
                            ..Default::default()
                        }),
                    });
                }
            }

            // ── Must-be-inside: child must have parent as ancestor
            // Uses `notParent` to fire only when the child is NOT inside
            // the expected parent — i.e., only on violations.
            let rule_id = format!(
                "sd-conformance-{}-must-be-in-{}",
                sanitize(&edge.child),
                sanitize(&edge.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 be a child of <{}>", edge.child, edge.parent),
                message: format!(
                    "<{}> must be used inside <{}>.\n\n\
                     Correct usage:\n  <{}>\n    <{} />\n  </{}>",
                    edge.child, edge.parent, edge.parent, edge.child, edge.parent,
                ),
                links: vec![],
                when: KonveyorCondition::FrontendReferenced {
                    referenced: FrontendReferencedFields {
                        pattern: format!("^{}$", edge.child),
                        location: "JSX_COMPONENT".into(),
                        component: None,
                        parent: None,
                        not_parent: Some(format!("^{}$", edge.parent)),
                        not_child: None,
                        parent_from: None,
                        value: None,
                        from: Some(pkg.to_string()),
                        file_pattern: None,
                    },
                },
                fix_strategy: Some(FixStrategyEntry {
                    strategy: "LlmAssisted".into(),
                    component: Some(edge.child.clone()),
                    replacement: Some(edge.parent.clone()),
                    ..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(parent, component_packages);
            let allowed_pattern = format!("^({})$", allowed_children.join("|"));
            let allowed_list = allowed_children.join(" or ");

            let rule_id = format!("sd-conformance-{}-requires-wrapper", sanitize(parent),);

            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,
                        not_child: Some(allowed_pattern),
                        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 rule_id = format!(
            "sd-context-{}-{}",
            sanitize(&change.component),
            sanitize(ctx_name),
        );

        // 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={}", 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,
                    not_child: None,
                    value: None,
                    from: Some(pkg.to_string()),
                    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,
                                not_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,
                                        not_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,
                                not_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,
                            not_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,
                            not_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,
                        not_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")
}

// ── 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,
                            not_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,
                                not_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,
                        not_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 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 rule_id = format!(
                        "sd-test-{}-role-{}-{}",
                        sanitize(&change.component),
                        sanitize(old_val),
                        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,
                                not_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 rule_id = format!(
                        "sd-test-{}-aria-label-{}-{}",
                        sanitize(&change.component),
                        sanitize(old_val),
                        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,
                                not_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 rule_id = format!(
                            "sd-test-{}-dom-{}-removed",
                            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,
                                    not_child: None,
                                    parent_from: None,
                                    value: Some(format!("^{}$", role)),
                                    from: None,
                                    file_pattern: Some(TEST_FILE_PATTERN.into()),
                                },
                            },
                            fix_strategy: None,
                        });
                    }
                }
            }

            _ => {}
        }
    }

    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.

// ── 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);

        // 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()).collect();
                    (parts[0].to_string(), attrs)
                } else {
                    continue;
                }
            }
            None => continue,
        };

        // Generate one rule per overridden attribute
        for attr in &overridden_attrs {
            let rule_id = format!(
                "sd-prop-override-{}-{}",
                sanitize(&change.component),
                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,
                        not_child: None,
                        parent_from: None,
                        value: None,
                        from: if pkg != "unknown" {
                            Some(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()
}

// ── 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()
}

// ── 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_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![
                semver_analyzer_core::types::sd::CompositionEdge {
                    parent: "Dropdown".into(),
                    child: "DropdownList".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: true,
                    bem_evidence: None,
                },
                semver_analyzer_core::types::sd::CompositionEdge {
                    parent: "DropdownList".into(),
                    child: "DropdownItem".into(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: 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("dropdownitem-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");
        }
    }

    #[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,
        }];

        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");
        }
    }
}