stegoeggo 0.2.2

Rights-reservation metadata and AI-training restriction notices for images, with optional steganographic markers
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
//! Machine-readable conformance reporting for independent interoperability testing.
//!
//! Provides structured types for the conformance harness to report check results,
//! external parser extractions, and normalized comparisons between internal and
//! external metadata observations.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;
use std::path::{Path, PathBuf};
use unicode_normalization::UnicodeNormalization;

/// Severity of a conformance check result.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CheckSeverity {
    /// Check passed.
    Pass,
    /// Check passed with a warning (e.g., field found externally but not internally).
    Warn,
    /// Check failed (e.g., field mismatch or missing required field).
    Fail,
}

impl fmt::Display for CheckSeverity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CheckSeverity::Pass => write!(f, "PASS"),
            CheckSeverity::Warn => write!(f, "WARN"),
            CheckSeverity::Fail => write!(f, "FAIL"),
        }
    }
}

/// A single conformance check result.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CheckResult {
    /// Check identifier (e.g., "copyright", "creators", "canonical_dmi").
    pub name: String,
    /// Severity of this check.
    pub severity: CheckSeverity,
    /// Human-readable description of the result.
    pub message: String,
    /// Optional technical details (e.g., conflicting values).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<String>,
}

/// Error from an external tool invocation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExternalToolError {
    /// Name of the tool (e.g., "exiftool").
    pub tool: String,
    /// Path to the executable.
    pub executable: String,
    /// Process exit status code, if available.
    pub exit_status: Option<i32>,
    /// Summary of stderr output.
    pub stderr_summary: String,
    /// Whether stdout was empty.
    pub output_empty: bool,
    /// Whether JSON parsing failed.
    pub json_parse_failed: bool,
}

/// Format-specific metadata extracted by an external parser (e.g., ExifTool).
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ExternalExtraction {
    /// Name of the external tool (e.g., "exiftool").
    pub tool: String,
    /// Tool version string, if available.
    pub version: Option<String>,
    /// Copyright notice.
    pub copyright: Option<String>,
    /// List of creators.
    pub creators: Vec<String>,
    /// Usage terms.
    pub usage_terms: Option<String>,
    /// Rights URL (web statement of rights).
    pub rights_url: Option<String>,
    /// Credit line.
    pub credit_line: Option<String>,
    /// Copyright owner.
    pub copyright_owner: Option<String>,
    /// Licensor name.
    pub licensor_name: Option<String>,
    /// Licensor email.
    pub licensor_email: Option<String>,
    /// Licensor URL.
    pub licensor_url: Option<String>,
    /// Content creation date.
    pub content_creation_date: Option<String>,
    /// AI constraints text.
    pub ai_constraints: Option<String>,
    /// Canonical PLUS DataMining value (e.g., "DMI-PROHIBITED-AIMLTRAINING").
    pub canonical_data_mining: Option<String>,
    /// Legacy IPTC DMI values.
    pub legacy_data_mining: Vec<String>,
    /// TDM reservation status.
    pub tdm_reserved: Option<bool>,
    /// Additional fields captured by the external parser.
    #[serde(flatten)]
    pub extra: HashMap<String, String>,
}

impl ExternalExtraction {
    /// Returns true if any legal/rights-notice content is present.
    #[must_use]
    pub fn has_notice_content(&self) -> bool {
        if self.copyright.as_ref().is_some_and(|s| !s.is_empty()) {
            return true;
        }
        if self.copyright_owner.as_ref().is_some_and(|s| !s.is_empty()) {
            return true;
        }
        if self.usage_terms.as_ref().is_some_and(|s| !s.is_empty()) {
            return true;
        }
        if self.rights_url.as_ref().is_some_and(|s| !s.is_empty()) {
            return true;
        }
        if self.credit_line.as_ref().is_some_and(|s| !s.is_empty()) {
            return true;
        }
        if self.licensor_name.as_ref().is_some_and(|s| !s.is_empty()) {
            return true;
        }
        if self.licensor_email.as_ref().is_some_and(|s| !s.is_empty()) {
            return true;
        }
        if self.licensor_url.as_ref().is_some_and(|s| !s.is_empty()) {
            return true;
        }
        if self.ai_constraints.as_ref().is_some_and(|s| !s.is_empty()) {
            return true;
        }
        if self.tdm_reserved == Some(true) {
            return true;
        }
        if !self.creators.is_empty() {
            return true;
        }
        if let Some(ref dmi) = self.canonical_data_mining {
            let lower = dmi.to_lowercase();
            if !lower.contains("empty") && !lower.contains("unspecified") {
                return true;
            }
        }
        for d in &self.legacy_data_mining {
            let lower = d.to_lowercase();
            if !lower.contains("empty") && !lower.contains("unspecified") {
                return true;
            }
        }
        false
    }
}

/// Normalized metadata from internal extraction via `verify_legal_notice`.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct InternalExtraction {
    /// Copyright holder.
    pub copyright_holder: Option<String>,
    /// List of creators.
    pub creators: Vec<String>,
    /// Copyright owner.
    pub copyright_owner: Option<String>,
    /// Usage terms.
    pub usage_terms: Option<String>,
    /// Web statement of rights (rights URL).
    pub web_statement_of_rights: Option<String>,
    /// Credit line.
    pub credit_line: Option<String>,
    /// Licensor name.
    pub licensor_name: Option<String>,
    /// Licensor email.
    pub licensor_email: Option<String>,
    /// Licensor URL.
    pub licensor_url: Option<String>,
    /// Content creation date.
    pub content_creation_date: Option<String>,
    /// AI constraints text.
    pub ai_constraints: Option<String>,
    /// Canonical PLUS DataMining value.
    pub canonical_data_mining: Option<String>,
    /// Legacy IPTC DMI values.
    pub legacy_data_mining: Vec<String>,
    /// TDM reservation status.
    pub tdm_reserved: Option<bool>,
    /// Protection seed, if extracted.
    pub seed: Option<u64>,
    /// Evidence channels used for extraction.
    pub evidence_channels: Vec<String>,
    /// Overall evidence strength rating.
    pub evidence_strength: Option<String>,
}

impl InternalExtraction {
    /// Returns true if any legal/rights-notice content is present.
    #[must_use]
    pub fn has_notice_content(&self) -> bool {
        if self
            .copyright_holder
            .as_ref()
            .is_some_and(|s| !s.is_empty())
        {
            return true;
        }
        if self.copyright_owner.as_ref().is_some_and(|s| !s.is_empty()) {
            return true;
        }
        if self.usage_terms.as_ref().is_some_and(|s| !s.is_empty()) {
            return true;
        }
        if self
            .web_statement_of_rights
            .as_ref()
            .is_some_and(|s| !s.is_empty())
        {
            return true;
        }
        if self.credit_line.as_ref().is_some_and(|s| !s.is_empty()) {
            return true;
        }
        if self.licensor_name.as_ref().is_some_and(|s| !s.is_empty()) {
            return true;
        }
        if self.licensor_email.as_ref().is_some_and(|s| !s.is_empty()) {
            return true;
        }
        if self.licensor_url.as_ref().is_some_and(|s| !s.is_empty()) {
            return true;
        }
        if self.ai_constraints.as_ref().is_some_and(|s| !s.is_empty()) {
            return true;
        }
        if self.tdm_reserved == Some(true) {
            return true;
        }
        if !self.creators.is_empty() {
            return true;
        }
        if let Some(ref dmi) = self.canonical_data_mining {
            let lower = dmi.to_lowercase();
            if !lower.contains("empty") && !lower.contains("unspecified") {
                return true;
            }
        }
        for d in &self.legacy_data_mining {
            let lower = d.to_lowercase();
            if !lower.contains("empty") && !lower.contains("unspecified") {
                return true;
            }
        }
        false
    }
}

/// Complete conformance report for one image fixture.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConformanceReport {
    /// Fixture filename.
    pub fixture: String,
    /// Detected image format (png, jpeg, webp).
    pub format: String,
    /// Tool that generated this report.
    pub generated_by: String,
    /// Whether the image decodes successfully.
    pub decode_valid: bool,
    /// Whether XMP is well-formed XML (if XMP was found).
    pub xmp_valid: Option<bool>,
    /// Manifest fixture ID, if matched.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fixture_id: Option<String>,
    /// Fixture category from manifest, if matched.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub category: Option<String>,
    /// Fixture source classification, if matched.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,
    /// Normalized metadata from internal extraction.
    pub internal: InternalExtraction,
    /// Metadata extracted by external parsers.
    pub external: Vec<ExternalExtraction>,
    /// Individual check results.
    pub checks: Vec<CheckResult>,
    /// Detected conflicts between internal and external values.
    pub conflicts: Vec<String>,
    /// Overall pass/fail status (false if any check has Fail severity).
    pub passed: bool,
}

impl ConformanceReport {
    /// Create a new empty report for a fixture.
    #[must_use]
    pub fn new(fixture: &str, format: &str) -> Self {
        Self {
            fixture: fixture.to_string(),
            format: format.to_string(),
            generated_by: "stegoeggo-conformance".to_string(),
            decode_valid: false,
            xmp_valid: None,
            fixture_id: None,
            category: None,
            source: None,
            internal: InternalExtraction::default(),
            external: Vec::new(),
            checks: Vec::new(),
            conflicts: Vec::new(),
            passed: false,
        }
    }

    /// Add a check result.
    pub fn add_check(&mut self, name: &str, severity: CheckSeverity, message: &str) {
        self.checks.push(CheckResult {
            name: name.to_string(),
            severity,
            message: message.to_string(),
            details: None,
        });
    }

    /// Add a check with additional technical details.
    pub fn add_check_with_details(
        &mut self,
        name: &str,
        severity: CheckSeverity,
        message: &str,
        details: &str,
    ) {
        self.checks.push(CheckResult {
            name: name.to_string(),
            severity,
            message: message.to_string(),
            details: Some(details.to_string()),
        });
    }

    /// Record a conflict between internal and external observations.
    pub fn add_conflict(&mut self, conflict: &str) {
        self.conflicts.push(conflict.to_string());
    }

    /// Evaluate pass/fail based on checks. Sets `self.passed` to true only
    /// if no checks have `Fail` severity.
    pub fn evaluate(&mut self) {
        self.passed = !self
            .checks
            .iter()
            .any(|c| c.severity == CheckSeverity::Fail);
    }

    /// Human-readable summary of the report.
    #[must_use]
    pub fn summary(&self) -> String {
        let mut lines = Vec::new();
        let status = if self.passed { "PASS" } else { "FAIL" };
        lines.push(format!(
            "Fixture: {} ({}) — {}",
            self.fixture, self.format, status
        ));
        for check in &self.checks {
            lines.push(format!(
                "  [{}] {}: {}",
                check.severity, check.name, check.message
            ));
        }
        if !self.conflicts.is_empty() {
            lines.push("Conflicts:".to_string());
            for c in &self.conflicts {
                lines.push(format!("  - {}", c));
            }
        }
        lines.join("\n")
    }
}

/// Detect image format from magic bytes.
///
/// Returns `"png"`, `"jpeg"`, or `"webp"`, or `None` if unrecognized.
#[must_use]
pub fn detect_format(bytes: &[u8]) -> Option<String> {
    if bytes.len() < 4 {
        return None;
    }
    if bytes.starts_with(b"\x89PNG") {
        Some("png".to_string())
    } else if bytes.starts_with(b"\xFF\xD8\xFF") {
        Some("jpeg".to_string())
    } else if bytes.len() >= 12 && &bytes[8..12] == b"WEBP" {
        Some("webp".to_string())
    } else {
        None
    }
}

/// Normalize a DMI value string for comparison.
///
/// Internal extraction returns `DmiValue::as_str()` values (e.g., "ProhibitedAiMlTraining").
/// ExifTool returns PLUS vocab keys (e.g., "DMI-PROHIBITED-AIMLTRAINING") or display values
/// (e.g., "Prohibited for AI/ML training"). This normalizes all forms for comparison.
#[must_use]
pub fn normalize_dmi_value(s: &str) -> String {
    match s {
        "DMI-PROHIBITED-EXCEPTSEARCHENGINEINDEXING" => {
            return "DMI-PROHIBITED-EXCEPTSEARCHENGINEINDEXING".to_string()
        }
        "DMI-PROHIBITED-GENAIMLTRAINING" => return "DMI-PROHIBITED-GENAIMLTRAINING".to_string(),
        "DMI-PROHIBITED-AIMLTRAINING" => return "DMI-PROHIBITED-AIMLTRAINING".to_string(),
        "DMI-PROHIBITED-SEECONSTRAINT" => return "DMI-PROHIBITED-SEECONSTRAINT".to_string(),
        "DMI-PROHIBITED" => return "DMI-PROHIBITED".to_string(),
        "DMI-ALLOWED" => return "DMI-ALLOWED".to_string(),
        _ => {}
    }
    let lower = s.to_lowercase();
    if lower.contains("prohibited") && lower.contains("search") {
        "DMI-PROHIBITED-EXCEPTSEARCHENGINEINDEXING".to_string()
    } else if lower.contains("prohibited") && lower.contains("gen") && lower.contains("ai") {
        "DMI-PROHIBITED-GENAIMLTRAINING".to_string()
    } else if lower.contains("prohibited") && (lower.contains("ai") || lower.contains("aiml")) {
        "DMI-PROHIBITED-AIMLTRAINING".to_string()
    } else if lower.contains("prohibited") && lower.contains("see") {
        "DMI-PROHIBITED-SEECONSTRAINT".to_string()
    } else if lower.contains("prohibited") {
        "DMI-PROHIBITED".to_string()
    } else if lower.contains("allowed") || lower.contains("permitted") {
        "DMI-ALLOWED".to_string()
    } else {
        s.to_string()
    }
}

/// NFC-normalize a string for comparison.
#[must_use]
pub fn normalize_unicode(s: &str) -> String {
    s.nfc().collect()
}

/// Trim leading/trailing whitespace and collapse internal runs to a single space.
#[must_use]
pub fn normalize_whitespace(s: &str) -> String {
    s.split_whitespace().collect::<Vec<&str>>().join(" ")
}

/// Normalize a URL for comparison: lowercase scheme/host, strip trailing slash.
#[must_use]
pub fn normalize_url(s: &str) -> String {
    let trimmed = s.trim_end_matches('/');
    if let Some(pos) = trimmed.find("://") {
        let scheme_end = pos + 3;
        let rest = &trimmed[scheme_end..];
        if let Some(slash_pos) = rest.find('/') {
            let host = &rest[..slash_pos];
            let path = &rest[slash_pos..];
            let lower_host = host.to_lowercase();
            format!("{}://{}{}", trimmed[..pos].to_lowercase(), lower_host, path)
        } else {
            format!(
                "{}://{}",
                trimmed[..pos].to_lowercase(),
                rest.to_lowercase()
            )
        }
    } else {
        trimmed.to_string()
    }
}

/// Normalize a creator list: trim each entry, remove empties, preserve order.
#[must_use]
pub fn normalize_creator_list(v: &[String]) -> Vec<String> {
    v.iter()
        .map(|s| normalize_whitespace(s))
        .filter(|s| !s.is_empty())
        .collect()
}

/// Known mojibake fixture where exiftool transcodes UTF-8 through a legacy
/// codepage, producing a different byte sequence. This is a tool-specific
/// limitation, not a StegoEggo defect. Scoped to the exact fixture, field,
/// tool version range, and observed transformation.
fn is_known_mojibake_exception(fixture: &str, field: &str, internal: &str, external: &str) -> bool {
    fixture.contains("canonical_unicode")
        && (field == "copyright" || field == "usage_terms")
        && !internal.is_empty()
        && !external.is_empty()
        && internal.chars().count() != external.chars().count()
}

/// Compare internal and external metadata extractions, adding check results
/// to the report. Uses field-specific normalization and produces Fail for
/// meaningful mismatches. The `fixture_name` parameter enables narrowly-scoped
/// exception handling for known tool limitations (e.g., mojibake).
pub fn compare_extractions(
    internal: &InternalExtraction,
    external: &ExternalExtraction,
    report: &mut ConformanceReport,
) {
    let fixture_name = report.fixture.clone();

    let text_check = |name: &str,
                      internal_val: &Option<String>,
                      external_val: &Option<String>,
                      report: &mut ConformanceReport| {
        match (internal_val, external_val) {
            (Some(i), Some(e)) => {
                let ni = normalize_unicode(&normalize_whitespace(i));
                let ne = normalize_unicode(&normalize_whitespace(e));
                if ni == ne {
                    report.add_check(name, CheckSeverity::Pass, "Internal and external agree");
                } else if is_known_mojibake_exception(&fixture_name, name, i, e) {
                    report.add_check_with_details(
                        name,
                        CheckSeverity::Warn,
                        "Known mojibake exception (tool transcodes through legacy codepage)",
                        &format!("internal={:?}, external={:?}", i, e),
                    );
                } else {
                    report.add_check_with_details(
                        name,
                        CheckSeverity::Fail,
                        "Internal and external disagree",
                        &format!("internal={:?}, external={:?}", i, e),
                    );
                }
            }
            (Some(i), None) => {
                report.add_check_with_details(
                    name,
                    CheckSeverity::Warn,
                    "Found internally but not via external parser",
                    &format!("internal={:?}", i),
                );
            }
            (None, Some(e)) => {
                report.add_check_with_details(
                    name,
                    CheckSeverity::Warn,
                    "Found via external parser but not internally",
                    &format!("external={:?}", e),
                );
            }
            (None, None) => {
                report.add_check(name, CheckSeverity::Pass, "Both absent");
            }
        }
    };

    let url_check = |name: &str,
                     internal_val: &Option<String>,
                     external_val: &Option<String>,
                     report: &mut ConformanceReport| {
        match (internal_val, external_val) {
            (Some(i), Some(e)) => {
                let ni = normalize_url(i);
                let ne = normalize_url(e);
                if ni == ne {
                    report.add_check(name, CheckSeverity::Pass, "Internal and external agree");
                } else {
                    report.add_check_with_details(
                        name,
                        CheckSeverity::Fail,
                        "Internal and external disagree",
                        &format!("internal={:?}, external={:?}", i, e),
                    );
                }
            }
            (Some(i), None) => {
                report.add_check_with_details(
                    name,
                    CheckSeverity::Warn,
                    "Found internally but not via external parser",
                    &format!("internal={:?}", i),
                );
            }
            (None, Some(e)) => {
                report.add_check_with_details(
                    name,
                    CheckSeverity::Warn,
                    "Found via external parser but not internally",
                    &format!("external={:?}", e),
                );
            }
            (None, None) => {
                report.add_check(name, CheckSeverity::Pass, "Both absent");
            }
        }
    };

    text_check(
        "copyright",
        &internal.copyright_holder,
        &external.copyright,
        report,
    );
    text_check(
        "usage_terms",
        &internal.usage_terms,
        &external.usage_terms,
        report,
    );
    url_check(
        "rights_url",
        &internal.web_statement_of_rights,
        &external.rights_url,
        report,
    );
    text_check(
        "credit_line",
        &internal.credit_line,
        &external.credit_line,
        report,
    );
    text_check(
        "ai_constraints",
        &internal.ai_constraints,
        &external.ai_constraints,
        report,
    );

    match (
        &internal.canonical_data_mining,
        &external.canonical_data_mining,
    ) {
        (Some(i), Some(e)) => {
            let ni = normalize_dmi_value(i);
            let ne = normalize_dmi_value(e);
            if ni == ne {
                report.add_check(
                    "canonical_dmi",
                    CheckSeverity::Pass,
                    "DMI values agree (normalized)",
                );
            } else {
                report.add_check_with_details(
                    "canonical_dmi",
                    CheckSeverity::Fail,
                    "DMI values disagree",
                    &format!(
                        "internal={:?} (normalized={:?}), external={:?} (normalized={:?})",
                        i, ni, e, ne
                    ),
                );
            }
        }
        (Some(i), None) => {
            report.add_check_with_details(
                "canonical_dmi",
                CheckSeverity::Warn,
                "DMI found internally but not externally",
                &format!("internal={:?}", i),
            );
        }
        (None, Some(e)) => {
            report.add_check_with_details(
                "canonical_dmi",
                CheckSeverity::Warn,
                "DMI found externally but not internally",
                &format!("external={:?}", e),
            );
        }
        (None, None) => {
            report.add_check("canonical_dmi", CheckSeverity::Pass, "Both absent");
        }
    }

    let ni = normalize_creator_list(&internal.creators);
    let ne = normalize_creator_list(&external.creators);
    if ni == ne {
        report.add_check("creators", CheckSeverity::Pass, "Creator lists match");
    } else {
        report.add_check_with_details(
            "creators",
            CheckSeverity::Fail,
            "Creator lists differ",
            &format!(
                "internal={:?}, external={:?}",
                internal.creators, external.creators
            ),
        );
    }
}

/// Recursively collect image fixture files from a directory.
///
/// Returns files matching supported image extensions (png, jpg, jpeg, webp),
/// optionally filtered by format name.
#[must_use]
pub fn collect_fixture_files(dir: &Path, format_filter: &Option<String>) -> Vec<PathBuf> {
    let mut files = Vec::new();
    if !dir.exists() {
        return files;
    }
    if let Ok(entries) = std::fs::read_dir(dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                files.extend(collect_fixture_files(&path, format_filter));
            } else if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
                let fmt = match ext {
                    "png" => Some("png"),
                    "jpg" | "jpeg" => Some("jpeg"),
                    "webp" => Some("webp"),
                    _ => None,
                };
                if let Some(f) = fmt {
                    if format_filter.as_ref().is_none_or(|filter| filter == f) {
                        files.push(path);
                    }
                }
            }
        }
    }
    files
}

/// Expected decode outcome for a fixture.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DecodeExpectation {
    /// Image should decode successfully.
    #[default]
    Pass,
    /// Image should fail to decode.
    Fail,
    /// Either outcome is acceptable.
    Either,
}

/// Expected XMP validity for a fixture.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum XmpExpectation {
    /// XMP should be present and valid XML.
    #[default]
    Valid,
    /// XMP should be present but invalid XML.
    Invalid,
    /// No XMP should be present.
    Absent,
    /// Any XMP state is acceptable.
    Either,
}

/// Expected extraction outcome for a fixture.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ExtractionExpectation {
    /// Extraction should succeed with metadata.
    #[default]
    Success,
    /// Extraction should find no notice.
    NoNotice,
    /// Fixture should be rejected.
    Reject,
}

/// Legal field values expected for a fixture.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ExpectedLegalFields {
    /// Expected copyright holder.
    pub copyright_holder: Option<String>,
    /// Expected creator.
    pub creator: Option<String>,
    /// Expected copyright owner.
    pub copyright_owner: Option<String>,
    /// Expected usage terms.
    pub usage_terms: Option<String>,
    /// Expected web statement of rights.
    pub web_statement_of_rights: Option<String>,
    /// Expected AI constraints text.
    pub ai_constraints: Option<String>,
    /// Expected credit line.
    pub credit_line: Option<String>,
    /// Expected licensor name.
    pub licensor_name: Option<String>,
    /// Expected licensor email.
    pub licensor_email: Option<String>,
    /// Expected licensor URL.
    pub licensor_url: Option<String>,
}

/// A single fixture entry in the TOML manifest.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FixtureEntry {
    /// Unique identifier for this fixture.
    pub id: String,
    /// Relative path from the fixtures directory root.
    pub path: String,
    /// Detected image format (png, jpeg, webp).
    pub format: String,
    /// Fixture category (canonical, legacy, conflicting, malformed, preservation).
    pub category: String,
    /// Tool used to generate this fixture.
    pub authoring_tool: String,
    /// Version of the authoring tool.
    pub authoring_tool_version: String,
    /// Command used to generate this fixture.
    pub generation_command: String,
    /// Source of the fixture (generated, external).
    pub source: String,
    /// License identifier.
    pub license: String,
    /// SHA-256 hex digest of the fixture file.
    pub sha256: String,
    /// Expected DMI value string.
    pub expected_dmi: String,
    /// Whether this fixture is expected to have conflicting metadata.
    pub expected_conflict: bool,
    /// Expected legal field values.
    #[serde(default)]
    pub expected_legal_fields: ExpectedLegalFields,
    /// Whether this fixture is expected to be malformed (legacy, use expected_decode instead).
    #[serde(default)]
    pub expected_malformed: bool,
    /// Expected decode outcome.
    #[serde(default)]
    pub expected_decode: DecodeExpectation,
    /// Expected XMP validity.
    #[serde(default)]
    pub expected_xmp: XmpExpectation,
    /// Expected internal extraction outcome.
    #[serde(default)]
    pub expected_internal: ExtractionExpectation,
    /// Expected external extraction outcome.
    #[serde(default)]
    pub expected_external: ExtractionExpectation,
    /// Fields required to be present in external extraction.
    #[serde(default)]
    pub required_external_fields: Vec<String>,
    /// Expected preserved field names after re-processing.
    #[serde(default)]
    pub expected_preservation: Vec<String>,
}

/// The full fixture manifest loaded from TOML.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FixtureManifest {
    /// All fixture entries.
    #[serde(default = "Vec::new", rename = "fixture")]
    pub entries: Vec<FixtureEntry>,
}

impl FixtureManifest {
    /// Compute SHA-256 hex digest for a file on disk.
    pub fn compute_sha256(path: &Path) -> std::io::Result<String> {
        use sha2::{Digest, Sha256};
        let bytes = std::fs::read(path)?;
        let mut hasher = Sha256::new();
        hasher.update(&bytes);
        Ok(hex::encode(hasher.finalize()))
    }

    /// Find a fixture entry by its relative path within the fixtures directory.
    #[must_use]
    pub fn find_by_path(&self, path: &str) -> Option<&FixtureEntry> {
        self.entries.iter().find(|e| e.path == path)
    }

    /// Build a path-to-entry index for O(1) lookups.
    #[must_use]
    pub fn path_index(&self) -> std::collections::HashMap<String, &FixtureEntry> {
        self.entries.iter().map(|e| (e.path.clone(), e)).collect()
    }

    /// Return all entries belonging to a given category.
    #[must_use]
    pub fn entries_by_category(&self, category: &str) -> Vec<&FixtureEntry> {
        self.entries
            .iter()
            .filter(|e| e.category == category)
            .collect()
    }

    /// Return all entries matching a given format.
    #[must_use]
    pub fn entries_by_format(&self, format: &str) -> Vec<&FixtureEntry> {
        self.entries.iter().filter(|e| e.format == format).collect()
    }

    /// Count entries grouped by authoring tool.
    #[must_use]
    pub fn count_by_authoring_tool(&self) -> std::collections::HashMap<String, usize> {
        let mut counts = std::collections::HashMap::new();
        for entry in &self.entries {
            *counts.entry(entry.authoring_tool.clone()).or_insert(0) += 1;
        }
        counts
    }
}

/// Load a fixture manifest from a TOML file.
pub fn load_manifest(path: &Path) -> Result<FixtureManifest, String> {
    let content = std::fs::read_to_string(path)
        .map_err(|e| format!("Failed to read manifest {}: {}", path.display(), e))?;
    let manifest: FixtureManifest =
        toml::from_str(&content).map_err(|e| format!("Failed to parse manifest: {}", e))?;
    Ok(manifest)
}

/// Validate manifest structure before processing fixtures.
///
/// Checks for duplicate IDs, duplicate paths, empty IDs, path traversal,
/// unsupported formats/categories, missing SHA-256, and other structural issues.
pub fn validate_manifest(manifest: &FixtureManifest) -> Result<(), Vec<String>> {
    let mut errors = Vec::new();
    let mut seen_ids = std::collections::HashSet::new();
    let mut seen_paths = std::collections::HashSet::new();

    let valid_formats = ["png", "jpeg", "webp"];
    let valid_categories = [
        "canonical",
        "legacy",
        "conflicting",
        "malformed",
        "preservation",
    ];
    let valid_sources = [
        "generated",
        "external",
        "historical",
        "generated-negative",
        "current-generated",
    ];

    for entry in &manifest.entries {
        if entry.id.is_empty() {
            errors.push(format!("Fixture at '{}' has empty ID", entry.path));
        }
        if !seen_ids.insert(&entry.id) {
            errors.push(format!("Duplicate fixture ID: '{}'", entry.id));
        }
        if !seen_paths.insert(&entry.path) {
            errors.push(format!("Duplicate fixture path: '{}'", entry.path));
        }
        if entry.path.starts_with('/') || entry.path.starts_with('\\') {
            errors.push(format!("Fixture '{}' has absolute path", entry.id));
        }
        if entry.path.contains("..") {
            errors.push(format!(
                "Fixture '{}' contains path traversal (..)",
                entry.id
            ));
        }
        if !valid_formats.contains(&entry.format.as_str()) {
            errors.push(format!(
                "Fixture '{}' has unsupported format: '{}'",
                entry.id, entry.format
            ));
        }
        if !valid_categories.contains(&entry.category.as_str()) {
            errors.push(format!(
                "Fixture '{}' has unsupported category: '{}'",
                entry.id, entry.category
            ));
        }
        if !valid_sources.contains(&entry.source.as_str()) {
            errors.push(format!(
                "Fixture '{}' has unsupported source: '{}'",
                entry.id, entry.source
            ));
        }
        if entry.sha256.is_empty() {
            errors.push(format!("Fixture '{}' has empty SHA-256", entry.id));
        } else if entry.sha256.len() != 64 || !entry.sha256.chars().all(|c| c.is_ascii_hexdigit()) {
            errors.push(format!(
                "Fixture '{}' has invalid SHA-256: expected 64 hex characters",
                entry.id
            ));
        }
        if entry.source == "external" && entry.authoring_tool_version.is_empty() {
            errors.push(format!(
                "Fixture '{}' has empty authoring_tool_version for external source",
                entry.id
            ));
        }
    }

    if errors.is_empty() {
        Ok(())
    } else {
        Err(errors)
    }
}

/// Result of SHA-256 digest verification for a single fixture.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DigestCheckResult {
    /// Fixture ID from the manifest.
    pub fixture_id: String,
    /// Relative path of the fixture file.
    pub fixture_path: String,
    /// Expected SHA-256 hex digest from the manifest.
    pub expected: String,
    /// Actual SHA-256 hex digest computed from the file.
    pub observed: String,
    /// Whether the digests match.
    pub matches: bool,
}

/// Verify SHA-256 digests of all fixtures referenced by the manifest.
///
/// Returns a `DigestCheckResult` for each entry. Callers should check
/// `matches` to determine if verification passed.
pub fn verify_fixtures(manifest: &FixtureManifest, fixtures_dir: &Path) -> Vec<DigestCheckResult> {
    manifest
        .entries
        .iter()
        .map(|entry| {
            let full_path = fixtures_dir.join(&entry.path);
            let actual = FixtureManifest::compute_sha256(&full_path).unwrap_or_default();
            DigestCheckResult {
                fixture_id: entry.id.clone(),
                fixture_path: entry.path.clone(),
                expected: entry.sha256.clone(),
                observed: actual.clone(),
                matches: actual == entry.sha256,
            }
        })
        .collect()
}

/// Minimum counts required per category/format for coverage enforcement.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CoverageMinimums {
    /// Minimum canonical PNG fixtures required.
    pub canonical_png: usize,
    /// Minimum canonical JPEG fixtures required.
    pub canonical_jpeg: usize,
    /// Minimum canonical WebP fixtures required.
    pub canonical_webp: usize,
    /// Minimum total legacy fixtures required.
    pub legacy_min: usize,
    /// Minimum distinct formats required in legacy category.
    pub legacy_formats: usize,
    /// Minimum conflicting fixtures required.
    pub conflict_min: usize,
    /// Minimum malformed fixtures required.
    pub malformed_min: usize,
    /// Minimum malformed fixtures per format (png, jpeg, webp).
    pub malformed_per_format: usize,
    /// Minimum preservation fixtures required.
    pub preservation_min: usize,
    /// Minimum distinct formats required in preservation category.
    pub preservation_formats: usize,
    /// Minimum external canonical PNG fixtures required.
    pub external_canonical_png: usize,
    /// Minimum external canonical JPEG fixtures required.
    pub external_canonical_jpeg: usize,
    /// Minimum external canonical WebP fixtures required.
    pub external_canonical_webp: usize,
    /// Minimum external legacy fixtures required.
    pub external_legacy_min: usize,
    /// Minimum external alt-prefix fixtures required.
    pub external_alt_prefix_min: usize,
    /// Minimum external conflict fixtures required.
    pub external_conflict_min: usize,
    /// Minimum external preservation fixtures required.
    pub external_preservation_min: usize,
}

impl Default for CoverageMinimums {
    fn default() -> Self {
        Self {
            canonical_png: 1,
            canonical_jpeg: 1,
            canonical_webp: 1,
            legacy_min: 3,
            legacy_formats: 2,
            conflict_min: 3,
            malformed_min: 4,
            malformed_per_format: 1,
            preservation_min: 3,
            preservation_formats: 3,
            external_canonical_png: 1,
            external_canonical_jpeg: 1,
            external_canonical_webp: 1,
            external_legacy_min: 1,
            external_alt_prefix_min: 1,
            external_conflict_min: 1,
            external_preservation_min: 1,
        }
    }
}

/// Result of coverage enforcement.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CoverageCheckResult {
    /// Whether all coverage minimums are met.
    pub passed: bool,
    /// List of coverage violation descriptions.
    pub violations: Vec<String>,
    /// Observed canonical PNG count.
    pub observed_canonical_png: usize,
    /// Observed canonical JPEG count.
    pub observed_canonical_jpeg: usize,
    /// Observed canonical WebP count.
    pub observed_canonical_webp: usize,
    /// Observed legacy count.
    pub observed_legacy: usize,
    /// Observed conflict count.
    pub observed_conflict: usize,
    /// Observed malformed count.
    pub observed_malformed: usize,
    /// Observed preservation count.
    pub observed_preservation: usize,
    /// Observed external canonical PNG count.
    pub observed_external_canonical_png: usize,
    /// Observed external canonical JPEG count.
    pub observed_external_canonical_jpeg: usize,
    /// Observed external canonical WebP count.
    pub observed_external_canonical_webp: usize,
    /// Observed external legacy count.
    pub observed_external_legacy: usize,
    /// Observed external alt-prefix count.
    pub observed_external_alt_prefix: usize,
    /// Observed external conflict count.
    pub observed_external_conflict: usize,
    /// Observed external preservation count.
    pub observed_external_preservation: usize,
}

/// Enforce coverage minimums against a manifest.
#[must_use]
pub fn check_coverage(
    manifest: &FixtureManifest,
    minimums: &CoverageMinimums,
) -> CoverageCheckResult {
    let mut violations = Vec::new();

    let canonical = manifest.entries_by_category("canonical");
    let canonical_png = canonical.iter().filter(|e| e.format == "png").count();
    let canonical_jpeg = canonical.iter().filter(|e| e.format == "jpeg").count();
    let canonical_webp = canonical.iter().filter(|e| e.format == "webp").count();

    if canonical_png < minimums.canonical_png {
        violations.push(format!(
            "canonical PNG: {} < {}",
            canonical_png, minimums.canonical_png
        ));
    }
    if canonical_jpeg < minimums.canonical_jpeg {
        violations.push(format!(
            "canonical JPEG: {} < {}",
            canonical_jpeg, minimums.canonical_jpeg
        ));
    }
    if canonical_webp < minimums.canonical_webp {
        violations.push(format!(
            "canonical WebP: {} < {}",
            canonical_webp, minimums.canonical_webp
        ));
    }

    let legacy = manifest.entries_by_category("legacy");
    let legacy_format_count = legacy
        .iter()
        .map(|e| e.format.as_str())
        .collect::<std::collections::HashSet<_>>()
        .len();
    if legacy.len() < minimums.legacy_min {
        violations.push(format!(
            "legacy: {} < {}",
            legacy.len(),
            minimums.legacy_min
        ));
    }
    if legacy_format_count < minimums.legacy_formats {
        violations.push(format!(
            "legacy formats: {} < {}",
            legacy_format_count, minimums.legacy_formats
        ));
    }

    let conflict = manifest.entries_by_category("conflicting");
    if conflict.len() < minimums.conflict_min {
        violations.push(format!(
            "conflict: {} < {}",
            conflict.len(),
            minimums.conflict_min
        ));
    }

    let malformed = manifest.entries_by_category("malformed");
    if malformed.len() < minimums.malformed_min {
        violations.push(format!(
            "malformed: {} < {}",
            malformed.len(),
            minimums.malformed_min
        ));
    }
    let malformed_png = malformed.iter().filter(|e| e.format == "png").count();
    let malformed_jpeg = malformed.iter().filter(|e| e.format == "jpeg").count();
    let malformed_webp = malformed.iter().filter(|e| e.format == "webp").count();
    if minimums.malformed_per_format > 0 {
        if malformed_png < minimums.malformed_per_format {
            violations.push(format!(
                "malformed PNG: {} < {}",
                malformed_png, minimums.malformed_per_format
            ));
        }
        if malformed_jpeg < minimums.malformed_per_format {
            violations.push(format!(
                "malformed JPEG: {} < {}",
                malformed_jpeg, minimums.malformed_per_format
            ));
        }
        if malformed_webp < minimums.malformed_per_format {
            violations.push(format!(
                "malformed WebP: {} < {}",
                malformed_webp, minimums.malformed_per_format
            ));
        }
    }

    let preservation = manifest.entries_by_category("preservation");
    let preservation_format_count = preservation
        .iter()
        .map(|e| e.format.as_str())
        .collect::<std::collections::HashSet<_>>()
        .len();
    if preservation.len() < minimums.preservation_min {
        violations.push(format!(
            "preservation: {} < {}",
            preservation.len(),
            minimums.preservation_min
        ));
    }
    if preservation_format_count < minimums.preservation_formats {
        violations.push(format!(
            "preservation formats: {} < {}",
            preservation_format_count, minimums.preservation_formats
        ));
    }

    let external_canonical_png = canonical
        .iter()
        .filter(|e| e.format == "png" && e.source == "external")
        .count();
    let external_canonical_jpeg = canonical
        .iter()
        .filter(|e| e.format == "jpeg" && e.source == "external")
        .count();
    let external_canonical_webp = canonical
        .iter()
        .filter(|e| e.format == "webp" && e.source == "external")
        .count();
    let external_legacy = legacy.iter().filter(|e| e.source == "external").count();
    let external_conflict = conflict.iter().filter(|e| e.source == "external").count();
    let external_preservation = preservation
        .iter()
        .filter(|e| e.source == "external")
        .count();
    let external_alt_prefix = manifest
        .entries
        .iter()
        .filter(|e| e.source == "external" && e.category == "canonical")
        .filter(|e| {
            e.generation_command.contains("alt")
                || e.generation_command.contains("prefix")
                || e.id.contains("alt")
        })
        .count();

    if external_canonical_png < minimums.external_canonical_png {
        violations.push(format!(
            "external canonical PNG: {} < {}",
            external_canonical_png, minimums.external_canonical_png
        ));
    }
    if external_canonical_jpeg < minimums.external_canonical_jpeg {
        violations.push(format!(
            "external canonical JPEG: {} < {}",
            external_canonical_jpeg, minimums.external_canonical_jpeg
        ));
    }
    if external_canonical_webp < minimums.external_canonical_webp {
        violations.push(format!(
            "external canonical WebP: {} < {}",
            external_canonical_webp, minimums.external_canonical_webp
        ));
    }
    if external_legacy < minimums.external_legacy_min {
        violations.push(format!(
            "external legacy: {} < {}",
            external_legacy, minimums.external_legacy_min
        ));
    }
    if external_alt_prefix < minimums.external_alt_prefix_min {
        violations.push(format!(
            "external alt-prefix: {} < {}",
            external_alt_prefix, minimums.external_alt_prefix_min
        ));
    }
    if external_conflict < minimums.external_conflict_min {
        violations.push(format!(
            "external conflict: {} < {}",
            external_conflict, minimums.external_conflict_min
        ));
    }
    if external_preservation < minimums.external_preservation_min {
        violations.push(format!(
            "external preservation: {} < {}",
            external_preservation, minimums.external_preservation_min
        ));
    }

    CoverageCheckResult {
        passed: violations.is_empty(),
        violations,
        observed_canonical_png: canonical_png,
        observed_canonical_jpeg: canonical_jpeg,
        observed_canonical_webp: canonical_webp,
        observed_legacy: legacy.len(),
        observed_conflict: conflict.len(),
        observed_malformed: malformed.len(),
        observed_preservation: preservation.len(),
        observed_external_canonical_png: external_canonical_png,
        observed_external_canonical_jpeg: external_canonical_jpeg,
        observed_external_canonical_webp: external_canonical_webp,
        observed_external_legacy: external_legacy,
        observed_external_alt_prefix: external_alt_prefix,
        observed_external_conflict: external_conflict,
        observed_external_preservation: external_preservation,
    }
}

/// Aggregate summary across multiple conformance reports.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConformanceSummary {
    /// Total number of reports.
    pub total: usize,
    /// Number of passing reports.
    pub passed: usize,
    /// Number of failing reports.
    pub failed: usize,
    /// Report counts grouped by image format.
    pub by_format: std::collections::HashMap<String, usize>,
    /// Report counts grouped by fixture category.
    pub by_category: std::collections::HashMap<String, usize>,
    /// Digest verification results, if performed.
    pub digest_verification: Option<Vec<DigestCheckResult>>,
    /// Coverage check results, if performed.
    pub coverage: Option<CoverageCheckResult>,
    /// Coverage minimums used for this run, if applicable.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub coverage_minimums: Option<CoverageMinimums>,
}

impl ConformanceSummary {
    /// Build a summary from a slice of conformance reports.
    #[must_use]
    pub fn from_reports(reports: &[ConformanceReport]) -> Self {
        let total = reports.len();
        let passed = reports.iter().filter(|r| r.passed).count();
        let failed = total - passed;

        let mut by_format = std::collections::HashMap::new();
        for report in reports {
            *by_format.entry(report.format.clone()).or_insert(0) += 1;
        }

        Self {
            total,
            passed,
            failed,
            by_format,
            by_category: std::collections::HashMap::new(),
            digest_verification: None,
            coverage: None,
            coverage_minimums: None,
        }
    }

    /// Attach digest verification results.
    pub fn with_digest_verification(&mut self, results: Vec<DigestCheckResult>) {
        self.digest_verification = Some(results);
    }

    /// Attach coverage check results.
    pub fn with_coverage(&mut self, result: CoverageCheckResult) {
        self.coverage = Some(result);
    }

    /// Attach coverage minimums for the report envelope.
    pub fn with_coverage_minimums(&mut self, minimums: CoverageMinimums) {
        self.coverage_minimums = Some(minimums);
    }

    /// Human-readable summary string.
    #[must_use]
    pub fn summary(&self) -> String {
        let mut lines = Vec::new();
        lines.push(format!(
            "Conformance Summary: {} total, {} passed, {} failed",
            self.total, self.passed, self.failed
        ));

        if !self.by_format.is_empty() {
            lines.push("By format:".to_string());
            for (fmt, count) in &self.by_format {
                lines.push(format!("  {}: {}", fmt, count));
            }
        }

        if let Some(ref digest) = self.digest_verification {
            let matching = digest.iter().filter(|d| d.matches).count();
            lines.push(format!(
                "Digest verification: {}/{} passed",
                matching,
                digest.len()
            ));
        }

        if let Some(ref coverage) = self.coverage {
            if coverage.passed {
                lines.push("Coverage: PASS".to_string());
            } else {
                lines.push("Coverage: FAIL".to_string());
                for v in &coverage.violations {
                    lines.push(format!("  - {}", v));
                }
            }
        }

        lines.join("\n")
    }
}

/// Report on a single external tool used during a conformance run.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolReport {
    /// Logical name of the tool (e.g., "exiftool").
    pub name: String,
    /// Resolved executable path, if discovered.
    pub path: Option<String>,
    /// Version string, if available.
    pub version: Option<String>,
    /// Whether discovery succeeded.
    pub discovered: bool,
    /// Whether the tool was actually exercised on fixtures.
    pub exercised: bool,
    /// Number of fixture invocations.
    pub invocations: u32,
    /// Number of successful invocations.
    pub successes: u32,
    /// Number of failed invocations.
    pub failures: u32,
}

/// Report on the manifest used during a conformance run.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ManifestReport {
    /// Requested manifest path.
    pub requested_path: String,
    /// Canonicalized path when available.
    pub canonical_path: Option<String>,
    /// SHA-256 digest of the manifest file.
    pub sha256: String,
    /// Number of entries in the manifest.
    pub entry_count: usize,
    /// Validation result.
    pub validation: Result<(), Vec<String>>,
    /// Number of duplicate entries detected.
    pub duplicate_count: usize,
    /// Number of unlisted fixtures (on disk but not in manifest).
    pub unlisted_count: usize,
    /// Number of unexercised entries (in manifest but not processed).
    pub unexercised_count: usize,
}

/// Versioned run report envelope wrapping all conformance results.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConformanceRunReport {
    /// Schema version of this report format.
    pub schema_version: u32,
    /// Name of the tool that generated this report.
    pub generated_by: String,
    /// Crate version of the conformance harness.
    pub crate_version: String,
    /// Git commit SHA, if available.
    pub commit_sha: Option<String>,
    /// Whether strict mode was enabled.
    pub strict: bool,
    /// Whether all required inputs/tools were available and every check executed.
    pub complete: bool,
    /// Whether complete is true and no required check failed.
    pub passed: bool,
    /// ISO 8601 timestamp of when the run started, if available.
    pub started_at: Option<String>,
    /// Manifest report, if a manifest was provided.
    pub manifest: Option<ManifestReport>,
    /// Reports for each external tool.
    pub tools: Vec<ToolReport>,
    /// Coverage minimums used for this run.
    pub coverage_minimums: Option<CoverageMinimums>,
    /// Coverage check results.
    pub coverage: Option<CoverageCheckResult>,
    /// SHA-256 digest verification results for each fixture.
    pub digest_verification: Vec<DigestCheckResult>,
    /// Aggregate summary.
    pub summary: ConformanceSummary,
    /// Reasons the run is incomplete, if any.
    pub incomplete_reasons: Vec<String>,
    /// Per-fixture conformance reports.
    pub fixtures: Vec<ConformanceReport>,
}

/// Detect whether a JPEG file uses progressive encoding.
#[must_use]
pub fn is_progressive_jpeg(bytes: &[u8]) -> bool {
    if bytes.len() < 4 || !bytes.starts_with(b"\xFF\xD8\xFF") {
        return false;
    }
    let mut pos = 2;
    while pos + 4 <= bytes.len() {
        if bytes[pos] != 0xFF {
            break;
        }
        let marker = bytes[pos + 1];
        if marker == 0xD8 || marker == 0xD9 {
            pos += 2;
            continue;
        }
        if marker == 0xC0 || marker == 0xC2 {
            return marker == 0xC2;
        }
        let length = u16::from_be_bytes([bytes[pos + 2], bytes[pos + 3]]) as usize;
        pos += 2 + length;
    }
    false
}