auditmysite 1.3.0

Resource-efficient WCAG 2.1 Accessibility Checker in Rust
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
//! Audit Report data structure
//!
//! Contains the complete results of an accessibility audit.

use std::collections::BTreeMap;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use crate::audit::scoring::{AccessibilityScorer, ViolationStatistics};
use crate::browser::ThrottleProfile;
use crate::cli::WcagLevel;
use crate::dark_mode::DarkModeAnalysis;
use crate::mobile::MobileFriendliness;
use crate::performance::{
    AnimationAnalysis, ContentWeight, CoverageAnalysis, CriticalChain, MinificationAnalysis,
    PerformanceScore, RenderBlockingAnalysis, ThirdPartyAttribution, WebVitals,
};
use crate::security::SecurityAnalysis;
use crate::seo::SeoAnalysis;
use crate::ux::UxAnalysis;
use crate::wcag::WcagResults;

/// Execution state shared by modules, subchecks and the overall audit.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ExecutionStatus {
    Completed,
    Partial,
    Failed,
    Skipped,
    NotApplicable,
    #[default]
    NotRequested,
}

/// One recorded module or sub-analysis run. `reason_code` is stable and safe
/// for public JSON; `message` is deliberately short and sanitized.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ModuleRun {
    pub module: String,
    pub status: ExecutionStatus,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub viewports: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub subchecks: Vec<SubcheckRun>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason_code: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SubcheckRun {
    pub subcheck: String,
    pub status: ExecutionStatus,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason_code: Option<String>,
}

/// Requested audit scope, independent of whether the measurements succeeded.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AuditScope {
    #[serde(default)]
    pub requested_modules: Vec<String>,
    pub full_audit: bool,
    pub interactive_mode: String,
    pub journey_budget_ms: u64,
    #[serde(default)]
    pub throttling_profiles: Vec<String>,
    #[serde(default)]
    pub viewports: Vec<ViewportDefinition>,
    pub dismiss_consent: bool,
    pub capture_screenshots: bool,
    pub capture_element_evidence: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ViewportDefinition {
    pub name: String,
    pub width: u32,
    pub height: u32,
    pub device_scale_factor: f64,
}

/// Public, reproducibility-oriented browser information. Executable paths and
/// launch flags intentionally stay out of the report.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ExecutionEnvironment {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub browser_version: Option<String>,
    pub headless: bool,
    #[serde(default)]
    pub source: String,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct NavigationSnapshot {
    pub requested_url: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub final_url: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub main_document_status: Option<u16>,
    #[serde(default)]
    pub redirect_count: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ready_state: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub stability: Vec<crate::interaction::stability::StabilityProvenance>,
}

#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AuditedContentState {
    BeforeConsent,
    AfterConsent,
    #[default]
    Unknown,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ConsentAuditState {
    pub detected: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cmp: Option<String>,
    pub dismissal_requested: bool,
    pub dismissed: bool,
    pub audited_content_state: AuditedContentState,
    #[serde(default)]
    pub status: Option<crate::browser::consent::ConsentHandlingStatus>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub evidence: Vec<String>,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AuditQualityStatus {
    #[default]
    Complete,
    Partial,
    Insufficient,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AuditQuality {
    pub status: AuditQualityStatus,
    pub qualified_results: bool,
    #[serde(default)]
    pub failed_rule_checks: usize,
    #[serde(default)]
    pub partial_or_failed_modules: usize,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub reasons: Vec<String>,
}

/// Complete execution/provenance block persisted with the raw audit report.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AuditExecution {
    #[serde(default)]
    pub scope: AuditScope,
    #[serde(default)]
    pub environment: ExecutionEnvironment,
    #[serde(default)]
    pub navigation: NavigationSnapshot,
    #[serde(default)]
    pub consent: ConsentAuditState,
    #[serde(default)]
    pub module_runs: Vec<ModuleRun>,
    #[serde(default)]
    pub quality: AuditQuality,
}

/// Performance vitals measured under a single network throttle profile.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThrottledPerfResult {
    pub profile: ThrottleProfile,
    /// LCP in milliseconds
    pub lcp_ms: Option<f64>,
    /// TBT in milliseconds
    pub tbt_ms: Option<f64>,
    /// CLS score
    pub cls: Option<f64>,
    /// Aggregate performance score (0–100)
    pub score: u32,
}

/// Screenshot bytes captured during the audit (desktop + mobile viewports).
/// Not serialized — only used for PDF output.
#[derive(Debug, Clone)]
pub struct PageScreenshots {
    pub desktop: Vec<u8>,
    pub mobile: Vec<u8>,
}

/// Cookie metadata snapshot around consent interaction. Cookie values are never stored.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ConsentPrivacySnapshot {
    pub before_interaction: Vec<ConsentCookieSignal>,
    pub after_interaction: Vec<ConsentCookieSignal>,
    pub added_after_interaction: Vec<ConsentCookieSignal>,
}

/// Cookie signal stored for consent/privacy comparison without cookie values.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub struct ConsentCookieSignal {
    pub name: String,
    pub domain: String,
    pub secure: bool,
    pub http_only: bool,
    pub same_site: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub provider: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub category: Option<String>,
}

/// Why device-preview screenshots are or are not available in this report.
/// Used by the PDF renderer to surface the right callout when screenshots
/// are missing (failure reason vs. not-requested).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(tag = "state", content = "reason")]
pub enum ScreenshotStatus {
    /// Screenshots were captured successfully.
    Captured,
    /// Capture was attempted but failed; the string holds a short reason.
    Failed(String),
    /// Capture was not attempted for this audit (e.g. batch mode).
    #[default]
    NotRequested,
}

/// Viewport screenshot with layout metadata
#[derive(Debug, Clone)]
pub struct ViewportScreenshot {
    pub bytes: Vec<u8>,
    pub width: u32,
    pub height: u32,
    pub device_scale_factor: f64,
    pub scroll_x: f64,
    pub scroll_y: f64,
}

/// Raw audit data for a single viewport pass.
/// Not serialized — kept in-memory for output builders.
#[derive(Debug, Clone)]
pub struct ViewportAuditData {
    pub wcag_results: WcagResults,
    pub accessibility_score: f32,
    pub performance: Option<PerformanceResults>,
    pub seo: Option<SeoAnalysis>,
    pub mobile: Option<MobileFriendliness>,
    pub ux: Option<crate::ux::UxAnalysis>,
    pub journey: Option<crate::journey::JourneyAnalysis>,
    pub screenshot: Option<ViewportScreenshot>,
    pub module_runs: Vec<ModuleRun>,
}

/// Dual-viewport raw results — desktop and mobile passes.
/// Not serialized — kept in-memory only.
#[derive(Debug, Clone)]
pub struct DualViewportResults {
    pub desktop: ViewportAuditData,
    pub mobile: ViewportAuditData,
}

/// Per-viewport scores for JSON / CLI output.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ViewportScoreSet {
    pub accessibility: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub performance: Option<u32>,
    pub overall: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ViewportScores {
    pub desktop: ViewportScoreSet,
    pub mobile: ViewportScoreSet,
    /// 70 % mobile + 30 % desktop (before security adjustment)
    pub weighted_overall: u32,
}

impl ViewportScores {
    /// Canonical accessibility score for a dual-viewport audit.
    ///
    /// The calculation uses the same displayed integer viewport scores that
    /// are serialized to JSON, so readers can reproduce the result exactly.
    pub fn weighted_accessibility(&self) -> u32 {
        (self.mobile.accessibility as f64 * 0.7 + self.desktop.accessibility as f64 * 0.3).round()
            as u32
    }
}

/// User-experience signals grouped together: mobile friendliness, dark-mode
/// support and performance-budget violations. First of the planned `AuditReport`
/// section structs that replace the flat list of optional module fields.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ExperienceSection {
    /// Mobile friendliness analysis (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mobile: Option<MobileFriendliness>,
    /// Dark mode support and quality analysis (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dark_mode: Option<DarkModeAnalysis>,
    /// Opt-in design-quality heuristics (#528, optional). Never affects
    /// accessibility/overall score, grade, or certificate.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub design_quality: Option<crate::design_quality::DesignQualityAnalysis>,
    /// Opt-in C2PA image-provenance check (EU AI Act Art. 50, optional,
    /// single-URL mode only). Never affects accessibility/overall score,
    /// grade, or certificate.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub ai_transparency: Option<crate::ai_transparency::AiTransparencyAnalysis>,
    /// Opt-in DNS-configuration check (CAA, DNSSEC, SPF/MX — #545, optional).
    /// Host-scoped rather than page-scoped (see `network::dns::module`), but
    /// still attached per-page here like the other opt-in modules. Never
    /// affects accessibility/overall score, grade, or certificate.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub network_dns: Option<crate::network::dns::NetworkDnsAnalysis>,
    /// Budget violations detected for this page
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub budget_violations: Vec<crate::audit::budget::BudgetViolation>,
}

/// Core accessibility results — the WCAG check output, the resulting score/grade/
/// certificate, violation statistics and the analyzed node count. Grouped into a
/// section so the `AuditReport` top level stays stable as modules evolve.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AccessibilitySection {
    /// WCAG check results
    pub wcag_results: WcagResults,
    /// Overall accessibility score (0-100)
    pub score: f32,
    /// Letter grade (A-F)
    pub grade: String,
    /// Certificate level (SEHR GUT, GUT, STABIL, AUSBAUFÄHIG, UNGENÜGEND)
    pub certificate: String,
    /// Detailed violation statistics
    pub statistics: ViolationStatistics,
    /// Number of AXTree nodes analyzed
    pub nodes_analyzed: usize,
    /// Audit execution scope, provenance and completeness. Kept alongside the
    /// core result so older raw-report caches can default it safely.
    #[serde(default)]
    pub execution: AuditExecution,
}

/// Discoverability signals grouped together: how findable and machine-readable
/// the page is — search engines (SEO), AI/LLM assistants, organic content
/// visibility, source quality and the detected tech stack.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct DiscoverabilitySection {
    /// SEO analysis (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub seo: Option<SeoAnalysis>,
    /// AI visibility analysis (LLM-Readability, Citation, Chunks, Knowledge Graph, Policy)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ai_visibility: Option<crate::ai_visibility::AiVisibilityAnalysis>,
    /// Content visibility analysis (organic visibility, local business, E-E-A-T, depth, topical authority)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_visibility: Option<crate::content_visibility::ContentVisibilityAnalysis>,
    /// Source quality analysis (Substanz / Konsistenz / Autorität)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_quality: Option<crate::source_quality::SourceQualityAnalysis>,
    /// Technology stack detection and stack-specific audit findings.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tech_stack: Option<crate::tech_stack::TechStackAnalysis>,
}

/// Complete audit report for a single URL
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditReport {
    /// The URL that was audited
    pub url: String,
    /// WCAG conformance level used for the audit
    pub wcag_level: WcagLevel,
    /// Timestamp when the audit was performed
    pub timestamp: DateTime<Utc>,
    /// Core accessibility results (WCAG output, score/grade/certificate, stats).
    pub accessibility: AccessibilitySection,
    /// Time taken to complete the audit (milliseconds)
    pub duration_ms: u64,
    /// Performance analysis (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub performance: Option<PerformanceResults>,
    /// Security analysis (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub security: Option<SecurityAnalysis>,
    /// HTML5 spec-conformance analysis (optional) — URL/page-level, not
    /// per-viewport, same placement rationale as `security`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub html_conform: Option<crate::html_conform::HtmlConformAnalysis>,
    /// User-experience signals grouped into one section: mobile friendliness,
    /// dark-mode support and performance-budget violations.
    #[serde(default)]
    pub experience: ExperienceSection,
    /// UX analysis (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ux: Option<UxAnalysis>,
    /// Journey analysis (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub journey: Option<crate::journey::JourneyAnalysis>,
    /// Discoverability signals grouped together: SEO, AI/LLM visibility, content
    /// visibility, source quality and tech-stack detection.
    #[serde(default)]
    pub discoverability: DiscoverabilitySection,
    /// Screenshots for PDF cover page (captured during audit, not serialized).
    #[serde(skip)]
    pub page_screenshots: Option<PageScreenshots>,
    /// Raw dual-viewport data (not serialized — in-memory only for output builders).
    #[serde(skip)]
    pub dual_viewport: Option<DualViewportResults>,
    /// Per-viewport scores (serialized for JSON consumers).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub viewport_scores: Option<ViewportScores>,
    /// Performance vitals measured under different network throttle profiles.
    /// Only populated for single-page audits when performance analysis is enabled.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub throttled_performance: Vec<ThrottledPerfResult>,
    /// Structural UI pattern detection results (MainNavigation, SkipLink, etc).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub patterns: Option<crate::patterns::PatternAnalysis>,
    /// Device preview screenshot capture state (issue #26).
    #[serde(default)]
    pub screenshot_status: ScreenshotStatus,
    /// Best practices analysis (console errors, vulnerable libraries)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub best_practices: Option<crate::best_practices::BestPracticesAnalysis>,
    /// Commerce / shop schema-completeness analysis (only on product pages)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub commerce: Option<crate::commerce::CommerceAnalysis>,
    /// Whether a consent banner was detected during the audit
    #[serde(default)]
    pub consent_banner_detected: bool,
    /// Which CMP was identified (if any)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub consent_banner_cmp: Option<String>,
    /// Whether the banner was successfully dismissed
    #[serde(default)]
    pub consent_banner_dismissed: bool,
    /// Cookie snapshot before/after consent interaction; values are never stored.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub consent_privacy: Option<ConsentPrivacySnapshot>,
    /// Accessibility-Journey-Layer result (populated when `--interactive != off`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub accessibility_journey: Option<crate::audit::normalized::AccessibilityJourney>,
    /// Interactive findings produced by the Accessibility-Journey-Layer
    /// evaluator. Empty when `--interactive=off`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub interactive_findings: Vec<crate::audit::normalized::InteractiveFinding>,
    /// Standalone screen-reader audit artifact. Written as sidecar JSON output.
    #[serde(skip)]
    pub screen_reader_audit: Option<crate::screen_reader::SrAuditReport>,
}

/// Performance analysis results wrapper
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceResults {
    /// Core Web Vitals
    pub vitals: WebVitals,
    /// Performance score
    pub score: PerformanceScore,
    /// Render-blocking resource analysis
    #[serde(skip_serializing_if = "Option::is_none")]
    pub render_blocking: Option<RenderBlockingAnalysis>,
    /// Page content weight / resource breakdown
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_weight: Option<ContentWeight>,
    /// Third-party resource attribution per origin (#138)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub third_party: Option<ThirdPartyAttribution>,
    /// Critical request chain / network dependency tree (#132)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub critical_chain: Option<CriticalChain>,
    /// Unminified JS/CSS asset detection (#111)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub minification: Option<MinificationAnalysis>,
    /// Non-composited animation detection (#105)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub animations: Option<AnimationAnalysis>,
    /// Unused JS (#106) and CSS (#107) via CDP Coverage API
    #[serde(skip_serializing_if = "Option::is_none")]
    pub coverage: Option<CoverageAnalysis>,
    /// Implausible or unmeasurable metrics detected during analysis (#291).
    /// Keys: "tbt_zero_heavy_page", "speed_index_fallback_to_lcp",
    /// "tti_fallback_to_lcp", "inp_not_measured".
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub measurement_warnings: Vec<String>,
}

impl AuditReport {
    /// Create a new audit report
    pub fn new(
        url: String,
        wcag_level: WcagLevel,
        wcag_results: WcagResults,
        duration_ms: u64,
    ) -> Self {
        let score = AccessibilityScorer::calculate_score(&wcag_results.violations);
        let grade = AccessibilityScorer::calculate_grade(score).to_string();
        let certificate = AccessibilityScorer::calculate_certificate(score).to_string();
        let statistics = AccessibilityScorer::calculate_statistics(&wcag_results.violations);
        let nodes_analyzed = wcag_results.nodes_checked;

        Self {
            url,
            wcag_level,
            timestamp: Utc::now(),
            accessibility: AccessibilitySection {
                wcag_results,
                score,
                grade,
                certificate,
                statistics,
                nodes_analyzed,
                execution: AuditExecution::default(),
            },
            duration_ms,
            performance: None,
            security: None,
            html_conform: None,
            experience: ExperienceSection::default(),
            ux: None,
            journey: None,
            discoverability: DiscoverabilitySection {
                seo: None,
                ai_visibility: None,
                content_visibility: None,
                source_quality: None,
                tech_stack: None,
            },
            page_screenshots: None,
            dual_viewport: None,
            viewport_scores: None,
            throttled_performance: Vec::new(),
            patterns: None,
            screenshot_status: ScreenshotStatus::NotRequested,
            best_practices: None,
            commerce: None,
            consent_banner_detected: false,
            consent_banner_cmp: None,
            consent_banner_dismissed: false,
            consent_privacy: None,
            accessibility_journey: None,
            interactive_findings: Vec::new(),
            screen_reader_audit: None,
        }
    }

    /// Set performance results
    pub fn with_performance(mut self, performance: PerformanceResults) -> Self {
        self.performance = Some(performance);
        self
    }

    /// Attach pattern detection results.
    pub fn with_patterns(mut self, patterns: crate::patterns::PatternAnalysis) -> Self {
        self.patterns = Some(patterns);
        self
    }

    /// Set SEO results
    pub fn with_seo(mut self, seo: SeoAnalysis) -> Self {
        self.discoverability.seo = Some(seo);
        self
    }

    /// Set security results
    pub fn with_security(mut self, security: SecurityAnalysis) -> Self {
        self.security = Some(security);
        self
    }

    /// Set HTML5 spec-conformance results
    pub fn with_html_conform(
        mut self,
        html_conform: crate::html_conform::HtmlConformAnalysis,
    ) -> Self {
        self.html_conform = Some(html_conform);
        self
    }

    /// Set mobile friendliness results
    pub fn with_mobile(mut self, mobile: MobileFriendliness) -> Self {
        self.experience.mobile = Some(mobile);
        self
    }

    /// Set UX analysis results
    pub fn with_ux(mut self, ux: UxAnalysis) -> Self {
        self.ux = Some(ux);
        self
    }

    /// Set journey analysis results
    pub fn with_journey(mut self, journey: crate::journey::JourneyAnalysis) -> Self {
        self.journey = Some(journey);
        self
    }

    /// Set dark mode analysis results
    pub fn with_dark_mode(mut self, dark_mode: DarkModeAnalysis) -> Self {
        self.experience.dark_mode = Some(dark_mode);
        self
    }

    /// Set design-quality analysis results (#528)
    pub fn with_design_quality(
        mut self,
        design_quality: crate::design_quality::DesignQualityAnalysis,
    ) -> Self {
        self.experience.design_quality = Some(design_quality);
        self
    }

    /// Set ai-transparency analysis results (EU AI Act Art. 50)
    pub fn with_ai_transparency(
        mut self,
        ai_transparency: crate::ai_transparency::AiTransparencyAnalysis,
    ) -> Self {
        self.experience.ai_transparency = Some(ai_transparency);
        self
    }

    /// Set DNS-configuration check results (#545)
    pub fn with_network_dns(
        mut self,
        network_dns: crate::network::dns::NetworkDnsAnalysis,
    ) -> Self {
        self.experience.network_dns = Some(network_dns);
        self
    }

    pub fn with_tech_stack(mut self, tech_stack: crate::tech_stack::TechStackAnalysis) -> Self {
        self.discoverability.tech_stack = Some(tech_stack);
        self
    }

    pub fn with_best_practices(mut self, bp: crate::best_practices::BestPracticesAnalysis) -> Self {
        self.best_practices = Some(bp);
        self
    }

    /// Get the total number of violations
    pub fn violation_count(&self) -> usize {
        self.accessibility.wcag_results.violations.len()
    }

    /// Check if the audit passed (no critical violations, score >= 70)
    pub fn passed(&self) -> bool {
        self.accessibility.score >= 70.0
            && !self
                .accessibility
                .wcag_results
                .violations
                .iter()
                .any(|v| v.severity == crate::wcag::Severity::Critical)
    }
}

// The weighted overall score is computed canonically in `audit::normalized`
// (see `NormalizedReport.overall_score` and `build_module_scores`). A second,
// divergent `AuditReport::overall_score()` previously lived here but was only
// reachable from tests; it was removed to keep a single source of truth (#447).

/// Batch audit report for multiple URLs
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchReport {
    /// Individual reports for each URL
    pub reports: Vec<AuditReport>,
    /// URLs that failed to audit (with error messages)
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub errors: Vec<BatchError>,
    /// Summary statistics
    pub summary: BatchSummary,
    /// Optional crawl/link diagnostics if the batch originated from crawler discovery
    #[serde(skip_serializing_if = "Option::is_none")]
    pub crawl_diagnostics: Option<CrawlDiagnostics>,
    /// Optional sitemap HTTP/indexability diagnostics when the batch originated
    /// from an XML sitemap.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub sitemap_diagnostics: Option<SitemapDiagnostics>,
    /// Cross-page consistency analysis (issues #44/#45/#46). None when the
    /// batch contains fewer than 2 pages.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub consistency: Option<crate::audit::batch_consistency::BatchConsistencyAnalysis>,
    /// How the audited URLs were discovered and sampled. Lets consumers tell a
    /// representative sample apart from full domain coverage (issue #261).
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub sample: Option<SampleMetadata>,
    /// Total execution time
    pub total_duration_ms: u64,
}

/// Where the audited URL set came from and how it was sampled.
///
/// Without this, a 20-of-500 sample is indistinguishable from a complete audit
/// in the report. Surfacing the population size, the applied limit and the
/// selection method makes the scope of a batch explicit (issue #261).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SampleMetadata {
    /// Origin of the candidate URLs: `"sitemap"`, `"crawl"` or `"url_file"`.
    pub source: String,
    /// Candidate URLs discovered before any limit/sampling was applied.
    pub total_discovered: usize,
    /// URLs actually selected and audited.
    pub audited: usize,
    /// The `--max-pages` limit, when one capped the audited set.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sample_limit: Option<usize>,
    /// How the audited subset was chosen: `"first_n"` (sitemap/discovery order)
    /// or `"all"` when every discovered URL was audited.
    pub selection: String,
    /// True when fewer URLs were audited than discovered — i.e. this is a sample,
    /// not full coverage.
    pub is_sample: bool,
}

/// Sitemap URL validation result for sitemap-driven batch reports.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SitemapDiagnostics {
    /// Number of sitemap URLs checked via HTTP.
    pub checked_urls: usize,
    /// Sitemap entries that do not resolve to a direct canonical 200 response,
    /// or that are marked noindex.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub http_issues: Vec<SitemapHttpIssue>,
    /// URLs present in the sitemap but not linked by any audited page.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub orphan_sitemap_urls: Vec<String>,
    /// Internal targets linked by audited pages but absent from the sitemap.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub linked_not_in_sitemap: Vec<String>,
    /// Sitemap entries blocked by a `Disallow` rule in `robots.txt` under
    /// `User-agent: *` — a URL with declared indexing intent (sitemap
    /// membership) that crawlers following `robots.txt` will not fetch (#549).
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub robots_conflicts: Vec<RobotsSitemapConflict>,
    /// Crawl-depth (BFS click-distance from a heuristic start page) through
    /// this batch run's internal link graph (#548). `None` when no
    /// reasonable start-page candidate was audited.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub crawl_depths: Option<CrawlDepthDiagnostics>,
}

/// Crawl-depth diagnostics for a sitemap-driven batch (#548): BFS distance
/// (in clicks) from a heuristically-chosen start page to every other
/// audited page, following each page's already-extracted internal link
/// targets.
///
/// Deliberately scoped to *this batch run's* link graph, not the true
/// site-wide graph: a link to a page outside the audited set can't be
/// followed further (that page's own outbound links are unknown), so depth
/// here is a lower bound within the audited pages, not a guarantee about
/// the real site. `partial_batch` flags when the audited set is smaller
/// than the full discovered sitemap (a `--max-pages` sample, or pages that
/// failed to audit), which makes that gap more likely to matter — the
/// report surfaces this as an explicit caveat rather than silently
/// presenting a partial graph as complete.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CrawlDepthDiagnostics {
    /// The page BFS started from (heuristic: shortest-path sitemap URL,
    /// root `/` naturally wins).
    pub start_url: String,
    /// Depth (in clicks) -> number of audited pages at that depth. 0 is the
    /// start page itself.
    pub depth_histogram: BTreeMap<usize, usize>,
    /// The most-clicks-away pages, capped and sorted deepest-first —
    /// intentionally not a full per-page dump (see #548).
    pub deepest_pages: Vec<CrawlDepthEntry>,
    /// Audited pages never reached by following internal links from
    /// `start_url` within this batch, capped — distinct from "very deep",
    /// not a default/fallback depth.
    pub unreachable_pages: Vec<String>,
    /// True when the audited set is smaller than the full discovered
    /// sitemap (sampling via `--max-pages`, or per-page audit failures) —
    /// depth and reachability are then only a partial view of the real
    /// site-wide link graph.
    pub partial_batch: bool,
}

/// One page's BFS click-distance from the crawl-depth start page.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CrawlDepthEntry {
    pub url: String,
    pub depth: usize,
}

/// One sitemap URL blocked by a `robots.txt` `Disallow` rule under
/// `User-agent: *` (#549) — a contradiction between declared indexing intent
/// (sitemap membership) and actual crawler access.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RobotsSitemapConflict {
    pub url: String,
    /// The specific `Disallow` path prefix that blocks this URL.
    pub rule: String,
}

/// One sitemap URL whose HTTP/indexability state contradicts sitemap guidance.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SitemapHttpIssue {
    /// Canonical issue kind: `"status"`, `"redirect"`, `"noindex"` or `"fetch_error"`.
    pub kind: String,
    pub url: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status_code: Option<u16>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub final_url: Option<String>,
    pub detail: String,
}

/// Severity of a broken or problematic link finding
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum BrokenLinkSeverity {
    High,
    Medium,
    Low,
}

/// A redirect chain with more than 1 hop detected during link checking.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RedirectChain {
    /// Page that contains the link
    pub source_url: String,
    /// Original link target
    pub target_url: String,
    /// Final resolved URL after all redirects
    pub final_url: String,
    /// Number of redirect hops
    pub hops: u8,
    /// Whether the link points to an external domain
    pub is_external: bool,
}

/// Optional crawl/link diagnostics attached to crawler-driven batch reports.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CrawlDiagnostics {
    /// Seed URL that started discovery
    pub seed_url: String,
    /// Number of discovered pages in the crawl set
    pub discovered_urls: usize,
    /// Number of unique internal links that were status-checked
    pub checked_internal_links: usize,
    /// Broken internal links (4xx/5xx or fetch failure)
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub broken_internal_links: Vec<BrokenLink>,
    /// Number of unique external links that were status-checked
    pub checked_external_links: usize,
    /// Broken external links (4xx/5xx or fetch failure)
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub broken_external_links: Vec<BrokenLink>,
    /// Links with more than 1 redirect hop
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub redirect_chains: Vec<RedirectChain>,
}

/// A broken internal link found during crawl-based link checking.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BrokenLink {
    /// Page that contains the broken link
    pub source_url: String,
    /// Link target that failed
    pub target_url: String,
    /// HTTP status code if available
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status_code: Option<u16>,
    /// Error reason for network/content failures
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    /// Whether the link points to an external domain
    pub is_external: bool,
    /// Number of redirect hops before reaching the final status (0 = direct)
    #[serde(default)]
    pub redirect_hops: u8,
    /// Severity derived from link type and status
    pub severity: BrokenLinkSeverity,
}

/// A failed URL audit
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchError {
    /// The URL that failed
    pub url: String,
    /// Error message
    pub error: String,
}

/// One WCAG rule that recurred across multiple pages in a batch audit.
/// Domain-level type; used by BatchSummary and the JSON output formatter.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RecurringRule {
    pub rule_id: String,
    pub title: String,
    pub wcag_criterion: String,
    pub wcag_level: String,
    pub severity: crate::taxonomy::Severity,
    /// Number of pages where this rule fired.
    pub affected_pages: usize,
    /// Sum of `occurrence_count` over all affected pages.
    pub total_occurrences: usize,
}

/// Summary statistics for a batch audit
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchSummary {
    /// Total URLs audited
    pub total_urls: usize,
    /// URLs that passed
    pub passed: usize,
    /// URLs that failed
    pub failed: usize,
    /// Average score across all URLs
    pub average_score: f64,
    /// Total violations found
    pub total_violations: usize,
    /// Top-10 WCAG rules by page frequency, computed across all audited pages.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub top_recurring_rules: Vec<RecurringRule>,
    /// Number of distinct WCAG + SEO rule IDs that fired anywhere across all pages.
    #[serde(default)]
    pub violated_rule_count: usize,
    /// Number of distinct WCAG Level-A rules with High/Critical severity across
    /// all pages (legal exposure indicator).
    #[serde(default)]
    pub legal_flags: usize,
    /// Sum of blocking-interaction-issue occurrences (unlabeled interactive
    /// elements, 4.1.2/2.1.1) across all pages. Mirrors the single-page
    /// `RiskAssessment.blocking_issues` signal so the batch CI verdict can
    /// fail on it too (#QA-028).
    #[serde(default)]
    pub blocking_issues: usize,
    /// Worst-case risk level across all audited pages.
    #[serde(default)]
    pub risk: crate::audit::normalized::RiskLevel,
    /// i18n key for the batch verdict sentence ("verdict-batch-excellent", …).
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub verdict_key: String,
    /// WCAG findings verified to share one template/component root cause
    /// across multiple pages — see `audit::template_dedup`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub template_clusters: Vec<crate::audit::template_dedup::TemplateCluster>,
    #[serde(default)]
    pub audit_quality: AuditQuality,
}

/// Compute top-10 recurring WCAG rules and total violated-rule count across
/// a set of normalized reports. Used by `BatchReport::from_reports` and the
/// JSON formatter for single-page summary blocks.
///
/// Returns `(top_recurring_rules, violated_rule_count)`.
pub fn compute_recurring_rules(
    reports: &[crate::audit::normalized::NormalizedReport],
) -> (Vec<RecurringRule>, usize) {
    use std::collections::{HashMap, HashSet};

    let violated_rule_count = reports
        .iter()
        .flat_map(|r| r.findings.iter().map(|f| f.rule_id.as_str()))
        .collect::<HashSet<_>>()
        .len();

    struct Acc {
        title: String,
        wcag_criterion: String,
        wcag_level: String,
        severity: crate::taxonomy::Severity,
        affected_pages: usize,
        total_occurrences: usize,
    }

    let mut by_rule: HashMap<String, Acc> = HashMap::new();
    for report in reports {
        for f in report.findings.iter().filter(|f| f.category == "wcag") {
            let entry = by_rule.entry(f.rule_id.clone()).or_insert(Acc {
                title: f.title.clone(),
                wcag_criterion: f.wcag_criterion.clone(),
                wcag_level: f.wcag_level.clone(),
                severity: f.severity,
                affected_pages: 0,
                total_occurrences: 0,
            });
            entry.affected_pages += 1;
            entry.total_occurrences += f.occurrence_count;
        }
    }

    let mut rules: Vec<RecurringRule> = by_rule
        .into_iter()
        .map(|(rule_id, a)| RecurringRule {
            rule_id,
            title: a.title,
            wcag_criterion: a.wcag_criterion,
            wcag_level: a.wcag_level,
            severity: a.severity,
            affected_pages: a.affected_pages,
            total_occurrences: a.total_occurrences,
        })
        .collect();
    rules.sort_by(|a, b| {
        b.affected_pages
            .cmp(&a.affected_pages)
            .then_with(|| b.total_occurrences.cmp(&a.total_occurrences))
            .then_with(|| b.severity.cmp(&a.severity))
    });
    rules.truncate(10);

    (rules, violated_rule_count)
}

/// Count the number of distinct WCAG Level-A rules with High/Critical severity
/// that appear across any of the given reports (legal exposure indicator).
///
/// Also accounts for legal exposure raised purely by the screen-reader BFSG
/// verdict (`RiskAssessment.legal_flags` can exceed the page's own WCAG
/// Level-A finding count, see `audit::normalized::compute_risk`). That signal
/// has no WCAG rule id of its own, so it is represented as a synthetic member
/// of the same distinct-signal set whenever it fires on at least one page —
/// otherwise a page could FAIL its single-page verdict on this signal while
/// contributing nothing to the batch's legal_flags summary (#QA-024).
fn compute_legal_flags(reports: &[crate::audit::normalized::NormalizedReport]) -> usize {
    use crate::taxonomy::Severity;
    use std::collections::HashSet;

    let mut rule_ids: HashSet<&str> = reports
        .iter()
        .flat_map(|r| r.findings.iter())
        .filter(|f| {
            f.wcag_level == "A" && matches!(f.severity, Severity::Critical | Severity::High)
        })
        .map(|f| f.rule_id.as_str())
        .collect();

    let sr_only_legal_exposure = reports.iter().any(|r| {
        let findings_based = r
            .findings
            .iter()
            .filter(|f| {
                f.wcag_level == "A" && matches!(f.severity, Severity::Critical | Severity::High)
            })
            .count();
        r.risk.legal_flags > findings_based
    });
    if sr_only_legal_exposure {
        rule_ids.insert("screen_reader.bfsg_noncompliant");
    }

    rule_ids.len()
}

/// Compute the worst-case risk level across a set of normalized reports.
///
/// Critical: any page is Critical.
/// High: ≥ 20% of pages are High (or worse).
/// Medium: ≥ 20% of pages are Medium or worse.
/// Low: otherwise.
///
/// Severity buckets are cumulative — a High-risk page also counts toward the
/// Medium threshold — so e.g. 1 High + 1 Medium page out of 10 (20% elevated)
/// correctly escalates to Medium instead of each bucket independently missing
/// the 20% cutoff and silently reporting Low (#QA-022).
pub fn compute_worst_risk(
    reports: &[crate::audit::normalized::NormalizedReport],
) -> crate::audit::normalized::RiskLevel {
    use crate::audit::normalized::RiskLevel;
    use std::collections::HashMap;

    let page_count = reports.len().max(1);
    let mut counts: HashMap<RiskLevel, usize> = HashMap::new();
    for r in reports {
        *counts.entry(r.risk.level).or_insert(0) += 1;
    }

    let critical = *counts.get(&RiskLevel::Critical).unwrap_or(&0);
    let high = *counts.get(&RiskLevel::High).unwrap_or(&0);
    let medium = *counts.get(&RiskLevel::Medium).unwrap_or(&0);

    if critical > 0 {
        RiskLevel::Critical
    } else if high * 5 >= page_count {
        RiskLevel::High
    } else if (high + medium) * 5 >= page_count {
        RiskLevel::Medium
    } else {
        RiskLevel::Low
    }
}

impl BatchReport {
    /// Create a batch report from individual reports and errors
    pub fn from_reports(
        reports: Vec<AuditReport>,
        errors: Vec<BatchError>,
        total_duration_ms: u64,
    ) -> Self {
        let total_urls = reports.len();
        let normalized_reports: Vec<crate::audit::normalized::NormalizedReport> = reports
            .iter()
            .map(|r| crate::audit::normalized::normalize(r).normalized)
            .collect();
        // Pass criterion: accessibility score ≥ 80, no critical findings, and
        // no legal exposure. See issue #253. Uses the page's own risk
        // assessment (`r.risk.legal_flags`) rather than recomputing from
        // findings, so screen-reader-derived legal exposure (#484) is not
        // silently dropped in batch mode while it fails the single-page
        // verdict (#QA-024).
        let passed = normalized_reports
            .iter()
            .filter(|r| r.score >= 80 && r.severity_counts.critical == 0 && r.risk.legal_flags == 0)
            .count();
        let failed = total_urls - passed;

        let average_score = if total_urls > 0 {
            normalized_reports
                .iter()
                .map(|r| r.score as f64)
                .sum::<f64>()
                / total_urls as f64
        } else {
            0.0
        };

        let total_violations = normalized_reports
            .iter()
            .flat_map(|r| r.findings.iter())
            .map(|f| f.occurrence_count)
            .sum();

        let (top_recurring_rules, violated_rule_count) =
            compute_recurring_rules(&normalized_reports);
        let template_clusters =
            crate::audit::template_dedup::detect_template_clusters(&normalized_reports);
        let legal_flags = compute_legal_flags(&normalized_reports);
        let blocking_issues = normalized_reports
            .iter()
            .map(|r| r.risk.blocking_issues)
            .sum();
        let risk = compute_worst_risk(&normalized_reports);
        let audit_quality = {
            let failed_rule_checks = normalized_reports
                .iter()
                .map(|report| report.execution.quality.failed_rule_checks)
                .sum();
            let partial_or_failed_modules = normalized_reports
                .iter()
                .map(|report| report.execution.quality.partial_or_failed_modules)
                .sum();
            let status = if normalized_reports
                .iter()
                .any(|report| report.execution.quality.status == AuditQualityStatus::Insufficient)
            {
                AuditQualityStatus::Insufficient
            } else if normalized_reports
                .iter()
                .any(|report| report.execution.quality.status == AuditQualityStatus::Partial)
            {
                AuditQualityStatus::Partial
            } else {
                AuditQualityStatus::Complete
            };
            AuditQuality {
                status,
                qualified_results: status != AuditQualityStatus::Complete,
                failed_rule_checks,
                partial_or_failed_modules,
                reasons: Vec::new(),
            }
        };
        let verdict_key = {
            let s = average_score.round() as u32;
            if s >= 90 {
                "verdict-batch-excellent"
            } else if s >= 70 {
                "verdict-batch-solid"
            } else if s >= 50 {
                "verdict-batch-deficient"
            } else {
                "verdict-batch-critical"
            }
            .to_string()
        };

        let mut result = Self {
            reports,
            errors,
            summary: BatchSummary {
                total_urls,
                passed,
                failed,
                average_score,
                total_violations,
                top_recurring_rules,
                violated_rule_count,
                legal_flags,
                blocking_issues,
                risk,
                verdict_key,
                template_clusters,
                audit_quality,
            },
            crawl_diagnostics: None,
            sitemap_diagnostics: None,
            consistency: None,
            sample: None,
            total_duration_ms,
        };
        result.consistency = crate::audit::batch_consistency::analyze(&result);
        result
    }

    pub fn with_crawl_diagnostics(mut self, diagnostics: CrawlDiagnostics) -> Self {
        self.crawl_diagnostics = Some(diagnostics);
        self
    }

    pub fn with_sitemap_diagnostics(mut self, diagnostics: SitemapDiagnostics) -> Self {
        self.sitemap_diagnostics = Some(diagnostics);
        self
    }

    pub fn with_sample(mut self, sample: SampleMetadata) -> Self {
        self.sample = Some(sample);
        self
    }
}

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

    #[test]
    fn test_audit_report_new() {
        let results = WcagResults::new();
        let report = AuditReport::new(
            "https://example.com".to_string(),
            WcagLevel::AA,
            results,
            500,
        );

        assert_eq!(report.url, "https://example.com");
        assert_eq!(report.accessibility.score, 100.0); // No violations = perfect score
        assert_eq!(report.duration_ms, 500);
        assert!(report.performance.is_none());
        assert!(report.discoverability.seo.is_none());
        assert!(report.security.is_none());
        assert!(report.experience.mobile.is_none());
    }

    #[test]
    fn test_batch_report() {
        let reports = vec![
            AuditReport::new(
                "https://a.com".to_string(),
                WcagLevel::AA,
                WcagResults::new(),
                100,
            ),
            AuditReport::new(
                "https://b.com".to_string(),
                WcagLevel::AA,
                WcagResults::new(),
                200,
            ),
        ];

        let batch = BatchReport::from_reports(reports, vec![], 300);

        assert_eq!(batch.summary.total_urls, 2);
        assert_eq!(batch.summary.passed, 2);
        assert_eq!(batch.summary.average_score, 100.0);
    }

    #[test]
    fn test_passed_with_perfect_score() {
        let report = AuditReport::new(
            "https://example.com".to_string(),
            WcagLevel::AA,
            WcagResults::new(),
            100,
        );
        assert!(report.passed());
    }

    #[test]
    fn test_passed_with_critical_violation() {
        let mut results = WcagResults::new();
        results.add_violation(crate::wcag::Violation::new(
            "1.1.1",
            "Non-text Content",
            WcagLevel::A,
            crate::wcag::Severity::Critical,
            "Missing alt",
            "node-1",
        ));
        let report = AuditReport::new(
            "https://example.com".to_string(),
            WcagLevel::AA,
            results,
            100,
        );
        assert!(!report.passed());
    }

    #[test]
    fn test_with_builder_methods() {
        let report = AuditReport::new(
            "https://example.com".to_string(),
            WcagLevel::AA,
            WcagResults::new(),
            100,
        );

        let report = report.with_security(crate::security::SecurityAnalysis {
            score: 80,
            grade: "A".to_string(),
            headers: Default::default(),
            ssl: Default::default(),
            issues: vec![],
            recommendations: vec![],
            protection: Default::default(),
            sourcemap_leaks: Default::default(),
        });

        assert!(report.security.is_some());
        assert_eq!(report.security.as_ref().unwrap().score, 80);
    }

    #[test]
    fn test_violation_count() {
        let mut results = WcagResults::new();
        results.add_violation(crate::wcag::Violation::new(
            "1.1.1",
            "Non-text Content",
            WcagLevel::A,
            crate::wcag::Severity::High,
            "Missing alt",
            "node-1",
        ));
        let report = AuditReport::new(
            "https://example.com".to_string(),
            WcagLevel::AA,
            results,
            100,
        );
        assert_eq!(report.violation_count(), 1);
    }

    #[test]
    fn batch_summary_has_recurring_rules_and_risk() {
        let reports = vec![
            AuditReport::new(
                "https://a.com".into(),
                WcagLevel::AA,
                WcagResults::new(),
                100,
            ),
            AuditReport::new(
                "https://b.com".into(),
                WcagLevel::AA,
                WcagResults::new(),
                100,
            ),
        ];
        let batch = BatchReport::from_reports(reports, vec![], 0);
        // No violations: no recurring rules, no violated rules, Low risk
        assert!(batch.summary.top_recurring_rules.is_empty());
        assert_eq!(batch.summary.violated_rule_count, 0);
        assert_eq!(batch.summary.legal_flags, 0);
        assert_eq!(batch.summary.risk, crate::audit::normalized::RiskLevel::Low);
    }

    #[test]
    fn compute_recurring_rules_aggregates_across_pages() {
        use crate::audit::normalized::normalize;
        use crate::wcag::Violation;

        let mut results1 = WcagResults::new();
        results1.add_violation(Violation::new(
            "1.1.1",
            "Alt",
            WcagLevel::A,
            crate::wcag::Severity::High,
            "Missing alt",
            "n1",
        ));

        let mut results2 = WcagResults::new();
        results2.add_violation(Violation::new(
            "1.1.1",
            "Alt",
            WcagLevel::A,
            crate::wcag::Severity::High,
            "Missing alt",
            "n2",
        ));

        let report1 = AuditReport::new("https://a.com".into(), WcagLevel::AA, results1, 100);
        let report2 = AuditReport::new("https://b.com".into(), WcagLevel::AA, results2, 100);
        let r1 = normalize(&report1);
        let r2 = normalize(&report2);

        let (rules, violated_count) = compute_recurring_rules(&[r1.normalized, r2.normalized]);
        assert_eq!(violated_count, 1, "one distinct rule fired");
        assert_eq!(rules.len(), 1);
        assert_eq!(rules[0].affected_pages, 2, "rule appeared on both pages");
        assert_eq!(rules[0].total_occurrences, 2);
    }

    #[test]
    fn compute_worst_risk_critical_if_any_critical_page() {
        use crate::audit::normalized::{normalize, RiskLevel};
        use crate::wcag::Violation;

        // Create two pages: one with no violations (Low risk) and one with
        // many critical violations that push it to Critical risk.
        let empty_report = AuditReport::new(
            "https://a.com".into(),
            WcagLevel::AA,
            WcagResults::new(),
            100,
        );
        let empty = normalize(&empty_report);

        // Build a report likely to be Critical risk: legal_flags > 0 + critical issues
        let mut results = WcagResults::new();
        for i in 0..3 {
            results.add_violation(Violation::new(
                "1.1.1",
                "Alt",
                WcagLevel::A,
                crate::wcag::Severity::Critical,
                "missing",
                format!("n{i}"),
            ));
        }
        let risky_report = AuditReport::new("https://b.com".into(), WcagLevel::AA, results, 50);
        let risky = normalize(&risky_report);

        let risk = compute_worst_risk(&[empty.normalized, risky.normalized]);
        // Risky page should pull the batch to at least Medium or higher
        assert!(
            matches!(
                risk,
                RiskLevel::Critical | RiskLevel::High | RiskLevel::Medium
            ),
            "batch risk must be elevated when one page has critical issues, got {:?}",
            risk
        );
    }
}