sbom-tools 0.1.19

Semantic SBOM diff and analysis tool
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
//! Quality metrics for SBOM assessment.
//!
//! Provides detailed metrics for different aspects of SBOM quality.

use std::collections::{BTreeMap, HashMap, HashSet};

use crate::model::{
    CompletenessDeclaration, ComponentType, CreatorType, CryptoAssetType, CryptoMaterialState,
    CryptoPrimitive, EolStatus, ExternalRefType, HashAlgorithm, NormalizedSbom, StalenessLevel,
};
use serde::{Deserialize, Serialize};

/// Overall completeness metrics for an SBOM
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompletenessMetrics {
    /// Percentage of components with versions (0-100)
    pub components_with_version: f32,
    /// Percentage of components with PURLs (0-100)
    pub components_with_purl: f32,
    /// Percentage of components with CPEs (0-100)
    pub components_with_cpe: f32,
    /// Percentage of components with suppliers (0-100)
    pub components_with_supplier: f32,
    /// Percentage of components with hashes (0-100)
    pub components_with_hashes: f32,
    /// Percentage of components with licenses (0-100)
    pub components_with_licenses: f32,
    /// Percentage of components with descriptions (0-100)
    pub components_with_description: f32,
    /// Whether document has creator information
    pub has_creator_info: bool,
    /// Whether document has timestamp
    pub has_timestamp: bool,
    /// Whether document has serial number/ID
    pub has_serial_number: bool,
    /// Total component count
    pub total_components: usize,
}

impl CompletenessMetrics {
    /// Calculate completeness metrics from an SBOM
    #[must_use]
    pub fn from_sbom(sbom: &NormalizedSbom) -> Self {
        let total = sbom.components.len();
        if total == 0 {
            return Self::empty();
        }

        let mut with_version = 0;
        let mut with_purl = 0;
        let mut with_cpe = 0;
        let mut with_supplier = 0;
        let mut with_hashes = 0;
        let mut with_licenses = 0;
        let mut with_description = 0;

        for comp in sbom.components.values() {
            if comp.version.is_some() {
                with_version += 1;
            }
            if comp.identifiers.purl.is_some() {
                with_purl += 1;
            }
            if !comp.identifiers.cpe.is_empty() {
                with_cpe += 1;
            }
            if comp.supplier.is_some() {
                with_supplier += 1;
            }
            if !comp.hashes.is_empty() {
                with_hashes += 1;
            }
            if !comp.licenses.declared.is_empty() || comp.licenses.concluded.is_some() {
                with_licenses += 1;
            }
            if comp.description.is_some() {
                with_description += 1;
            }
        }

        let pct = |count: usize| (count as f32 / total as f32) * 100.0;

        Self {
            components_with_version: pct(with_version),
            components_with_purl: pct(with_purl),
            components_with_cpe: pct(with_cpe),
            components_with_supplier: pct(with_supplier),
            components_with_hashes: pct(with_hashes),
            components_with_licenses: pct(with_licenses),
            components_with_description: pct(with_description),
            has_creator_info: !sbom.document.creators.is_empty(),
            has_timestamp: true, // Always set in our model
            has_serial_number: sbom.document.serial_number.is_some(),
            total_components: total,
        }
    }

    /// Create empty metrics
    #[must_use]
    pub const fn empty() -> Self {
        Self {
            components_with_version: 0.0,
            components_with_purl: 0.0,
            components_with_cpe: 0.0,
            components_with_supplier: 0.0,
            components_with_hashes: 0.0,
            components_with_licenses: 0.0,
            components_with_description: 0.0,
            has_creator_info: false,
            has_timestamp: false,
            has_serial_number: false,
            total_components: 0,
        }
    }

    /// Calculate overall completeness score (0-100)
    #[must_use]
    pub fn overall_score(&self, weights: &CompletenessWeights) -> f32 {
        let mut score = 0.0;
        let mut total_weight = 0.0;

        // Component field scores
        score += self.components_with_version * weights.version;
        total_weight += weights.version * 100.0;

        score += self.components_with_purl * weights.purl;
        total_weight += weights.purl * 100.0;

        score += self.components_with_cpe * weights.cpe;
        total_weight += weights.cpe * 100.0;

        score += self.components_with_supplier * weights.supplier;
        total_weight += weights.supplier * 100.0;

        score += self.components_with_hashes * weights.hashes;
        total_weight += weights.hashes * 100.0;

        score += self.components_with_licenses * weights.licenses;
        total_weight += weights.licenses * 100.0;

        // Document metadata scores
        if self.has_creator_info {
            score += 100.0 * weights.creator_info;
        }
        total_weight += weights.creator_info * 100.0;

        if self.has_serial_number {
            score += 100.0 * weights.serial_number;
        }
        total_weight += weights.serial_number * 100.0;

        if total_weight > 0.0 {
            (score / total_weight) * 100.0
        } else {
            0.0
        }
    }
}

/// Weights for completeness score calculation
#[derive(Debug, Clone)]
pub struct CompletenessWeights {
    pub version: f32,
    pub purl: f32,
    pub cpe: f32,
    pub supplier: f32,
    pub hashes: f32,
    pub licenses: f32,
    pub creator_info: f32,
    pub serial_number: f32,
}

impl Default for CompletenessWeights {
    fn default() -> Self {
        Self {
            version: 1.0,
            purl: 1.5, // Higher weight for PURL
            cpe: 0.5,  // Lower weight, nice to have
            supplier: 1.0,
            hashes: 1.0,
            licenses: 1.2, // Important for compliance
            creator_info: 0.3,
            serial_number: 0.2,
        }
    }
}

// ============================================================================
// Hash quality metrics
// ============================================================================

/// Hash/integrity quality metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HashQualityMetrics {
    /// Components with any hash
    pub components_with_any_hash: usize,
    /// Components with at least one strong hash (SHA-256+, SHA-3, BLAKE, Blake3)
    pub components_with_strong_hash: usize,
    /// Components with only weak hashes (MD5, SHA-1) and no strong backup
    pub components_with_weak_only: usize,
    /// Distribution of hash algorithms across all components
    pub algorithm_distribution: BTreeMap<String, usize>,
    /// Total hash entries across all components
    pub total_hashes: usize,
}

impl HashQualityMetrics {
    /// Calculate hash quality metrics from an SBOM
    #[must_use]
    pub fn from_sbom(sbom: &NormalizedSbom) -> Self {
        let mut with_any = 0;
        let mut with_strong = 0;
        let mut with_weak_only = 0;
        let mut distribution: BTreeMap<String, usize> = BTreeMap::new();
        let mut total_hashes = 0;

        for comp in sbom.components.values() {
            if comp.hashes.is_empty() {
                continue;
            }
            with_any += 1;
            total_hashes += comp.hashes.len();

            let mut has_strong = false;
            let mut has_weak = false;

            for hash in &comp.hashes {
                let label = hash_algorithm_label(&hash.algorithm);
                *distribution.entry(label).or_insert(0) += 1;

                if is_strong_hash(&hash.algorithm) {
                    has_strong = true;
                } else {
                    has_weak = true;
                }
            }

            if has_strong {
                with_strong += 1;
            } else if has_weak {
                with_weak_only += 1;
            }
        }

        Self {
            components_with_any_hash: with_any,
            components_with_strong_hash: with_strong,
            components_with_weak_only: with_weak_only,
            algorithm_distribution: distribution,
            total_hashes,
        }
    }

    /// Calculate integrity quality score (0-100)
    ///
    /// Base 60% for any-hash coverage + 40% bonus for strong-hash coverage,
    /// with a penalty for weak-only components.
    #[must_use]
    pub fn quality_score(&self, total_components: usize) -> f32 {
        if total_components == 0 {
            return 0.0;
        }

        let any_coverage = self.components_with_any_hash as f32 / total_components as f32;
        let strong_coverage = self.components_with_strong_hash as f32 / total_components as f32;
        let weak_only_ratio = self.components_with_weak_only as f32 / total_components as f32;

        let base = any_coverage * 60.0;
        let strong_bonus = strong_coverage * 40.0;
        let weak_penalty = weak_only_ratio * 10.0;

        (base + strong_bonus - weak_penalty).clamp(0.0, 100.0)
    }
}

/// Whether a hash algorithm is considered cryptographically strong
fn is_strong_hash(algo: &HashAlgorithm) -> bool {
    matches!(
        algo,
        HashAlgorithm::Sha256
            | HashAlgorithm::Sha384
            | HashAlgorithm::Sha512
            | HashAlgorithm::Sha3_256
            | HashAlgorithm::Sha3_384
            | HashAlgorithm::Sha3_512
            | HashAlgorithm::Blake2b256
            | HashAlgorithm::Blake2b384
            | HashAlgorithm::Blake2b512
            | HashAlgorithm::Blake3
            | HashAlgorithm::Streebog256
            | HashAlgorithm::Streebog512
    )
}

/// Human-readable label for a hash algorithm
fn hash_algorithm_label(algo: &HashAlgorithm) -> String {
    match algo {
        HashAlgorithm::Md5 => "MD5".to_string(),
        HashAlgorithm::Sha1 => "SHA-1".to_string(),
        HashAlgorithm::Sha256 => "SHA-256".to_string(),
        HashAlgorithm::Sha384 => "SHA-384".to_string(),
        HashAlgorithm::Sha512 => "SHA-512".to_string(),
        HashAlgorithm::Sha3_256 => "SHA3-256".to_string(),
        HashAlgorithm::Sha3_384 => "SHA3-384".to_string(),
        HashAlgorithm::Sha3_512 => "SHA3-512".to_string(),
        HashAlgorithm::Blake2b256 => "BLAKE2b-256".to_string(),
        HashAlgorithm::Blake2b384 => "BLAKE2b-384".to_string(),
        HashAlgorithm::Blake2b512 => "BLAKE2b-512".to_string(),
        HashAlgorithm::Blake3 => "BLAKE3".to_string(),
        HashAlgorithm::Streebog256 => "Streebog-256".to_string(),
        HashAlgorithm::Streebog512 => "Streebog-512".to_string(),
        HashAlgorithm::Other(s) => s.clone(),
    }
}

// ============================================================================
// Identifier quality metrics
// ============================================================================

/// Identifier quality metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IdentifierMetrics {
    /// Components with valid PURLs
    pub valid_purls: usize,
    /// Components with invalid/malformed PURLs
    pub invalid_purls: usize,
    /// Components with valid CPEs
    pub valid_cpes: usize,
    /// Components with invalid/malformed CPEs
    pub invalid_cpes: usize,
    /// Components with SWID tags
    pub with_swid: usize,
    /// Unique ecosystems identified
    pub ecosystems: Vec<String>,
    /// Components missing all identifiers (only name)
    pub missing_all_identifiers: usize,
}

impl IdentifierMetrics {
    /// Calculate identifier metrics from an SBOM
    #[must_use]
    pub fn from_sbom(sbom: &NormalizedSbom) -> Self {
        let mut valid_purls = 0;
        let mut invalid_purls = 0;
        let mut valid_cpes = 0;
        let mut invalid_cpes = 0;
        let mut with_swid = 0;
        let mut missing_all = 0;
        let mut ecosystems = std::collections::HashSet::new();

        for comp in sbom.components.values() {
            let has_purl = comp.identifiers.purl.is_some();
            let has_cpe = !comp.identifiers.cpe.is_empty();
            let has_swid = comp.identifiers.swid.is_some();

            if let Some(ref purl) = comp.identifiers.purl {
                if is_valid_purl(purl) {
                    valid_purls += 1;
                    // Extract ecosystem from PURL
                    if let Some(eco) = extract_ecosystem_from_purl(purl) {
                        ecosystems.insert(eco);
                    }
                } else {
                    invalid_purls += 1;
                }
            }

            for cpe in &comp.identifiers.cpe {
                if is_valid_cpe(cpe) {
                    valid_cpes += 1;
                } else {
                    invalid_cpes += 1;
                }
            }

            if has_swid {
                with_swid += 1;
            }

            if !has_purl && !has_cpe && !has_swid {
                missing_all += 1;
            }
        }

        let mut ecosystem_list: Vec<String> = ecosystems.into_iter().collect();
        ecosystem_list.sort();

        Self {
            valid_purls,
            invalid_purls,
            valid_cpes,
            invalid_cpes,
            with_swid,
            ecosystems: ecosystem_list,
            missing_all_identifiers: missing_all,
        }
    }

    /// Calculate identifier quality score (0-100)
    #[must_use]
    pub fn quality_score(&self, total_components: usize) -> f32 {
        if total_components == 0 {
            return 0.0;
        }

        let with_valid_id = self.valid_purls + self.valid_cpes + self.with_swid;
        let coverage =
            (with_valid_id.min(total_components) as f32 / total_components as f32) * 100.0;

        // Penalize invalid identifiers
        let invalid_count = self.invalid_purls + self.invalid_cpes;
        let penalty = (invalid_count as f32 / total_components as f32) * 20.0;

        (coverage - penalty).clamp(0.0, 100.0)
    }
}

/// License quality metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LicenseMetrics {
    /// Components with declared licenses
    pub with_declared: usize,
    /// Components with concluded licenses
    pub with_concluded: usize,
    /// Components with valid SPDX expressions
    pub valid_spdx_expressions: usize,
    /// Components with non-standard license names
    pub non_standard_licenses: usize,
    /// Components with NOASSERTION license
    pub noassertion_count: usize,
    /// Components with deprecated SPDX license identifiers
    pub deprecated_licenses: usize,
    /// Components with restrictive/copyleft licenses (GPL family)
    pub restrictive_licenses: usize,
    /// Specific copyleft license identifiers found
    pub copyleft_license_ids: Vec<String>,
    /// Unique licenses found
    pub unique_licenses: Vec<String>,
}

impl LicenseMetrics {
    /// Calculate license metrics from an SBOM
    #[must_use]
    pub fn from_sbom(sbom: &NormalizedSbom) -> Self {
        let mut with_declared = 0;
        let mut with_concluded = 0;
        let mut valid_spdx = 0;
        let mut non_standard = 0;
        let mut noassertion = 0;
        let mut deprecated = 0;
        let mut restrictive = 0;
        let mut licenses = HashSet::new();
        let mut copyleft_ids = HashSet::new();

        for comp in sbom.components.values() {
            if !comp.licenses.declared.is_empty() {
                with_declared += 1;
                for lic in &comp.licenses.declared {
                    let expr = &lic.expression;
                    licenses.insert(expr.clone());

                    if expr == "NOASSERTION" {
                        noassertion += 1;
                    } else if is_valid_spdx_license(expr) {
                        valid_spdx += 1;
                    } else {
                        non_standard += 1;
                    }

                    if is_deprecated_spdx_license(expr) {
                        deprecated += 1;
                    }
                    if is_restrictive_license(expr) {
                        restrictive += 1;
                        copyleft_ids.insert(expr.clone());
                    }
                }
            }

            if comp.licenses.concluded.is_some() {
                with_concluded += 1;
            }
        }

        let mut license_list: Vec<String> = licenses.into_iter().collect();
        license_list.sort();

        let mut copyleft_list: Vec<String> = copyleft_ids.into_iter().collect();
        copyleft_list.sort();

        Self {
            with_declared,
            with_concluded,
            valid_spdx_expressions: valid_spdx,
            non_standard_licenses: non_standard,
            noassertion_count: noassertion,
            deprecated_licenses: deprecated,
            restrictive_licenses: restrictive,
            copyleft_license_ids: copyleft_list,
            unique_licenses: license_list,
        }
    }

    /// Calculate license quality score (0-100)
    #[must_use]
    pub fn quality_score(&self, total_components: usize) -> f32 {
        if total_components == 0 {
            return 0.0;
        }

        let coverage = (self.with_declared as f32 / total_components as f32) * 60.0;

        // Bonus for SPDX compliance
        let spdx_ratio = if self.with_declared > 0 {
            self.valid_spdx_expressions as f32 / self.with_declared as f32
        } else {
            0.0
        };
        let spdx_bonus = spdx_ratio * 30.0;

        // Penalty for NOASSERTION
        let noassertion_penalty =
            (self.noassertion_count as f32 / total_components.max(1) as f32) * 10.0;

        // Penalty for deprecated licenses (2 points each, capped)
        let deprecated_penalty = (self.deprecated_licenses as f32 * 2.0).min(10.0);

        (coverage + spdx_bonus - noassertion_penalty - deprecated_penalty).clamp(0.0, 100.0)
    }
}

/// Vulnerability information quality metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VulnerabilityMetrics {
    /// Components with vulnerability information
    pub components_with_vulns: usize,
    /// Total vulnerabilities reported
    pub total_vulnerabilities: usize,
    /// Vulnerabilities with CVSS scores
    pub with_cvss: usize,
    /// Vulnerabilities with CWE information
    pub with_cwe: usize,
    /// Vulnerabilities with remediation info
    pub with_remediation: usize,
    /// Components with VEX status
    pub with_vex_status: usize,
}

impl VulnerabilityMetrics {
    /// Calculate vulnerability metrics from an SBOM
    #[must_use]
    pub fn from_sbom(sbom: &NormalizedSbom) -> Self {
        let mut components_with_vulns = 0;
        let mut total_vulns = 0;
        let mut with_cvss = 0;
        let mut with_cwe = 0;
        let mut with_remediation = 0;
        let mut with_vex = 0;

        for comp in sbom.components.values() {
            if !comp.vulnerabilities.is_empty() {
                components_with_vulns += 1;
            }

            for vuln in &comp.vulnerabilities {
                total_vulns += 1;

                if !vuln.cvss.is_empty() {
                    with_cvss += 1;
                }
                if !vuln.cwes.is_empty() {
                    with_cwe += 1;
                }
                if vuln.remediation.is_some() {
                    with_remediation += 1;
                }
            }

            if comp.vex_status.is_some()
                || comp.vulnerabilities.iter().any(|v| v.vex_status.is_some())
            {
                with_vex += 1;
            }
        }

        Self {
            components_with_vulns,
            total_vulnerabilities: total_vulns,
            with_cvss,
            with_cwe,
            with_remediation,
            with_vex_status: with_vex,
        }
    }

    /// Calculate vulnerability documentation quality score (0-100)
    ///
    /// Returns `None` when no vulnerability data exists, signaling that this
    /// category should be excluded from the weighted score (N/A-aware).
    /// This prevents inflating the overall score when vulnerability assessment
    /// was not performed.
    #[must_use]
    pub fn documentation_score(&self) -> Option<f32> {
        if self.total_vulnerabilities == 0 {
            return None; // No vulnerability data — treat as N/A
        }

        let cvss_ratio = self.with_cvss as f32 / self.total_vulnerabilities as f32;
        let cwe_ratio = self.with_cwe as f32 / self.total_vulnerabilities as f32;
        let remediation_ratio = self.with_remediation as f32 / self.total_vulnerabilities as f32;

        Some(
            remediation_ratio
                .mul_add(30.0, cvss_ratio.mul_add(40.0, cwe_ratio * 30.0))
                .min(100.0),
        )
    }
}

// ============================================================================
// Dependency graph quality metrics
// ============================================================================

/// Maximum edge count before skipping expensive graph analysis
const MAX_EDGES_FOR_GRAPH_ANALYSIS: usize = 50_000;

// ============================================================================
// Software complexity index
// ============================================================================

/// Complexity level bands for the software complexity index
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum ComplexityLevel {
    /// Simplicity 75–100 (raw complexity 0–0.25)
    Low,
    /// Simplicity 50–74 (raw complexity 0.26–0.50)
    Moderate,
    /// Simplicity 25–49 (raw complexity 0.51–0.75)
    High,
    /// Simplicity 0–24 (raw complexity 0.76–1.00)
    VeryHigh,
}

impl ComplexityLevel {
    /// Determine complexity level from a simplicity score (0–100)
    #[must_use]
    pub const fn from_score(simplicity: f32) -> Self {
        match simplicity as u32 {
            75..=100 => Self::Low,
            50..=74 => Self::Moderate,
            25..=49 => Self::High,
            _ => Self::VeryHigh,
        }
    }

    /// Human-readable label
    #[must_use]
    pub const fn label(&self) -> &'static str {
        match self {
            Self::Low => "Low",
            Self::Moderate => "Moderate",
            Self::High => "High",
            Self::VeryHigh => "Very High",
        }
    }
}

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

/// Breakdown of the five factors that compose the software complexity index.
/// Each factor is normalized to 0.0–1.0 where higher = more complex.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComplexityFactors {
    /// Log-scaled edge density: `min(1.0, ln(1 + edges/components) / ln(20))`
    pub dependency_volume: f32,
    /// Depth ratio: `min(1.0, max_depth / 15.0)`
    pub normalized_depth: f32,
    /// Hub dominance: `min(1.0, max_out_degree / max(components * 0.25, 4))`
    pub fanout_concentration: f32,
    /// Cycle density: `min(1.0, cycle_count / max(1, components * 0.05))`
    pub cycle_ratio: f32,
    /// Extra disconnected subgraphs: `(islands - 1) / max(1, components - 1)`
    pub fragmentation: f32,
}

/// Dependency graph quality metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DependencyMetrics {
    /// Total dependency relationships
    pub total_dependencies: usize,
    /// Components with at least one dependency
    pub components_with_deps: usize,
    /// Maximum dependency depth (computed via BFS from roots)
    pub max_depth: Option<usize>,
    /// Average dependency depth across all reachable components
    pub avg_depth: Option<f32>,
    /// Orphan components (no incoming or outgoing deps)
    pub orphan_components: usize,
    /// Root components (no incoming deps, but has outgoing)
    pub root_components: usize,
    /// Number of dependency cycles detected
    pub cycle_count: usize,
    /// Number of disconnected subgraphs (islands)
    pub island_count: usize,
    /// Whether graph analysis was skipped due to size
    pub graph_analysis_skipped: bool,
    /// Maximum out-degree (most dependencies from a single component)
    pub max_out_degree: usize,
    /// Software complexity index (0–100, higher = simpler). `None` when graph analysis skipped.
    pub software_complexity_index: Option<f32>,
    /// Complexity level band. `None` when graph analysis skipped.
    pub complexity_level: Option<ComplexityLevel>,
    /// Factor breakdown. `None` when graph analysis skipped.
    pub complexity_factors: Option<ComplexityFactors>,
}

impl DependencyMetrics {
    /// Calculate dependency metrics from an SBOM
    #[must_use]
    pub fn from_sbom(sbom: &NormalizedSbom) -> Self {
        use crate::model::CanonicalId;

        let total_deps = sbom.edges.len();

        // Build adjacency lists using CanonicalId.value() for string keys
        let mut children: HashMap<&str, Vec<&str>> = HashMap::new();
        let mut has_outgoing: HashSet<&str> = HashSet::new();
        let mut has_incoming: HashSet<&str> = HashSet::new();

        for edge in &sbom.edges {
            children
                .entry(edge.from.value())
                .or_default()
                .push(edge.to.value());
            has_outgoing.insert(edge.from.value());
            has_incoming.insert(edge.to.value());
        }

        let all_ids: Vec<&str> = sbom.components.keys().map(CanonicalId::value).collect();

        let orphans = all_ids
            .iter()
            .filter(|c| !has_outgoing.contains(*c) && !has_incoming.contains(*c))
            .count();

        let roots: Vec<&str> = has_outgoing
            .iter()
            .filter(|c| !has_incoming.contains(*c))
            .copied()
            .collect();
        let root_count = roots.len();

        // Compute max out-degree (single pass over adjacency, O(V))
        let max_out_degree = children.values().map(Vec::len).max().unwrap_or(0);

        // Skip expensive graph analysis for very large graphs
        if total_deps > MAX_EDGES_FOR_GRAPH_ANALYSIS {
            return Self {
                total_dependencies: total_deps,
                components_with_deps: has_outgoing.len(),
                max_depth: None,
                avg_depth: None,
                orphan_components: orphans,
                root_components: root_count,
                cycle_count: 0,
                island_count: 0,
                graph_analysis_skipped: true,
                max_out_degree,
                software_complexity_index: None,
                complexity_level: None,
                complexity_factors: None,
            };
        }

        // BFS from roots to compute depth
        let (max_depth, avg_depth) = compute_depth(&roots, &children);

        // DFS cycle detection
        let cycle_count = detect_cycles(&all_ids, &children);

        // Union-Find for island/subgraph detection
        let island_count = count_islands(&all_ids, &sbom.edges);

        // Compute software complexity index
        let component_count = all_ids.len();
        let (complexity_index, complexity_lvl, factors) = compute_complexity(
            total_deps,
            component_count,
            max_depth.unwrap_or(0),
            max_out_degree,
            cycle_count,
            orphans,
            island_count,
        );

        Self {
            total_dependencies: total_deps,
            components_with_deps: has_outgoing.len(),
            max_depth,
            avg_depth,
            orphan_components: orphans,
            root_components: root_count,
            cycle_count,
            island_count,
            graph_analysis_skipped: false,
            max_out_degree,
            software_complexity_index: Some(complexity_index),
            complexity_level: Some(complexity_lvl),
            complexity_factors: Some(factors),
        }
    }

    /// Calculate dependency graph quality score (0-100)
    #[must_use]
    pub fn quality_score(&self, total_components: usize) -> f32 {
        if total_components == 0 {
            return 0.0;
        }

        // Score based on how many components have dependency info
        let coverage = if total_components > 1 {
            (self.components_with_deps as f32 / (total_components - 1) as f32) * 100.0
        } else {
            100.0 // Single component SBOM
        };

        // Slight penalty for orphan components
        let orphan_ratio = self.orphan_components as f32 / total_components as f32;
        let orphan_penalty = orphan_ratio * 10.0;

        // Penalty for cycles (5 points each, capped at 20)
        let cycle_penalty = (self.cycle_count as f32 * 5.0).min(20.0);

        // Penalty for excessive islands (>3 in multi-component SBOMs)
        let island_penalty = if total_components > 5 && self.island_count > 3 {
            ((self.island_count - 3) as f32 * 3.0).min(15.0)
        } else {
            0.0
        };

        (coverage - orphan_penalty - cycle_penalty - island_penalty).clamp(0.0, 100.0)
    }
}

/// BFS from roots to compute max and average depth
fn compute_depth(
    roots: &[&str],
    children: &HashMap<&str, Vec<&str>>,
) -> (Option<usize>, Option<f32>) {
    use std::collections::VecDeque;

    if roots.is_empty() {
        return (None, None);
    }

    let mut visited: HashSet<&str> = HashSet::new();
    let mut queue: VecDeque<(&str, usize)> = VecDeque::new();
    let mut max_d: usize = 0;
    let mut total_depth: usize = 0;
    let mut count: usize = 0;

    for &root in roots {
        if visited.insert(root) {
            queue.push_back((root, 0));
        }
    }

    while let Some((node, depth)) = queue.pop_front() {
        max_d = max_d.max(depth);
        total_depth += depth;
        count += 1;

        if let Some(kids) = children.get(node) {
            for &kid in kids {
                if visited.insert(kid) {
                    queue.push_back((kid, depth + 1));
                }
            }
        }
    }

    let avg = if count > 0 {
        Some(total_depth as f32 / count as f32)
    } else {
        None
    };

    (Some(max_d), avg)
}

/// DFS-based cycle detection (white/gray/black coloring)
fn detect_cycles(all_nodes: &[&str], children: &HashMap<&str, Vec<&str>>) -> usize {
    const WHITE: u8 = 0;
    const GRAY: u8 = 1;
    const BLACK: u8 = 2;

    let mut color: HashMap<&str, u8> = HashMap::with_capacity(all_nodes.len());
    for &node in all_nodes {
        color.insert(node, WHITE);
    }

    let mut cycles = 0;

    fn dfs<'a>(
        node: &'a str,
        children: &HashMap<&str, Vec<&'a str>>,
        color: &mut HashMap<&'a str, u8>,
        cycles: &mut usize,
    ) {
        color.insert(node, GRAY);

        if let Some(kids) = children.get(node) {
            for &kid in kids {
                match color.get(kid).copied().unwrap_or(WHITE) {
                    GRAY => *cycles += 1, // back edge = cycle
                    WHITE => dfs(kid, children, color, cycles),
                    _ => {}
                }
            }
        }

        color.insert(node, BLACK);
    }

    for &node in all_nodes {
        if color.get(node).copied().unwrap_or(WHITE) == WHITE {
            dfs(node, children, &mut color, &mut cycles);
        }
    }

    cycles
}

/// Union-Find to count disconnected subgraphs (islands)
fn count_islands(all_nodes: &[&str], edges: &[crate::model::DependencyEdge]) -> usize {
    if all_nodes.is_empty() {
        return 0;
    }

    // Map node IDs to indices
    let node_idx: HashMap<&str, usize> =
        all_nodes.iter().enumerate().map(|(i, &n)| (n, i)).collect();

    let mut parent: Vec<usize> = (0..all_nodes.len()).collect();
    let mut rank: Vec<u8> = vec![0; all_nodes.len()];

    fn find(parent: &mut Vec<usize>, x: usize) -> usize {
        if parent[x] != x {
            parent[x] = find(parent, parent[x]); // path compression
        }
        parent[x]
    }

    fn union(parent: &mut Vec<usize>, rank: &mut [u8], a: usize, b: usize) {
        let ra = find(parent, a);
        let rb = find(parent, b);
        if ra != rb {
            if rank[ra] < rank[rb] {
                parent[ra] = rb;
            } else if rank[ra] > rank[rb] {
                parent[rb] = ra;
            } else {
                parent[rb] = ra;
                rank[ra] += 1;
            }
        }
    }

    for edge in edges {
        if let (Some(&a), Some(&b)) = (
            node_idx.get(edge.from.value()),
            node_idx.get(edge.to.value()),
        ) {
            union(&mut parent, &mut rank, a, b);
        }
    }

    // Count unique roots
    let mut roots = HashSet::new();
    for i in 0..all_nodes.len() {
        roots.insert(find(&mut parent, i));
    }

    roots.len()
}

/// Compute the software complexity index and factor breakdown.
///
/// Returns `(simplicity_index, complexity_level, factors)`.
/// `simplicity_index` is 0–100 where 100 = simplest.
fn compute_complexity(
    edges: usize,
    components: usize,
    max_depth: usize,
    max_out_degree: usize,
    cycle_count: usize,
    _orphans: usize,
    islands: usize,
) -> (f32, ComplexityLevel, ComplexityFactors) {
    if components == 0 {
        let factors = ComplexityFactors {
            dependency_volume: 0.0,
            normalized_depth: 0.0,
            fanout_concentration: 0.0,
            cycle_ratio: 0.0,
            fragmentation: 0.0,
        };
        return (100.0, ComplexityLevel::Low, factors);
    }

    // Factor 1: dependency volume — log-scaled edge density
    let edge_ratio = edges as f64 / components as f64;
    let dependency_volume = ((1.0 + edge_ratio).ln() / 20.0_f64.ln()).min(1.0) as f32;

    // Factor 2: normalized depth
    let normalized_depth = (max_depth as f32 / 15.0).min(1.0);

    // Factor 3: fanout concentration — hub dominance
    // Floor of 4.0 prevents small graphs from being penalized for max_out_degree of 1
    let fanout_denom = (components as f32 * 0.25).max(4.0);
    let fanout_concentration = (max_out_degree as f32 / fanout_denom).min(1.0);

    // Factor 4: cycle ratio
    let cycle_threshold = (components as f32 * 0.05).max(1.0);
    let cycle_ratio = (cycle_count as f32 / cycle_threshold).min(1.0);

    // Factor 5: fragmentation — extra disconnected subgraphs beyond the ideal of 1
    // Uses (islands - 1) because orphans are already counted as individual islands.
    let extra_islands = islands.saturating_sub(1);
    let fragmentation = if components > 1 {
        (extra_islands as f32 / (components - 1) as f32).min(1.0)
    } else {
        0.0
    };

    let factors = ComplexityFactors {
        dependency_volume,
        normalized_depth,
        fanout_concentration,
        cycle_ratio,
        fragmentation,
    };

    let raw_complexity = 0.30 * dependency_volume
        + 0.20 * normalized_depth
        + 0.20 * fanout_concentration
        + 0.20 * cycle_ratio
        + 0.10 * fragmentation;

    let simplicity_index = (100.0 - raw_complexity * 100.0).clamp(0.0, 100.0);
    let level = ComplexityLevel::from_score(simplicity_index);

    (simplicity_index, level, factors)
}

// ============================================================================
// Provenance metrics
// ============================================================================

/// Document provenance and authorship quality metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProvenanceMetrics {
    /// Whether the SBOM was created by an identified tool
    pub has_tool_creator: bool,
    /// Whether the tool creator includes version information
    pub has_tool_version: bool,
    /// Whether an organization is identified as creator
    pub has_org_creator: bool,
    /// Whether any creator has a contact email
    pub has_contact_email: bool,
    /// Whether the document has a serial number / namespace
    pub has_serial_number: bool,
    /// Whether the document has a name
    pub has_document_name: bool,
    /// Age of the SBOM in days (since creation timestamp)
    pub timestamp_age_days: u32,
    /// Whether the SBOM is considered fresh (< 90 days old)
    pub is_fresh: bool,
    /// Whether a primary/described component is identified
    pub has_primary_component: bool,
    /// SBOM lifecycle phase (from CycloneDX 1.5+ metadata)
    pub lifecycle_phase: Option<String>,
    /// Self-declared completeness level of the SBOM
    pub completeness_declaration: CompletenessDeclaration,
    /// Whether the SBOM has a digital signature
    pub has_signature: bool,
    /// Whether the SBOM has data provenance citations (CycloneDX 1.7+)
    pub has_citations: bool,
    /// Number of data provenance citations
    pub citations_count: usize,
}

/// Freshness threshold in days
const FRESHNESS_THRESHOLD_DAYS: u32 = 90;

impl ProvenanceMetrics {
    /// Calculate provenance metrics from an SBOM
    #[must_use]
    pub fn from_sbom(sbom: &NormalizedSbom) -> Self {
        let doc = &sbom.document;

        let has_tool_creator = doc
            .creators
            .iter()
            .any(|c| c.creator_type == CreatorType::Tool);
        let has_tool_version = doc.creators.iter().any(|c| {
            c.creator_type == CreatorType::Tool
                && (c.name.contains(' ') || c.name.contains('/') || c.name.contains('@'))
        });
        let has_org_creator = doc
            .creators
            .iter()
            .any(|c| c.creator_type == CreatorType::Organization);
        let has_contact_email = doc.creators.iter().any(|c| c.email.is_some());

        let age_days = (chrono::Utc::now() - doc.created).num_days().max(0) as u32;

        Self {
            has_tool_creator,
            has_tool_version,
            has_org_creator,
            has_contact_email,
            has_serial_number: doc.serial_number.is_some(),
            has_document_name: doc.name.is_some(),
            timestamp_age_days: age_days,
            is_fresh: age_days < FRESHNESS_THRESHOLD_DAYS,
            has_primary_component: sbom.primary_component_id.is_some(),
            lifecycle_phase: doc.lifecycle_phase.clone(),
            completeness_declaration: doc.completeness_declaration.clone(),
            has_signature: doc.signature.is_some(),
            has_citations: doc.citations_count > 0,
            citations_count: doc.citations_count,
        }
    }

    /// Calculate provenance quality score (0-100)
    ///
    /// Weighted checklist: tool creator (15%), tool version (5%), org creator (12%),
    /// contact email (8%), serial number (8%), document name (5%), freshness (12%),
    /// primary component (12%), completeness declaration (8%), signature (5%),
    /// lifecycle phase (10% CDX-only).
    #[must_use]
    pub fn quality_score(&self, is_cyclonedx: bool) -> f32 {
        let mut score = 0.0;
        let mut total_weight = 0.0;

        let completeness_declared =
            self.completeness_declaration != CompletenessDeclaration::Unknown;

        let checks: &[(bool, f32)] = &[
            (self.has_tool_creator, 15.0),
            (self.has_tool_version, 5.0),
            (self.has_org_creator, 12.0),
            (self.has_contact_email, 8.0),
            (self.has_serial_number, 8.0),
            (self.has_document_name, 5.0),
            (self.is_fresh, 12.0),
            (self.has_primary_component, 12.0),
            (completeness_declared, 8.0),
            (self.has_signature, 5.0),
        ];

        for &(present, weight) in checks {
            if present {
                score += weight;
            }
            total_weight += weight;
        }

        // Lifecycle phase: only applicable for CycloneDX 1.5+
        if is_cyclonedx {
            let weight = 10.0;
            if self.lifecycle_phase.is_some() {
                score += weight;
            }
            total_weight += weight;

            // Data provenance citations bonus (CycloneDX 1.7+)
            let citations_weight = 5.0;
            if self.has_citations {
                score += citations_weight;
            }
            total_weight += citations_weight;
        }

        if total_weight > 0.0 {
            (score / total_weight) * 100.0
        } else {
            0.0
        }
    }
}

// ============================================================================
// Auditability metrics
// ============================================================================

/// External reference and auditability quality metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditabilityMetrics {
    /// Components with VCS (version control) references
    pub components_with_vcs: usize,
    /// Components with website references
    pub components_with_website: usize,
    /// Components with security advisory references
    pub components_with_advisories: usize,
    /// Components with any external reference
    pub components_with_any_external_ref: usize,
    /// Whether the document has a security contact
    pub has_security_contact: bool,
    /// Whether the document has a vulnerability disclosure URL
    pub has_vuln_disclosure_url: bool,
}

impl AuditabilityMetrics {
    /// Calculate auditability metrics from an SBOM
    #[must_use]
    pub fn from_sbom(sbom: &NormalizedSbom) -> Self {
        let mut with_vcs = 0;
        let mut with_website = 0;
        let mut with_advisories = 0;
        let mut with_any = 0;

        for comp in sbom.components.values() {
            if comp.external_refs.is_empty() {
                continue;
            }
            with_any += 1;

            let has_vcs = comp
                .external_refs
                .iter()
                .any(|r| r.ref_type == ExternalRefType::Vcs);
            let has_website = comp
                .external_refs
                .iter()
                .any(|r| r.ref_type == ExternalRefType::Website);
            let has_advisories = comp
                .external_refs
                .iter()
                .any(|r| r.ref_type == ExternalRefType::Advisories);

            if has_vcs {
                with_vcs += 1;
            }
            if has_website {
                with_website += 1;
            }
            if has_advisories {
                with_advisories += 1;
            }
        }

        Self {
            components_with_vcs: with_vcs,
            components_with_website: with_website,
            components_with_advisories: with_advisories,
            components_with_any_external_ref: with_any,
            has_security_contact: sbom.document.security_contact.is_some(),
            has_vuln_disclosure_url: sbom.document.vulnerability_disclosure_url.is_some(),
        }
    }

    /// Calculate auditability quality score (0-100)
    ///
    /// Component-level coverage (60%) + document-level security metadata (40%).
    #[must_use]
    pub fn quality_score(&self, total_components: usize) -> f32 {
        if total_components == 0 {
            return 0.0;
        }

        // Component-level: external ref coverage
        let ref_coverage =
            (self.components_with_any_external_ref as f32 / total_components as f32) * 40.0;
        let vcs_coverage = (self.components_with_vcs as f32 / total_components as f32) * 20.0;

        // Document-level security metadata
        let security_contact_score = if self.has_security_contact { 20.0 } else { 0.0 };
        let disclosure_score = if self.has_vuln_disclosure_url {
            20.0
        } else {
            0.0
        };

        (ref_coverage + vcs_coverage + security_contact_score + disclosure_score).min(100.0)
    }
}

// ============================================================================
// Lifecycle metrics
// ============================================================================

/// Component lifecycle quality metrics (requires enrichment data)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LifecycleMetrics {
    /// Components that have reached end-of-life
    pub eol_components: usize,
    /// Components classified as stale (no updates for 1+ years)
    pub stale_components: usize,
    /// Components explicitly marked as deprecated
    pub deprecated_components: usize,
    /// Components with archived repositories
    pub archived_components: usize,
    /// Components with a newer version available
    pub outdated_components: usize,
    /// Components that had lifecycle enrichment data
    pub enriched_components: usize,
    /// Enrichment coverage percentage (0-100)
    pub enrichment_coverage: f32,
}

impl LifecycleMetrics {
    /// Calculate lifecycle metrics from an SBOM
    ///
    /// These metrics are only meaningful after enrichment. When
    /// `enrichment_coverage == 0`, the lifecycle score should be
    /// treated as N/A and excluded from the weighted total.
    #[must_use]
    pub fn from_sbom(sbom: &NormalizedSbom) -> Self {
        let total = sbom.components.len();
        let mut eol = 0;
        let mut stale = 0;
        let mut deprecated = 0;
        let mut archived = 0;
        let mut outdated = 0;
        let mut enriched = 0;

        for comp in sbom.components.values() {
            let has_lifecycle_data = comp.eol.is_some() || comp.staleness.is_some();
            if has_lifecycle_data {
                enriched += 1;
            }

            if let Some(ref eol_info) = comp.eol
                && eol_info.status == EolStatus::EndOfLife
            {
                eol += 1;
            }

            if let Some(ref stale_info) = comp.staleness {
                match stale_info.level {
                    StalenessLevel::Stale | StalenessLevel::Abandoned => stale += 1,
                    StalenessLevel::Deprecated => deprecated += 1,
                    StalenessLevel::Archived => archived += 1,
                    _ => {}
                }
                if stale_info.is_deprecated {
                    deprecated += 1;
                }
                if stale_info.is_archived {
                    archived += 1;
                }
                if stale_info.latest_version.is_some() {
                    outdated += 1;
                }
            }
        }

        let coverage = if total > 0 {
            (enriched as f32 / total as f32) * 100.0
        } else {
            0.0
        };

        Self {
            eol_components: eol,
            stale_components: stale,
            deprecated_components: deprecated,
            archived_components: archived,
            outdated_components: outdated,
            enriched_components: enriched,
            enrichment_coverage: coverage,
        }
    }

    /// Whether enrichment data is available for scoring
    #[must_use]
    pub fn has_data(&self) -> bool {
        self.enriched_components > 0
    }

    /// Calculate lifecycle quality score (0-100)
    ///
    /// Starts at 100, subtracts penalties for problematic components.
    /// Returns `None` if no enrichment data is available.
    #[must_use]
    pub fn quality_score(&self) -> Option<f32> {
        if !self.has_data() {
            return None;
        }

        let mut score = 100.0_f32;

        // EOL: severe penalty (15 points each, capped at 60)
        score -= (self.eol_components as f32 * 15.0).min(60.0);
        // Stale: moderate penalty (5 points each, capped at 30)
        score -= (self.stale_components as f32 * 5.0).min(30.0);
        // Deprecated/archived: moderate penalty (3 points each, capped at 20)
        score -= ((self.deprecated_components + self.archived_components) as f32 * 3.0).min(20.0);
        // Outdated: mild penalty (1 point each, capped at 10)
        score -= (self.outdated_components as f32 * 1.0).min(10.0);

        Some(score.clamp(0.0, 100.0))
    }
}

// ============================================================================
// Cryptography Metrics
// ============================================================================

/// Cryptographic asset metrics for quantum readiness and crypto hygiene assessment.
///
/// Computed from components with `component_type == Cryptographic` and
/// populated `crypto_properties`. Returns `None` for quality score when
/// no crypto components are present (N/A-aware).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CryptographyMetrics {
    /// Total number of cryptographic-asset components
    pub total_crypto_components: usize,
    /// Number of algorithm assets
    pub algorithms_count: usize,
    /// Number of certificate assets
    pub certificates_count: usize,
    /// Number of key material assets
    pub keys_count: usize,
    /// Number of protocol assets
    pub protocols_count: usize,
    /// Algorithms with `nistQuantumSecurityLevel > 0`
    pub quantum_safe_count: usize,
    /// Algorithms with `nistQuantumSecurityLevel == 0`
    pub quantum_vulnerable_count: usize,
    /// Algorithms flagged as weak/broken (MD5, SHA-1, DES, etc.)
    pub weak_algorithm_count: usize,
    /// Hybrid PQC combiner algorithms
    pub hybrid_pqc_count: usize,
    /// Certificates past `notValidAfter`
    pub expired_certificates: usize,
    /// Certificates expiring within 90 days
    pub expiring_soon_certificates: usize,
    /// Key material in `compromised` state
    pub compromised_keys: usize,
    /// Symmetric keys < 128 bits or asymmetric keys below recommended minimum
    pub inadequate_key_sizes: usize,
    /// Names of weak/broken algorithms found
    pub weak_algorithm_names: Vec<String>,

    // --- Algorithm completeness (slot 1: Crpt) ---
    /// Algorithms with an OID identifier
    pub algorithms_with_oid: usize,
    /// Algorithms with `algorithm_family` set
    pub algorithms_with_family: usize,
    /// Algorithms with a recognized primitive (not `Other`)
    pub algorithms_with_primitive: usize,
    /// Algorithms with classical or quantum security level set
    pub algorithms_with_security_level: usize,

    // --- Cross-reference resolution (slot 4: Refs) ---
    /// Certificates with `signature_algorithm_ref` set
    pub certs_with_signature_algo_ref: usize,
    /// Keys with `algorithm_ref` set
    pub keys_with_algorithm_ref: usize,
    /// Protocols with at least one cipher suite
    pub protocols_with_cipher_suites: usize,

    // --- Key lifecycle (slot 5: Life) ---
    /// Keys with `state` tracked
    pub keys_with_state: usize,
    /// Keys with `secured_by` protection
    pub keys_with_protection: usize,
    /// Keys with `creation_date` or `activation_date`
    pub keys_with_lifecycle_dates: usize,

    // --- Certificate health (slot 5: Life) ---
    /// Certificates with both `not_valid_before` and `not_valid_after`
    pub certs_with_validity_dates: usize,
}

impl CryptographyMetrics {
    /// Compute cryptography metrics from an SBOM.
    #[must_use]
    pub fn from_sbom(sbom: &NormalizedSbom) -> Self {
        let mut m = Self::default();

        for comp in sbom.components.values() {
            if comp.component_type != ComponentType::Cryptographic {
                continue;
            }
            m.total_crypto_components += 1;

            let Some(cp) = &comp.crypto_properties else {
                continue;
            };

            match cp.asset_type {
                CryptoAssetType::Algorithm => {
                    m.algorithms_count += 1;
                    if cp.oid.is_some() {
                        m.algorithms_with_oid += 1;
                    }
                    if let Some(algo) = &cp.algorithm_properties {
                        if algo.algorithm_family.is_some() {
                            m.algorithms_with_family += 1;
                        }
                        if !matches!(algo.primitive, CryptoPrimitive::Other(_)) {
                            m.algorithms_with_primitive += 1;
                        }
                        if algo.classical_security_level.is_some()
                            || algo.nist_quantum_security_level.is_some()
                        {
                            m.algorithms_with_security_level += 1;
                        }
                        if algo.is_quantum_safe() {
                            m.quantum_safe_count += 1;
                        } else if algo.nist_quantum_security_level == Some(0) {
                            m.quantum_vulnerable_count += 1;
                        }
                        if algo.is_weak_by_name(&comp.name) {
                            m.weak_algorithm_count += 1;
                            m.weak_algorithm_names.push(comp.name.clone());
                        }
                        if algo.is_hybrid_pqc() {
                            m.hybrid_pqc_count += 1;
                        }
                    }
                }
                CryptoAssetType::Certificate => {
                    m.certificates_count += 1;
                    if let Some(cert) = &cp.certificate_properties {
                        if cert.not_valid_before.is_some() && cert.not_valid_after.is_some() {
                            m.certs_with_validity_dates += 1;
                        }
                        if cert.signature_algorithm_ref.is_some() {
                            m.certs_with_signature_algo_ref += 1;
                        }
                        if cert.is_expired() {
                            m.expired_certificates += 1;
                        } else if cert.is_expiring_soon(90) {
                            m.expiring_soon_certificates += 1;
                        }
                    }
                }
                CryptoAssetType::RelatedCryptoMaterial => {
                    m.keys_count += 1;
                    if let Some(mat) = &cp.related_crypto_material_properties {
                        if mat.state.is_some() {
                            m.keys_with_state += 1;
                        }
                        if mat.secured_by.is_some() {
                            m.keys_with_protection += 1;
                        }
                        if mat.creation_date.is_some() || mat.activation_date.is_some() {
                            m.keys_with_lifecycle_dates += 1;
                        }
                        if mat.algorithm_ref.is_some() {
                            m.keys_with_algorithm_ref += 1;
                        }
                        if mat.state == Some(CryptoMaterialState::Compromised) {
                            m.compromised_keys += 1;
                        }
                        // Flag inadequate key sizes
                        if let Some(size) = mat.size {
                            let is_symmetric = matches!(
                                mat.material_type,
                                crate::model::CryptoMaterialType::SymmetricKey
                                    | crate::model::CryptoMaterialType::SecretKey
                            );
                            if (is_symmetric && size < 128) || (!is_symmetric && size < 2048) {
                                m.inadequate_key_sizes += 1;
                            }
                        }
                    }
                }
                CryptoAssetType::Protocol => {
                    m.protocols_count += 1;
                    if let Some(proto) = &cp.protocol_properties
                        && !proto.cipher_suites.is_empty()
                    {
                        m.protocols_with_cipher_suites += 1;
                    }
                }
                _ => {}
            }
        }

        m
    }

    /// Whether any crypto components exist (i.e., CBOM data is present).
    #[must_use]
    pub fn has_data(&self) -> bool {
        self.total_crypto_components > 0
    }

    /// Percentage of algorithms that are quantum-safe (0-100).
    /// Returns 100 if no algorithms are present.
    #[must_use]
    pub fn quantum_readiness_score(&self) -> f32 {
        if self.algorithms_count == 0 {
            return 100.0;
        }
        (self.quantum_safe_count as f32 / self.algorithms_count as f32) * 100.0
    }

    /// Quality score (0-100) based on crypto hygiene. Returns `None` if no crypto data.
    #[must_use]
    pub fn quality_score(&self) -> Option<f32> {
        if !self.has_data() {
            return None;
        }

        let mut score = 100.0_f32;

        // Weak algorithms: severe penalty (15 each, capped at 50)
        score -= (self.weak_algorithm_count as f32 * 15.0).min(50.0);
        // Quantum-vulnerable: moderate penalty (8 each, capped at 40)
        score -= (self.quantum_vulnerable_count as f32 * 8.0).min(40.0);
        // Expired certs: moderate penalty (10 each, capped at 30)
        score -= (self.expired_certificates as f32 * 10.0).min(30.0);
        // Compromised keys: severe penalty (20 each, capped at 40)
        score -= (self.compromised_keys as f32 * 20.0).min(40.0);
        // Inadequate key sizes: mild penalty (5 each, capped at 20)
        score -= (self.inadequate_key_sizes as f32 * 5.0).min(20.0);
        // Expiring-soon certs: mild penalty (3 each, capped at 15)
        score -= (self.expiring_soon_certificates as f32 * 3.0).min(15.0);
        // Hybrid PQC bonus: +2 each (capped at +10)
        score += (self.hybrid_pqc_count as f32 * 2.0).min(10.0);

        Some(score.clamp(0.0, 100.0))
    }

    // ----- Per-category scores for CBOM ScoringProfile -----

    /// Crypto completeness: how fully documented are the crypto assets?
    #[must_use]
    pub fn crypto_completeness_score(&self) -> f32 {
        if self.algorithms_count == 0 {
            return 100.0;
        }
        let family_pct = self.algorithms_with_family as f32 / self.algorithms_count as f32;
        let primitive_pct = self.algorithms_with_primitive as f32 / self.algorithms_count as f32;
        let level_pct = self.algorithms_with_security_level as f32 / self.algorithms_count as f32;
        (family_pct * 40.0 + primitive_pct * 30.0 + level_pct * 30.0).clamp(0.0, 100.0)
    }

    /// Crypto identifier quality: OID coverage.
    #[must_use]
    pub fn crypto_identifier_score(&self) -> f32 {
        if self.algorithms_count == 0 {
            return 100.0;
        }
        let oid_pct = self.algorithms_with_oid as f32 / self.algorithms_count as f32;
        (oid_pct * 100.0).clamp(0.0, 100.0)
    }

    /// Algorithm strength: penalizes broken/weak/quantum-vulnerable algorithms.
    #[must_use]
    pub fn algorithm_strength_score(&self) -> f32 {
        if self.algorithms_count == 0 {
            return 100.0;
        }
        let mut score = 100.0_f32;
        score -= (self.weak_algorithm_count as f32 * 15.0).min(60.0);
        score -= (self.inadequate_key_sizes as f32 * 8.0).min(30.0);
        if self.algorithms_count > 0 {
            let vuln_pct = self.quantum_vulnerable_count as f32 / self.algorithms_count as f32;
            score -= vuln_pct * 30.0;
        }
        score.clamp(0.0, 100.0)
    }

    /// Crypto dependency references: how well are cert/key/protocol -> algorithm refs resolved?
    #[must_use]
    pub fn crypto_dependency_score(&self) -> f32 {
        let linkable = self.certificates_count + self.keys_count + self.protocols_count;
        if linkable == 0 {
            return 100.0;
        }
        let resolved = self.certs_with_signature_algo_ref
            + self.keys_with_algorithm_ref
            + self.protocols_with_cipher_suites;
        let pct = resolved as f32 / linkable as f32;
        (pct * 100.0).clamp(0.0, 100.0)
    }

    /// Crypto lifecycle: merged key management + certificate health.
    #[must_use]
    pub fn crypto_lifecycle_score(&self) -> f32 {
        let mut score = 100.0_f32;

        if self.keys_count > 0 {
            let state_pct = self.keys_with_state as f32 / self.keys_count as f32;
            let protection_pct = self.keys_with_protection as f32 / self.keys_count as f32;
            let lifecycle_pct = self.keys_with_lifecycle_dates as f32 / self.keys_count as f32;
            let key_completeness =
                (state_pct * 0.4 + protection_pct * 0.3 + lifecycle_pct * 0.3) * 100.0;
            score = score * 0.5 + key_completeness * 0.5;
            score -= (self.compromised_keys as f32 * 20.0).min(40.0);
            score -= (self.inadequate_key_sizes as f32 * 5.0).min(20.0);
        }

        if self.certificates_count > 0 {
            let validity_pct =
                self.certs_with_validity_dates as f32 / self.certificates_count as f32;
            score -= (1.0 - validity_pct) * 15.0;
            score -= (self.expired_certificates as f32 * 15.0).min(45.0);
            score -= (self.expiring_soon_certificates as f32 * 5.0).min(20.0);
        }

        score.clamp(0.0, 100.0)
    }

    /// PQC readiness: quantum migration preparedness.
    #[must_use]
    pub fn pqc_readiness_score(&self) -> f32 {
        if self.algorithms_count == 0 {
            return 100.0;
        }
        let mut score = 0.0_f32;
        let qs_pct = self.quantum_safe_count as f32 / self.algorithms_count as f32;
        score += qs_pct * 60.0;
        if self.hybrid_pqc_count > 0 {
            score += 15.0;
        }
        if self.weak_algorithm_count == 0 {
            score += 25.0;
        } else {
            score += (25.0 - self.weak_algorithm_count as f32 * 5.0).max(0.0);
        }
        score.clamp(0.0, 100.0)
    }

    /// Percentage of algorithms that are quantum-safe (for overview display).
    #[must_use]
    pub fn quantum_readiness_pct(&self) -> f32 {
        if self.algorithms_count == 0 {
            return 0.0;
        }
        (self.quantum_safe_count as f32 / self.algorithms_count as f32) * 100.0
    }

    /// Category labels for CBOM quality chart.
    #[must_use]
    pub const fn cbom_category_labels() -> [&'static str; 8] {
        ["Crpt", "OIDs", "Algo", "Refs", "Life", "PQC", "Prov", "Lic"]
    }
}

// ============================================================================
// Helper functions
// ============================================================================

fn is_valid_purl(purl: &str) -> bool {
    // Basic PURL validation: pkg:type/namespace/name@version
    purl.starts_with("pkg:") && purl.contains('/')
}

fn extract_ecosystem_from_purl(purl: &str) -> Option<String> {
    // Extract type from pkg:type/...
    if let Some(rest) = purl.strip_prefix("pkg:")
        && let Some(slash_idx) = rest.find('/')
    {
        return Some(rest[..slash_idx].to_string());
    }
    None
}

fn is_valid_cpe(cpe: &str) -> bool {
    // Basic CPE validation
    cpe.starts_with("cpe:2.3:") || cpe.starts_with("cpe:/")
}

fn is_valid_spdx_license(expr: &str) -> bool {
    // Common SPDX license identifiers
    const COMMON_SPDX: &[&str] = &[
        "MIT",
        "Apache-2.0",
        "GPL-2.0",
        "GPL-3.0",
        "BSD-2-Clause",
        "BSD-3-Clause",
        "ISC",
        "MPL-2.0",
        "LGPL-2.1",
        "LGPL-3.0",
        "AGPL-3.0",
        "Unlicense",
        "CC0-1.0",
        "0BSD",
        "EPL-2.0",
        "CDDL-1.0",
        "Artistic-2.0",
        "GPL-2.0-only",
        "GPL-2.0-or-later",
        "GPL-3.0-only",
        "GPL-3.0-or-later",
        "LGPL-2.1-only",
        "LGPL-2.1-or-later",
        "LGPL-3.0-only",
        "LGPL-3.0-or-later",
    ];

    // Check for common licenses or expressions
    let trimmed = expr.trim();
    COMMON_SPDX.contains(&trimmed)
        || trimmed.contains(" AND ")
        || trimmed.contains(" OR ")
        || trimmed.contains(" WITH ")
}

/// Whether a license identifier is on the SPDX deprecated list.
///
/// These are license IDs that SPDX has deprecated in favor of more specific
/// identifiers (e.g., `GPL-2.0` → `GPL-2.0-only` or `GPL-2.0-or-later`).
fn is_deprecated_spdx_license(expr: &str) -> bool {
    const DEPRECATED: &[&str] = &[
        "GPL-2.0",
        "GPL-2.0+",
        "GPL-3.0",
        "GPL-3.0+",
        "LGPL-2.0",
        "LGPL-2.0+",
        "LGPL-2.1",
        "LGPL-2.1+",
        "LGPL-3.0",
        "LGPL-3.0+",
        "AGPL-1.0",
        "AGPL-3.0",
        "GFDL-1.1",
        "GFDL-1.2",
        "GFDL-1.3",
        "BSD-2-Clause-FreeBSD",
        "BSD-2-Clause-NetBSD",
        "eCos-2.0",
        "Nunit",
        "StandardML-NJ",
        "wxWindows",
    ];
    let trimmed = expr.trim();
    DEPRECATED.contains(&trimmed)
}

/// Whether a license is considered restrictive/copyleft (GPL family).
///
/// This is informational — restrictive licenses are not inherently a quality
/// issue, but organizations need to know about them for compliance.
fn is_restrictive_license(expr: &str) -> bool {
    let trimmed = expr.trim().to_uppercase();
    trimmed.starts_with("GPL")
        || trimmed.starts_with("LGPL")
        || trimmed.starts_with("AGPL")
        || trimmed.starts_with("EUPL")
        || trimmed.starts_with("SSPL")
        || trimmed.starts_with("OSL")
        || trimmed.starts_with("CPAL")
        || trimmed.starts_with("CC-BY-SA")
        || trimmed.starts_with("CC-BY-NC")
}

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

    #[test]
    fn test_purl_validation() {
        assert!(is_valid_purl("pkg:npm/@scope/name@1.0.0"));
        assert!(is_valid_purl("pkg:maven/group/artifact@1.0"));
        assert!(!is_valid_purl("npm:something"));
        assert!(!is_valid_purl("invalid"));
    }

    #[test]
    fn test_cpe_validation() {
        assert!(is_valid_cpe("cpe:2.3:a:vendor:product:1.0:*:*:*:*:*:*:*"));
        assert!(is_valid_cpe("cpe:/a:vendor:product:1.0"));
        assert!(!is_valid_cpe("something:else"));
    }

    #[test]
    fn test_spdx_license_validation() {
        assert!(is_valid_spdx_license("MIT"));
        assert!(is_valid_spdx_license("Apache-2.0"));
        assert!(is_valid_spdx_license("MIT AND Apache-2.0"));
        assert!(is_valid_spdx_license("GPL-2.0 OR MIT"));
    }

    #[test]
    fn test_strong_hash_classification() {
        assert!(is_strong_hash(&HashAlgorithm::Sha256));
        assert!(is_strong_hash(&HashAlgorithm::Sha3_256));
        assert!(is_strong_hash(&HashAlgorithm::Blake3));
        assert!(!is_strong_hash(&HashAlgorithm::Md5));
        assert!(!is_strong_hash(&HashAlgorithm::Sha1));
        assert!(!is_strong_hash(&HashAlgorithm::Other("custom".to_string())));
    }

    #[test]
    fn test_deprecated_license_detection() {
        assert!(is_deprecated_spdx_license("GPL-2.0"));
        assert!(is_deprecated_spdx_license("LGPL-2.1"));
        assert!(is_deprecated_spdx_license("AGPL-3.0"));
        assert!(!is_deprecated_spdx_license("GPL-2.0-only"));
        assert!(!is_deprecated_spdx_license("MIT"));
        assert!(!is_deprecated_spdx_license("Apache-2.0"));
    }

    #[test]
    fn test_restrictive_license_detection() {
        assert!(is_restrictive_license("GPL-3.0-only"));
        assert!(is_restrictive_license("LGPL-2.1-or-later"));
        assert!(is_restrictive_license("AGPL-3.0-only"));
        assert!(is_restrictive_license("EUPL-1.2"));
        assert!(is_restrictive_license("CC-BY-SA-4.0"));
        assert!(!is_restrictive_license("MIT"));
        assert!(!is_restrictive_license("Apache-2.0"));
        assert!(!is_restrictive_license("BSD-3-Clause"));
    }

    #[test]
    fn test_hash_quality_score_no_components() {
        let metrics = HashQualityMetrics {
            components_with_any_hash: 0,
            components_with_strong_hash: 0,
            components_with_weak_only: 0,
            algorithm_distribution: BTreeMap::new(),
            total_hashes: 0,
        };
        assert_eq!(metrics.quality_score(0), 0.0);
    }

    #[test]
    fn test_hash_quality_score_all_strong() {
        let metrics = HashQualityMetrics {
            components_with_any_hash: 10,
            components_with_strong_hash: 10,
            components_with_weak_only: 0,
            algorithm_distribution: BTreeMap::new(),
            total_hashes: 10,
        };
        assert_eq!(metrics.quality_score(10), 100.0);
    }

    #[test]
    fn test_hash_quality_score_weak_only_penalty() {
        let metrics = HashQualityMetrics {
            components_with_any_hash: 10,
            components_with_strong_hash: 0,
            components_with_weak_only: 10,
            algorithm_distribution: BTreeMap::new(),
            total_hashes: 10,
        };
        // 60 (any) + 0 (strong) - 10 (weak penalty) = 50
        assert_eq!(metrics.quality_score(10), 50.0);
    }

    #[test]
    fn test_lifecycle_no_enrichment_returns_none() {
        let metrics = LifecycleMetrics {
            eol_components: 0,
            stale_components: 0,
            deprecated_components: 0,
            archived_components: 0,
            outdated_components: 0,
            enriched_components: 0,
            enrichment_coverage: 0.0,
        };
        assert!(!metrics.has_data());
        assert!(metrics.quality_score().is_none());
    }

    #[test]
    fn test_lifecycle_with_eol_penalty() {
        let metrics = LifecycleMetrics {
            eol_components: 2,
            stale_components: 0,
            deprecated_components: 0,
            archived_components: 0,
            outdated_components: 0,
            enriched_components: 10,
            enrichment_coverage: 100.0,
        };
        // 100 - 30 (2 * 15) = 70
        assert_eq!(metrics.quality_score(), Some(70.0));
    }

    #[test]
    fn test_cycle_detection_no_cycles() {
        let children: HashMap<&str, Vec<&str>> =
            HashMap::from([("a", vec!["b"]), ("b", vec!["c"])]);
        let all_nodes = vec!["a", "b", "c"];
        assert_eq!(detect_cycles(&all_nodes, &children), 0);
    }

    #[test]
    fn test_cycle_detection_with_cycle() {
        let children: HashMap<&str, Vec<&str>> =
            HashMap::from([("a", vec!["b"]), ("b", vec!["c"]), ("c", vec!["a"])]);
        let all_nodes = vec!["a", "b", "c"];
        assert_eq!(detect_cycles(&all_nodes, &children), 1);
    }

    #[test]
    fn test_depth_computation() {
        let children: HashMap<&str, Vec<&str>> =
            HashMap::from([("root", vec!["a", "b"]), ("a", vec!["c"])]);
        let roots = vec!["root"];
        let (max_d, avg_d) = compute_depth(&roots, &children);
        assert_eq!(max_d, Some(2)); // root -> a -> c
        assert!(avg_d.is_some());
    }

    #[test]
    fn test_depth_empty_roots() {
        let children: HashMap<&str, Vec<&str>> = HashMap::new();
        let roots: Vec<&str> = vec![];
        let (max_d, avg_d) = compute_depth(&roots, &children);
        assert_eq!(max_d, None);
        assert_eq!(avg_d, None);
    }

    #[test]
    fn test_provenance_quality_score() {
        let metrics = ProvenanceMetrics {
            has_tool_creator: true,
            has_tool_version: true,
            has_org_creator: true,
            has_contact_email: true,
            has_serial_number: true,
            has_document_name: true,
            timestamp_age_days: 10,
            is_fresh: true,
            has_primary_component: true,
            lifecycle_phase: Some("build".to_string()),
            completeness_declaration: CompletenessDeclaration::Complete,
            has_signature: true,
            has_citations: true,
            citations_count: 3,
        };
        // All checks pass for CycloneDX
        assert_eq!(metrics.quality_score(true), 100.0);
    }

    #[test]
    fn test_provenance_score_without_cyclonedx() {
        let metrics = ProvenanceMetrics {
            has_tool_creator: true,
            has_tool_version: true,
            has_org_creator: true,
            has_contact_email: true,
            has_serial_number: true,
            has_document_name: true,
            timestamp_age_days: 10,
            is_fresh: true,
            has_primary_component: true,
            lifecycle_phase: None,
            completeness_declaration: CompletenessDeclaration::Complete,
            has_signature: true,
            has_citations: false,
            citations_count: 0,
        };
        // Lifecycle phase and citations excluded for non-CDX
        assert_eq!(metrics.quality_score(false), 100.0);
    }

    #[test]
    fn test_complexity_empty_graph() {
        let (simplicity, level, factors) = compute_complexity(0, 0, 0, 0, 0, 0, 0);
        assert_eq!(simplicity, 100.0);
        assert_eq!(level, ComplexityLevel::Low);
        assert_eq!(factors.dependency_volume, 0.0);
    }

    #[test]
    fn test_complexity_single_node() {
        // 1 component, no edges, no cycles, 1 orphan, 1 island
        let (simplicity, level, _) = compute_complexity(0, 1, 0, 0, 0, 1, 1);
        assert!(
            simplicity >= 80.0,
            "Single node simplicity {simplicity} should be >= 80"
        );
        assert_eq!(level, ComplexityLevel::Low);
    }

    #[test]
    fn test_complexity_monotonic_edges() {
        // More edges should never increase simplicity
        let (s1, _, _) = compute_complexity(5, 10, 2, 3, 0, 1, 1);
        let (s2, _, _) = compute_complexity(20, 10, 2, 3, 0, 1, 1);
        assert!(
            s2 <= s1,
            "More edges should not increase simplicity: {s2} vs {s1}"
        );
    }

    #[test]
    fn test_complexity_monotonic_cycles() {
        let (s1, _, _) = compute_complexity(10, 10, 2, 3, 0, 1, 1);
        let (s2, _, _) = compute_complexity(10, 10, 2, 3, 3, 1, 1);
        assert!(
            s2 <= s1,
            "More cycles should not increase simplicity: {s2} vs {s1}"
        );
    }

    #[test]
    fn test_complexity_monotonic_depth() {
        let (s1, _, _) = compute_complexity(10, 10, 2, 3, 0, 1, 1);
        let (s2, _, _) = compute_complexity(10, 10, 10, 3, 0, 1, 1);
        assert!(
            s2 <= s1,
            "More depth should not increase simplicity: {s2} vs {s1}"
        );
    }

    #[test]
    fn test_complexity_graph_skipped() {
        // When graph_analysis_skipped, DependencyMetrics should have None complexity fields.
        // We test compute_complexity separately; the from_sbom integration handles the None case.
        let (simplicity, _, _) = compute_complexity(100, 50, 5, 10, 2, 5, 3);
        assert!(simplicity >= 0.0 && simplicity <= 100.0);
    }

    #[test]
    fn test_complexity_level_bands() {
        assert_eq!(ComplexityLevel::from_score(100.0), ComplexityLevel::Low);
        assert_eq!(ComplexityLevel::from_score(75.0), ComplexityLevel::Low);
        assert_eq!(ComplexityLevel::from_score(74.0), ComplexityLevel::Moderate);
        assert_eq!(ComplexityLevel::from_score(50.0), ComplexityLevel::Moderate);
        assert_eq!(ComplexityLevel::from_score(49.0), ComplexityLevel::High);
        assert_eq!(ComplexityLevel::from_score(25.0), ComplexityLevel::High);
        assert_eq!(ComplexityLevel::from_score(24.0), ComplexityLevel::VeryHigh);
        assert_eq!(ComplexityLevel::from_score(0.0), ComplexityLevel::VeryHigh);
    }

    #[test]
    fn test_completeness_declaration_display() {
        assert_eq!(CompletenessDeclaration::Complete.to_string(), "complete");
        assert_eq!(
            CompletenessDeclaration::IncompleteFirstPartyOnly.to_string(),
            "incomplete (first-party only)"
        );
        assert_eq!(CompletenessDeclaration::Unknown.to_string(), "unknown");
    }

    // ── CryptographyMetrics scoring tests ──

    #[test]
    fn crypto_completeness_all_documented() {
        let m = CryptographyMetrics {
            algorithms_count: 4,
            algorithms_with_family: 4,
            algorithms_with_primitive: 4,
            algorithms_with_security_level: 4,
            ..Default::default()
        };
        let score = m.crypto_completeness_score();
        assert!(
            (score - 100.0).abs() < 0.1,
            "fully documented → 100, got {score}"
        );
    }

    #[test]
    fn crypto_completeness_partial() {
        let m = CryptographyMetrics {
            algorithms_count: 4,
            algorithms_with_family: 2,         // 50%
            algorithms_with_primitive: 4,      // 100%
            algorithms_with_security_level: 0, // 0%
            ..Default::default()
        };
        // 0.5*40 + 1.0*30 + 0.0*30 = 20+30+0 = 50
        let score = m.crypto_completeness_score();
        assert!((score - 50.0).abs() < 0.1, "partial → 50, got {score}");
    }

    #[test]
    fn crypto_identifier_full_oid_coverage() {
        let m = CryptographyMetrics {
            algorithms_count: 5,
            algorithms_with_oid: 5,
            ..Default::default()
        };
        assert!((m.crypto_identifier_score() - 100.0).abs() < 0.1);
    }

    #[test]
    fn crypto_identifier_no_oids() {
        let m = CryptographyMetrics {
            algorithms_count: 5,
            algorithms_with_oid: 0,
            ..Default::default()
        };
        assert!((m.crypto_identifier_score() - 0.0).abs() < 0.1);
    }

    #[test]
    fn algorithm_strength_weak_penalty() {
        let m = CryptographyMetrics {
            algorithms_count: 5,
            weak_algorithm_count: 2,
            ..Default::default()
        };
        // 100 - 2*15 = 70
        let score = m.algorithm_strength_score();
        assert!((score - 70.0).abs() < 0.1, "2 weak → 70, got {score}");
    }

    #[test]
    fn algorithm_strength_quantum_vulnerable() {
        let m = CryptographyMetrics {
            algorithms_count: 10,
            quantum_vulnerable_count: 10,
            ..Default::default()
        };
        // 100 - (10/10)*30 = 70
        let score = m.algorithm_strength_score();
        assert!(
            (score - 70.0).abs() < 0.1,
            "all quantum vuln → 70, got {score}"
        );
    }

    #[test]
    fn crypto_lifecycle_compromised_keys() {
        let m = CryptographyMetrics {
            keys_count: 3,
            keys_with_state: 3,
            keys_with_protection: 3,
            keys_with_lifecycle_dates: 3,
            compromised_keys: 1,
            ..Default::default()
        };
        let score = m.crypto_lifecycle_score();
        // With full key completeness: 100*0.5 + 100*0.5 = 100, then -20 penalty
        assert!(score < 85.0);
        assert!(score > 50.0);
    }

    #[test]
    fn crypto_lifecycle_expired_certs() {
        let m = CryptographyMetrics {
            certificates_count: 4,
            certs_with_validity_dates: 4,
            expired_certificates: 2,
            expiring_soon_certificates: 1,
            ..Default::default()
        };
        let score = m.crypto_lifecycle_score();
        // 100 - 2*15 - 1*5 = 100 - 30 - 5 = 65
        assert!(score < 70.0);
    }

    #[test]
    fn pqc_readiness_all_quantum_safe() {
        let m = CryptographyMetrics {
            algorithms_count: 5,
            quantum_safe_count: 5,
            hybrid_pqc_count: 2,
            weak_algorithm_count: 0,
            ..Default::default()
        };
        // (5/5)*60 + 15 + 25 = 100
        let score = m.pqc_readiness_score();
        assert!(
            (score - 100.0).abs() < 0.1,
            "all safe + hybrid → 100, got {score}"
        );
    }

    #[test]
    fn pqc_readiness_no_quantum_safe() {
        let m = CryptographyMetrics {
            algorithms_count: 5,
            quantum_safe_count: 0,
            hybrid_pqc_count: 0,
            weak_algorithm_count: 0,
            ..Default::default()
        };
        // 0*60 + 0 + 25 = 25
        let score = m.pqc_readiness_score();
        assert!(
            (score - 25.0).abs() < 0.1,
            "no safe, no weak → 25, got {score}"
        );
    }

    #[test]
    fn crypto_dependency_all_resolved() {
        let m = CryptographyMetrics {
            certificates_count: 2,
            keys_count: 3,
            protocols_count: 1,
            certs_with_signature_algo_ref: 2,
            keys_with_algorithm_ref: 3,
            protocols_with_cipher_suites: 1,
            ..Default::default()
        };
        assert!((m.crypto_dependency_score() - 100.0).abs() < 0.1);
    }

    #[test]
    fn crypto_dependency_none_resolved() {
        let m = CryptographyMetrics {
            certificates_count: 2,
            keys_count: 3,
            protocols_count: 1,
            ..Default::default()
        };
        assert!((m.crypto_dependency_score() - 0.0).abs() < 0.1);
    }

    #[test]
    fn quality_score_none_when_no_crypto() {
        let m = CryptographyMetrics::default();
        assert!(m.quality_score().is_none());
    }

    #[test]
    fn quantum_readiness_pct_zero_algorithms() {
        let m = CryptographyMetrics::default();
        assert!((m.quantum_readiness_pct() - 0.0).abs() < 0.01);
    }
}