auditmysite 1.0.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
//! Report ViewModel — structured, block-based presentation model
//!
//! Transforms raw audit data into a ViewModel where each block maps 1:1
//! to a report section. The renderer (pdf.rs) only calls add_component()
//! with data from the ViewModel — zero data transformation in the renderer.

use std::path::PathBuf;

use crate::cli::ReportLevel;
use crate::wcag::Severity;

/// Signal detail: category name mapped to a list of (check_label, passed, detail).
pub type SignalDetails = Vec<(String, Vec<(String, bool, String)>)>;

/// Configuration for PDF report generation
pub struct ReportConfig {
    pub level: ReportLevel,
    pub logo_path: Option<PathBuf>,
    pub locale: String,
}

impl Default for ReportConfig {
    fn default() -> Self {
        Self {
            level: ReportLevel::Standard,
            logo_path: None,
            locale: "de".to_string(),
        }
    }
}

// ─── Shared Enums ───────────────────────────────────────────────────────────

/// Priority, Effort and ExecutionPriority are domain prioritization concepts and
/// now live in `audit::prioritization`; re-exported here so existing
/// `report_model::{Priority, Effort, ExecutionPriority}` references keep working.
pub use crate::audit::prioritization::{Effort, ExecutionPriority, Priority};

/// Responsible role for a fix
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Role {
    Development,
    Editorial,
    DesignUx,
    ProjectManagement,
}

impl Role {
    pub fn label(&self, en: bool) -> &'static str {
        match self {
            Role::Development => {
                if en {
                    "Development"
                } else {
                    "Entwicklung"
                }
            }
            Role::Editorial => {
                if en {
                    "Content"
                } else {
                    "Redaktion"
                }
            }
            Role::DesignUx => "Design / UX",
            Role::ProjectManagement => {
                if en {
                    "Project management"
                } else {
                    "Projektleitung"
                }
            }
        }
    }
}

// ─── Evaluation Summary Types ────────────────────────────────────────────────

/// Snapshot summary of all findings — derived from AuditSummary for quick access in renderers.
pub struct FindingSummary {
    pub total: usize,
    pub critical: usize,
    pub high: usize,
    pub medium: usize,
    pub low: usize,
    pub verdict: String,
    pub dominant_issue_note: Option<String>,
    pub cross_impact_notes: Vec<String>,
    pub issue_pattern_label: String,
}

/// Summary of actionable tasks organized by semantic execution priority.
pub struct TaskSummary {
    pub blocker_count: usize,
    pub high_count: usize,
    pub medium_count: usize,
    pub low_count: usize,
    pub total_count: usize,
    /// Label of the role responsible for the most tasks
    pub primary_role: String,
}

/// Thematic cluster of related findings sharing a dimension or subcategory.
pub struct FindingCluster {
    pub label: String,
    pub dimension: String,
    pub finding_count: usize,
    pub occurrence_total: usize,
    pub severity_label: String,
    pub finding_titles: Vec<String>,
}

/// System-level diagnosis section: pattern analysis, clusters, systematic assessment.
pub struct DiagnosisBlock {
    pub section_title: String,
    pub pattern_label: String,
    pub pattern_description: String,
    pub is_systematic: bool,
    /// (dimension, finding_count, severity_label) per category
    pub category_breakdown: Vec<(String, usize, String)>,
    pub dominant_issue: Option<String>,
    pub verdict_intro: String,
    pub clusters: Vec<FindingCluster>,
}

// ─── Report ViewModel (Single Report) ───────────────────────────────────────

/// Complete ViewModel for a single audit report.
/// Each block maps 1:1 to a report section — the renderer does zero data transformation.
pub struct ReportViewModel {
    pub meta: MetaBlock,
    pub cover: CoverBlock,
    pub summary: SummaryBlock,
    pub executive: ExecutiveNarrativeBlock,
    pub methodology: MethodologyBlock,
    pub modules: ModulesBlock,
    pub severity: SeverityBlock,
    pub findings: FindingsBlock,
    pub diagnosis: DiagnosisBlock,
    pub module_details: ModuleDetailsBlock,
    pub actions: ActionsBlock,
    pub appendix: AppendixBlock,
    /// Recognized structural patterns (positive signals).
    pub positive_signals: PositiveSignalsBlock,
}

/// Positive structural patterns recognized in the page.
/// Rendered as a green "what's working well" section in the PDF.
pub struct PositiveSignalsBlock {
    pub items: Vec<PositiveSignal>,
}

pub struct PositiveSignal {
    pub title: String,
    pub description: String,
    /// True when all structural criteria for the pattern matched.
    pub strong: bool,
}

impl PositiveSignalsBlock {
    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }
}

/// Report metadata for engine setup
pub struct MetaBlock {
    pub title: String,
    pub subtitle: String,
    pub date: String,
    pub version: String,
    pub author: String,
    pub report_level: ReportLevel,
    pub score_label: String,
}

/// Cover page data
pub struct CoverBlock {
    pub brand: String,
    pub title: String,
    pub domain: String,
    pub subtitle: String,
    pub date: String,
    pub score: u32,
    pub grade: String,
    pub certificate: String,
    /// 4-level maturity label for cover display
    pub maturity_label: String,
    pub total_issues: u32,
    pub critical_issues: u32,
    pub modules: Vec<String>,
    /// Desktop accessibility score from dual-viewport pass (if available)
    pub desktop_score: Option<u32>,
    /// Mobile accessibility score from dual-viewport pass (if available)
    pub mobile_score: Option<u32>,
}

/// Hero summary / Kurzfazit data
pub struct SummaryBlock {
    /// Accessibility-only score (corrected after suppressions).
    pub score: u32,
    /// Module-weighted overall score across all active modules.
    pub overall_score: u32,
    pub grade: String,
    pub certificate: String,
    /// 4-level maturity classification: "Kritisch" / "Instabil" / "Solide Basis" / "Stark"
    pub maturity_label: String,
    /// Problem distribution: "Strukturelle Defizite" / "Kritische Einzelprobleme" / "Feinschliff"
    pub problem_type: String,
    pub domain: String,
    pub date: String,
    pub executive_lead: String,
    /// When a single rule dominates ≥ 45 % of urgent findings: highlighted note for callout display.
    pub dominant_issue_note: Option<String>,
    pub verdict: String,
    pub score_note: Option<String>,
    pub metrics: Vec<MetricItem>,
    pub top_actions: Vec<String>,
    pub positive_aspects: Vec<String>,
    /// Overall impact assessment: [(label, value), ...] e.g. ("Nutzer", "eingeschränkt")
    pub overall_impact: Vec<(String, String)>,
    /// Cross-module technical insights: short bullet strings
    pub technical_overview: Vec<String>,
    /// Score-range benchmark context (e.g. "Besser als ~60% der geprüften Seiten")
    pub benchmark_context: String,
    /// Concrete current business impact (1 sentence for KV: "Die Seite wird schlechter gefunden…")
    pub business_consequence: String,
    /// Forward-looking consequence: what happens if nothing is fixed
    pub consequence: String,
    /// Risk level label (Gering / Mittel / Hoch / Kritisch)
    pub risk_level: String,
    /// Risk summary (one sentence)
    pub risk_summary: String,
}

/// Precomputed copy and structure for the executive PDF narrative.
pub struct ExecutiveNarrativeBlock {
    pub cover_eyebrow: String,
    pub cover_kicker: String,
    pub key_points: Vec<String>,
    pub next_steps_callout_body: String,
}

/// A single KPI metric for the hero summary
pub struct MetricItem {
    pub title: String,
    pub value: String,
    pub accent_color: Option<String>,
}

/// Methodology section
pub struct MethodologyBlock {
    pub scope: String,
    pub method: String,
    pub limitations: String,
    pub disclaimer: String,
    pub audit_facts: Vec<(String, String)>,
    pub confidence_summary: Vec<(String, String)>,
    pub capabilities: Vec<CapabilitySignal>,
}

/// Module scores for dashboard and comparison
pub struct ModulesBlock {
    pub dashboard: Vec<ModuleScore>,
    pub overall_score: Option<u32>,
    pub overall_interpretation: Option<String>,
}

/// A single module's score data
pub struct ModuleScore {
    pub name: String,
    pub score: u32,
    pub measurement_type: String,
    pub interpretation: String,
    pub card_context: String,
    pub score_context: String,
    pub key_lever: String,
    pub good_threshold: u32,
    pub warn_threshold: u32,
}

/// Pre-computed severity breakdown
pub struct SeverityBlock {
    pub critical: u32,
    pub high: u32,
    pub medium: u32,
    pub low: u32,
    pub total: u32,
    pub has_issues: bool,
    /// Number of findings classified as component/template issues (occurrence_count >= 10).
    pub component_issues: u32,
    /// Total occurrences attributed to component issues.
    pub component_occurrences: u32,
}

/// Findings grouped into a single severity tier (Critical / High / Medium / Low).
/// Only non-empty tiers are included in `FindingsBlock.by_severity`.
pub struct FindingSeverityTier {
    pub severity: Severity,
    pub label: String,
    pub findings: Vec<FindingGroup>,
    pub total_occurrences: usize,
}

/// Criticality tier — separates mandatory (BFSG-relevant) from optimization findings
/// so the report can show them in clearly distinct sections (#245).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum CriticalityTier {
    /// Level 1 — must be fixed: WCAG A/AA violations with BFSG relevance.
    Mandatory,
    /// Level 2 — should/can be fixed: SEO, AI visibility, dark mode, UX heuristics, WCAG AAA.
    Optimization,
}

/// Decide the criticality tier of a finding for the BFSG-vs-Optimierung split (#245).
///
/// Mandatory tier covers WCAG Level A/AA violations (legal/BFSG risk). Everything
/// else (SEO, AI visibility, dark mode, WCAG AAA, …) is classified as Optimization.
pub fn classify_criticality_tier(category: &str, wcag_level: &str) -> CriticalityTier {
    if category == "wcag" && matches!(wcag_level, "A" | "AA") {
        CriticalityTier::Mandatory
    } else {
        CriticalityTier::Optimization
    }
}

/// Findings grouped by criticality tier (Mandatory / Optimization), each containing
/// the same findings further sub-grouped by severity for structured rendering.
pub struct FindingCriticalityGroup {
    pub tier: CriticalityTier,
    /// Localized tier label (e.g. "Pflicht — muss behoben werden").
    pub label: String,
    /// Short eyebrow label (e.g. "EBENE 1 · PFLICHT").
    pub eyebrow: String,
    /// One-sentence explanation of what this tier contains.
    pub intro: String,
    pub by_severity: Vec<FindingSeverityTier>,
    pub total_findings: usize,
    pub total_occurrences: usize,
}

/// Grouped findings, already sorted by impact
pub struct FindingsBlock {
    pub summary: FindingSummary,
    pub clusters: Vec<FindingCluster>,
    pub top_findings: Vec<FindingGroup>,
    pub all_findings: Vec<FindingGroup>,
    /// Findings pre-partitioned into severity tiers (Critical → High → Medium → Low).
    /// Renderers can use this for structured, tier-first display without re-sorting.
    pub by_severity: Vec<FindingSeverityTier>,
    /// Findings grouped first by criticality tier (Mandatory / Optimization), then by
    /// severity. Renderers use this to enforce the visual+structural BFSG-vs-Optimierung
    /// split required by issue #245.
    pub by_tier: Vec<FindingCriticalityGroup>,
}

/// Module detail presentations (unchanged from before)
pub struct ModuleDetailsBlock {
    pub search_experience: Option<SearchExperiencePresentation>,
    pub performance: Option<PerformancePresentation>,
    pub seo: Option<SeoPresentation>,
    pub security: Option<SecurityPresentation>,
    pub mobile: Option<MobilePresentation>,
    pub ux: Option<UxPresentation>,
    pub journey: Option<JourneyPresentation>,
    pub dark_mode: Option<DarkModePresentation>,
    pub source_quality: Option<crate::source_quality::SourceQualityAnalysis>,
    pub ai_visibility: Option<crate::ai_visibility::AiVisibilityAnalysis>,
    pub tech_stack: Option<crate::tech_stack::TechStackAnalysis>,
    pub content_visibility: Option<crate::content_visibility::ContentVisibilityAnalysis>,
    pub best_practices: Option<crate::best_practices::BestPracticesAnalysis>,
    pub patterns: Option<crate::patterns::PatternAnalysis>,
    pub has_any: bool,
}

/// Composite front-report score for findability, content clarity, trust and machine readability.
pub struct SearchExperiencePresentation {
    pub score: u32,
    pub label: String,
    pub interpretation: String,
    pub components: Vec<SearchExperienceComponent>,
    pub warnings: Vec<String>,
}

pub struct SearchExperienceComponent {
    pub label: String,
    pub score: u32,
    pub weight_pct: u32,
    pub explanation: String,
}

/// Dark mode analysis presentation block
pub struct DarkModePresentation {
    pub supported: bool,
    pub score: u32,
    pub detection_methods: Vec<String>,
    pub color_scheme_css: bool,
    pub meta_color_scheme: Option<String>,
    pub css_custom_properties: u32,
    pub dark_contrast_violations: u32,
    pub dark_only_violations: u32,
    pub light_only_violations: u32,
    pub print_stylesheet_detected: bool,
    pub print_interactive_chrome_hidden: bool,
    pub print_content_not_clipped: bool,
    pub print_clipped_elements: u32,
    pub forced_colors_detected: bool,
    pub forced_colors_active_matches: bool,
    pub forced_color_adjust_count: u32,
    pub forced_colors_focus_visible: bool,
    pub vision_deficiency_modes: Vec<VisionDeficiencyModePresentation>,
    /// (severity, description) pairs for issues
    pub issues: Vec<(String, String)>,
}

pub struct VisionDeficiencyModePresentation {
    pub mode: String,
    pub contrast_violations: u32,
    pub new_contrast_violations: u32,
    pub use_of_color_violations: u32,
}

/// Action plan as pre-mapped roadmap columns
pub struct ActionsBlock {
    pub roadmap_columns: Vec<RoadmapColumnData>,
    pub role_assignments: Vec<RoleAssignment>,
    pub intro_text: String,
    /// Visual phase overview shown before the detailed roadmap
    pub phase_preview: Vec<PhasePreview>,
    /// Label for the entire action block, context-sensitive
    pub block_title: String,
    pub task_summary: TaskSummary,
}

pub struct RoadmapColumnData {
    pub title: String,
    pub description: String,
    pub accent_color: String,
    pub items: Vec<RoadmapItemData>,
}

pub struct RoadmapItemData {
    pub action: String,
    pub role: String,
    pub priority: String,
    pub execution_priority: String,
    pub effort: String,
    pub benefit: String,
    /// Business-oriented effect on users (e.g. "Screenreader-Nutzer können navigieren")
    pub user_effect: String,
    /// Risk reduction effect (e.g. "Reduziert WCAG-Verstoßrisiko")
    pub risk_effect: String,
    /// Conversion/UX effect (e.g. "Verbessert Orientierung und Klickrate")
    pub conversion_effect: String,
}

/// A single phase in the visual phase overview (shown before the detailed roadmap)
pub struct PhasePreview {
    pub phase_label: String,
    pub accent_color: String,
    pub description: String,
    pub item_count: usize,
    pub top_items: Vec<String>,
}

/// Technical appendix
pub struct AppendixBlock {
    pub violations: Vec<AppendixViolation>,
    pub score_methodology: String,
    pub has_violations: bool,
}

// ─── Finding Types (shared between single and batch) ────────────────────────

/// Four-stage narrative arc: Diagnose → Ursache → Wirkung → Umsetzung.
/// Each field holds a complete, renderer-ready sentence — no raw labels.
pub struct NarrativeArc {
    /// What was observed — occurrence-enriched diagnosis sentence.
    pub diagnose: String,
    /// Why it happens — root cause with technical context.
    pub ursache: String,
    /// What it means — user and business impact combined.
    pub wirkung: String,
    /// How to fix it — actionable recommendation with effort context.
    pub umsetzung: String,
}

/// A grouped finding with customer-facing explanation
pub struct FindingGroup {
    pub title: String,
    pub rule_id: String,
    pub wcag_criterion: String,
    pub wcag_level: String,
    /// Official reference URL for the criterion (e.g. WCAG Understanding page).
    pub help_url: Option<String>,
    pub dimension: Option<String>,
    pub subcategory: Option<String>,
    pub issue_class: Option<String>,
    pub severity: Severity,
    pub priority: Priority,
    pub customer_description: String,
    pub user_impact: String,
    pub business_impact: String,
    pub typical_cause: String,
    pub recommendation: String,
    pub technical_note: String,
    pub confidence: String,
    pub false_positive_risk: String,
    pub verification: String,
    pub complexity: String,
    pub complexity_reason: String,
    pub expected_impact: String,
    pub bfsg_relevance: String,
    pub remediation_priority: String,
    pub occurrence_count: usize,
    pub affected_urls: Vec<String>,
    pub affected_elements: usize,
    pub additional_occurrences: usize,
    pub pattern_clusters: Vec<FindingPatternCluster>,
    pub location_hints: Vec<String>,
    pub representative_occurrences: Vec<RepresentativeOccurrence>,
    pub responsible_role: Role,
    pub effort: Effort,
    pub execution_priority: ExecutionPriority,
    pub examples: Vec<ExampleBlock>,
    /// Structural cause hint for findings with high occurrence counts (template/component pattern).
    pub structural_cause: Option<String>,
    /// True when this finding is classified as a component/template issue (occurrence_count >= 10).
    pub is_component_issue: bool,
    /// Criticality tier — Mandatory (BFSG-relevant) or Optimization (#245).
    pub criticality_tier: CriticalityTier,
    /// Precomputed narrative arc for story-flow rendering.
    pub narrative: NarrativeArc,
}

/// Occurrence-analysis result structs are produced by domain logic in
/// `audit::occurrence_analysis`; re-exported here so existing
/// `report_model::{RepresentativeOccurrence, FindingPatternCluster}` references
/// keep working.
pub use crate::audit::occurrence_analysis::{FindingPatternCluster, RepresentativeOccurrence};

pub struct CapabilitySignal {
    pub signal: String,
    pub source: String,
    pub confidence: String,
    pub surfaces: Vec<String>,
    pub note: String,
}

/// Code example showing bad vs. good pattern
pub struct ExampleBlock {
    pub bad: String,
    pub good: String,
    pub decorative: Option<String>,
}

/// Positive aspect of the audit
pub struct PositiveAspect {
    pub area: String,
    pub description: String,
}

// ─── Module Detail Presentations ────────────────────────────────────────────

/// Vitals for one viewport (desktop or mobile).
#[derive(Debug, Clone)]
pub struct PerformanceViewport {
    pub score: u32,
    pub grade: String,
    /// (metric_name, formatted_value, rating)
    pub vitals: Vec<(String, String, String)>,
}

/// One row in the throttled-performance table.
pub struct ThrottledPerfEntry {
    pub profile_name: String,
    pub lcp: String,
    pub tbt: String,
    pub cls: String,
    pub score: u32,
}

/// Per-origin row for third-party attribution display
pub struct ThirdPartyOriginRow {
    pub origin: String,
    pub provider: Option<String>,
    pub category: Option<String>,
    pub request_count: u32,
    pub transfer_kb: f64,
    pub resource_kinds: String,
}

/// Third-party attribution presentation
pub struct ThirdPartyPresentation {
    pub origins: Vec<ThirdPartyOriginRow>,
    pub total_origins: u32,
    pub total_kb: f64,
    pub total_requests: u32,
    pub is_significant: bool,
}

/// Critical request chain summary
pub struct CriticalChainPresentation {
    pub max_depth: usize,
    pub critical_path_ms: String,
    pub critical_path_kb: String,
    pub total_requests: usize,
}

/// Unminified assets summary
pub struct MinificationPresentation {
    pub total_count: usize,
    pub total_savings_kb: f64,
    pub top_assets: Vec<(String, String, String)>, // (url_truncated, kind, savings_kb_str)
    pub legacy_count: usize,
    pub legacy_wasted_kb: f64,
    pub legacy_assets: Vec<(String, String, String)>, // (url_truncated, signature, wasted_kb_str)
}

/// JS/CSS coverage (unused code) summary
pub struct CoveragePresentation {
    pub js_used_pct: Option<f64>,
    pub js_unused_kb: Option<f64>,
    pub css_used_pct: Option<f64>,
    pub css_total_rules: Option<u32>,
    pub css_used_rules: Option<u32>,
}

/// Non-composited animation findings
pub struct AnimationPresentation {
    pub total_count: usize,
    pub affected_properties: Vec<String>,
    pub findings: Vec<(String, String, String)>, // (kind, property, source_truncated)
}

/// Oversized image row for display
pub struct OversizedImageRow {
    pub src: String,
    pub natural: String,
    pub display: String,
}

/// Image efficiency section for SEO presentation
pub struct ImageEfficiencyPresentation {
    pub total_images: usize,
    pub modern_format_pct: f64,
    pub legacy_count: usize,
    pub oversized: Vec<OversizedImageRow>,
}

pub struct PerformancePresentation {
    pub score: u32,
    pub grade: String,
    pub interpretation: String,
    /// Flat vitals list (mobile, or blended if no split available)
    pub vitals: Vec<(String, String, String)>,
    /// Per-viewport breakdown — Some when both desktop and mobile were measured
    pub desktop: Option<PerformanceViewport>,
    pub mobile: Option<PerformanceViewport>,
    pub additional_metrics: Vec<(String, String)>,
    pub recommendations: Vec<String>,
    /// Render-blocking: (label, value) pairs for display
    pub render_blocking_metrics: Vec<(String, String)>,
    /// Render-blocking suggestions
    pub render_blocking_suggestions: Vec<String>,
    /// Whether render-blocking or heavy third-party load was detected
    pub has_render_blocking: bool,
    /// Throttled network performance profiles (empty if not measured)
    pub throttled_profiles: Vec<ThrottledPerfEntry>,
    /// CLS shift attribution (top 5, value + start_time + element)
    pub cls_attribution: Vec<(String, String, String)>,
    /// Third-party attribution — None if not collected
    pub third_party: Option<ThirdPartyPresentation>,
    /// Critical request chain summary
    pub critical_chain: Option<CriticalChainPresentation>,
    /// Unminified assets
    pub minification: Option<MinificationPresentation>,
    /// JS/CSS coverage
    pub coverage: Option<CoveragePresentation>,
    /// Non-composited animations
    pub animations: Option<AnimationPresentation>,
    /// Implausible or unmeasurable metrics detected during headless measurement (#291).
    pub measurement_warnings: Vec<String>,
}

pub struct SeoPresentation {
    pub score: u32,
    pub interpretation: String,
    pub meta_tags: Vec<(String, String)>,
    pub meta_issues: Vec<(String, Severity, String)>,
    pub heading_summary: String,
    pub social_summary: String,
    pub technical_summary: Vec<(String, String)>,
    pub tracking_summary: Vec<(String, String)>,
    pub tracking_summary_text: String,
    pub profile: Option<SeoProfilePresentation>,
    /// robots.txt audit — informational only
    pub robots: Option<RobotsPresentation>,
    /// Page health analysis presentation
    pub page_health: Option<PageHealthPresentation>,
    /// SERP pass presentation
    pub serp: Option<SerpPresentation>,
    /// Image efficiency analysis
    pub image_efficiency: Option<ImageEfficiencyPresentation>,
    /// TechnicalSeo issues (noindex, hreflang gaps, crawl budget) — (issue_type, message, severity_label)
    pub technical_issues: Vec<(String, String, String)>,
}

/// SERP pass presentation
pub struct SerpPresentation {
    pub score: u32,
    pub pass_count: u32,
    pub warning_count: u32,
    pub fail_count: u32,
    /// (category, label, status_label, detail)
    pub signals: Vec<(String, String, String, String)>,
    /// Rich result types eligible (e.g. "FAQ", "Breadcrumb")
    pub rich_result_types: Vec<String>,
}

/// Page health presentation block
pub struct PageHealthPresentation {
    /// (issue_type, message, severity)
    pub issues: Vec<(String, String, String)>,
    /// KV pairs: (label, value)
    pub url_info: Vec<(String, String)>,
    /// (check, count, severity, detail)
    pub html_issues: Vec<(String, u32, String, String)>,
    /// (status, detail)
    pub html_validator: Option<(String, String)>,
    /// (www_status_label, non_www_label, is_consolidated)
    pub www_status: Option<(String, String, bool)>,
    /// (status, is_soft_404)
    pub soft_404: Option<(u16, bool)>,
    pub has_any_issue: bool,
}

/// Pre-processed robots.txt display data
pub struct RobotsPresentation {
    pub error: Option<String>,
    pub has_wildcard_disallow_all: bool,
    pub blocks_ai_crawlers: bool,
    pub blocks_ai_citation: bool,
    pub inferred_policy: String,
    pub sitemaps: Vec<String>,
    pub crawl_delays: Vec<(String, u32)>,
    /// (user-agent, bot_class_label, allows_count, disallows_count, fully_blocked)
    pub bot_rows: Vec<(String, String, usize, usize, bool)>,
    /// AI crawlers that are explicitly blocked
    pub blocked_ai_bots: Vec<String>,
    /// Page has noindex and appears in sitemap.xml (true = problem found)
    pub noindex_in_sitemap: Option<bool>,
}

/// SEO Content Profile presentation data
pub struct SeoProfilePresentation {
    // Content Identity
    pub identity_summary: String,
    pub site_name: String,
    pub content_type: String,
    pub language: String,
    pub category_hints: Vec<String>,
    pub identity_facts: Vec<(String, String)>,
    // Page Classification
    pub page_type: String,
    pub page_attributes: Vec<String>,
    pub content_depth_score: u32,
    pub structural_richness_score: u32,
    pub media_text_balance_score: u32,
    pub intent_fit_score: u32,
    pub page_profile_summary: String,
    pub optimization_note: String,
    pub page_profile_facts: Vec<(String, String)>,
    // Schema Inventory: (type, completeness%, details)
    pub schema_rows: Vec<(String, String, String)>,
    pub schema_count: usize,
    // Signal Strength: (category, score%, rating_label)
    pub signal_rows: Vec<(String, String, String)>,
    pub signal_overall_pct: u32,
    // Signal Details: (category_name, [(check_label, passed, detail)])
    pub signal_details: SignalDetails,
    // Maturity
    pub maturity_level: String,
    pub maturity_description: String,
    pub maturity_techniques_used: u32,
    pub maturity_techniques_total: u32,
}

pub struct SecurityPresentation {
    pub score: u32,
    pub grade: String,
    pub interpretation: String,
    pub headers: Vec<(String, String, String)>,
    pub ssl_info: Vec<(String, String)>,
    pub issues: Vec<(String, Severity, String)>,
    pub recommendations: Vec<String>,
    /// (service name, kind label) pairs detected from response headers
    pub protection: Vec<(String, String)>,
    pub has_waf: bool,
    pub has_cdn: bool,
}

pub struct MobilePresentation {
    pub score: u32,
    pub interpretation: String,
    pub viewport: Vec<(String, String)>,
    pub touch_targets: Vec<(String, String)>,
    pub font_analysis: Vec<(String, String)>,
    pub content_sizing: Vec<(String, String)>,
    pub issues: Vec<(String, Severity, String)>,
}

/// UX analysis presentation block
pub struct UxPresentation {
    pub score: u32,
    pub grade: String,
    pub interpretation: String,
    pub dimensions: Vec<UxDimensionPresentation>,
    pub issues: Vec<UxIssuePresentation>,
}

pub struct UxDimensionPresentation {
    pub kind: crate::ux::UxDimensionKind,
    pub name: String,
    pub score: u32,
    pub summary: String,
}

pub struct UxIssuePresentation {
    pub kind: crate::ux::UxIssueKind,
    pub dimension: String,
    pub severity: String,
    pub problem: String,
    pub impact: String,
    pub recommendation: String,
    pub values: crate::ux::UxIssueValues,
}

pub struct JourneyPresentation {
    pub score: u32,
    pub grade: String,
    pub page_intent: String,
    pub interpretation: String,
    pub dimensions: Vec<JourneyDimensionPresentation>,
    pub friction_points: Vec<FrictionPointPresentation>,
}

pub struct JourneyDimensionPresentation {
    pub kind: crate::journey::JourneyDimensionKind,
    pub name: String,
    pub score: u32,
    pub weight_pct: u32,
    pub summary: String,
}

pub struct FrictionPointPresentation {
    pub kind: crate::journey::FrictionKind,
    pub step: String,
    pub severity: String,
    pub problem: String,
    pub impact: String,
    pub recommendation: String,
    pub values: crate::journey::FrictionValues,
}

// ─── Shared Helper Types ────────────────────────────────────────────────────

#[derive(Clone)]
pub struct ActionItem {
    pub action: String,
    pub benefit: String,
    pub role: Role,
    pub priority: Priority,
    pub execution_priority: ExecutionPriority,
    pub effort: Effort,
    /// Whether the underlying finding is a systemic template/component issue
    /// (fix once, applies everywhere) vs. a local/individual occurrence. Drives
    /// the action plan's "by problem level" grouping.
    pub is_systemic: bool,
}

pub struct RoleAssignment {
    pub role: Role,
    pub responsibilities: Vec<String>,
}

/// Aggregated violation: one entry per WCAG rule, with all affected elements
pub struct AppendixViolation {
    pub rule: String,
    pub rule_name: String,
    pub severity: Severity,
    pub message: String,
    pub fix_suggestion: Option<String>,
    pub affected_elements: Vec<AffectedElement>,
}

/// Single affected element within an aggregated violation
pub struct AffectedElement {
    pub selector: String,
    pub node_id: String,
}

// ─── Batch Report Presentation ──────────────────────────────────────────────

/// Cover data (used by batch reports)
pub struct CoverData {
    pub title: String,
    pub url: String,
    pub date: String,
    pub version: String,
}

/// One aggregated row per interactive category in the batch report.
pub struct InteractiveCategoryRow {
    pub category: String,
    pub affected_urls: usize,
    pub max_severity: Severity,
}

/// Aggregated summary of interactive journey findings across all audited pages.
pub struct InteractiveJourneySummary {
    /// Total pages that ran the interactive phase (had at least one trace or finding)
    pub total_pages_tested: usize,
    /// Number of pages with at least one interactive finding
    pub pages_with_issues: usize,
    /// Per-category aggregation, sorted by affected_urls descending
    pub categories: Vec<InteractiveCategoryRow>,
    /// True if any Critical interactive finding was found across all pages
    pub has_critical: bool,
}

/// Complete presentation model for a batch audit report
pub struct BatchPresentation {
    pub cover: CoverData,
    pub portfolio_summary: PortfolioSummary,
    pub top_issues: Vec<FindingGroup>,
    pub issue_frequency: Vec<IssueFrequency>,
    pub action_plan: ActionPlan,
    pub url_ranking: Vec<UrlSummary>,
    pub url_details: Vec<CompactUrlSummary>,
    pub url_matrix: Vec<UrlMatrixRow>,
    pub appendix: BatchAppendixData,
    pub interactive_summary: Option<InteractiveJourneySummary>,
}

pub struct ActionPlan {
    pub quick_wins: Vec<ActionItem>,
    pub medium_term: Vec<ActionItem>,
    pub structural: Vec<ActionItem>,
    pub role_assignments: Vec<RoleAssignment>,
}

/// A group of pages that share an identical SEO content value across the site.
///
/// `kind` is a canonical, language-neutral key (`"title"`, `"meta_description"`,
/// or `"h1"`); the PDF layer derives the localized label at render time (#406).
/// `value` is the verbatim shared content (truncated for display).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DuplicateContentGroup {
    pub kind: String,
    pub value: String,
    pub urls: Vec<String>,
}

/// A canonical-tag conflict found on a single page (#423).
///
/// `kind` is a canonical, language-neutral key (`"noindex_conflict"` or
/// `"og_url_mismatch"`); the PDF layer derives the localized label at render
/// time (#406). `detail` carries the offending values for context.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CanonicalIssue {
    pub kind: String,
    pub url: String,
    pub detail: String,
}

/// A non-reciprocal hreflang relationship (#423): `source_url` declares an
/// hreflang entry pointing to `target_url` (also in the audited set), but the
/// target does not declare a return link back to the source.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct HreflangIssue {
    pub source_url: String,
    pub target_url: String,
    pub lang: String,
}

pub struct PortfolioSummary {
    pub total_urls: usize,
    pub passed: usize,
    pub failed: usize,
    pub average_score: f64,
    /// Weighted overall score across all active modules (averaged over URLs)
    pub average_overall_score: u32,
    pub total_violations: usize,
    pub duration_ms: u64,
    pub verdict_text: String,
    pub worst_urls: Vec<(String, f32)>,
    pub best_urls: Vec<(String, f32)>,
    pub severity_distribution: SeverityDistribution,
    /// Aggregated risk level across all URLs (worst-case)
    pub risk_level: String,
    /// Risk summary text
    pub risk_summary: String,
    /// Averaged module scores across all URLs (module_name, average_score)
    pub module_averages: Vec<(String, u32)>,
    /// List of active module names
    pub active_modules: Vec<String>,
    /// Domain name (extracted from first URL)
    pub domain: String,
    /// Certificate label based on the primary WCAG/accessibility score
    pub certificate: String,
    /// Grade based on the primary WCAG/accessibility score
    pub grade: String,
    pub page_type_distribution: Vec<(String, usize, u32)>,
    pub distribution_insights: Vec<String>,
    pub strongest_content_pages: Vec<(String, String, u32)>,
    pub weakest_content_pages: Vec<(String, String, u32)>,
    pub top_topics: Vec<(String, usize)>,
    pub overlap_pairs: Vec<(String, String, u32)>,
    /// Near-duplicate content pairs detected via SimHash (url_a, url_b, similarity_pct)
    pub near_duplicates: Vec<(String, String, u8)>,
    pub crawl_links: Option<CrawlLinkSummary>,
    /// Aggregated budget violations across all pages (metric, budget_label, #urls_violated, severity_label)
    pub budget_summary: Vec<(String, String, usize, String)>,
    /// Aggregated render-blocking summary across all pages (metric_label, value_label)
    pub render_blocking_summary: Vec<(String, String)>,
    /// Schema type distribution: (schema_type_label, url_count) sorted descending
    pub schema_distribution: Vec<(String, usize)>,
    /// Number of pages with no structured data at all
    pub pages_without_schema: usize,
    /// Cross-page duplicate content groups (identical title / meta description / H1)
    pub duplicate_content: Vec<DuplicateContentGroup>,
    /// Per-page canonical-tag conflicts aggregated across the site
    pub canonical_issues: Vec<CanonicalIssue>,
    /// Non-reciprocal hreflang relationships between audited pages
    pub hreflang_issues: Vec<HreflangIssue>,
    /// Sitemap entries with HTTP/indexability issues
    pub sitemap_http_issues: Vec<crate::audit::SitemapHttpIssue>,
    /// Sitemap entries not linked by any audited page
    pub orphan_sitemap_urls: Vec<String>,
    /// Internal linked URLs that are absent from the sitemap
    pub linked_not_in_sitemap: Vec<String>,
}

pub struct CrawlLinkSummary {
    pub seed_url: String,
    pub checked_internal_links: usize,
    pub broken_internal_links: Vec<BrokenLinkRow>,
    pub checked_external_links: usize,
    pub broken_external_links: Vec<BrokenLinkRow>,
    pub redirect_chains: Vec<RedirectChainRow>,
}

pub struct BrokenLinkRow {
    pub source_url: String,
    pub target_url: String,
    pub status: String,
    pub is_external: bool,
    pub severity: String,
    pub redirect_hops: u8,
}

pub struct RedirectChainRow {
    pub source_url: String,
    pub target_url: String,
    pub final_url: String,
    pub hops: u8,
    pub is_external: bool,
}

pub struct SeverityDistribution {
    pub critical: usize,
    pub high: usize,
    pub medium: usize,
    pub low: usize,
}

pub struct IssueFrequency {
    pub problem: String,
    pub wcag: String,
    pub occurrences: usize,
    pub affected_urls: usize,
    pub priority: Priority,
}

pub struct UrlSummary {
    pub url: String,
    pub score: f32,
    /// Weighted overall score across all active modules
    pub overall_score: u32,
    pub grade: String,
    pub critical_violations: usize,
    pub total_violations: usize,
    pub passed: bool,
    pub priority: Priority,
}

pub struct CompactUrlSummary {
    pub url: String,
    pub score: f32,
    pub grade: String,
    pub critical_violations: usize,
    pub total_violations: usize,
    pub page_type: Option<String>,
    pub page_attributes: Vec<String>,
    pub page_semantic_score: Option<u32>,
    pub biggest_lever: String,
    pub topic_terms: Vec<String>,
    pub top_issues: Vec<String>,
    pub module_scores: Vec<(String, u32)>,
}

/// One row of the URL matrix table (batch reports)
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct UrlMatrixRow {
    pub rank: usize,
    pub url: String,
    pub title: Option<String>,
    /// Pages within the batch that link to this URL
    pub inbound_links: usize,
    /// All outgoing links from this page (internal + external)
    pub outbound_links: u32,
    pub word_count: u32,
}

pub struct BatchAppendixData {
    pub per_url: Vec<UrlAppendix>,
}

pub struct UrlAppendix {
    pub url: String,
    pub violations: Vec<AppendixViolation>,
}