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
//! TypeScript SD (Source-Level Diff) pipeline implementation.
//!
//! Orchestrates the v2 source-level analysis in two phases:
//!
//! **Phase A — Diff (scoped to changed files):**
//! 1. Find changed `.tsx` source files via `git diff --name-only`
//! 2. Read component source at both refs via `git show`
//! 3. Extract `ComponentSourceProfile`s and diff them → `SourceLevelChange`
//!
//! **Phase B — Full to-version (all component files):**
//! 4. Enumerate ALL component `.tsx` files at the to-ref via `git ls-tree`
//! 5. Extract profiles for all components in the to-version
//! 6. Build composition trees for ALL families → `CompositionTree`
//! 7. Diff trees (for changed families only) → `CompositionChange`
//! 8. Generate conformance checks from ALL to-version trees → `ConformanceCheck`
//!
//! This separation ensures conformance rules cover the entire new API
//! (not just families with changes), while migration rules are scoped
//! to actual diffs.
//!
//! All analysis is deterministic — no LLM, no confidence scores.

use crate::composition::build_composition_tree;
use crate::source_profile::{self, diff::diff_profiles};

use semver_analyzer_core::types::sd::{
    ComponentSourceProfile, CompositionChange, CompositionChangeType, CompositionTree,
    ConformanceCheck, ConformanceCheckType, SdPipelineResult,
};

use anyhow::Result;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::path::Path;
use std::process::Command;
use tracing::{debug, info, info_span, warn};

/// Run the full SD pipeline for a TypeScript/React project.
///
/// Phase A: diff changed files for source-level changes.
/// Phase B: extract full to-version profiles, build composition trees
/// for all families, generate conformance checks.
///
/// If `css_profiles` is provided (from a dependency CSS repo), they're
/// used to enrich composition trees with grid layout nesting.
pub fn run_sd(
    repo: &Path,
    from_ref: &str,
    to_ref: &str,
    css_profiles: Option<&HashMap<String, crate::css_profile::CssBlockProfile>>,
) -> Result<SdPipelineResult> {
    let _span = info_span!("sd_pipeline", %from_ref, %to_ref).entered();

    // ════════════════════════════════════════════════════════════════
    // Phase A: Diff — scoped to changed files
    // ════════════════════════════════════════════════════════════════

    let changed_files = find_changed_component_files(repo, from_ref, to_ref)?;
    info!(count = changed_files.len(), "changed component files found");

    let mut old_profiles: HashMap<String, ComponentSourceProfile> = HashMap::new();
    let mut all_source_changes = Vec::new();

    // Extract profiles at both refs for changed files, diff them
    for file_info in &changed_files {
        let old_source = read_git_file(repo, from_ref, &file_info.path);
        let new_source = read_git_file(repo, to_ref, &file_info.path);

        if let Some(ref source) = old_source {
            let profile =
                source_profile::extract_profile(&file_info.component_name, &file_info.path, source);
            // When a component exists in both main and deprecated paths,
            // prefer the main (non-deprecated) version.
            let is_deprecated = file_info.path.contains("/deprecated/");
            if let Some(existing) = old_profiles.get(&file_info.component_name) {
                let existing_is_deprecated = existing.file.contains("/deprecated/");
                if existing_is_deprecated && !is_deprecated {
                    old_profiles.insert(file_info.component_name.clone(), profile);
                }
            } else {
                old_profiles.insert(file_info.component_name.clone(), profile);
            }
        }

        // new_source profiles are populated in Phase B (full extraction)
        // but we need them here for diffing, so extract inline
        if let (Some(old_src), Some(new_src)) = (&old_source, &new_source) {
            let old_p = source_profile::extract_profile(
                &file_info.component_name,
                &file_info.path,
                old_src,
            );
            let new_p = source_profile::extract_profile(
                &file_info.component_name,
                &file_info.path,
                new_src,
            );

            let changes = diff_profiles(&old_p, &new_p);
            if !changes.is_empty() {
                debug!(
                    component = %file_info.component_name,
                    changes = changes.len(),
                    "source-level changes detected"
                );
            }
            all_source_changes.extend(changes);
        }
    }

    info!(
        total_changes = all_source_changes.len(),
        "Phase A complete: source-level diff"
    );

    // ════════════════════════════════════════════════════════════════
    // Phase B: Full to-version extraction
    // ════════════════════════════════════════════════════════════════

    // Find ALL component .tsx files at the to-ref
    let all_to_files = find_all_component_files(repo, to_ref)?;
    info!(
        count = all_to_files.len(),
        "all component files in to-version"
    );

    // Extract profiles for all to-version components.
    // When a component exists in both main and deprecated paths (e.g., Modal),
    // the main (non-deprecated) version takes priority — it represents the
    // canonical v6 API surface that consumers should migrate to.
    let mut new_profiles: HashMap<String, ComponentSourceProfile> = HashMap::new();
    for file_info in &all_to_files {
        if let Some(source) = read_git_file(repo, to_ref, &file_info.path) {
            let profile = source_profile::extract_profile(
                &file_info.component_name,
                &file_info.path,
                &source,
            );
            let is_deprecated = file_info.path.contains("/deprecated/");
            if let Some(existing) = new_profiles.get(&file_info.component_name) {
                let existing_is_deprecated = existing.file.contains("/deprecated/");
                // Main path wins over deprecated path
                if existing_is_deprecated && !is_deprecated {
                    new_profiles.insert(file_info.component_name.clone(), profile);
                }
                // else: keep the existing (non-deprecated or first-seen)
            } else {
                new_profiles.insert(file_info.component_name.clone(), profile);
            }
        }
    }

    info!(
        new_profiles = new_profiles.len(),
        "to-version profiles extracted"
    );

    // Group ALL to-version files by family
    let all_families = group_by_family(&all_to_files);
    // Track which families had changes (for composition diffing)
    let changed_families: HashSet<String> = changed_files
        .iter()
        .filter_map(|f| f.family.clone())
        .collect();

    // ── B1: Build all to-version composition trees ──────────────────
    //
    // For each family, build the tree with ALL component files in the
    // directory (including internal/non-exported ones like ModalBox,
    // ModalContent). This lets us trace rendering chains through
    // internal components. Afterwards, collapse non-exported nodes.
    let mut composition_trees = Vec::new();
    let mut family_exports_map: BTreeMap<String, Vec<String>> = BTreeMap::new();

    for (family_name, family_files) in &all_families {
        let new_exports = read_family_exports_from_dir(repo, to_ref, family_name, family_files);

        // Collect ALL family member names (including internal components)
        let all_member_names: Vec<String> = family_files
            .iter()
            .map(|f| f.component_name.clone())
            .collect();

        // Collect profiles for ALL members (not just exports)
        let all_family_profiles = collect_family_profiles(&new_profiles, &all_member_names);

        // Build tree with all members, using exports[0] as root
        // Pass all member names so the builder sees the internal components
        let mut all_members_for_tree = new_exports.clone();
        for name in &all_member_names {
            if !all_members_for_tree.contains(name) {
                all_members_for_tree.push(name.clone());
            }
        }

        let full_tree = build_composition_tree(&all_family_profiles, &all_members_for_tree);

        if let Some(mut tree) = full_tree {
            // Collapse non-exported nodes: remove internal components
            // and transfer their edges to their parents.
            let exports_set: HashSet<&str> = new_exports.iter().map(|s| s.as_str()).collect();
            collapse_internal_nodes(&mut tree, &exports_set);
            composition_trees.push(tree);
        }

        family_exports_map.insert(family_name.clone(), new_exports);
    }

    // ── B2: Delegation projection ───────────────────────────────────
    //
    // Wrapper families (e.g., Dropdown wraps Menu) have sparse trees
    // because they lack BEM tokens. Project edges from the delegate
    // family's tree using `extends_props` (e.g., DropdownListProps
    // extends MenuListProps → DropdownList maps to MenuList).
    // This must happen BEFORE diffing so composition diffs see the
    // projected edges.

    let trees_snapshot: Vec<CompositionTree> = composition_trees.clone();
    project_delegate_trees(&mut composition_trees, &new_profiles, &trees_snapshot);

    // ── B2.5: CSS grid nesting enrichment ─────────────────────────────
    //
    // If CSS profiles are available (from a dependency CSS repo), use
    // grid layout signals to refine nesting:
    //   - Elements with grid-column → direct children of block grid
    //   - Elements WITHOUT grid-column → must be nested inside a grid item
    //   - Variable child refs (--block__main--toggle--...) → explicit containment
    if let Some(css_profs) = css_profiles {
        enrich_trees_with_css(&mut composition_trees, css_profs, &new_profiles);
    }

    // ── B3: Composition diff + conformance checks ───────────────────
    //
    // Now that trees have full edges (including projected ones), diff
    // changed families and generate conformance checks from all trees.
    let mut composition_changes = Vec::new();
    let mut conformance_checks = Vec::new();
    let mut old_composition_trees = Vec::new();

    for tree in &composition_trees {
        let family_name = &tree.root;

        // Conformance checks from ALL to-version trees
        let checks = generate_conformance_checks(family_name, tree, &new_profiles);
        conformance_checks.extend(checks);

        // Composition diff only for families with changes
        if changed_families.contains(family_name) {
            if let Some(family_files) = all_families.get(family_name) {
                let new_exports = family_exports_map
                    .get(family_name)
                    .cloned()
                    .unwrap_or_default();
                let old_exports =
                    read_family_exports_from_dir(repo, from_ref, family_name, family_files);
                let old_family_profiles =
                    extract_family_profiles_at_ref(repo, from_ref, &old_exports, family_files);
                let old_tree = build_composition_tree(&old_family_profiles, &old_exports);

                let changes = diff_composition_trees(
                    family_name,
                    old_tree.as_ref(),
                    tree,
                    &old_exports,
                    &new_exports,
                );
                composition_changes.extend(changes);

                // Persist old tree for downstream cross-family analysis
                if let Some(ot) = old_tree {
                    old_composition_trees.push(ot);
                }
            }
        }
    }

    info!(
        composition_trees = composition_trees.len(),
        composition_changes = composition_changes.len(),
        conformance_checks = conformance_checks.len(),
        "Phase B complete: composition analysis"
    );

    // Build serializable prop maps for child→prop detection
    let old_component_props: HashMap<String, BTreeSet<String>> = old_profiles
        .iter()
        .map(|(name, profile)| (name.clone(), profile.all_props.clone()))
        .collect();
    let new_component_props: HashMap<String, BTreeSet<String>> = new_profiles
        .iter()
        .map(|(name, profile)| (name.clone(), profile.all_props.clone()))
        .collect();
    let old_component_prop_types: HashMap<String, BTreeMap<String, String>> = old_profiles
        .iter()
        .filter(|(_, profile)| !profile.prop_types.is_empty())
        .map(|(name, profile)| (name.clone(), profile.prop_types.clone()))
        .collect();
    let new_component_prop_types: HashMap<String, BTreeMap<String, String>> = new_profiles
        .iter()
        .filter(|(_, profile)| !profile.prop_types.is_empty())
        .map(|(name, profile)| (name.clone(), profile.prop_types.clone()))
        .collect();
    let new_required_props: HashMap<String, BTreeSet<String>> = new_profiles
        .iter()
        .filter(|(_, profile)| !profile.required_props.is_empty())
        .map(|(name, profile)| (name.clone(), profile.required_props.clone()))
        .collect();

    // Build component→package maps for both versions.
    // Used for detecting deprecated↔main migrations.
    let old_component_packages: HashMap<String, String> = old_profiles
        .iter()
        .filter_map(|(name, profile)| {
            resolve_component_package(&profile.file).map(|pkg| (name.clone(), pkg))
        })
        .collect();

    let component_packages: HashMap<String, String> = new_profiles
        .iter()
        .filter_map(|(name, profile)| {
            resolve_component_package(&profile.file).map(|pkg| (name.clone(), pkg))
        })
        .collect();

    Ok(SdPipelineResult {
        source_level_changes: all_source_changes,
        composition_trees,
        old_composition_trees,
        composition_changes,
        conformance_checks,
        component_packages,
        old_component_packages,
        old_component_props,
        new_component_props,
        old_component_prop_types,
        new_component_prop_types,
        new_required_props,
        dep_repo_packages: HashMap::new(), // populated by orchestrator from --dep-repo
        removed_css_blocks: Vec::new(),    // populated by orchestrator from dep-repo diff
        old_profiles,
        new_profiles,
    })
}

// ── Internal types ──────────────────────────────────────────────────────

/// A component source file with extracted metadata.
#[derive(Debug, Clone)]
struct ComponentFile {
    /// Relative path to the .tsx file.
    path: String,
    /// Component name derived from the filename (e.g., "Dropdown").
    component_name: String,
    /// Family directory name (e.g., "Dropdown" from ".../components/Dropdown/...").
    family: Option<String>,
}

// ── File discovery ──────────────────────────────────────────────────────

/// Find changed component .tsx files between two refs via `git diff`.
fn find_changed_component_files(
    repo: &Path,
    from_ref: &str,
    to_ref: &str,
) -> Result<Vec<ComponentFile>> {
    let output = Command::new("git")
        .args([
            "-C",
            &repo.to_string_lossy(),
            "diff",
            "--name-only",
            &format!("{}..{}", from_ref, to_ref),
            "--",
            "*.tsx",
        ])
        .output()?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("git diff --name-only failed: {}", stderr);
    }

    Ok(parse_component_file_list(&String::from_utf8_lossy(
        &output.stdout,
    )))
}

/// Find ALL component .tsx files at a specific ref via `git ls-tree`.
///
/// `git ls-tree` doesn't support glob pathspecs, so we enumerate all
/// files and filter to `.tsx` in Rust.
fn find_all_component_files(repo: &Path, git_ref: &str) -> Result<Vec<ComponentFile>> {
    let output = Command::new("git")
        .args([
            "-C",
            &repo.to_string_lossy(),
            "ls-tree",
            "-r",
            "--name-only",
            git_ref,
        ])
        .output()?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        warn!(%stderr, "git ls-tree failed, falling back to empty");
        return Ok(Vec::new());
    }

    // Filter to .tsx files in Rust (git ls-tree doesn't support globs)
    let all_output = String::from_utf8_lossy(&output.stdout);
    let tsx_only: String = all_output
        .lines()
        .filter(|line| line.ends_with(".tsx"))
        .collect::<Vec<_>>()
        .join("\n");

    Ok(parse_component_file_list(&tsx_only))
}

/// Parse a newline-separated file list into ComponentFile entries.
fn parse_component_file_list(output: &str) -> Vec<ComponentFile> {
    output
        .lines()
        .filter_map(|line| {
            let path = line.trim().to_string();
            if path.is_empty() || should_exclude_from_sd(&path) {
                return None;
            }
            let component_name = extract_component_name(&path)?;
            let family = extract_family_from_path(&path);
            Some(ComponentFile {
                path,
                component_name,
                family,
            })
        })
        .collect()
}

/// Whether a file should be excluded from SD analysis.
fn should_exclude_from_sd(path: &str) -> bool {
    // Test files and mocks
    path.contains(".test.") || path.contains(".spec.")
    || path.contains("__tests__") || path.contains("__mocks__")
    // Index/barrel files
    || path.ends_with("/index.tsx") || path == "index.tsx"
    // Build output
    || path.contains("/dist/") || path.starts_with("dist/")
    // Declaration files
    || path.ends_with(".d.ts") || path.ends_with(".d.tsx")
    // Demo/example files
    || path.contains("/examples/") || path.contains("/demos/")
    // Figma code connect files
    || path.contains(".figma.")
}

/// Extract the component name from a .tsx filename.
///
/// Convention: `Dropdown.tsx` → "Dropdown"
/// Only returns names that start with uppercase (React component convention).
fn extract_component_name(path: &str) -> Option<String> {
    let filename = path.rsplit('/').next()?;
    let stem = filename.strip_suffix(".tsx")?;

    // Must start with uppercase (React component convention)
    if stem.starts_with(|c: char| c.is_ascii_uppercase()) {
        Some(stem.to_string())
    } else {
        None
    }
}

/// Extract the component family directory name from a file path.
///
/// e.g., "packages/react-core/src/components/Masthead/Masthead.tsx" → "Masthead"
fn extract_family_from_path(path: &str) -> Option<String> {
    let parts: Vec<&str> = path.split('/').collect();
    for (i, part) in parts.iter().enumerate() {
        if *part == "components" && i + 1 < parts.len() && i + 2 < parts.len() {
            return Some(parts[i + 1].to_string());
        }
    }
    None
}

// ── Family / profile helpers ────────────────────────────────────────────

/// Group files by their family directory.
fn group_by_family(files: &[ComponentFile]) -> BTreeMap<String, Vec<&ComponentFile>> {
    let mut groups: BTreeMap<String, Vec<&ComponentFile>> = BTreeMap::new();
    for file in files {
        if let Some(ref family) = file.family {
            groups.entry(family.clone()).or_default().push(file);
        }
    }
    groups
}

/// Collect profiles from an existing profile map for a given family's exports.
fn collect_family_profiles(
    all_profiles: &HashMap<String, semver_analyzer_core::types::sd::ComponentSourceProfile>,
    family_exports: &[String],
) -> HashMap<String, semver_analyzer_core::types::sd::ComponentSourceProfile> {
    family_exports
        .iter()
        .filter_map(|name| all_profiles.get(name).map(|p| (name.clone(), p.clone())))
        .collect()
}

/// Extract profiles for family members at a specific git ref by reading source.
fn extract_family_profiles_at_ref(
    repo: &Path,
    git_ref: &str,
    family_exports: &[String],
    family_files: &[&ComponentFile],
) -> HashMap<String, semver_analyzer_core::types::sd::ComponentSourceProfile> {
    let mut profiles = HashMap::new();

    let family_dir = family_files
        .first()
        .and_then(|f| f.path.rsplit_once('/').map(|(dir, _)| dir.to_string()))
        .unwrap_or_default();

    for component_name in family_exports {
        let file_path = format!("{}/{}.tsx", family_dir, component_name);
        if let Some(source) = read_git_file(repo, git_ref, &file_path) {
            let profile = source_profile::extract_profile(component_name, &file_path, &source);
            profiles.insert(component_name.clone(), profile);
        }
    }

    profiles
}

/// Read family exports from the index file at a given ref.
///
/// Determines the family directory from the file list, reads `index.ts`
/// or `index.tsx`, and parses re-exported component names.
fn read_family_exports_from_dir(
    repo: &Path,
    git_ref: &str,
    family: &str,
    family_files: &[&ComponentFile],
) -> Vec<String> {
    let family_dir = family_files
        .first()
        .and_then(|f| f.path.rsplit_once('/').map(|(dir, _)| dir.to_string()))
        .unwrap_or_default();

    // Try index.ts first, then index.tsx
    for index_name in &["index.ts", "index.tsx"] {
        let index_path = format!("{}/{}", family_dir, index_name);
        if let Some(content) = read_git_file(repo, git_ref, &index_path) {
            let exports = parse_index_exports(&content, family);
            if !exports.is_empty() {
                return exports;
            }
        }
    }

    // Fallback: use component names from the file list
    let mut names: Vec<String> = family_files
        .iter()
        .map(|f| f.component_name.clone())
        .collect();
    if let Some(pos) = names.iter().position(|n| n == family) {
        names.swap(0, pos);
    }
    names
}

/// Parse re-exports from an index.ts file.
///
/// Handles patterns like:
/// - `export { Dropdown } from './Dropdown';`
/// - `export { default as Dropdown } from './Dropdown';`
/// - `export * from './Dropdown';` (derives name from path)
fn parse_index_exports(content: &str, family: &str) -> Vec<String> {
    let mut exports = Vec::new();
    let mut seen = HashSet::new();

    for line in content.lines() {
        let trimmed = line.trim();
        if !trimmed.starts_with("export") {
            continue;
        }

        // `export * from './Dropdown'` → derive component name from path
        if trimmed.starts_with("export *") || trimmed.starts_with("export type *") {
            if let Some(path) = extract_from_path(trimmed) {
                let name = path.strip_prefix("./").unwrap_or(&path).to_string();
                if name.starts_with(|c: char| c.is_ascii_uppercase()) && seen.insert(name.clone()) {
                    exports.push(name);
                }
            }
            continue;
        }

        // `export { X, Y as Z } from './...'`
        if let Some(brace_start) = trimmed.find('{') {
            if let Some(brace_end) = trimmed.find('}') {
                let names_str = &trimmed[brace_start + 1..brace_end];
                for part in names_str.split(',') {
                    let part = part.trim();
                    let name = if let Some((_before, after)) = part.split_once(" as ") {
                        after.trim().to_string()
                    } else {
                        part.to_string()
                    };
                    if name.starts_with(|c: char| c.is_ascii_uppercase())
                        && !name.ends_with("Props")
                        && seen.insert(name.clone())
                    {
                        exports.push(name);
                    }
                }
            }
        }
    }

    // Put the family-matching component first (it's the root)
    if let Some(pos) = exports.iter().position(|n| n == family) {
        exports.swap(0, pos);
    }

    exports
}

/// Extract the `from '...'` path from an export statement.
fn extract_from_path(line: &str) -> Option<String> {
    let from_idx = line.find("from ")?;
    let after_from = &line[from_idx + 5..];
    let quote = after_from.chars().next()?;
    if quote != '\'' && quote != '"' {
        return None;
    }
    let end = after_from[1..].find(quote)?;
    Some(after_from[1..1 + end].to_string())
}

// ── CSS grid nesting enrichment ─────────────────────────────────────────

/// Enrich composition trees with CSS grid layout nesting.
///
/// For each tree, find the matching CSS profile (by block name) and use
/// grid layout signals to move edges from flat (root → all) to nested
/// (root → grid-items, grid-items → non-grid-items).
///
/// Algorithm:
/// 1. Match CSS profile to tree via the BEM block name
/// 2. Identify grid items (elements with `grid-column`) → direct children of root
/// 3. Identify non-grid elements → must be nested inside a grid item
/// 4. Use `variable_child_refs` to determine which grid item contains which non-grid element
/// 5. For unresolved non-grid elements, assign to the nearest flex container
fn enrich_trees_with_css(
    trees: &mut [CompositionTree],
    css_profiles: &HashMap<String, crate::css_profile::CssBlockProfile>,
    react_profiles: &HashMap<String, semver_analyzer_core::types::sd::ComponentSourceProfile>,
) {
    for tree in trees.iter_mut() {
        // Match CSS profile by finding the BEM block used by the root or
        // its children. Try the root's bem_block first, then the dominant
        // block among family members.
        let css_profile = find_matching_css_profile(tree, react_profiles, css_profiles);
        let Some(css_prof) = css_profile else {
            continue;
        };

        debug!(
            family = %tree.root,
            css_block = %css_prof.block,
            elements = css_prof.elements.len(),
            "enriching tree with CSS grid layout"
        );

        // Map family member names → their BEM element name (kebab-case)
        // e.g., "MastheadMain" → "main", "MastheadBrand" → "brand"
        let root_lower = tree.root.to_lowercase();
        let member_to_element: HashMap<&str, String> = tree
            .family_members
            .iter()
            .filter_map(|name| {
                let lower = name.to_lowercase();
                if lower == root_lower {
                    return None; // Root maps to "" (block itself)
                }
                // Strip the root prefix to get the element suffix
                let suffix = lower.strip_prefix(&root_lower)?;
                // Convert to kebab-case for CSS matching
                // "main" → "main", "brand" → "brand"
                // For multi-word: "expandablecontent" → need to match "expandable-content"
                Some((name.as_str(), suffix.to_string()))
            })
            .collect();

        // Reverse map: element → member name
        let element_to_member: HashMap<&str, &str> = member_to_element
            .iter()
            .map(|(member, element)| (element.as_str(), *member))
            .collect();

        // Helper: look up CSS element info with kebab fallback
        let lookup_css_el = |element: &str| -> Option<&crate::css_profile::CssElementInfo> {
            css_prof.elements.get(element).or_else(|| {
                css_prof
                    .elements
                    .iter()
                    .find(|(k, _)| k.replace('-', "") == element)
                    .map(|(_, v)| v)
            })
        };

        // Classify members into three categories:
        //
        // 1. stable_grid: has grid-column that NEVER reverts → direct child of root
        // 2. promoted_grid: has grid-column but reverts in some mode → inside mode-switcher
        // 3. non_grid: no grid-column at all → inside some container
        let mut stable_grid: HashSet<&str> = HashSet::new();
        let mut promoted_grid: HashSet<&str> = HashSet::new();
        let mut non_grid: HashSet<&str> = HashSet::new();

        for (member, element) in &member_to_element {
            if let Some(info) = lookup_css_el(element) {
                if info.has_grid_column {
                    if info.grid_column_reverts {
                        promoted_grid.insert(member);
                    } else {
                        stable_grid.insert(member);
                    }
                } else {
                    non_grid.insert(member);
                }
            }
        }

        if stable_grid.is_empty() && promoted_grid.is_empty() && non_grid.is_empty() {
            continue;
        }

        // Find the mode-switching container (display: contents ↔ flex)
        let mode_switcher: Option<&str> = member_to_element
            .iter()
            .find(|(_, element)| {
                lookup_css_el(element).is_some_and(|info| {
                    info.is_mode_switcher
                        || (info.display_values.contains("var") && info.has_grid_column)
                })
            })
            .map(|(member, _)| *member);

        debug!(
            family = %tree.root,
            stable_grid = ?stable_grid,
            promoted_grid = ?promoted_grid,
            non_grid = ?non_grid,
            mode_switcher = ?mode_switcher,
            "CSS grid classification"
        );

        // Build a set of sibling pairs from CSS `+` / `~` selectors.
        // If two elements have a sibling relationship in CSS, they must NOT
        // be nested — the flex-container heuristic must not create a
        // parent→child edge between them.
        let css_siblings: HashSet<(String, String)> = css_prof
            .sibling_relationships
            .iter()
            .flat_map(|(a, b)| {
                let a_norm = a.replace('-', "");
                let b_norm = b.replace('-', "");
                vec![(a_norm.clone(), b_norm.clone()), (b_norm, a_norm)]
            })
            .collect();

        // Build a set of elements that :has() selectors prove are direct
        // children of the block root (parent == ""). When :has(> .child)
        // appears on the block root, the child is root-level and must NOT
        // be nested inside a sibling element.
        let root_level_children: HashSet<String> = css_prof
            .has_containment
            .iter()
            .filter(|(parent, _)| parent.is_empty())
            .map(|(_, child)| child.replace('-', ""))
            .collect();

        // Helper: check if two elements are CSS siblings
        let are_css_siblings = |parent_member: &str, child_member: &str| -> bool {
            let parent_el = member_to_element.get(parent_member);
            let child_el = member_to_element.get(child_member);
            if let (Some(p), Some(c)) = (parent_el, child_el) {
                css_siblings.contains(&(p.clone(), c.clone()))
            } else {
                false
            }
        };

        // Helper: check if a member is proven to be a root-level child via :has()
        let is_root_level_child = |member: &str| -> bool {
            member_to_element
                .get(member)
                .is_some_and(|el| root_level_children.contains(el))
        };

        // Move promoted_grid items under the mode-switcher (skip self)
        if let Some(switcher) = mode_switcher {
            for &member in &promoted_grid {
                if member == switcher {
                    continue; // Don't move the mode-switcher under itself
                }
                tree.edges
                    .retain(|e| !(e.parent == tree.root && e.child == member));
                if !tree
                    .edges
                    .iter()
                    .any(|e| e.parent == switcher && e.child == member)
                {
                    tree.edges.push(semver_analyzer_core::types::sd::CompositionEdge {
                        parent: switcher.to_string(),
                        child: member.to_string(),
                        relationship: semver_analyzer_core::types::sd::ChildRelationship::DirectChild,
                        required: false,
                        bem_evidence: Some(format!(
                            "CSS grid nesting: {} grid-column reverts in some mode → inside {} (mode-switcher)",
                            member, switcher
                        )),
                    });
                }
            }
        }

        // Move non-grid items using variable_child_refs from the mode-switcher
        if let Some(switcher) = mode_switcher {
            let switcher_element = &member_to_element[switcher];
            if let Some(info) = lookup_css_el(switcher_element) {
                for child_ref in &info.variable_child_refs {
                    let child_member = element_to_member.get(child_ref.as_str()).or_else(|| {
                        let no_hyphen = child_ref.replace('-', "");
                        element_to_member
                            .iter()
                            .find(|(k, _)| k.replace('-', "") == no_hyphen)
                            .map(|(_, v)| v)
                    });

                    if let Some(child) = child_member {
                        // Only move non-grid items via var refs
                        // (stable_grid items stay as direct children of root)
                        if !non_grid.contains(child) {
                            continue;
                        }
                        tree.edges
                            .retain(|e| !(e.parent == tree.root && e.child == *child));
                        if !tree
                            .edges
                            .iter()
                            .any(|e| e.parent == switcher && e.child == *child)
                        {
                            tree.edges.push(semver_analyzer_core::types::sd::CompositionEdge {
                                parent: switcher.to_string(),
                                child: child.to_string(),
                                relationship: semver_analyzer_core::types::sd::ChildRelationship::DirectChild,
                                required: false,
                                bem_evidence: Some(format!(
                                    "CSS grid nesting: {} (no grid-column) → {} (var ref --{}__{}--{})",
                                    child, switcher, css_prof.block, switcher_element, child_ref
                                )),
                            });
                        }
                    }
                }
            }
        }

        // For remaining non-grid items not yet assigned, find their container.
        // A non-grid item must be inside SOME flex/grid container that IS a
        // grid item or promoted_grid item. Among the containers, pick the one
        // that is itself a flex container (display: flex).
        //
        // GUARD: Only run this heuristic when there IS a grid context (at
        // least one element has grid-column). Without grid signals, the
        // layout is not grid-based and BEM siblings should stay as direct
        // children of root. The flex-container heuristic was designed for
        // Masthead-style CSS grid layouts; applying it to pure-flex families
        // like Card, EmptyState, or Toolbar incorrectly nests siblings.
        if stable_grid.is_empty() && promoted_grid.is_empty() {
            debug!(
                family = %tree.root,
                non_grid = ?non_grid,
                "Skipping flex-container fallback — no grid context"
            );
            // Fall through to CSS descendant nesting below
        } else {
            let unassigned: Vec<&str> = non_grid
                .iter()
                .filter(|member| {
                    !tree
                        .edges
                        .iter()
                        .any(|e| e.child == **member && e.parent != tree.root)
                })
                .copied()
                .collect();

            if !unassigned.is_empty() {
                // For each unassigned non-grid item, find which flex container
                // it belongs to. Prefer the promoted_grid container (e.g., brand
                // is a flex container inside main) over stable_grid containers
                // (e.g., content is a flex container at root level).
                //
                // Heuristic: a non-grid item likely belongs in a flex container
                // whose BEM element name is a prefix of the non-grid item's
                // element name (e.g., "logo" could go in "brand" or "content",
                // but if we can't determine, pick the most specific container).
                let all_flex_containers: Vec<(&str, &str)> = member_to_element
                    .iter()
                    .filter(|(member, element)| {
                        **member != tree.root
                            && (mode_switcher != Some(**member))
                            && lookup_css_el(element)
                                .is_some_and(|info| info.display_values.contains("flex"))
                    })
                    .map(|(member, element)| (*member, element.as_str()))
                    .collect();

                for &member in &unassigned {
                    let member_element = &member_to_element[member];

                    // Try to find a container whose variable_child_refs include this element
                    let via_var_ref = all_flex_containers.iter().find(|(_, el)| {
                        lookup_css_el(el).is_some_and(|info| {
                            info.variable_child_refs.contains(member_element.as_str())
                        })
                    });

                    let container = if let Some((c, _)) = via_var_ref {
                        Some(*c)
                    } else if all_flex_containers.len() == 1 {
                        Some(all_flex_containers[0].0)
                    } else {
                        // Multiple flex containers — use sizing heuristic:
                        // A sized non-grid element (width/max-height) goes in
                        // the rigid flex container (flex-shrink: 0), not in
                        // the wrapping one (flex-wrap: wrap).
                        let child_has_sizing =
                            lookup_css_el(member_element).is_some_and(|info| info.has_sizing);

                        if child_has_sizing {
                            // Find the rigid (non-wrapping) flex container
                            all_flex_containers
                                .iter()
                                .find(|(_, el)| {
                                    lookup_css_el(el).is_some_and(|info| {
                                        info.flex_shrink_zero && !info.flex_wrap
                                    })
                                })
                                .map(|(c, _)| *c)
                        } else {
                            // Non-sized element → prefer the wrapping container
                            all_flex_containers
                                .iter()
                                .find(|(_, el)| {
                                    lookup_css_el(el).is_some_and(|info| info.flex_wrap)
                                })
                                .map(|(c, _)| *c)
                        }
                    };

                    if let Some(container) = container {
                        // Guard: skip self-referential edges
                        if container == member {
                            continue;
                        }
                        // Guard: skip if CSS proves they are siblings
                        if are_css_siblings(container, member) {
                            debug!(
                                family = %tree.root,
                                parent = %container,
                                child = %member,
                                "CSS siblings — skipping flex container nesting"
                            );
                            continue;
                        }
                        // Guard: skip if :has() proves child is root-level
                        if is_root_level_child(member) {
                            debug!(
                                family = %tree.root,
                                parent = %container,
                                child = %member,
                                "CSS :has() proves root-level child — skipping flex container nesting"
                            );
                            continue;
                        }
                        tree.edges
                            .retain(|e| !(e.parent == tree.root && e.child == member));
                        if !tree
                            .edges
                            .iter()
                            .any(|e| e.parent == container && e.child == member)
                        {
                            tree.edges
                                .push(semver_analyzer_core::types::sd::CompositionEdge {
                                parent: container.to_string(),
                                child: member.to_string(),
                                relationship:
                                    semver_analyzer_core::types::sd::ChildRelationship::DirectChild,
                                required: false,
                                bem_evidence: Some(format!(
                                "CSS grid nesting: {} (no grid-column) inside {} (flex container)",
                                member, container
                            )),
                            });
                        }
                    }
                }
            }
        } // end else: has grid context

        // ── CSS descendant nesting ──────────────────────────────────────
        //
        // Use `descendant_nesting` from the CSS profile to discover
        // parent→child relationships between BEM elements that aren't
        // captured by grid analysis, React context, or DOM nesting.
        //
        // CSS selectors like `.pf-v6-c-menu__content > .pf-v6-c-menu__list`
        // prove that `content` wraps `list`. If both map to family members
        // (MenuContent and MenuList), create an intermediate edge and
        // suppress the root edge.
        for (css_parent, css_child) in &css_prof.descendant_nesting {
            // Normalize: CSS uses kebab-case, member_to_element uses lowercase
            let parent_normalized = css_parent.replace('-', "");
            let child_normalized = css_child.replace('-', "");

            let parent_member = element_to_member
                .get(css_parent.as_str())
                .or_else(|| {
                    element_to_member
                        .iter()
                        .find(|(k, _)| k.replace('-', "") == parent_normalized)
                        .map(|(_, v)| v)
                })
                .copied();

            let child_member = element_to_member
                .get(css_child.as_str())
                .or_else(|| {
                    element_to_member
                        .iter()
                        .find(|(k, _)| k.replace('-', "") == child_normalized)
                        .map(|(_, v)| v)
                })
                .copied();

            if let (Some(parent), Some(child)) = (parent_member, child_member) {
                // Skip self-referential edges
                if parent == child {
                    continue;
                }
                // Skip if this edge already exists
                if tree
                    .edges
                    .iter()
                    .any(|e| e.parent == parent && e.child == child)
                {
                    continue;
                }

                debug!(
                    family = %tree.root,
                    parent = %parent,
                    child = %child,
                    css_parent = %css_parent,
                    css_child = %css_child,
                    "CSS descendant nesting: adding intermediate edge"
                );

                // Remove any root→child edge that this intermediate replaces
                tree.edges
                    .retain(|e| !(e.parent == tree.root && e.child == child));

                tree.edges
                    .push(semver_analyzer_core::types::sd::CompositionEdge {
                        parent: parent.to_string(),
                        child: child.to_string(),
                        relationship:
                            semver_analyzer_core::types::sd::ChildRelationship::DirectChild,
                        required: false,
                        bem_evidence: Some(format!(
                            "CSS descendant nesting: .{}__{}  .{}__{}",
                            css_prof.block, css_parent, css_prof.block, css_child
                        )),
                    });
            }
        }
    }
}

/// Find the CSS profile matching a composition tree's component family.
fn find_matching_css_profile<'a>(
    tree: &CompositionTree,
    react_profiles: &HashMap<String, semver_analyzer_core::types::sd::ComponentSourceProfile>,
    css_profiles: &'a HashMap<String, crate::css_profile::CssBlockProfile>,
) -> Option<&'a crate::css_profile::CssBlockProfile> {
    // Try matching by the root component's bem_block
    if let Some(root_profile) = react_profiles.get(&tree.root) {
        if let Some(ref block) = root_profile.bem_block {
            if let Some(css_prof) = css_profiles.get(block) {
                return Some(css_prof);
            }
        }
    }

    // Try matching by the dominant bem_block among family members
    let mut block_counts: HashMap<&str, usize> = HashMap::new();
    for member in &tree.family_members {
        if let Some(profile) = react_profiles.get(member) {
            if let Some(ref block) = profile.bem_block {
                *block_counts.entry(block.as_str()).or_default() += 1;
            }
        }
    }

    let dominant = block_counts
        .into_iter()
        .max_by_key(|(_, count)| *count)
        .map(|(block, _)| block)?;

    css_profiles.get(dominant)
}

// ── Internal node collapsing ────────────────────────────────────────────

/// Collapse non-exported nodes from a composition tree.
///
/// Internal components (like ModalBox, ModalContent) form the rendering
/// chain between exported parent and exported children, but consumers
/// never see them. This function:
///
/// 1. Finds edges where an internal node is an intermediary
///    (e.g., Modal → ModalContent (internal) → ModalBox (internal))
/// 2. Removes the internal nodes from `family_members`
/// 3. For each internal node, transfers its child edges to its parent(s)
///    (e.g., if A → Internal → B, creates A → B)
/// 4. Removes edges that reference internal nodes
fn collapse_internal_nodes(tree: &mut CompositionTree, exports: &HashSet<&str>) {
    // Find internal (non-exported) nodes
    let internal_nodes: HashSet<String> = tree
        .family_members
        .iter()
        .filter(|name| !exports.contains(name.as_str()))
        .cloned()
        .collect();

    if internal_nodes.is_empty() {
        return;
    }

    // Build adjacency: parent → [children]
    let mut parent_to_children: HashMap<String, Vec<String>> = HashMap::new();
    for edge in &tree.edges {
        parent_to_children
            .entry(edge.parent.clone())
            .or_default()
            .push(edge.child.clone());
    }

    // Iteratively collapse internal nodes. Each pass resolves one level
    // of internal chain (e.g., first pass: ModalBox → ModalBody becomes
    // ModalContent → ModalBody; second pass: ModalContent → ModalBody
    // becomes Modal → ModalBody).
    //
    // We iterate until no more edges reference internal nodes.
    loop {
        let mut new_edges = Vec::new();
        let mut made_progress = false;

        for internal in &internal_nodes {
            // Find parents of this internal node (may include other internals)
            let parents: Vec<String> = tree
                .edges
                .iter()
                .filter(|e| e.child == *internal)
                .map(|e| e.parent.clone())
                .collect();

            // Find children of this internal node
            let children: Vec<(String, semver_analyzer_core::types::sd::CompositionEdge)> = tree
                .edges
                .iter()
                .filter(|e| e.parent == *internal)
                .map(|e| (e.child.clone(), e.clone()))
                .collect();

            if !parents.is_empty() && !children.is_empty() {
                made_progress = true;
            }

            for parent in &parents {
                for (child, original_edge) in &children {
                    if parent == child {
                        continue;
                    }
                    new_edges.push(semver_analyzer_core::types::sd::CompositionEdge {
                        parent: parent.clone(),
                        child: child.clone(),
                        relationship: original_edge.relationship.clone(),
                        required: original_edge.required,
                        bem_evidence: Some(format!(
                            "Collapsed through internal {}: {}{}{}",
                            internal, parent, internal, child
                        )),
                    });
                }
            }
        }

        // Remove edges that have an internal node as parent OR child
        tree.edges
            .retain(|e| !internal_nodes.contains(&e.parent) && !internal_nodes.contains(&e.child));

        // Add transitive edges (some may still reference internals — next iteration handles)
        tree.edges.extend(new_edges);

        if !made_progress {
            break;
        }

        // Check if any edges still reference internal nodes
        let still_has_internal = tree
            .edges
            .iter()
            .any(|e| internal_nodes.contains(&e.parent) || internal_nodes.contains(&e.child));
        if !still_has_internal {
            break;
        }
    }

    // Deduplicate edges
    let mut seen = HashSet::new();
    tree.edges
        .retain(|e| seen.insert((e.parent.clone(), e.child.clone())));

    // Remove internal nodes from family_members
    tree.family_members
        .retain(|name| !internal_nodes.contains(name));
}

// ── Delegation projection ───────────────────────────────────────────────

/// Project edges from delegate family trees onto wrapper family trees.
///
/// A wrapper family (e.g., Dropdown) wraps another family (e.g., Menu).
/// Each wrapper component extends the corresponding delegate's Props:
///   DropdownProps extends MenuProps
///   DropdownListProps extends MenuListProps
///   DropdownItemProps extends MenuItemProps
///
/// If Menu's tree has edges like Menu → MenuList → MenuItem, this function
/// projects them as Dropdown → DropdownList → DropdownItem.
fn project_delegate_trees(
    trees: &mut [CompositionTree],
    all_profiles: &HashMap<String, semver_analyzer_core::types::sd::ComponentSourceProfile>,
    all_trees: &[CompositionTree],
) {
    // Build a lookup: component name → which tree it belongs to
    let mut component_to_tree: HashMap<&str, usize> = HashMap::new();
    for (i, tree) in all_trees.iter().enumerate() {
        for member in &tree.family_members {
            component_to_tree.insert(member.as_str(), i);
        }
    }

    for tree in trees.iter_mut() {
        // Skip trees that already have meaningful edges
        // (more than just internal rendering edges)
        let non_internal_edges = tree
            .edges
            .iter()
            .filter(|e| {
                e.relationship != semver_analyzer_core::types::sd::ChildRelationship::Internal
            })
            .count();
        if non_internal_edges > 0 {
            continue;
        }

        // Build the wrapping map: wrapper_component → delegate_component
        // by matching `extends_props` to components in other families.
        //
        // e.g., DropdownList.extends_props = ["MenuListProps"]
        //       → strip "Props" suffix → "MenuList"
        //       → if "MenuList" exists in another family's tree → map DropdownList → MenuList
        let mut wrapper_to_delegate: HashMap<String, String> = HashMap::new();
        let mut delegate_tree_idx: Option<usize> = None;

        for member in &tree.family_members {
            let Some(profile) = all_profiles.get(member) else {
                continue;
            };

            for ext in &profile.extends_props {
                // Strip "Props" suffix to get the component name
                let delegate_name = ext.strip_suffix("Props").unwrap_or(ext).to_string();

                if let Some(&tree_idx) = component_to_tree.get(delegate_name.as_str()) {
                    // Skip self-family references
                    if tree.family_members.contains(&delegate_name) {
                        continue;
                    }
                    wrapper_to_delegate.insert(member.clone(), delegate_name);
                    delegate_tree_idx = Some(tree_idx);
                }
            }
        }

        if wrapper_to_delegate.is_empty() {
            continue;
        }

        let Some(dt_idx) = delegate_tree_idx else {
            continue;
        };
        let delegate_tree = &all_trees[dt_idx];

        // Build reverse map: delegate → wrapper
        let mut delegate_to_wrapper: HashMap<&str, &str> = HashMap::new();
        for (wrapper, delegate) in &wrapper_to_delegate {
            delegate_to_wrapper.insert(delegate.as_str(), wrapper.as_str());
        }

        debug!(
            family = %tree.root,
            delegate_family = %delegate_tree.root,
            mappings = ?wrapper_to_delegate,
            "projecting delegate tree edges"
        );

        // Project edges from the delegate tree
        for edge in &delegate_tree.edges {
            let Some(wrapper_parent) = delegate_to_wrapper.get(edge.parent.as_str()) else {
                continue;
            };
            let Some(wrapper_child) = delegate_to_wrapper.get(edge.child.as_str()) else {
                continue;
            };

            // Check we don't already have this edge
            let already_exists = tree
                .edges
                .iter()
                .any(|e| e.parent == *wrapper_parent && e.child == *wrapper_child);
            if already_exists {
                continue;
            }

            tree.edges
                .push(semver_analyzer_core::types::sd::CompositionEdge {
                    parent: wrapper_parent.to_string(),
                    child: wrapper_child.to_string(),
                    relationship: edge.relationship.clone(),
                    required: edge.required,
                    bem_evidence: Some(format!(
                        "Projected from {} tree: {} extends {}, {} extends {}",
                        delegate_tree.root, wrapper_parent, edge.parent, wrapper_child, edge.child,
                    )),
                });
        }
    }
}

// ── Composition tree diffing ────────────────────────────────────────────

/// Diff old and new composition trees to produce `CompositionChange` entries.
fn diff_composition_trees(
    family: &str,
    old_tree: Option<&CompositionTree>,
    new_tree: &CompositionTree,
    old_exports: &[String],
    new_exports: &[String],
) -> Vec<CompositionChange> {
    let mut changes = Vec::new();
    let old_exports_set: HashSet<&str> = old_exports.iter().map(|s| s.as_str()).collect();
    let new_exports_set: HashSet<&str> = new_exports.iter().map(|s| s.as_str()).collect();

    // Detect added/removed family members
    for name in &new_exports_set {
        if !old_exports_set.contains(name) {
            changes.push(CompositionChange {
                family: family.to_string(),
                change_type: CompositionChangeType::FamilyMemberAdded {
                    member: name.to_string(),
                },
                description: format!("{} is a new component in the {} family", name, family),
                before_pattern: None,
                after_pattern: None,
            });
        }
    }
    for name in &old_exports_set {
        if !new_exports_set.contains(name) {
            changes.push(CompositionChange {
                family: family.to_string(),
                change_type: CompositionChangeType::FamilyMemberRemoved {
                    member: name.to_string(),
                },
                description: format!("{} was removed from the {} family", name, family),
                before_pattern: None,
                after_pattern: None,
            });
        }
    }

    // Build edge maps for easy comparison
    let old_edges = old_tree.map(|t| build_edge_map(t)).unwrap_or_default();
    let new_edges = build_edge_map(new_tree);

    // Find new required children (edges in new but not in old)
    for ((parent, child), edge) in &new_edges {
        if !old_edges.contains_key(&(parent.clone(), child.clone())) {
            changes.push(CompositionChange {
                family: family.to_string(),
                change_type: CompositionChangeType::NewRequiredChild {
                    parent: parent.clone(),
                    new_child: child.clone(),
                    wraps: vec![],
                },
                description: format!(
                    "{} now expects {} as a child component{}",
                    parent,
                    child,
                    if edge.required { " (required)" } else { "" }
                ),
                before_pattern: None,
                after_pattern: Some(format!("<{}>\n  <{} />\n</{}>", parent, child, parent)),
            });
        }
    }

    changes
}

/// Build a lookup map from (parent, child) to the edge for a composition tree.
fn build_edge_map(
    tree: &CompositionTree,
) -> HashMap<(String, String), &semver_analyzer_core::types::sd::CompositionEdge> {
    tree.edges
        .iter()
        .map(|e| ((e.parent.clone(), e.child.clone()), e))
        .collect()
}

// ── Conformance check generation ────────────────────────────────────────

/// Generate conformance checks from a composition tree.
///
/// Each edge in the tree becomes a conformance check that validates
/// consumer JSX structure.
fn generate_conformance_checks(
    family: &str,
    tree: &CompositionTree,
    profiles: &HashMap<String, ComponentSourceProfile>,
) -> Vec<ConformanceCheck> {
    let mut checks = Vec::new();

    // Build parent lookup: child → [parent]
    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 edges (not consumer-facing)
        if edge.relationship == semver_analyzer_core::types::sd::ChildRelationship::Internal {
            continue;
        }

        // MissingChild: parent should contain this required child
        if edge.required {
            checks.push(ConformanceCheck {
                family: family.to_string(),
                check_type: ConformanceCheckType::MissingChild {
                    parent: edge.parent.clone(),
                    expected_child: edge.child.clone(),
                },
                description: format!(
                    "{} should contain a {} child component",
                    edge.parent, edge.child
                ),
                correct_example: Some(format!(
                    "<{}>\n  <{} />\n</{}>",
                    edge.parent, edge.child, edge.parent
                )),
            });
        }

        // InvalidDirectChild: child should not be a direct child of grandparent
        if let Some(grandparents) = child_to_parents.get(edge.parent.as_str()) {
            for grandparent in grandparents {
                checks.push(ConformanceCheck {
                    family: family.to_string(),
                    check_type: ConformanceCheckType::InvalidDirectChild {
                        parent: grandparent.to_string(),
                        child: edge.child.clone(),
                        expected_parent: edge.parent.clone(),
                    },
                    description: format!(
                        "{} should be inside {}, not directly inside {}",
                        edge.child, edge.parent, grandparent
                    ),
                    correct_example: Some(format!(
                        "<{}>\n  <{}>\n    <{} />\n  </{}>\n</{}>",
                        grandparent, edge.parent, edge.child, edge.parent, grandparent
                    )),
                });
            }
        }
    }

    // ExclusiveWrapper: detect parent components where all direct children
    // must be one of the family's BEM element children.
    //
    // Heuristic: find all BEM element direct children of the root. If at
    // least one is a generic wrapper (has_children_prop, renders div/span),
    // then the root uses a wrapper pattern — ALL BEM direct children form
    // the allowed set, and any non-family component placed directly inside
    // the root is a violation.
    //
    // Examples:
    //   InputGroup  → allowed: {InputGroupItem, InputGroupText}
    //   ActionList  → allowed: {ActionListGroup}
    //   Card        → NOT detected (CardHeader/CardBody/CardFooter are content
    //                 components, none is a generic div/span wrapper)
    let root = &tree.root;
    let direct_child_edges: Vec<_> = tree
        .edges
        .iter()
        .filter(|e| {
            e.parent == *root
                && e.relationship == semver_analyzer_core::types::sd::ChildRelationship::DirectChild
        })
        .collect();

    // Find all BEM element children of the root
    let bem_children: Vec<&str> = direct_child_edges
        .iter()
        .filter(|e| {
            e.bem_evidence
                .as_ref()
                .is_some_and(|ev| ev.contains("BEM element"))
        })
        .map(|e| e.child.as_str())
        .collect();

    // Check if at least one BEM child is a generic wrapper (div/span with children)
    let has_generic_wrapper = bem_children.iter().any(|name| {
        profiles.get(*name).is_some_and(|p| {
            p.has_children_prop
                && p.children_slot_path
                    .first()
                    .is_some_and(|tag| matches!(tag.as_str(), "div" | "span"))
        })
    });

    if has_generic_wrapper && !bem_children.is_empty() {
        // The allowed set starts with all BEM direct children
        let mut allowed: Vec<String> = bem_children.iter().map(|s| s.to_string()).collect();

        // Also add family members that self-wrap in one of the BEM children
        // (internal edges, e.g., InputGroupText internally renders InputGroupItem)
        for edge in &tree.edges {
            if edge.relationship == semver_analyzer_core::types::sd::ChildRelationship::Internal
                && bem_children.contains(&edge.child.as_str())
                && !allowed.contains(&edge.parent)
            {
                allowed.push(edge.parent.clone());
            }
        }

        // Find the primary wrapper (the generic one) for the example
        let primary_wrapper = bem_children
            .iter()
            .find(|name| {
                profiles.get(**name).is_some_and(|p| {
                    p.has_children_prop
                        && p.children_slot_path
                            .first()
                            .is_some_and(|tag| matches!(tag.as_str(), "div" | "span"))
                })
            })
            .unwrap_or(&bem_children[0]);

        let allowed_list = allowed.join(", ");
        checks.push(ConformanceCheck {
            family: family.to_string(),
            check_type: ConformanceCheckType::ExclusiveWrapper {
                parent: root.clone(),
                allowed_children: allowed.clone(),
            },
            description: format!(
                "All children of {} must be wrapped in {}",
                root, allowed_list
            ),
            correct_example: Some(format!(
                "<{}>\n  <{}>\n    {{/* your content */}}\n  </{}>\n</{}>",
                root, primary_wrapper, primary_wrapper, root
            )),
        });
    }

    checks
}

// ── Package resolution ──────────────────────────────────────────────────

/// Resolve npm package name from a file path.
///
/// "packages/react-core/src/components/Modal/Modal.tsx" → "@patternfly/react-core"
/// "packages/react-core/src/deprecated/components/Modal/Modal.tsx" → "@patternfly/react-core/deprecated"
fn resolve_component_package(file_path: &str) -> Option<String> {
    let parts: Vec<&str> = file_path.split('/').collect();
    let pkg_idx = parts.iter().position(|&p| p == "packages")?;
    let pkg_dir = parts.get(pkg_idx + 1)?;
    let mut pkg_name = format!("@patternfly/{}", pkg_dir);

    if parts.contains(&"deprecated") {
        pkg_name.push_str("/deprecated");
    } else if parts.contains(&"next") {
        pkg_name.push_str("/next");
    }

    Some(pkg_name)
}

// ── Git helpers ─────────────────────────────────────────────────────────

/// Read a file from a git ref.
fn read_git_file(repo: &Path, git_ref: &str, file_path: &str) -> Option<String> {
    let output = Command::new("git")
        .args(["show", &format!("{}:{}", git_ref, file_path)])
        .current_dir(repo)
        .output()
        .ok()?;

    if output.status.success() {
        Some(String::from_utf8_lossy(&output.stdout).to_string())
    } else {
        None
    }
}

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

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

    #[test]
    fn test_extract_component_name() {
        assert_eq!(
            extract_component_name("packages/react-core/src/components/Dropdown/Dropdown.tsx"),
            Some("Dropdown".to_string())
        );
        assert_eq!(
            extract_component_name("packages/react-core/src/components/Modal/ModalHeader.tsx"),
            Some("ModalHeader".to_string())
        );
        assert_eq!(
            extract_component_name("packages/react-core/src/helpers/util.tsx"),
            None
        );
        assert_eq!(
            extract_component_name("packages/react-core/src/components/Dropdown/Dropdown.ts"),
            None
        );
    }

    #[test]
    fn test_extract_family_from_path() {
        assert_eq!(
            extract_family_from_path("packages/react-core/src/components/Dropdown/Dropdown.tsx"),
            Some("Dropdown".to_string())
        );
        assert_eq!(
            extract_family_from_path("packages/react-core/src/components/Modal/ModalHeader.tsx"),
            Some("Modal".to_string())
        );
        assert_eq!(extract_family_from_path("src/helpers/util.tsx"), None);
    }

    #[test]
    fn test_should_exclude_from_sd() {
        assert!(should_exclude_from_sd(
            "src/components/Dropdown/Dropdown.test.tsx"
        ));
        assert!(should_exclude_from_sd(
            "src/components/Dropdown/Dropdown.spec.tsx"
        ));
        assert!(should_exclude_from_sd(
            "src/components/Dropdown/__tests__/Dropdown.tsx"
        ));
        assert!(should_exclude_from_sd("src/components/Dropdown/index.tsx"));
        assert!(should_exclude_from_sd("dist/components/Dropdown.tsx"));
        assert!(should_exclude_from_sd(
            "src/components/Dropdown/examples/Basic.tsx"
        ));
        assert!(!should_exclude_from_sd(
            "src/components/Dropdown/Dropdown.tsx"
        ));
    }

    #[test]
    fn test_parse_index_exports() {
        let content = r#"
export { Dropdown } from './Dropdown';
export { DropdownItem } from './DropdownItem';
export { DropdownList } from './DropdownList';
export type { DropdownProps } from './Dropdown';
"#;
        let exports = parse_index_exports(content, "Dropdown");
        assert_eq!(exports, vec!["Dropdown", "DropdownItem", "DropdownList"]);
    }

    #[test]
    fn test_parse_index_exports_star() {
        let content = r#"
export * from './Modal';
export * from './ModalHeader';
export * from './ModalBody';
export * from './ModalFooter';
"#;
        let exports = parse_index_exports(content, "Modal");
        assert_eq!(
            exports,
            vec!["Modal", "ModalHeader", "ModalBody", "ModalFooter"]
        );
    }

    #[test]
    fn test_parse_index_exports_default_as() {
        let content = r#"
export { default as Dropdown } from './Dropdown';
export { default as DropdownItem } from './DropdownItem';
"#;
        let exports = parse_index_exports(content, "Dropdown");
        assert_eq!(exports, vec!["Dropdown", "DropdownItem"]);
    }

    #[test]
    fn test_parse_index_exports_family_first() {
        let content = r#"
export { DropdownItem } from './DropdownItem';
export { Dropdown } from './Dropdown';
export { DropdownList } from './DropdownList';
"#;
        let exports = parse_index_exports(content, "Dropdown");
        assert_eq!(exports[0], "Dropdown");
        assert!(exports.contains(&"DropdownItem".to_string()));
        assert!(exports.contains(&"DropdownList".to_string()));
    }

    #[test]
    fn test_extract_from_path() {
        assert_eq!(
            extract_from_path("export { Dropdown } from './Dropdown';"),
            Some("./Dropdown".to_string())
        );
        assert_eq!(
            extract_from_path("export * from \"./Modal\";"),
            Some("./Modal".to_string())
        );
        assert_eq!(extract_from_path("export { Dropdown };"), None);
    }

    #[test]
    fn test_generate_conformance_checks() {
        use semver_analyzer_core::types::sd::{ChildRelationship, CompositionEdge};

        let tree = CompositionTree {
            root: "Dropdown".to_string(),
            family_members: vec![
                "Dropdown".to_string(),
                "DropdownList".to_string(),
                "DropdownItem".to_string(),
            ],
            edges: vec![
                CompositionEdge {
                    parent: "Dropdown".to_string(),
                    child: "DropdownList".to_string(),
                    relationship: ChildRelationship::DirectChild,
                    required: true,
                    bem_evidence: None,
                },
                CompositionEdge {
                    parent: "DropdownList".to_string(),
                    child: "DropdownItem".to_string(),
                    relationship: ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: None,
                },
            ],
        };

        let checks = generate_conformance_checks("Dropdown", &tree, &HashMap::new());

        assert!(checks.iter().any(|c| matches!(
            &c.check_type,
            ConformanceCheckType::MissingChild {
                parent,
                expected_child
            } if parent == "Dropdown" && expected_child == "DropdownList"
        )));

        assert!(checks.iter().any(|c| matches!(
            &c.check_type,
            ConformanceCheckType::InvalidDirectChild {
                parent,
                child,
                expected_parent
            } if parent == "Dropdown" && child == "DropdownItem" && expected_parent == "DropdownList"
        )));
    }

    #[test]
    fn test_parse_component_file_list() {
        let output = "packages/react-core/src/components/Modal/Modal.tsx\n\
                       packages/react-core/src/components/Modal/ModalHeader.tsx\n\
                       packages/react-core/src/helpers/util.tsx\n\
                       packages/react-core/src/components/Modal/Modal.test.tsx\n\
                       packages/react-core/src/components/Modal/index.tsx\n";

        let files = parse_component_file_list(output);
        assert_eq!(files.len(), 2); // Only Modal.tsx and ModalHeader.tsx
        assert_eq!(files[0].component_name, "Modal");
        assert_eq!(files[1].component_name, "ModalHeader");
        assert_eq!(files[0].family, Some("Modal".to_string()));
    }

    // ── CSS enrichment guard tests ──────────────────────────────────

    use crate::css_profile::{CssBlockProfile, CssElementInfo};
    use semver_analyzer_core::types::sd::{CompositionEdge, CompositionTree};
    use std::collections::BTreeMap;

    #[allow(dead_code)]
    fn make_css_element(display: &str, is_flex: bool) -> CssElementInfo {
        let mut info = CssElementInfo::default();
        info.display_values.insert(display.to_string());
        if is_flex {
            info.display_values.insert("flex".to_string());
        }
        info
    }

    fn make_source_profile(name: &str) -> ComponentSourceProfile {
        ComponentSourceProfile {
            name: name.to_string(),
            ..Default::default()
        }
    }

    fn make_source_profile_with_block(name: &str, block: &str) -> ComponentSourceProfile {
        ComponentSourceProfile {
            name: name.to_string(),
            bem_block: Some(block.to_string()),
            ..Default::default()
        }
    }

    /// Real PatternFly case: PageSidebar has a self-referential edge
    /// (PageSidebar → PageSidebar) from the CSS enrichment because
    /// the sidebar element is a flex container and also appears as a
    /// non-grid element. The self-referential guard must block this.
    #[test]
    fn test_self_referential_edge_blocked_page_sidebar() {
        // Simulate the Page family: PageSidebar and PageSidebarBody
        let mut trees = vec![CompositionTree {
            root: "Page".into(),
            family_members: vec![
                "Page".into(),
                "PageSidebar".into(),
                "PageSidebarBody".into(),
            ],
            edges: vec![
                CompositionEdge {
                    parent: "Page".into(),
                    child: "PageSidebar".into(),
                    relationship: semver_analyzer_core::types::sd::ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: Some("BEM element".into()),
                },
                CompositionEdge {
                    parent: "Page".into(),
                    child: "PageSidebarBody".into(),
                    relationship: semver_analyzer_core::types::sd::ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: Some("BEM element".into()),
                },
            ],
        }];

        // CSS profile: sidebar is a flex container, sidebar-body has no grid-column
        let mut elements = BTreeMap::new();
        elements.insert("sidebar".to_string(), {
            let mut info = CssElementInfo::default();
            info.display_values.insert("flex".to_string());
            info
        });
        elements.insert("sidebar-body".to_string(), CssElementInfo::default());

        let css_profile = CssBlockProfile {
            block: "page".into(),
            elements,
            has_containment: vec![],
            descendant_nesting: vec![],
            sibling_relationships: vec![],
        };

        let mut css_profiles = HashMap::new();
        css_profiles.insert("page".to_string(), css_profile);

        let mut react_profiles = HashMap::new();
        react_profiles.insert(
            "Page".to_string(),
            make_source_profile_with_block("Page", "page"),
        );
        react_profiles.insert(
            "PageSidebar".to_string(),
            make_source_profile("PageSidebar"),
        );
        react_profiles.insert(
            "PageSidebarBody".to_string(),
            make_source_profile("PageSidebarBody"),
        );

        enrich_trees_with_css(&mut trees, &css_profiles, &react_profiles);

        // There must NOT be a PageSidebar → PageSidebar edge
        let self_edges: Vec<_> = trees[0]
            .edges
            .iter()
            .filter(|e| e.parent == e.child)
            .collect();
        assert!(
            self_edges.is_empty(),
            "Self-referential edges must be blocked. Found: {:?}",
            self_edges
        );
    }

    /// Real PatternFly case: TextInputGroupMain and TextInputGroupUtilities
    /// are siblings under TextInputGroup. CSS has
    /// `.pf-v6-c-text-input-group:has(> .pf-v6-c-text-input-group__utilities)`
    /// proving utilities is a root-level direct child, NOT inside main.
    #[test]
    fn test_has_containment_prevents_sibling_nesting_textinputgroup() {
        let mut trees = vec![CompositionTree {
            root: "TextInputGroup".into(),
            family_members: vec![
                "TextInputGroup".into(),
                "TextInputGroupMain".into(),
                "TextInputGroupUtilities".into(),
            ],
            edges: vec![
                CompositionEdge {
                    parent: "TextInputGroup".into(),
                    child: "TextInputGroupMain".into(),
                    relationship: semver_analyzer_core::types::sd::ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: Some("BEM element".into()),
                },
                CompositionEdge {
                    parent: "TextInputGroup".into(),
                    child: "TextInputGroupUtilities".into(),
                    relationship: semver_analyzer_core::types::sd::ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: Some("BEM element".into()),
                },
            ],
        }];

        let mut elements = BTreeMap::new();
        elements.insert("main".to_string(), {
            let mut info = CssElementInfo::default();
            info.display_values.insert("flex".to_string());
            info
        });
        elements.insert("utilities".to_string(), {
            let mut info = CssElementInfo::default();
            info.display_values.insert("flex".to_string());
            info
        });

        let css_profile = CssBlockProfile {
            block: "text-input-group".into(),
            elements,
            has_containment: vec![("".to_string(), "utilities".to_string())],
            descendant_nesting: vec![],
            sibling_relationships: vec![],
        };

        let mut css_profiles = HashMap::new();
        css_profiles.insert("text-input-group".to_string(), css_profile);

        let mut react_profiles = HashMap::new();
        react_profiles.insert(
            "TextInputGroup".into(),
            make_source_profile_with_block("TextInputGroup", "text-input-group"),
        );
        react_profiles.insert(
            "TextInputGroupMain".into(),
            make_source_profile("TextInputGroupMain"),
        );
        react_profiles.insert(
            "TextInputGroupUtilities".into(),
            make_source_profile("TextInputGroupUtilities"),
        );

        enrich_trees_with_css(&mut trees, &css_profiles, &react_profiles);

        let bad_nesting: Vec<_> = trees[0]
            .edges
            .iter()
            .filter(|e| e.parent == "TextInputGroupMain" && e.child == "TextInputGroupUtilities")
            .collect();
        assert!(
            bad_nesting.is_empty(),
            "TextInputGroupUtilities must NOT be nested inside TextInputGroupMain. Found: {:?}",
            bad_nesting
        );

        let root_edges: Vec<_> = trees[0]
            .edges
            .iter()
            .filter(|e| e.parent == "TextInputGroup" && e.child == "TextInputGroupUtilities")
            .collect();
        assert!(
            !root_edges.is_empty(),
            "TextInputGroupUtilities should remain as a child of TextInputGroup"
        );
    }

    /// Real PatternFly case: Card header contains title (proven by CSS
    /// `.pf-v6-c-card__header .pf-v6-c-card__title`). Valid nesting.
    #[test]
    fn test_css_descendant_nesting_card_header_title() {
        let mut trees = vec![CompositionTree {
            root: "Card".into(),
            family_members: vec![
                "Card".into(),
                "CardHeader".into(),
                "CardTitle".into(),
                "CardBody".into(),
            ],
            edges: vec![
                CompositionEdge {
                    parent: "Card".into(),
                    child: "CardHeader".into(),
                    relationship: semver_analyzer_core::types::sd::ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: Some("BEM element".into()),
                },
                CompositionEdge {
                    parent: "Card".into(),
                    child: "CardTitle".into(),
                    relationship: semver_analyzer_core::types::sd::ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: Some("BEM element".into()),
                },
                CompositionEdge {
                    parent: "Card".into(),
                    child: "CardBody".into(),
                    relationship: semver_analyzer_core::types::sd::ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: Some("BEM element".into()),
                },
            ],
        }];

        let mut elements = BTreeMap::new();
        elements.insert("header".to_string(), {
            let mut info = CssElementInfo::default();
            info.display_values.insert("flex".to_string());
            info
        });
        elements.insert("title".to_string(), CssElementInfo::default());
        elements.insert("body".to_string(), CssElementInfo::default());

        let css_profile = CssBlockProfile {
            block: "card".into(),
            elements,
            has_containment: vec![],
            descendant_nesting: vec![("header".to_string(), "title".to_string())],
            sibling_relationships: vec![],
        };

        let mut css_profiles = HashMap::new();
        css_profiles.insert("card".to_string(), css_profile);

        let mut react_profiles = HashMap::new();
        react_profiles.insert(
            "Card".into(),
            make_source_profile_with_block("Card", "card"),
        );
        react_profiles.insert("CardHeader".into(), make_source_profile("CardHeader"));
        react_profiles.insert("CardTitle".into(), make_source_profile("CardTitle"));
        react_profiles.insert("CardBody".into(), make_source_profile("CardBody"));

        enrich_trees_with_css(&mut trees, &css_profiles, &react_profiles);

        let header_title: Vec<_> = trees[0]
            .edges
            .iter()
            .filter(|e| e.parent == "CardHeader" && e.child == "CardTitle")
            .collect();
        assert!(
            !header_title.is_empty(),
            "CardHeader → CardTitle should be created from CSS descendant selector"
        );

        let root_title: Vec<_> = trees[0]
            .edges
            .iter()
            .filter(|e| e.parent == "Card" && e.child == "CardTitle")
            .collect();
        assert!(
            root_title.is_empty(),
            "Card → CardTitle root edge should be removed (subsumed by CardHeader → CardTitle)"
        );
    }

    /// CSS sibling selectors prevent nesting.
    #[test]
    fn test_css_sibling_selector_prevents_nesting() {
        let mut trees = vec![CompositionTree {
            root: "Page".into(),
            family_members: vec![
                "Page".into(),
                "PageSidebar".into(),
                "PageMainContainer".into(),
            ],
            edges: vec![
                CompositionEdge {
                    parent: "Page".into(),
                    child: "PageSidebar".into(),
                    relationship: semver_analyzer_core::types::sd::ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: Some("BEM element".into()),
                },
                CompositionEdge {
                    parent: "Page".into(),
                    child: "PageMainContainer".into(),
                    relationship: semver_analyzer_core::types::sd::ChildRelationship::DirectChild,
                    required: false,
                    bem_evidence: Some("BEM element".into()),
                },
            ],
        }];

        let mut elements = BTreeMap::new();
        elements.insert("sidebar".to_string(), {
            let mut info = CssElementInfo::default();
            info.display_values.insert("flex".to_string());
            info
        });
        elements.insert("main-container".to_string(), CssElementInfo::default());

        let css_profile = CssBlockProfile {
            block: "page".into(),
            elements,
            has_containment: vec![],
            descendant_nesting: vec![],
            sibling_relationships: vec![("sidebar".to_string(), "main-container".to_string())],
        };

        let mut css_profiles = HashMap::new();
        css_profiles.insert("page".to_string(), css_profile);

        let mut react_profiles = HashMap::new();
        react_profiles.insert(
            "Page".into(),
            make_source_profile_with_block("Page", "page"),
        );
        react_profiles.insert("PageSidebar".into(), make_source_profile("PageSidebar"));
        react_profiles.insert(
            "PageMainContainer".into(),
            make_source_profile("PageMainContainer"),
        );

        enrich_trees_with_css(&mut trees, &css_profiles, &react_profiles);

        let bad_nesting: Vec<_> = trees[0]
            .edges
            .iter()
            .filter(|e| e.parent == "PageSidebar" && e.child == "PageMainContainer")
            .collect();
        assert!(bad_nesting.is_empty(),
            "CSS sibling selector proves PageMainContainer is a sibling of PageSidebar. Found: {:?}", bad_nesting);
    }
}