sbom-tools 0.1.22

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
//! SBOM Quality Scorer.
//!
//! Main scoring engine that combines metrics and compliance checking
//! into an overall quality assessment.

use crate::model::{CompletenessDeclaration, NormalizedSbom, SbomFormat};
use serde::{Deserialize, Serialize};
use serde_json::Value;

use super::compliance::{ComplianceChecker, ComplianceLevel, ComplianceResult};
use super::metrics::{
    AuditabilityMetrics, CompletenessMetrics, CompletenessWeights, CryptographyMetrics,
    DependencyMetrics, HashQualityMetrics, IdentifierMetrics, LicenseMetrics, LifecycleMetrics,
    ProvenanceMetrics, VulnerabilityMetrics,
};

/// Quality scoring engine version
pub const SCORING_ENGINE_VERSION: &str = "2.1";

/// Returns true if any of the JSON pointers resolves to a non-empty value in `raw`.
/// Used by the AI-readiness profile to inspect model-card fields preserved in
/// `Component.extensions.raw` that are not surfaced into the typed model.
fn has_non_empty_pointer(raw: Option<&Value>, pointers: &[&str]) -> bool {
    pointers
        .iter()
        .filter_map(|pointer| raw.and_then(|value| value.pointer(pointer)))
        .any(|value| match value {
            Value::Null => false,
            Value::Array(items) => !items.is_empty(),
            Value::Object(entries) => !entries.is_empty(),
            Value::String(text) => !text.trim().is_empty(),
            _ => true,
        })
}

/// Returns true if a component is connected to the vulnerability/exploitability
/// tooling stack: it carries at least one vulnerability reference (which
/// OSV/KEV/EPSS/VEX enrichment acts on) OR a security/advisory external
/// reference an analyst can pivot on. This realizes the BSI thesis that an AI
/// SBOM is only useful when linked to cybersecurity tooling.
fn ml_has_exploitability_reference(component: &crate::model::Component) -> bool {
    use crate::model::ExternalRefType;
    if !component.vulnerabilities.is_empty() {
        return true;
    }
    component.external_refs.iter().any(|r| {
        matches!(
            r.ref_type,
            ExternalRefType::Advisories
                | ExternalRefType::SecurityContact
                | ExternalRefType::VulnerabilityAssertion
                | ExternalRefType::ExploitabilityStatement
        )
    })
}

/// Scoring profile determines weights and thresholds
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum ScoringProfile {
    /// Minimal requirements - basic identification
    Minimal,
    /// Standard requirements - recommended for most use cases
    Standard,
    /// Security-focused - emphasizes vulnerability info and supply chain
    Security,
    /// License-focused - emphasizes license compliance
    LicenseCompliance,
    /// EU Cyber Resilience Act - emphasizes supply chain transparency and security disclosure
    Cra,
    /// BSI TR-03183-2 (German national CRA-aligned SBOM technical guideline).
    /// Stricter than CRA on hashes and identifiers; uses CRA-style weights.
    BsiTr03183_2,
    /// Comprehensive - all aspects equally weighted
    Comprehensive,
    /// CBOM - cryptographic BOM focus (algorithm strength, PQC readiness, key/cert lifecycle)
    Cbom,
    /// AI/ML readiness - evaluates model-card completeness for machine-learning components
    AiReadiness,
}

impl ScoringProfile {
    /// Get the compliance level associated with this profile
    #[must_use]
    pub const fn compliance_level(&self) -> ComplianceLevel {
        match self {
            Self::Minimal => ComplianceLevel::Minimum,
            Self::Standard | Self::LicenseCompliance => ComplianceLevel::Standard,
            Self::Security => ComplianceLevel::NtiaMinimum,
            Self::Cra => ComplianceLevel::CraPhase2,
            Self::BsiTr03183_2 => ComplianceLevel::BsiTr03183_2,
            Self::Comprehensive => ComplianceLevel::Comprehensive,
            Self::Cbom => ComplianceLevel::Comprehensive,
            Self::AiReadiness => ComplianceLevel::Comprehensive,
        }
    }

    /// Get weights for this profile
    ///
    /// All weights sum to 1.0. The lifecycle weight is applied only when
    /// enrichment data is available; otherwise it is redistributed.
    const fn weights(self) -> ScoringWeights {
        match self {
            Self::Minimal => ScoringWeights {
                completeness: 0.35,
                identifiers: 0.20,
                licenses: 0.10,
                vulnerabilities: 0.05,
                dependencies: 0.10,
                integrity: 0.05,
                provenance: 0.10,
                lifecycle: 0.05,
            },
            Self::Standard => ScoringWeights {
                completeness: 0.25,
                identifiers: 0.20,
                licenses: 0.12,
                vulnerabilities: 0.08,
                dependencies: 0.10,
                integrity: 0.08,
                provenance: 0.10,
                lifecycle: 0.07,
            },
            Self::Security => ScoringWeights {
                completeness: 0.12,
                identifiers: 0.18,
                licenses: 0.05,
                vulnerabilities: 0.20,
                dependencies: 0.10,
                integrity: 0.15,
                provenance: 0.10,
                lifecycle: 0.10,
            },
            Self::LicenseCompliance => ScoringWeights {
                completeness: 0.15,
                identifiers: 0.12,
                licenses: 0.35,
                vulnerabilities: 0.05,
                dependencies: 0.10,
                integrity: 0.05,
                provenance: 0.10,
                lifecycle: 0.08,
            },
            Self::Cra => ScoringWeights {
                completeness: 0.12,
                identifiers: 0.18,
                licenses: 0.08,
                vulnerabilities: 0.15,
                dependencies: 0.12,
                integrity: 0.12,
                provenance: 0.15,
                lifecycle: 0.08,
            },
            // BSI TR-03183-2 emphasises identifiers and integrity (mandatory hashes)
            // even more than CRA, while still tracking provenance/dependencies.
            Self::BsiTr03183_2 => ScoringWeights {
                completeness: 0.10,
                identifiers: 0.22,
                licenses: 0.08,
                vulnerabilities: 0.10,
                dependencies: 0.12,
                integrity: 0.18,
                provenance: 0.12,
                lifecycle: 0.08,
            },
            Self::Comprehensive => ScoringWeights {
                completeness: 0.15,
                identifiers: 0.13,
                licenses: 0.13,
                vulnerabilities: 0.10,
                dependencies: 0.12,
                integrity: 0.12,
                provenance: 0.13,
                lifecycle: 0.12,
            },
            // CBOM slots are reinterpreted:
            // completeness->CryptoCompl, identifiers->OIDs, licenses->AlgoStrength,
            // vulnerabilities->CryptoRefs, dependencies->CryptoLifecycle,
            // integrity->PQCReadiness, provenance->Provenance(std), lifecycle->Licenses(std)
            Self::Cbom => ScoringWeights {
                completeness: 0.15,
                identifiers: 0.15,
                licenses: 0.22,
                vulnerabilities: 0.10,
                dependencies: 0.13,
                integrity: 0.15,
                provenance: 0.08,
                lifecycle: 0.02,
            },
            // AiReadiness uses a dedicated scoring path; these weights are only a
            // structural fallback and are never reached in normal execution.
            Self::AiReadiness => ScoringWeights {
                completeness: 0.25,
                identifiers: 0.15,
                licenses: 0.15,
                vulnerabilities: 0.10,
                dependencies: 0.10,
                integrity: 0.08,
                provenance: 0.10,
                lifecycle: 0.07,
            },
        }
    }
}

/// Weights for overall score calculation (sum to 1.0)
#[derive(Debug, Clone)]
struct ScoringWeights {
    completeness: f32,
    identifiers: f32,
    licenses: f32,
    vulnerabilities: f32,
    dependencies: f32,
    integrity: f32,
    provenance: f32,
    lifecycle: f32,
}

impl ScoringWeights {
    /// Return weights as an array for iteration
    fn as_array(&self) -> [f32; 8] {
        [
            self.completeness,
            self.identifiers,
            self.licenses,
            self.vulnerabilities,
            self.dependencies,
            self.integrity,
            self.provenance,
            self.lifecycle,
        ]
    }

    /// Renormalize weights, excluding categories marked as N/A.
    ///
    /// When a category has no applicable data (e.g., lifecycle without
    /// enrichment), its weight is proportionally redistributed.
    fn renormalize(&self, available: &[bool; 8]) -> [f32; 8] {
        let raw = self.as_array();
        let total_available: f32 = raw
            .iter()
            .zip(available)
            .filter(|&(_, a)| *a)
            .map(|(w, _)| w)
            .sum();

        if total_available <= 0.0 {
            return [0.0; 8];
        }

        let scale = 1.0 / total_available;
        let mut result = [0.0_f32; 8];
        for (i, (&w, &avail)) in raw.iter().zip(available).enumerate() {
            result[i] = if avail { w * scale } else { 0.0 };
        }
        result
    }
}

/// Quality grade based on score
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum QualityGrade {
    /// Excellent: 90-100
    A,
    /// Good: 80-89
    B,
    /// Fair: 70-79
    C,
    /// Poor: 60-69
    D,
    /// Failing: <60
    F,
}

impl QualityGrade {
    /// Create grade from score
    #[must_use]
    pub const fn from_score(score: f32) -> Self {
        // Guard against NaN (all comparisons return false) and out-of-range values
        let clamped = if score > 100.0 {
            100
        } else if score >= 0.0 {
            score as u32
        } else {
            0
        };
        match clamped {
            90..=100 => Self::A,
            80..=89 => Self::B,
            70..=79 => Self::C,
            60..=69 => Self::D,
            _ => Self::F,
        }
    }

    /// Get grade letter
    #[must_use]
    pub const fn letter(&self) -> &'static str {
        match self {
            Self::A => "A",
            Self::B => "B",
            Self::C => "C",
            Self::D => "D",
            Self::F => "F",
        }
    }

    /// Get grade description
    #[must_use]
    pub const fn description(&self) -> &'static str {
        match self {
            Self::A => "Excellent",
            Self::B => "Good",
            Self::C => "Fair",
            Self::D => "Poor",
            Self::F => "Failing",
        }
    }
}

/// Recommendation for improving quality
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Recommendation {
    /// Priority (1 = highest, 5 = lowest)
    pub priority: u8,
    /// Category of the recommendation
    pub category: RecommendationCategory,
    /// Human-readable message
    pub message: String,
    /// Estimated impact on score (0-100)
    pub impact: f32,
    /// Affected components (if applicable)
    pub affected_count: usize,
}

/// Single AI-readiness check result
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct AiCheck {
    /// Machine-readable ID, e.g. "AI-001"
    pub id: String,
    /// Human-readable name
    pub name: String,
    /// Whether the check passed for every ML component
    pub passed: bool,
    /// Optional detail message (per-component pass/fail)
    pub detail: Option<String>,
    /// Relative weight of this check (0.0–1.0)
    pub weight: f32,
}

/// AI/ML model-card completeness metrics (populated only for the `AiReadiness` profile)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct AiReadinessMetrics {
    /// Number of ML model components found
    pub ml_component_count: usize,
    /// True when no ML components were found — the score is N/A
    pub not_applicable: bool,
    /// Human-readable reason for N/A (when `not_applicable` is true)
    pub na_reason: Option<String>,
    /// Per-check results
    pub checks: Vec<AiCheck>,
    /// Number of ML components that passed every check
    pub components_fully_documented: usize,
}

impl AiReadinessMetrics {
    /// Whether AI readiness is not applicable to this SBOM (no ML components).
    #[must_use]
    pub const fn is_not_applicable(&self) -> bool {
        self.not_applicable
    }
}

/// Category for recommendations
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum RecommendationCategory {
    Completeness,
    Identifiers,
    Licenses,
    Vulnerabilities,
    Dependencies,
    Compliance,
    Integrity,
    Provenance,
    Lifecycle,
}

impl RecommendationCategory {
    #[must_use]
    pub const fn name(&self) -> &'static str {
        match self {
            Self::Completeness => "Completeness",
            Self::Identifiers => "Identifiers",
            Self::Licenses => "Licenses",
            Self::Vulnerabilities => "Vulnerabilities",
            Self::Dependencies => "Dependencies",
            Self::Compliance => "Compliance",
            Self::Integrity => "Integrity",
            Self::Provenance => "Provenance",
            Self::Lifecycle => "Lifecycle",
        }
    }
}

/// Complete quality report for an SBOM
#[derive(Debug, Clone, Serialize, Deserialize)]
#[must_use]
#[non_exhaustive]
pub struct QualityReport {
    /// Scoring engine version
    pub scoring_engine_version: String,
    /// Overall score (0-100)
    pub overall_score: f32,
    /// Overall grade
    pub grade: QualityGrade,
    /// Scoring profile used
    pub profile: ScoringProfile,

    // Individual category scores (0-100)
    /// Completeness score
    pub completeness_score: f32,
    /// Identifier quality score
    pub identifier_score: f32,
    /// License quality score
    pub license_score: f32,
    /// Vulnerability documentation score (`None` if no vulnerability data)
    pub vulnerability_score: Option<f32>,
    /// Dependency graph quality score
    pub dependency_score: f32,
    /// Hash/integrity quality score
    pub integrity_score: f32,
    /// Provenance quality score (combined provenance + auditability)
    pub provenance_score: f32,
    /// Lifecycle quality score (`None` if no enrichment data)
    pub lifecycle_score: Option<f32>,

    // Detailed metrics
    /// Detailed completeness metrics
    pub completeness_metrics: CompletenessMetrics,
    /// Detailed identifier metrics
    pub identifier_metrics: IdentifierMetrics,
    /// Detailed license metrics
    pub license_metrics: LicenseMetrics,
    /// Detailed vulnerability metrics
    pub vulnerability_metrics: VulnerabilityMetrics,
    /// Detailed dependency metrics
    pub dependency_metrics: DependencyMetrics,
    /// Hash/integrity metrics
    pub hash_quality_metrics: HashQualityMetrics,
    /// Provenance metrics
    pub provenance_metrics: ProvenanceMetrics,
    /// Auditability metrics
    pub auditability_metrics: AuditabilityMetrics,
    /// Lifecycle metrics (enrichment-dependent)
    pub lifecycle_metrics: LifecycleMetrics,
    /// Cryptography quality score (`None` if no crypto components)
    pub cryptography_score: Option<f32>,
    /// Cryptography metrics (CBOM)
    pub cryptography_metrics: CryptographyMetrics,

    /// Compliance check result
    pub compliance: ComplianceResult,
    /// Prioritized recommendations
    pub recommendations: Vec<Recommendation>,
    /// AI/ML readiness metrics (`Some` only when profile is `AiReadiness`)
    pub ai_readiness_metrics: Option<AiReadinessMetrics>,
}

/// Quality scorer for SBOMs
#[derive(Debug, Clone)]
pub struct QualityScorer {
    /// Scoring profile
    profile: ScoringProfile,
    /// Completeness weights
    completeness_weights: CompletenessWeights,
    /// Optional CRA sidecar metadata; when set, the embedded compliance check
    /// (used to drive recommendations under `ScoringProfile::Cra`) consults
    /// the sidecar for fields the SBOM doesn't carry.
    cra_sidecar: Option<crate::model::CraSidecarMetadata>,
    /// Optional CRA Annex III/IV product class. Sidecar `productClass` (when
    /// present on `cra_sidecar`) wins over this value at check time.
    cra_product_class: Option<crate::model::CraProductClass>,
}

impl QualityScorer {
    /// Create a new quality scorer with the given profile
    #[must_use]
    pub fn new(profile: ScoringProfile) -> Self {
        Self {
            profile,
            completeness_weights: CompletenessWeights::default(),
            cra_sidecar: None,
            cra_product_class: None,
        }
    }

    /// Set custom completeness weights
    #[must_use]
    pub const fn with_completeness_weights(mut self, weights: CompletenessWeights) -> Self {
        self.completeness_weights = weights;
        self
    }

    /// Attach CRA sidecar metadata for the embedded compliance check.
    #[must_use]
    pub fn with_cra_sidecar(mut self, sidecar: crate::model::CraSidecarMetadata) -> Self {
        self.cra_sidecar = Some(sidecar);
        self
    }

    /// Set the CRA Annex III/IV product class explicitly (for severity
    /// calibration when the embedded compliance check runs under
    /// `ScoringProfile::Cra`). Sidecar `productClass` overrides this.
    #[must_use]
    pub const fn with_cra_product_class(mut self, class: crate::model::CraProductClass) -> Self {
        self.cra_product_class = Some(class);
        self
    }

    /// Score an SBOM
    pub fn score(&self, sbom: &NormalizedSbom) -> QualityReport {
        // AI readiness uses a dedicated scoring path that is incompatible with the
        // standard 8-category pipeline.
        if self.profile == ScoringProfile::AiReadiness {
            return self.score_ai_readiness(sbom);
        }

        let total_components = sbom.components.len();
        let is_cyclonedx = sbom.document.format == SbomFormat::CycloneDx;

        // Calculate all metrics
        let completeness_metrics = CompletenessMetrics::from_sbom(sbom);
        let identifier_metrics = IdentifierMetrics::from_sbom(sbom);
        let license_metrics = LicenseMetrics::from_sbom(sbom);
        let vulnerability_metrics = VulnerabilityMetrics::from_sbom(sbom);
        let dependency_metrics = DependencyMetrics::from_sbom(sbom);
        let hash_quality_metrics = HashQualityMetrics::from_sbom(sbom);
        let provenance_metrics = ProvenanceMetrics::from_sbom(sbom);
        let auditability_metrics = AuditabilityMetrics::from_sbom(sbom);
        let lifecycle_metrics = LifecycleMetrics::from_sbom(sbom);
        let cryptography_metrics = CryptographyMetrics::from_sbom(sbom);

        // Calculate individual category scores
        let completeness_score = completeness_metrics.overall_score(&self.completeness_weights);
        let identifier_score = identifier_metrics.quality_score(total_components);
        let license_score = license_metrics.quality_score(total_components);
        let vulnerability_score = vulnerability_metrics.documentation_score();
        let dependency_score = dependency_metrics.quality_score(total_components);
        let integrity_score = hash_quality_metrics.quality_score(total_components);
        let provenance_raw = provenance_metrics.quality_score(is_cyclonedx);
        let auditability_raw = auditability_metrics.quality_score(total_components);
        // Combine provenance and auditability (60/40 split)
        let provenance_score = provenance_raw * 0.6 + auditability_raw * 0.4;
        let lifecycle_score = lifecycle_metrics.quality_score();
        let cryptography_score = cryptography_metrics.quality_score();

        // For CBOM profile, substitute crypto-specific scores into the 8 slots
        let is_cbom = self.profile == ScoringProfile::Cbom;
        let (available, scores) = if is_cbom && cryptography_metrics.has_data() {
            let cm = &cryptography_metrics;
            (
                [true; 8], // all categories available for CBOM
                [
                    cm.crypto_completeness_score(), // slot 1: Crpt
                    cm.crypto_identifier_score(),   // slot 2: OIDs
                    cm.algorithm_strength_score(),  // slot 3: Algo
                    cm.crypto_dependency_score(),   // slot 4: Refs
                    cm.crypto_lifecycle_score(),    // slot 5: Life
                    cm.pqc_readiness_score(),       // slot 6: PQC
                    provenance_score,               // slot 7: Prov (standard)
                    license_score,                  // slot 8: Lic  (standard)
                ],
            )
        } else {
            // Standard SBOM scoring
            let vuln_available = vulnerability_score.is_some();
            let lifecycle_available = lifecycle_score.is_some();
            (
                [
                    true,                // completeness
                    true,                // identifiers
                    true,                // licenses
                    vuln_available,      // vulnerabilities
                    true,                // dependencies
                    true,                // integrity
                    true,                // provenance
                    lifecycle_available, // lifecycle
                ],
                [
                    completeness_score,
                    identifier_score,
                    license_score,
                    vulnerability_score.unwrap_or(0.0),
                    dependency_score,
                    integrity_score,
                    provenance_score,
                    lifecycle_score.unwrap_or(0.0),
                ],
            )
        };

        // Calculate weighted overall score with N/A renormalization
        let weights = self.profile.weights();
        let norm = weights.renormalize(&available);

        let mut overall_score: f32 = scores.iter().zip(norm.iter()).map(|(s, w)| s * w).sum();
        overall_score = overall_score.min(100.0);

        // Apply hard penalty caps for critical issues
        overall_score = self.apply_score_caps(
            overall_score,
            &lifecycle_metrics,
            &dependency_metrics,
            &hash_quality_metrics,
            &cryptography_metrics,
            total_components,
        );

        // Run compliance check (with sidecar + product class if configured)
        let mut compliance_checker = ComplianceChecker::new(self.profile.compliance_level());
        if let Some(sc) = self.cra_sidecar.clone() {
            compliance_checker = compliance_checker.with_sidecar(sc);
        }
        if let Some(c) = self.cra_product_class {
            compliance_checker = compliance_checker.with_product_class(c);
        }
        let compliance = compliance_checker.check(sbom);

        // Generate recommendations
        let recommendations = self.generate_recommendations(
            &completeness_metrics,
            &identifier_metrics,
            &license_metrics,
            &dependency_metrics,
            &hash_quality_metrics,
            &provenance_metrics,
            &lifecycle_metrics,
            &compliance,
            total_components,
        );

        QualityReport {
            scoring_engine_version: SCORING_ENGINE_VERSION.to_string(),
            overall_score,
            grade: QualityGrade::from_score(overall_score),
            profile: self.profile,
            completeness_score,
            identifier_score,
            license_score,
            vulnerability_score,
            dependency_score,
            integrity_score,
            provenance_score,
            lifecycle_score,
            completeness_metrics,
            identifier_metrics,
            license_metrics,
            vulnerability_metrics,
            dependency_metrics,
            hash_quality_metrics,
            provenance_metrics,
            auditability_metrics,
            lifecycle_metrics,
            cryptography_score,
            cryptography_metrics,
            compliance,
            recommendations,
            ai_readiness_metrics: None,
        }
    }

    /// Score ML model-card completeness for the AI-readiness profile.
    ///
    /// Filters to `MachineLearningModel` components and evaluates eleven checks
    /// (AI-001..AI-011): AI-001..AI-009 cover model-card transparency, AI-010 is
    /// a weight-hash integrity check, and AI-011 verifies the component is
    /// connected to the vulnerability/exploitability tooling stack. The
    /// returned `QualityReport` has all standard category scores zeroed/`None`;
    /// the rich data lives in `ai_readiness_metrics`.
    /// When the SBOM has no ML components the report is marked not-applicable.
    fn score_ai_readiness(&self, sbom: &NormalizedSbom) -> QualityReport {
        use crate::model::ComponentType;

        // Standard metrics are still computed so the report is structurally valid.
        let completeness_metrics = CompletenessMetrics::from_sbom(sbom);
        let identifier_metrics = IdentifierMetrics::from_sbom(sbom);
        let license_metrics = LicenseMetrics::from_sbom(sbom);
        let vulnerability_metrics = VulnerabilityMetrics::from_sbom(sbom);
        let dependency_metrics = DependencyMetrics::from_sbom(sbom);
        let hash_quality_metrics = HashQualityMetrics::from_sbom(sbom);
        let provenance_metrics = ProvenanceMetrics::from_sbom(sbom);
        let auditability_metrics = AuditabilityMetrics::from_sbom(sbom);
        let lifecycle_metrics = LifecycleMetrics::from_sbom(sbom);

        let compliance = ComplianceChecker::new(self.profile.compliance_level()).check(sbom);

        let make_report = |overall_score: f32,
                           grade: QualityGrade,
                           recommendations: Vec<Recommendation>,
                           metrics: AiReadinessMetrics| QualityReport {
            scoring_engine_version: SCORING_ENGINE_VERSION.to_string(),
            overall_score,
            grade,
            profile: self.profile,
            completeness_score: 0.0,
            identifier_score: 0.0,
            license_score: 0.0,
            vulnerability_score: None,
            dependency_score: 0.0,
            integrity_score: 0.0,
            provenance_score: 0.0,
            lifecycle_score: None,
            completeness_metrics: completeness_metrics.clone(),
            identifier_metrics: identifier_metrics.clone(),
            license_metrics: license_metrics.clone(),
            vulnerability_metrics: vulnerability_metrics.clone(),
            dependency_metrics: dependency_metrics.clone(),
            hash_quality_metrics: hash_quality_metrics.clone(),
            provenance_metrics: provenance_metrics.clone(),
            auditability_metrics: auditability_metrics.clone(),
            lifecycle_metrics: lifecycle_metrics.clone(),
            cryptography_score: None,
            cryptography_metrics: CryptographyMetrics::default(),
            compliance: compliance.clone(),
            recommendations,
            ai_readiness_metrics: Some(metrics),
        };

        let ml_components: Vec<_> = sbom
            .components
            .values()
            .filter(|c| c.component_type == ComponentType::MachineLearningModel)
            .collect();

        if ml_components.is_empty() {
            let metrics = AiReadinessMetrics {
                ml_component_count: 0,
                not_applicable: true,
                na_reason: Some(
                    "No machine-learning-model components found in this SBOM".to_string(),
                ),
                checks: Vec::new(),
                components_fully_documented: 0,
            };
            return make_report(0.0, QualityGrade::F, Vec::new(), metrics);
        }

        // Per-check (id, name, weight). AI-010 adds the integrity dimension —
        // model-weight tampering is the canonical AI supply-chain attack — so it
        // carries weight comparable to the transparency checks. The literals are
        // chosen for readability; they no longer sum to exactly 1.0 once AI-010 is
        // added, so they are renormalized below to keep the total at 1.0.
        const CHECK_DEFS: [(&str, &str, f32); 11] = [
            ("AI-001", "Model card URL present", 0.15),
            ("AI-002", "Architecture family declared", 0.12),
            ("AI-003", "Training datasets referenced", 0.12),
            ("AI-004", "Quantitative analysis present", 0.12),
            ("AI-005", "Fairness assessments included", 0.11),
            ("AI-006", "Energy consumption disclosed", 0.10),
            ("AI-007", "Use-cases documented", 0.10),
            ("AI-008", "Known limitations stated", 0.09),
            ("AI-009", "Ethical considerations present", 0.09),
            ("AI-010", "Model weight hashes present", 0.12),
            // AI-011 closes the BSI "vulnerability/exploitability referencing"
            // gap for AI clusters: a model is only connected to the security
            // tooling stack if it carries a CVE/advisory reference that OSV/KEV
            // /EPSS/VEX can act on. Weighted like the integrity check (AI-010).
            ("AI-011", "Exploitability/advisory reference present", 0.12),
        ];

        // Renormalize the per-check weights so they sum to exactly 1.0. Without
        // this the literals above total 1.12 and a fully documented model would
        // score >100 (before the .min(100.0) clamp), distorting partial scores.
        let weight_sum: f32 = CHECK_DEFS.iter().map(|(_, _, w)| *w).sum();

        let n = ml_components.len();
        let mut total_weighted_score = 0.0_f32;
        let mut components_fully_documented = 0_usize;
        let mut component_details: Vec<Vec<String>> = vec![Vec::new(); CHECK_DEFS.len()];
        let mut failing_components = vec![0_usize; CHECK_DEFS.len()];

        for component in &ml_components {
            let ml = component.ml_model.as_ref();
            let raw = component.extensions.raw.as_ref();

            let results: [bool; 11] = [
                // AI-001: model card URL
                ml.and_then(|m| m.model_card_url.as_ref()).is_some(),
                // AI-002: architecture family
                ml.and_then(|m| m.architecture_family.as_ref()).is_some(),
                // AI-003: training datasets
                ml.is_some_and(|m| !m.training_datasets.is_empty()),
                // AI-004: quantitative analysis — typed performance metrics, with
                // a raw-pointer fallback for SBOMs parsed before typed extraction.
                ml.is_some_and(|m| !m.performance_metrics.is_empty())
                    || has_non_empty_pointer(
                        raw,
                        &[
                            "/modelCard/quantitativeAnalysis",
                            "/mlModel/modelCard/quantitativeAnalysis",
                        ],
                    ),
                // AI-005: fairness assessments. Fallback pointer corrected to the
                // spec path `fairnessAssessments` (was the non-spec ...Considerations).
                ml.is_some_and(|m| !m.fairness.is_empty())
                    || has_non_empty_pointer(
                        raw,
                        &[
                            "/modelCard/considerations/fairnessAssessments",
                            "/mlModel/modelCard/considerations/fairnessAssessments",
                            "/mlModel/considerations/fairnessAssessments",
                            // Legacy non-spec key, retained for back-compat.
                            "/modelCard/considerations/fairnessConsiderations",
                            "/mlModel/modelCard/considerations/fairnessConsiderations",
                            "/mlModel/considerations/fairnessConsiderations",
                        ],
                    ),
                // AI-006: energy consumption
                ml.and_then(|m| m.energy_kwh_training).is_some(),
                // AI-007: use-cases
                ml.is_some_and(|m| !m.use_cases.is_empty())
                    || has_non_empty_pointer(
                        raw,
                        &[
                            "/modelCard/considerations/useCases",
                            "/mlModel/modelCard/considerations/useCases",
                            "/mlModel/considerations/useCases",
                        ],
                    ),
                // AI-008: limitations
                ml.and_then(|m| m.limitations.as_ref()).is_some(),
                // AI-009: ethical considerations
                ml.is_some_and(|m| !m.ethical_considerations.is_empty())
                    || has_non_empty_pointer(
                        raw,
                        &[
                            "/modelCard/considerations/ethicalConsiderations",
                            "/mlModel/modelCard/considerations/ethicalConsiderations",
                            "/mlModel/considerations/ethicalConsiderations",
                        ],
                    ),
                // AI-010: model weight hashes present. Integrity check — a
                // MachineLearningModel component must carry at least one hash so
                // its weights can be verified against tampering. Hashes typically
                // arrive via HuggingFace enrichment (siblings[].lfs.sha256).
                !component.hashes.is_empty(),
                // AI-011: exploitability/advisory reference present. The model is
                // only connected to the cybersecurity tooling stack (OSV/KEV/EPSS
                // /VEX) when it carries at least one vulnerability reference OR a
                // security/advisory external reference an analyst can pivot on.
                ml_has_exploitability_reference(component),
            ];

            if results.iter().all(|&p| p) {
                components_fully_documented += 1;
            }

            total_weighted_score += results
                .iter()
                .zip(CHECK_DEFS.iter())
                .map(|(&passed, (_, _, w))| if passed { *w / weight_sum } else { 0.0 })
                .sum::<f32>();

            for (i, &passed) in results.iter().enumerate() {
                component_details[i].push(format!(
                    "{}: {}",
                    component.name,
                    if passed { "pass" } else { "fail" }
                ));
                if !passed {
                    failing_components[i] += 1;
                }
            }
        }

        let checks: Vec<AiCheck> = CHECK_DEFS
            .iter()
            .enumerate()
            .map(|(i, (id, name, weight))| {
                let failures = failing_components[i];
                let detail = if component_details[i].is_empty() {
                    None
                } else {
                    Some(format!(
                        "{}/{} components passed; {}",
                        n - failures,
                        n,
                        component_details[i].join("; ")
                    ))
                };
                AiCheck {
                    id: (*id).to_string(),
                    name: (*name).to_string(),
                    passed: failures == 0,
                    detail,
                    // Expose the renormalized weight so reported weights sum to 1.0.
                    weight: *weight / weight_sum,
                }
            })
            .collect();

        // Average across all ML components, scaled to 0-100.
        let overall_score = ((total_weighted_score / n as f32) * 100.0).min(100.0);

        let mut recommendations: Vec<Recommendation> = checks
            .iter()
            .zip(failing_components.iter())
            .filter(|(c, _)| !c.passed)
            .enumerate()
            .map(|(i, (chk, &affected_count))| Recommendation {
                priority: (i as u8 / 3) + 1,
                category: RecommendationCategory::Completeness,
                message: format!("[{}] {}", chk.id, chk.name),
                impact: chk.weight * 100.0,
                affected_count,
            })
            .collect();

        recommendations.sort_by(|a, b| {
            a.priority.cmp(&b.priority).then_with(|| {
                b.impact
                    .partial_cmp(&a.impact)
                    .unwrap_or(std::cmp::Ordering::Equal)
            })
        });

        let metrics = AiReadinessMetrics {
            ml_component_count: n,
            not_applicable: false,
            na_reason: None,
            checks,
            components_fully_documented,
        };

        make_report(
            overall_score,
            QualityGrade::from_score(overall_score),
            recommendations,
            metrics,
        )
    }

    /// Apply hard score caps for critical issues
    fn apply_score_caps(
        &self,
        mut score: f32,
        lifecycle: &LifecycleMetrics,
        deps: &DependencyMetrics,
        hashes: &HashQualityMetrics,
        crypto: &CryptographyMetrics,
        total_components: usize,
    ) -> f32 {
        let is_security_profile =
            matches!(self.profile, ScoringProfile::Security | ScoringProfile::Cra);

        // EOL components: cap at D grade for security-focused profiles
        if is_security_profile && lifecycle.eol_components > 0 {
            score = score.min(69.0);
        }

        // Dependency cycles: cap at B grade
        if deps.cycle_count > 0
            && matches!(
                self.profile,
                ScoringProfile::Security | ScoringProfile::Cra | ScoringProfile::Comprehensive
            )
        {
            score = score.min(89.0);
        }

        // No hashes at all: cap at C grade for Security profile
        if matches!(self.profile, ScoringProfile::Security)
            && total_components > 0
            && hashes.components_with_any_hash == 0
        {
            score = score.min(79.0);
        }

        // Weak-only hashes: cap at B grade for Security profile
        if matches!(self.profile, ScoringProfile::Security)
            && hashes.components_with_weak_only > 0
            && hashes.components_with_strong_hash == 0
        {
            score = score.min(89.0);
        }

        // CBOM-specific hard caps
        if self.profile == ScoringProfile::Cbom && crypto.has_data() {
            if crypto.weak_algorithm_count > 0 {
                score = score.min(69.0);
            }
            if crypto.compromised_keys > 0 {
                score = score.min(79.0);
            }
            if crypto.quantum_safe_count == 0 && crypto.algorithms_count > 0 {
                score = score.min(79.0);
            }
        }

        score
    }

    #[allow(clippy::too_many_arguments)]
    fn generate_recommendations(
        &self,
        completeness: &CompletenessMetrics,
        identifiers: &IdentifierMetrics,
        licenses: &LicenseMetrics,
        dependencies: &DependencyMetrics,
        hashes: &HashQualityMetrics,
        provenance: &ProvenanceMetrics,
        lifecycle: &LifecycleMetrics,
        compliance: &ComplianceResult,
        total_components: usize,
    ) -> Vec<Recommendation> {
        let mut recommendations = Vec::new();

        // Priority 1: Compliance errors
        if compliance.error_count > 0 {
            recommendations.push(Recommendation {
                priority: 1,
                category: RecommendationCategory::Compliance,
                message: format!(
                    "Fix {} compliance error(s) to meet {} requirements",
                    compliance.error_count,
                    compliance.level.name()
                ),
                impact: 20.0,
                affected_count: compliance.error_count,
            });
        }

        // Priority 1: EOL components
        if lifecycle.eol_components > 0 {
            recommendations.push(Recommendation {
                priority: 1,
                category: RecommendationCategory::Lifecycle,
                message: format!(
                    "{} component(s) have reached end-of-life — upgrade or replace",
                    lifecycle.eol_components
                ),
                impact: 15.0,
                affected_count: lifecycle.eol_components,
            });
        }

        // Priority 1: Missing versions (critical for identification)
        let missing_versions = total_components
            - ((completeness.components_with_version / 100.0) * total_components as f32) as usize;
        if missing_versions > 0 {
            recommendations.push(Recommendation {
                priority: 1,
                category: RecommendationCategory::Completeness,
                message: "Add version information to all components".to_string(),
                impact: (missing_versions as f32 / total_components.max(1) as f32) * 15.0,
                affected_count: missing_versions,
            });
        }

        // Priority 2: Weak-only hashes
        if hashes.components_with_weak_only > 0 {
            recommendations.push(Recommendation {
                priority: 2,
                category: RecommendationCategory::Integrity,
                message: "Upgrade weak hashes (MD5/SHA-1) to SHA-256 or stronger".to_string(),
                impact: 10.0,
                affected_count: hashes.components_with_weak_only,
            });
        }

        // Priority 2: Missing PURLs (important for identification)
        if identifiers.missing_all_identifiers > 0 {
            recommendations.push(Recommendation {
                priority: 2,
                category: RecommendationCategory::Identifiers,
                message: "Add PURL or CPE identifiers to components".to_string(),
                impact: (identifiers.missing_all_identifiers as f32
                    / total_components.max(1) as f32)
                    * 20.0,
                affected_count: identifiers.missing_all_identifiers,
            });
        }

        // Priority 2: Invalid identifiers
        let invalid_ids = identifiers.invalid_purls + identifiers.invalid_cpes;
        if invalid_ids > 0 {
            recommendations.push(Recommendation {
                priority: 2,
                category: RecommendationCategory::Identifiers,
                message: "Fix malformed PURL/CPE identifiers".to_string(),
                impact: 10.0,
                affected_count: invalid_ids,
            });
        }

        // Priority 2: Missing tool creator info
        if !provenance.has_tool_creator {
            recommendations.push(Recommendation {
                priority: 2,
                category: RecommendationCategory::Provenance,
                message: "Add SBOM creation tool information".to_string(),
                impact: 8.0,
                affected_count: 0,
            });
        }

        // Priority 3: Dependency cycles
        if dependencies.cycle_count > 0 {
            recommendations.push(Recommendation {
                priority: 3,
                category: RecommendationCategory::Dependencies,
                message: format!(
                    "{} dependency cycle(s) detected — review dependency graph",
                    dependencies.cycle_count
                ),
                impact: 10.0,
                affected_count: dependencies.cycle_count,
            });
        }

        // Priority 2-3: Software complexity
        if let Some(level) = &dependencies.complexity_level {
            match level {
                super::metrics::ComplexityLevel::VeryHigh => {
                    recommendations.push(Recommendation {
                        priority: 2,
                        category: RecommendationCategory::Dependencies,
                        message:
                            "Dependency structure is very complex — review for unnecessary transitive dependencies"
                                .to_string(),
                        impact: 8.0,
                        affected_count: dependencies.total_dependencies,
                    });
                }
                super::metrics::ComplexityLevel::High => {
                    recommendations.push(Recommendation {
                        priority: 3,
                        category: RecommendationCategory::Dependencies,
                        message:
                            "Dependency structure is complex — consider reducing hub dependencies or flattening deep chains"
                                .to_string(),
                        impact: 5.0,
                        affected_count: dependencies.total_dependencies,
                    });
                }
                _ => {}
            }
        }

        // Priority 3: Missing licenses
        let missing_licenses = total_components - licenses.with_declared;
        if missing_licenses > 0 && (missing_licenses as f32 / total_components.max(1) as f32) > 0.2
        {
            recommendations.push(Recommendation {
                priority: 3,
                category: RecommendationCategory::Licenses,
                message: "Add license information to components".to_string(),
                impact: (missing_licenses as f32 / total_components.max(1) as f32) * 12.0,
                affected_count: missing_licenses,
            });
        }

        // Priority 3: NOASSERTION licenses
        if licenses.noassertion_count > 0 {
            recommendations.push(Recommendation {
                priority: 3,
                category: RecommendationCategory::Licenses,
                message: "Replace NOASSERTION with actual license information".to_string(),
                impact: 5.0,
                affected_count: licenses.noassertion_count,
            });
        }

        // Priority 3: VCS URL coverage
        if total_components > 0 {
            let missing_vcs = total_components.saturating_sub(
                ((completeness.components_with_hashes / 100.0) * total_components as f32) as usize,
            );
            if missing_vcs > total_components / 2 {
                recommendations.push(Recommendation {
                    priority: 3,
                    category: RecommendationCategory::Provenance,
                    message: "Add VCS (source repository) URLs to components".to_string(),
                    impact: 5.0,
                    affected_count: missing_vcs,
                });
            }
        }

        // Priority 4: Non-standard licenses
        if licenses.non_standard_licenses > 0 {
            recommendations.push(Recommendation {
                priority: 4,
                category: RecommendationCategory::Licenses,
                message: "Use SPDX license identifiers for better interoperability".to_string(),
                impact: 3.0,
                affected_count: licenses.non_standard_licenses,
            });
        }

        // Priority 4: Outdated components
        if lifecycle.outdated_components > 0 {
            recommendations.push(Recommendation {
                priority: 4,
                category: RecommendationCategory::Lifecycle,
                message: format!(
                    "{} component(s) are outdated — newer versions available",
                    lifecycle.outdated_components
                ),
                impact: 5.0,
                affected_count: lifecycle.outdated_components,
            });
        }

        // Priority 4: Missing completeness declaration
        if provenance.completeness_declaration == CompletenessDeclaration::Unknown
            && matches!(
                self.profile,
                ScoringProfile::Cra | ScoringProfile::Comprehensive
            )
        {
            recommendations.push(Recommendation {
                priority: 4,
                category: RecommendationCategory::Provenance,
                message: "Add compositions section with aggregate completeness declaration"
                    .to_string(),
                impact: 5.0,
                affected_count: 0,
            });
        }

        // Priority 4: Missing dependency information
        if total_components > 1 && dependencies.total_dependencies == 0 {
            recommendations.push(Recommendation {
                priority: 4,
                category: RecommendationCategory::Dependencies,
                message: "Add dependency relationships between components".to_string(),
                impact: 10.0,
                affected_count: total_components,
            });
        }

        // Priority 4: Many orphan components
        if dependencies.orphan_components > 1
            && (dependencies.orphan_components as f32 / total_components.max(1) as f32) > 0.3
        {
            recommendations.push(Recommendation {
                priority: 4,
                category: RecommendationCategory::Dependencies,
                message: "Review orphan components that have no dependency relationships"
                    .to_string(),
                impact: 5.0,
                affected_count: dependencies.orphan_components,
            });
        }

        // Priority 5: Missing supplier information
        let missing_suppliers = total_components
            - ((completeness.components_with_supplier / 100.0) * total_components as f32) as usize;
        if missing_suppliers > 0
            && (missing_suppliers as f32 / total_components.max(1) as f32) > 0.5
        {
            recommendations.push(Recommendation {
                priority: 5,
                category: RecommendationCategory::Completeness,
                message: "Add supplier information to components".to_string(),
                impact: (missing_suppliers as f32 / total_components.max(1) as f32) * 8.0,
                affected_count: missing_suppliers,
            });
        }

        // Priority 5: Missing hashes
        let missing_hashes = total_components
            - ((completeness.components_with_hashes / 100.0) * total_components as f32) as usize;
        if missing_hashes > 0
            && matches!(
                self.profile,
                ScoringProfile::Security | ScoringProfile::Comprehensive
            )
        {
            recommendations.push(Recommendation {
                priority: 5,
                category: RecommendationCategory::Integrity,
                message: "Add cryptographic hashes for integrity verification".to_string(),
                impact: (missing_hashes as f32 / total_components.max(1) as f32) * 5.0,
                affected_count: missing_hashes,
            });
        }

        // Priority 5: Consider SBOM signing (only if not already signed)
        if !provenance.has_signature
            && matches!(
                self.profile,
                ScoringProfile::Security | ScoringProfile::Cra | ScoringProfile::Comprehensive
            )
        {
            recommendations.push(Recommendation {
                priority: 5,
                category: RecommendationCategory::Integrity,
                message: "Consider adding a digital signature to the SBOM".to_string(),
                impact: 3.0,
                affected_count: 0,
            });
        }

        // Sort by priority, then by impact
        recommendations.sort_by(|a, b| {
            a.priority.cmp(&b.priority).then_with(|| {
                b.impact
                    .partial_cmp(&a.impact)
                    .unwrap_or(std::cmp::Ordering::Equal)
            })
        });

        recommendations
    }
}

impl Default for QualityScorer {
    fn default() -> Self {
        Self::new(ScoringProfile::Standard)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::{Component, ComponentType, DocumentMetadata, MlModelInfo};
    use serde_json::json;

    #[test]
    fn test_grade_from_score() {
        assert_eq!(QualityGrade::from_score(95.0), QualityGrade::A);
        assert_eq!(QualityGrade::from_score(85.0), QualityGrade::B);
        assert_eq!(QualityGrade::from_score(75.0), QualityGrade::C);
        assert_eq!(QualityGrade::from_score(65.0), QualityGrade::D);
        assert_eq!(QualityGrade::from_score(55.0), QualityGrade::F);
    }

    #[test]
    fn test_scoring_profile_compliance_level() {
        assert_eq!(
            ScoringProfile::Minimal.compliance_level(),
            ComplianceLevel::Minimum
        );
        assert_eq!(
            ScoringProfile::Security.compliance_level(),
            ComplianceLevel::NtiaMinimum
        );
        assert_eq!(
            ScoringProfile::Comprehensive.compliance_level(),
            ComplianceLevel::Comprehensive
        );
        assert_eq!(
            ScoringProfile::AiReadiness.compliance_level(),
            ComplianceLevel::Comprehensive
        );
    }

    #[test]
    fn test_scoring_weights_sum_to_one() {
        let profiles = [
            ScoringProfile::Minimal,
            ScoringProfile::Standard,
            ScoringProfile::Security,
            ScoringProfile::LicenseCompliance,
            ScoringProfile::Cra,
            ScoringProfile::Comprehensive,
            ScoringProfile::Cbom,
            ScoringProfile::AiReadiness,
        ];
        for profile in &profiles {
            let w = profile.weights();
            let sum: f32 = w.as_array().iter().sum();
            assert!(
                (sum - 1.0).abs() < 0.01,
                "{profile:?} weights sum to {sum}, expected 1.0"
            );
        }
    }

    #[test]
    fn test_renormalize_all_available() {
        let w = ScoringProfile::Standard.weights();
        let available = [true; 8];
        let norm = w.renormalize(&available);
        let sum: f32 = norm.iter().sum();
        assert!((sum - 1.0).abs() < 0.001);
    }

    #[test]
    fn test_renormalize_lifecycle_unavailable() {
        let w = ScoringProfile::Standard.weights();
        let mut available = [true; 8];
        available[7] = false; // lifecycle
        let norm = w.renormalize(&available);
        let sum: f32 = norm.iter().sum();
        assert!((sum - 1.0).abs() < 0.001);
        assert_eq!(norm[7], 0.0);
    }

    #[test]
    fn test_scoring_engine_version() {
        assert_eq!(SCORING_ENGINE_VERSION, "2.1");
    }

    #[test]
    fn cbom_hard_cap_weak_algorithms() {
        use crate::model::{
            AlgorithmProperties, CanonicalId, Component, ComponentType, CryptoAssetType,
            CryptoPrimitive, CryptoProperties, NormalizedSbom,
        };

        let mut sbom = NormalizedSbom::default();
        // Add a weak crypto component (MD5 algorithm)
        let mut comp = Component::new("MD5".to_string(), "md5-ref".to_string());
        comp.component_type = ComponentType::Cryptographic;
        comp.crypto_properties = Some(
            CryptoProperties::new(CryptoAssetType::Algorithm).with_algorithm_properties(
                AlgorithmProperties::new(CryptoPrimitive::Hash)
                    .with_algorithm_family("MD5".to_string())
                    .with_nist_quantum_security_level(0),
            ),
        );
        sbom.components
            .insert(CanonicalId::from_name_version("md5", None), comp);

        let scorer = QualityScorer::new(ScoringProfile::Cbom);
        let report = scorer.score(&sbom);
        // Weak algorithm → D max (69)
        assert!(
            report.overall_score <= 69.0,
            "weak algo should cap at D, got {}",
            report.overall_score
        );
    }

    fn ml_component(bom_ref: &str, name: &str, ml: MlModelInfo, raw: Value) -> Component {
        let mut component =
            Component::new(name.to_string(), bom_ref.to_string()).with_version("1.0.0".to_string());
        component.component_type = ComponentType::MachineLearningModel;
        component.ml_model = Some(ml);
        component.extensions.raw = Some(raw);
        component
    }

    #[test]
    fn test_ai_readiness_not_applicable_without_ml_components() {
        let sbom = NormalizedSbom::new(DocumentMetadata::default());
        let report = QualityScorer::new(ScoringProfile::AiReadiness).score(&sbom);
        let metrics = report
            .ai_readiness_metrics
            .expect("AI readiness metrics should be present");
        assert!(metrics.is_not_applicable());
        assert_eq!(metrics.ml_component_count, 0);
        assert!(metrics.checks.is_empty());
    }

    #[test]
    fn test_ai_readiness_reads_nested_model_card_extensions() {
        let mut sbom = NormalizedSbom::new(DocumentMetadata::default());
        let ml = MlModelInfo {
            architecture_family: Some("transformer".to_string()),
            training_datasets: vec![crate::model::DatasetRef {
                reference: None,
                name: Some("wikipedia-2.5B".to_string()),
                purl: None,
            }],
            energy_kwh_training: Some(1500.0),
            model_card_url: Some("https://example.test/model-card".to_string()),
            limitations: Some("Only validated for English text".to_string()),
            ..MlModelInfo::default()
        };
        let raw = json!({
            "mlModel": {
                "modelCard": {
                    "quantitativeAnalysis": {
                        "performanceMetrics": [{ "type": "accuracy", "value": 0.97 }]
                    },
                    "considerations": {
                        "fairnessConsiderations": ["Assessed on demographic parity"],
                        "useCases": ["Document classification"],
                        "ethicalConsiderations": ["Human review required for sensitive domains"]
                    }
                }
            }
        });
        let mut component = ml_component("ml-1", "bert-base", ml, raw);
        // A weight hash makes the AI-010 integrity check pass.
        component.hashes.push(crate::model::Hash::new(
            crate::model::HashAlgorithm::Sha256,
            "a".repeat(64),
        ));
        // A vulnerability reference makes the AI-011 exploitability check pass.
        component
            .vulnerabilities
            .push(crate::model::VulnerabilityRef::new(
                "CVE-2024-0001".to_string(),
                crate::model::VulnerabilitySource::Cve,
            ));
        sbom.add_component(component);

        let report = QualityScorer::new(ScoringProfile::AiReadiness).score(&sbom);
        let metrics = report
            .ai_readiness_metrics
            .expect("AI readiness metrics should be present");
        assert!(!metrics.is_not_applicable());
        // All eleven checks should pass → fully documented, perfect score.
        for check in &metrics.checks {
            assert!(check.passed, "expected {} to pass", check.id);
        }
        assert_eq!(metrics.checks.len(), 11, "AI-001..AI-011 are all reported");
        // The renormalized per-check weights must still sum to 1.0.
        let weight_total: f32 = metrics.checks.iter().map(|c| c.weight).sum();
        assert!(
            (weight_total - 1.0).abs() < 0.001,
            "renormalized weights must sum to 1.0, got {weight_total}"
        );
        assert_eq!(metrics.components_fully_documented, 1);
        assert!((report.overall_score - 100.0).abs() < 0.01);
        assert_eq!(report.grade, QualityGrade::A);
    }

    #[test]
    fn test_ai_readiness_fails_check_when_any_model_is_missing_it() {
        let mut sbom = NormalizedSbom::new(DocumentMetadata::default());
        let complete_ml = MlModelInfo {
            architecture_family: Some("transformer".to_string()),
            training_datasets: vec![crate::model::DatasetRef {
                reference: None,
                name: Some("dataset".to_string()),
                purl: None,
            }],
            energy_kwh_training: Some(10.0),
            model_card_url: Some("https://example.test/model-card".to_string()),
            limitations: Some("Only validated for English text".to_string()),
            ..MlModelInfo::default()
        };
        let complete_raw = json!({
            "mlModel": { "modelCard": {
                "quantitativeAnalysis": { "performanceMetrics": [{ "type": "accuracy", "value": 0.98 }] },
                "considerations": {
                    "fairnessConsiderations": ["Reviewed"],
                    "useCases": ["Classification"],
                    "ethicalConsiderations": ["Human review required"]
                }
            }}
        });
        sbom.add_component(ml_component(
            "ml-1",
            "complete-model",
            complete_ml.clone(),
            complete_raw,
        ));

        // Second model is missing fairness assessments.
        let incomplete_raw = json!({
            "mlModel": { "modelCard": {
                "quantitativeAnalysis": { "performanceMetrics": [{ "type": "accuracy", "value": 0.94 }] },
                "considerations": {
                    "useCases": ["Classification"],
                    "ethicalConsiderations": ["Human review required"]
                }
            }}
        });
        sbom.add_component(ml_component(
            "ml-2",
            "incomplete-model",
            complete_ml,
            incomplete_raw,
        ));

        let report = QualityScorer::new(ScoringProfile::AiReadiness).score(&sbom);
        let metrics = report
            .ai_readiness_metrics
            .expect("AI readiness metrics should be present");
        let fairness = metrics
            .checks
            .iter()
            .find(|c| c.id == "AI-005")
            .expect("AI-005 should be present");
        assert!(
            !fairness.passed,
            "AI-005 should fail when any model is missing fairness data"
        );
        assert!(
            fairness
                .detail
                .as_deref()
                .unwrap_or_default()
                .contains("1/2 components passed")
        );
        let rec = report
            .recommendations
            .iter()
            .find(|r| r.message.contains("AI-005"))
            .expect("missing fairness recommendation");
        assert_eq!(rec.affected_count, 1);
    }

    #[test]
    fn test_ai_010_weight_hash_integrity_check() {
        let mut sbom = NormalizedSbom::new(DocumentMetadata::default());

        // A model with no hashes fails AI-010; one with a hash passes it.
        let bare = ml_component("ml-1", "no-hash", MlModelInfo::default(), json!({}));
        sbom.add_component(bare);

        let mut hashed = ml_component("ml-2", "with-hash", MlModelInfo::default(), json!({}));
        hashed.hashes.push(crate::model::Hash::new(
            crate::model::HashAlgorithm::Sha256,
            "b".repeat(64),
        ));
        sbom.add_component(hashed);

        let report = QualityScorer::new(ScoringProfile::AiReadiness).score(&sbom);
        let metrics = report
            .ai_readiness_metrics
            .expect("AI readiness metrics should be present");

        let ai010 = metrics
            .checks
            .iter()
            .find(|c| c.id == "AI-010")
            .expect("AI-010 should be present");
        // One of two models lacks a hash, so the aggregate check fails.
        assert!(
            !ai010.passed,
            "AI-010 should fail when any model is missing weight hashes"
        );
        assert!(
            ai010
                .detail
                .as_deref()
                .unwrap_or_default()
                .contains("1/2 components passed"),
            "AI-010 detail should report 1/2 models passing"
        );
    }

    #[test]
    fn test_ai_011_exploitability_reference_check() {
        use crate::model::{
            ExternalRefType, ExternalReference, VulnerabilityRef, VulnerabilitySource,
        };

        let mut sbom = NormalizedSbom::new(DocumentMetadata::default());

        // Model 1: carries a vulnerability reference → AI-011 passes.
        let mut with_vuln = ml_component("ml-1", "with-vuln", MlModelInfo::default(), json!({}));
        with_vuln.vulnerabilities.push(VulnerabilityRef::new(
            "CVE-2024-1234".to_string(),
            VulnerabilitySource::Cve,
        ));
        sbom.add_component(with_vuln);

        // Model 2: carries a security advisory external reference → AI-011 passes.
        let mut with_advisory =
            ml_component("ml-2", "with-advisory", MlModelInfo::default(), json!({}));
        with_advisory.external_refs.push(ExternalReference {
            ref_type: ExternalRefType::Advisories,
            url: "https://example.test/advisory".to_string(),
            comment: None,
            hashes: Vec::new(),
        });
        sbom.add_component(with_advisory);

        let report = QualityScorer::new(ScoringProfile::AiReadiness).score(&sbom);
        let metrics = report
            .ai_readiness_metrics
            .expect("AI readiness metrics should be present");
        let ai011 = metrics
            .checks
            .iter()
            .find(|c| c.id == "AI-011")
            .expect("AI-011 should be present");
        assert!(
            ai011.passed,
            "AI-011 should pass when every model carries a vuln or advisory reference"
        );
    }

    #[test]
    fn test_ai_011_fails_without_exploitability_reference() {
        let mut sbom = NormalizedSbom::new(DocumentMetadata::default());
        // A model with neither a vuln ref nor an advisory external reference.
        sbom.add_component(ml_component(
            "ml-1",
            "no-refs",
            MlModelInfo::default(),
            json!({}),
        ));

        let report = QualityScorer::new(ScoringProfile::AiReadiness).score(&sbom);
        let metrics = report
            .ai_readiness_metrics
            .expect("AI readiness metrics should be present");
        let ai011 = metrics
            .checks
            .iter()
            .find(|c| c.id == "AI-011")
            .expect("AI-011 should be present");
        assert!(
            !ai011.passed,
            "AI-011 should fail when a model has no exploitability/advisory reference"
        );
    }
}