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
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
//! Source Quality Analysis
//!
//! Interprets data from existing audit modules (Accessibility, SEO, Security,
//! UX) to assess the quality of a website **as an information source**.
//!
//! Three dimensions are scored:
//! - **Substance** — Does the site treat its content as valuable?
//! - **Consistency** — Does the site maintain its own standards?
//! - **Authority** — Does the site present itself as a trustworthy source?
//!
//! **Disclaimer**: This is a purely technical assessment based on structural,
//! semantic, and metadata signals. It does NOT evaluate whether the content
//! itself is factually correct, complete, or up to date.
//!
//! ## Localization (#406)
//!
//! Analysis bakes **canonical English** text into the struct (and thus JSON):
//! every `name`/`detail`/`label`/`disclaimer` is produced with `en = true`.
//! Each signal additionally carries a stable [`QualitySignalKind`] plus the raw
//! interpolated values, so the PDF layer can re-derive localized text via
//! [`source_quality_signal_text`] / [`source_quality_dimension_label`] /
//! [`source_quality_disclaimer`] in the run language.

pub mod module;
pub use module::SourceQualityModule;

use serde::{Deserialize, Serialize};

use crate::audit::AuditReport;
use crate::seo::schema::SchemaType;
use crate::taxonomy::module_score_grade;

// ─── Public types ────────────────────────────────────────────────────────────

/// Complete source quality analysis for a single page
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SourceQualityAnalysis {
    /// Overall source quality score (0–100)
    pub score: u32,
    /// Letter grade (A–F)
    pub grade: String,
    /// Substance dimension
    pub substance: DimensionScore,
    /// Consistency dimension (limited for single page, full in batch)
    pub consistency: DimensionScore,
    /// Authority dimension
    pub authority: DimensionScore,
    /// Always-present disclaimer (canonical English)
    pub disclaimer: String,
}

/// Stable identifier for which dimension a [`DimensionScore`] represents.
///
/// Lets the PDF layer re-derive a localized dimension name without parsing the
/// canonical-English `name` field.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum DimensionKind {
    Substance,
    Consistency,
    Authority,
}

/// Score for a single quality dimension
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DimensionScore {
    /// Which dimension this is (for localized re-derivation)
    pub kind: DimensionKind,
    /// Dimension name (canonical English)
    pub name: String,
    /// Score (0–100)
    pub score: u32,
    /// Short assessment (canonical English; derived from `score`)
    pub label: String,
    /// Individual signals evaluated
    pub signals: Vec<QualitySignal>,
}

/// Stable identifier for a concrete quality signal.
///
/// One variant per distinct signal text/detail shape. Together with the raw
/// values stored on [`QualitySignal`] this fully reproduces the human-readable
/// `name`/`detail` strings in any language.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum QualitySignalKind {
    // Substance
    HeadingStructure,
    ContentVolume,
    StructuredData,
    MetaDescription,
    LanguageDeclaration,
    ImageDescriptions,
    SemanticStructure,
    // Authority
    Https,
    SecurityHeaders,
    PublisherIdentity,
    CanonicalUrl,
    SocialMeta,
    Accessibility,
    TrustSignals,
    // Consistency (single page)
    HeadingHierarchy,
    NamedControls,
    NoCriticalErrors,
    LanguageConsistency,
    // Consistency (batch / cross-page)
    ScoreStability,
    MetaDescriptionCoverage,
    StructuredDataCoverage,
    LanguageDeclarationCoverage,
    HstsCoverage,
    ErrorFreePages,
}

/// The interpolated values a signal text may reference.
///
/// Stored on every [`QualitySignal`] alongside `present` so that
/// [`source_quality_signal_text`] can reproduce the detail string for any
/// locale. Only the fields relevant to the signal's `kind` are populated.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SignalValues {
    /// Heading depth (HeadingStructure)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub depth: Option<u32>,
    /// Whether an H1 is present (HeadingStructure)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub has_h1: Option<bool>,
    /// Word count (ContentVolume)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub word_count: Option<u32>,
    /// Detected Schema.org types (StructuredData, present case)
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub schema_types: Vec<String>,
    /// Declared language code (LanguageDeclaration, present case)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lang: Option<String>,
    /// A generic count (ImageDescriptions, SemanticStructure, HeadingHierarchy,
    /// NamedControls, NoCriticalErrors, SecurityHeaders)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub count: Option<u32>,
    /// Whether <main> is missing in the AX tree (SemanticStructure)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub missing_main: Option<bool>,
    /// An accessibility/UX score (Accessibility, TrustSignals)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub score: Option<f32>,
    /// A cross-page coverage percentage (*Coverage, ErrorFreePages)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub percent: Option<u32>,
    /// Cross-page standard deviation (ScoreStability)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub std_dev: Option<f32>,
}

/// A single measurable signal contributing to a dimension score
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QualitySignal {
    /// Stable signal identifier (for localized re-derivation)
    pub kind: QualitySignalKind,
    /// What was checked (canonical English)
    pub name: String,
    /// Whether the signal is positive
    pub present: bool,
    /// Weight of this signal within its dimension (0.0–1.0)
    pub weight: f32,
    /// Human-readable detail (canonical English)
    pub detail: String,
    /// Interpolated values needed to reproduce `detail` in another language
    #[serde(default)]
    pub values: SignalValues,
}

impl QualitySignal {
    /// Build a signal, baking canonical-English `name`/`detail` from its kind +
    /// values via [`source_quality_signal_text`].
    fn new(kind: QualitySignalKind, present: bool, weight: f32, values: SignalValues) -> Self {
        let (name, detail) = source_quality_signal_text(kind, present, &values, true);
        QualitySignal {
            kind,
            name,
            present,
            weight,
            detail,
            values,
        }
    }
}

// ─── Localized text (single source of truth) ─────────────────────────────────

const DISCLAIMER_DE: &str = "Diese Bewertung basiert ausschließlich auf technischen Signalen \
    (Struktur, Semantik, Metadaten, Sicherheit). Sie beurteilt nicht, ob die \
    dargestellten Inhalte inhaltlich korrekt, vollständig oder aktuell sind.";

const DISCLAIMER_EN: &str = "This assessment is based solely on technical signals \
    (structure, semantics, metadata, security). It does not judge whether the \
    presented content is factually correct, complete or up to date.";

/// The always-present disclaimer in the requested language.
pub fn source_quality_disclaimer(en: bool) -> String {
    if en { DISCLAIMER_EN } else { DISCLAIMER_DE }.to_string()
}

/// Localized dimension name for a [`DimensionKind`].
pub fn source_quality_dimension_name(kind: DimensionKind, en: bool) -> &'static str {
    match (kind, en) {
        (DimensionKind::Substance, true) => "Substance",
        (DimensionKind::Substance, false) => "Substanz",
        (DimensionKind::Consistency, true) => "Consistency",
        (DimensionKind::Consistency, false) => "Konsistenz",
        (DimensionKind::Authority, true) => "Authority",
        (DimensionKind::Authority, false) => "Autorität",
    }
}

/// Localized "no data" label used when a dimension has no signals.
pub fn source_quality_no_data_label(en: bool) -> String {
    if en { "No data" } else { "Keine Daten" }.to_string()
}

/// Localized band label for a dimension score (single source of truth).
pub fn source_quality_dimension_label(score: u32, en: bool) -> String {
    if en {
        match score {
            90..=100 => "Excellent",
            75..=89 => "Good",
            60..=74 => "Needs improvement",
            40..=59 => "Inadequate",
            _ => "Critical",
        }
    } else {
        match score {
            90..=100 => "Sehr gut",
            75..=89 => "Gut",
            60..=74 => "Verbesserungswürdig",
            40..=59 => "Ausbaufähig",
            _ => "Kritisch",
        }
    }
    .to_string()
}

/// The single source of truth for signal `name`/`detail` text.
///
/// Returns `(name, detail)` in German or English for the given `kind`,
/// `present` flag, and interpolated `values`. Analysis calls it with
/// `en = true` to bake canonical English; the PDF layer calls it with the run
/// language to re-derive localized text.
pub fn source_quality_signal_text(
    kind: QualitySignalKind,
    present: bool,
    values: &SignalValues,
    en: bool,
) -> (String, String) {
    use QualitySignalKind::*;

    let name: String = match (kind, en) {
        (HeadingStructure, true) => "Heading structure".into(),
        (HeadingStructure, false) => "Überschriftenstruktur".into(),
        (ContentVolume, true) => "Content volume".into(),
        (ContentVolume, false) => "Inhaltsumfang".into(),
        (StructuredData, true) | (StructuredDataCoverage, true) => "Structured data".into(),
        (StructuredData, false) | (StructuredDataCoverage, false) => "Strukturierte Daten".into(),
        (MetaDescription, true) => "Meta description".into(),
        (MetaDescription, false) => "Meta-Beschreibung".into(),
        (LanguageDeclaration, true) | (LanguageDeclarationCoverage, true) => {
            "Language declaration".into()
        }
        (LanguageDeclaration, false) | (LanguageDeclarationCoverage, false) => {
            "Sprachdeklaration".into()
        }
        (ImageDescriptions, true) => "Image descriptions".into(),
        (ImageDescriptions, false) => "Bildbeschreibungen".into(),
        (SemanticStructure, true) => "Semantic structure".into(),
        (SemanticStructure, false) => "Semantische Struktur".into(),
        (Https, _) => "HTTPS".into(),
        (SecurityHeaders, true) => "Security headers".into(),
        (SecurityHeaders, false) => "Sicherheits-Header".into(),
        (PublisherIdentity, true) => "Publisher identity".into(),
        (PublisherIdentity, false) => "Herausgeber-Identität".into(),
        (CanonicalUrl, _) => "Canonical URL".into(),
        (SocialMeta, true) => "Social meta".into(),
        (SocialMeta, false) => "Social-Meta".into(),
        (Accessibility, true) => "Accessibility".into(),
        (Accessibility, false) => "Barrierefreiheit".into(),
        (TrustSignals, true) => "Trust signals".into(),
        (TrustSignals, false) => "Vertrauenssignale".into(),
        (HeadingHierarchy, true) => "Heading hierarchy".into(),
        (HeadingHierarchy, false) => "Überschriften-Hierarchie".into(),
        (NamedControls, true) => "Named controls".into(),
        (NamedControls, false) => "Benannte Bedienelemente".into(),
        (NoCriticalErrors, true) => "No critical errors".into(),
        (NoCriticalErrors, false) => "Keine kritischen Fehler".into(),
        (LanguageConsistency, true) => "Language consistency".into(),
        (LanguageConsistency, false) => "Sprachkonsistenz".into(),
        (ScoreStability, true) => "Score stability".into(),
        (ScoreStability, false) => "Score-Stabilität".into(),
        (MetaDescriptionCoverage, true) => "Meta descriptions".into(),
        (MetaDescriptionCoverage, false) => "Meta-Beschreibungen".into(),
        (HstsCoverage, true) => "HSTS coverage".into(),
        (HstsCoverage, false) => "HSTS-Abdeckung".into(),
        (ErrorFreePages, true) => "Error-free pages".into(),
        (ErrorFreePages, false) => "Fehlerfreie Seiten".into(),
    };

    let count = values.count.unwrap_or(0);
    let percent = values.percent.unwrap_or(0);

    let detail: String = match kind {
        HeadingStructure => {
            let depth = values.depth.unwrap_or(0);
            let has_h1 = values.has_h1.unwrap_or(false);
            if has_h1 && depth >= 3 {
                if en {
                    format!("Structured outline down to H{}", depth)
                } else {
                    format!("Strukturierte Gliederung bis H{}", depth)
                }
            } else if !has_h1 {
                if en {
                    "No H1 heading present".into()
                } else {
                    "Keine H1-Überschrift vorhanden".into()
                }
            } else if en {
                format!("Flat outline (only down to H{})", depth)
            } else {
                format!("Flache Gliederung (nur bis H{})", depth)
            }
        }
        ContentVolume => {
            let word_count = values.word_count.unwrap_or(0);
            if en {
                format!(
                    "{} words{}",
                    word_count,
                    if present {
                        ""
                    } else {
                        " (heuristic: typically ≥ 300 words recommended)"
                    }
                )
            } else {
                format!(
                    "{} Wörter{}",
                    word_count,
                    if present {
                        ""
                    } else {
                        " (Heuristik: typisch ≥ 300 Wörter empfohlen)"
                    }
                )
            }
        }
        StructuredData => {
            if present {
                format!("Schema.org: {}", values.schema_types.join(", "))
            } else if en {
                "No structured data".into()
            } else {
                "Keine strukturierten Daten".into()
            }
        }
        MetaDescription => {
            if present {
                if en {
                    "Meaningful meta description present".into()
                } else {
                    "Aussagekräftige Meta-Beschreibung vorhanden".into()
                }
            } else if en {
                "Missing or too short meta description".into()
            } else {
                "Keine oder zu kurze Meta-Beschreibung".into()
            }
        }
        LanguageDeclaration => {
            if present {
                let lang = values.lang.as_deref().unwrap_or("?");
                if en {
                    format!("Language declared: {}", lang)
                } else {
                    format!("Sprache deklariert: {}", lang)
                }
            } else if en {
                "No language declaration".into()
            } else {
                "Keine Sprachdeklaration".into()
            }
        }
        ImageDescriptions => {
            if present {
                if en {
                    "All images have alternative text".into()
                } else {
                    "Alle Bilder haben Alternativtexte".into()
                }
            } else if en {
                format!("{} images without alternative text", count)
            } else {
                format!("{} Bilder ohne Alternativtext", count)
            }
        }
        SemanticStructure => {
            let missing_main = values.missing_main.unwrap_or(false);
            if present {
                if en {
                    "Correct landmark regions".into()
                } else {
                    "Korrekte Landmark-Regionen".into()
                }
            } else if missing_main {
                if en {
                    "<main> landmark not detectable in the accessibility tree".into()
                } else {
                    "<main>-Landmark im Accessibility Tree nicht nachweisbar".into()
                }
            } else if en {
                format!("{} structural issues", count)
            } else {
                format!("{} Strukturprobleme", count)
            }
        }
        Https => {
            if present {
                if en {
                    "Encrypted connection".into()
                } else {
                    "Verschlüsselte Verbindung".into()
                }
            } else if en {
                "No HTTPS encryption".into()
            } else {
                "Keine HTTPS-Verschlüsselung".into()
            }
        }
        SecurityHeaders => {
            if en {
                format!("{}/4 relevant security headers set", count)
            } else {
                format!("{}/4 relevante Security-Header gesetzt", count)
            }
        }
        PublisherIdentity => {
            if present {
                if en {
                    "Organization/publisher identified via Schema.org".into()
                } else {
                    "Organisation/Herausgeber per Schema.org identifiziert".into()
                }
            } else if en {
                "No publisher markup".into()
            } else {
                "Kein Herausgeber-Markup".into()
            }
        }
        CanonicalUrl => {
            if present {
                if en {
                    "Canonical URL declared".into()
                } else {
                    "Kanonische URL deklariert".into()
                }
            } else if en {
                "No canonical URL".into()
            } else {
                "Keine Canonical-URL".into()
            }
        }
        SocialMeta => {
            if present {
                if en {
                    "Open Graph metadata present".into()
                } else {
                    "Open Graph Metadaten vorhanden".into()
                }
            } else if en {
                "Incomplete social metadata".into()
            } else {
                "Unvollständige Social-Metadaten".into()
            }
        }
        Accessibility => {
            let score = values.score.unwrap_or(0.0);
            if en {
                format!(
                    "Accessibility score: {:.0}{}",
                    score,
                    if present { "" } else { " (low)" }
                )
            } else {
                format!(
                    "Accessibility-Score: {:.0}{}",
                    score,
                    if present { "" } else { " (niedrig)" }
                )
            }
        }
        TrustSignals => {
            let score = values.score.unwrap_or(0.0);
            if en {
                format!(
                    "UX trust score: {:.0}{}",
                    score,
                    if present { "" } else { " (weak)" }
                )
            } else {
                format!(
                    "UX Trust-Score: {:.0}{}",
                    score,
                    if present { "" } else { " (schwach)" }
                )
            }
        }
        HeadingHierarchy => {
            if present {
                if en {
                    "Gapless heading hierarchy".into()
                } else {
                    "Lückenlose Überschriften-Hierarchie".into()
                }
            } else if en {
                format!("{} hierarchy issues", count)
            } else {
                format!("{} Hierarchie-Probleme", count)
            }
        }
        NamedControls => {
            if present {
                if en {
                    "All interactive elements correctly named".into()
                } else {
                    "Alle interaktiven Elemente korrekt benannt".into()
                }
            } else if en {
                format!("{} elements without an accessible name", count)
            } else {
                format!("{} Elemente ohne zugänglichen Namen", count)
            }
        }
        NoCriticalErrors => {
            if present {
                if en {
                    "No critical accessibility violations".into()
                } else {
                    "Keine kritischen Accessibility-Verstöße".into()
                }
            } else if en {
                format!("{} critical violations", count)
            } else {
                format!("{} kritische Verstöße", count)
            }
        }
        LanguageConsistency => {
            if present {
                if en {
                    "Language correctly declared".into()
                } else {
                    "Sprache korrekt deklariert".into()
                }
            } else if en {
                "Missing language declaration".into()
            } else {
                "Fehlende Sprachdeklaration".into()
            }
        }
        ScoreStability => {
            let std_dev = values.std_dev.unwrap_or(0.0);
            if en {
                format!(
                    "Standard deviation: {:.1}{}",
                    std_dev,
                    if present {
                        " (stable)"
                    } else {
                        " (inconsistent)"
                    }
                )
            } else {
                format!(
                    "Standardabweichung: {:.1}{}",
                    std_dev,
                    if present {
                        " (stabil)"
                    } else {
                        " (inkonsistent)"
                    }
                )
            }
        }
        MetaDescriptionCoverage => {
            if en {
                format!("{}% of pages with a meta description", percent)
            } else {
                format!("{}% der Seiten mit Meta-Beschreibung", percent)
            }
        }
        StructuredDataCoverage => {
            if en {
                format!("{}% of pages with Schema.org", percent)
            } else {
                format!("{}% der Seiten mit Schema.org", percent)
            }
        }
        LanguageDeclarationCoverage => {
            if en {
                format!("{}% of pages with a language declaration", percent)
            } else {
                format!("{}% der Seiten mit Sprachdeklaration", percent)
            }
        }
        HstsCoverage => {
            if en {
                format!("{}% of pages with HSTS", percent)
            } else {
                format!("{}% der Seiten mit HSTS", percent)
            }
        }
        ErrorFreePages => {
            if en {
                format!("{}% of pages without critical errors", percent)
            } else {
                format!("{}% der Seiten ohne kritische Fehler", percent)
            }
        }
    };

    (name, detail)
}

// ─── Analysis entry point ────────────────────────────────────────────────────

/// Derive source quality from an existing audit report (single page).
///
/// Produces canonical-English text in the struct (and thus JSON).
pub fn analyze_source_quality(report: &AuditReport) -> SourceQualityAnalysis {
    let substance = evaluate_substance(report);
    let consistency = evaluate_single_page_consistency(report);
    let authority = evaluate_authority(report);

    let score = weighted_average(&[
        (substance.score, 40),
        (consistency.score, 25),
        (authority.score, 35),
    ]);

    SourceQualityAnalysis {
        score,
        grade: module_score_grade(score).to_string(),
        substance,
        consistency,
        authority,
        disclaimer: source_quality_disclaimer(true),
    }
}

/// Derive source quality for batch mode with cross-page consistency.
///
/// Produces canonical-English text in the struct (and thus JSON).
pub fn analyze_source_quality_batch(reports: &[AuditReport]) -> SourceQualityAnalysis {
    if reports.is_empty() {
        return empty_analysis();
    }

    // Average substance and authority across pages
    let substance_scores: Vec<DimensionScore> = reports.iter().map(evaluate_substance).collect();
    let authority_scores: Vec<DimensionScore> = reports.iter().map(evaluate_authority).collect();

    let avg_substance = average_dimensions(&substance_scores, DimensionKind::Substance);
    let avg_authority = average_dimensions(&authority_scores, DimensionKind::Authority);

    // Cross-page consistency (the real batch value)
    let consistency = evaluate_cross_page_consistency(reports);

    let score = weighted_average(&[
        (avg_substance.score, 35),
        (consistency.score, 30),
        (avg_authority.score, 35),
    ]);

    SourceQualityAnalysis {
        score,
        grade: module_score_grade(score).to_string(),
        substance: avg_substance,
        consistency,
        authority: avg_authority,
        disclaimer: source_quality_disclaimer(true),
    }
}

// ─── Substance ───────────────────────────────────────────────────────────────

fn evaluate_substance(report: &AuditReport) -> DimensionScore {
    use QualitySignalKind::*;
    let mut signals = Vec::new();

    // 1. Heading structure depth
    if let Some(seo) = &report.discoverability.seo {
        let has_h1 = seo.headings.h1_count > 0;
        let depth = seo
            .headings
            .headings
            .iter()
            .map(|h| h.level)
            .max()
            .unwrap_or(0);
        let good_depth = depth >= 3;

        signals.push(QualitySignal::new(
            HeadingStructure,
            has_h1 && good_depth,
            0.20,
            SignalValues {
                depth: Some(depth as u32),
                has_h1: Some(has_h1),
                ..Default::default()
            },
        ));

        // 2. Word count / content density
        let word_count = seo.technical.word_count;
        signals.push(QualitySignal::new(
            ContentVolume,
            word_count >= 300,
            0.15,
            SignalValues {
                word_count: Some(word_count),
                ..Default::default()
            },
        ));

        // 3. Schema.org structured data
        let has_schema = seo.structured_data.has_structured_data;
        let schema_types: Vec<String> = seo
            .structured_data
            .types
            .iter()
            .map(|t| t.as_str().to_string())
            .collect();
        signals.push(QualitySignal::new(
            StructuredData,
            has_schema,
            0.20,
            SignalValues {
                schema_types,
                ..Default::default()
            },
        ));

        // 4. Meta description
        let has_meta_desc = seo.meta.description.as_ref().is_some_and(|d| d.len() >= 50);
        signals.push(QualitySignal::new(
            MetaDescription,
            has_meta_desc,
            0.10,
            SignalValues::default(),
        ));

        // 5. Language declaration
        let has_lang = seo.technical.has_lang;
        signals.push(QualitySignal::new(
            LanguageDeclaration,
            has_lang,
            0.10,
            SignalValues {
                lang: seo.technical.lang.clone(),
                ..Default::default()
            },
        ));
    }

    // 6. Accessibility — image alt text coverage
    let image_violations = report
        .accessibility
        .wcag_results
        .violations
        .iter()
        .filter(|v| v.rule == "1.1.1")
        .count();
    signals.push(QualitySignal::new(
        ImageDescriptions,
        image_violations == 0,
        0.15,
        SignalValues {
            count: Some(image_violations as u32),
            ..Default::default()
        },
    ));

    // 7. Landmark structure
    let landmark_violations = report
        .accessibility
        .wcag_results
        .violations
        .iter()
        .filter(|v| v.rule_name.contains("Landmark"))
        .count();
    let missing_main_in_ax = report
        .interactive_findings
        .iter()
        .any(|f| f.category == "Landmark" && f.message.contains("Kein <main>-Landmark"));
    let good_landmarks = landmark_violations == 0 && !missing_main_in_ax;
    signals.push(QualitySignal::new(
        SemanticStructure,
        good_landmarks,
        0.10,
        SignalValues {
            count: Some(landmark_violations as u32),
            missing_main: Some(missing_main_in_ax),
            ..Default::default()
        },
    ));

    build_dimension(DimensionKind::Substance, signals)
}

// ─── Authority ───────────────────────────────────────────────────────────────

fn evaluate_authority(report: &AuditReport) -> DimensionScore {
    use QualitySignalKind::*;
    let mut signals = Vec::new();

    // 1. HTTPS
    let has_https = report.url.starts_with("https://");
    signals.push(QualitySignal::new(
        Https,
        has_https,
        0.15,
        SignalValues::default(),
    ));

    // 2. Security headers
    if let Some(sec) = &report.security {
        let header_count = [
            sec.headers.strict_transport_security.is_some(),
            sec.headers.content_security_policy.is_some(),
            sec.headers.x_content_type_options.is_some(),
            sec.headers.referrer_policy.is_some(),
        ]
        .iter()
        .filter(|&&b| b)
        .count();

        signals.push(QualitySignal::new(
            SecurityHeaders,
            header_count >= 3,
            0.15,
            SignalValues {
                count: Some(header_count as u32),
                ..Default::default()
            },
        ));
    }

    // 3. Schema.org Organization / Author
    if let Some(seo) = &report.discoverability.seo {
        let has_org = seo.structured_data.types.iter().any(|t| {
            t.is_organization_like() || matches!(t, SchemaType::Person | SchemaType::WebSite)
        });
        signals.push(QualitySignal::new(
            PublisherIdentity,
            has_org,
            0.20,
            SignalValues::default(),
        ));

        // 4. Canonical URL
        let has_canonical = seo.technical.has_canonical;
        signals.push(QualitySignal::new(
            CanonicalUrl,
            has_canonical,
            0.10,
            SignalValues::default(),
        ));

        // 5. Social meta / Open Graph
        let has_og = seo
            .social
            .open_graph
            .as_ref()
            .is_some_and(|og| og.title.is_some() && og.description.is_some());
        signals.push(QualitySignal::new(
            SocialMeta,
            has_og,
            0.10,
            SignalValues::default(),
        ));
    }

    // 6. Accessibility score as quality signal
    let a11y_good = report.accessibility.score >= 80.0;
    signals.push(QualitySignal::new(
        Accessibility,
        a11y_good,
        0.15,
        SignalValues {
            score: Some(report.accessibility.score),
            ..Default::default()
        },
    ));

    // 7. Trust signals from UX module
    if let Some(ux) = &report.ux {
        let trust_good = ux.trust_signals.score >= 70;
        signals.push(QualitySignal::new(
            TrustSignals,
            trust_good,
            0.15,
            SignalValues {
                score: Some(ux.trust_signals.score as f32),
                ..Default::default()
            },
        ));
    }

    build_dimension(DimensionKind::Authority, signals)
}

// ─── Consistency (single page) ───────────────────────────────────────────────

fn evaluate_single_page_consistency(report: &AuditReport) -> DimensionScore {
    use QualitySignalKind::*;
    let mut signals = Vec::new();

    // 1. Heading hierarchy (no skips)
    if let Some(seo) = &report.discoverability.seo {
        let issue_count = seo.headings.issues.len();
        signals.push(QualitySignal::new(
            HeadingHierarchy,
            issue_count == 0,
            0.25,
            SignalValues {
                count: Some(issue_count as u32),
                ..Default::default()
            },
        ));
    }

    // 2. All interactive elements named
    let unnamed_interactive = report
        .accessibility
        .wcag_results
        .violations
        .iter()
        .filter(|v| v.rule == "4.1.2" || v.rule == "1.1.1")
        .count();
    signals.push(QualitySignal::new(
        NamedControls,
        unnamed_interactive == 0,
        0.25,
        SignalValues {
            count: Some(unnamed_interactive as u32),
            ..Default::default()
        },
    ));

    // 3. No critical WCAG violations
    let critical = report.accessibility.statistics.critical;
    signals.push(QualitySignal::new(
        NoCriticalErrors,
        critical == 0,
        0.25,
        SignalValues {
            count: Some(critical as u32),
            ..Default::default()
        },
    ));

    // 4. Language consistency
    if let Some(seo) = &report.discoverability.seo {
        let has_lang = seo.technical.has_lang;
        signals.push(QualitySignal::new(
            LanguageConsistency,
            has_lang,
            0.25,
            SignalValues::default(),
        ));
    }

    build_dimension(DimensionKind::Consistency, signals)
}

// ─── Consistency (batch / cross-page) ────────────────────────────────────────

fn evaluate_cross_page_consistency(reports: &[AuditReport]) -> DimensionScore {
    use QualitySignalKind::*;
    let total = reports.len() as f32;
    let mut signals = Vec::new();

    // 1. Score stability (low standard deviation = consistent)
    let scores: Vec<f32> = reports.iter().map(|r| r.accessibility.score).collect();
    let mean = scores.iter().sum::<f32>() / total;
    let variance = scores.iter().map(|s| (s - mean).powi(2)).sum::<f32>() / total;
    let std_dev = variance.sqrt();
    signals.push(QualitySignal::new(
        ScoreStability,
        std_dev < 15.0,
        0.20,
        SignalValues {
            std_dev: Some(std_dev),
            ..Default::default()
        },
    ));

    // 2. Meta description coverage
    let with_meta: usize = reports
        .iter()
        .filter(|r| {
            r.discoverability
                .seo
                .as_ref()
                .and_then(|s| s.meta.description.as_ref())
                .is_some_and(|d| d.len() >= 50)
        })
        .count();
    let meta_pct = (with_meta as f32 / total * 100.0) as u32;
    signals.push(QualitySignal::new(
        MetaDescriptionCoverage,
        meta_pct >= 90,
        0.15,
        SignalValues {
            percent: Some(meta_pct),
            ..Default::default()
        },
    ));

    // 3. Schema.org coverage
    let with_schema: usize = reports
        .iter()
        .filter(|r| {
            r.discoverability
                .seo
                .as_ref()
                .is_some_and(|s| s.structured_data.has_structured_data)
        })
        .count();
    let schema_pct = (with_schema as f32 / total * 100.0) as u32;
    signals.push(QualitySignal::new(
        StructuredDataCoverage,
        schema_pct >= 80,
        0.15,
        SignalValues {
            percent: Some(schema_pct),
            ..Default::default()
        },
    ));

    // 4. Language declaration coverage
    let with_lang: usize = reports
        .iter()
        .filter(|r| {
            r.discoverability
                .seo
                .as_ref()
                .is_some_and(|s| s.technical.has_lang)
        })
        .count();
    let lang_pct = (with_lang as f32 / total * 100.0) as u32;
    signals.push(QualitySignal::new(
        LanguageDeclarationCoverage,
        lang_pct >= 95,
        0.15,
        SignalValues {
            percent: Some(lang_pct),
            ..Default::default()
        },
    ));

    // 5. Security header consistency
    let with_hsts: usize = reports
        .iter()
        .filter(|r| {
            r.security
                .as_ref()
                .is_some_and(|s| s.headers.strict_transport_security.is_some())
        })
        .count();
    let hsts_pct = (with_hsts as f32 / total * 100.0) as u32;
    signals.push(QualitySignal::new(
        HstsCoverage,
        hsts_pct >= 95,
        0.15,
        SignalValues {
            percent: Some(hsts_pct),
            ..Default::default()
        },
    ));

    // 6. No pages with critical violations
    let pages_with_critical: usize = reports
        .iter()
        .filter(|r| r.accessibility.statistics.critical > 0)
        .count();
    let clean_pct = ((total as usize - pages_with_critical) as f32 / total * 100.0) as u32;
    signals.push(QualitySignal::new(
        ErrorFreePages,
        pages_with_critical == 0,
        0.20,
        SignalValues {
            percent: Some(clean_pct),
            ..Default::default()
        },
    ));

    build_dimension(DimensionKind::Consistency, signals)
}

// ─── Helpers ─────────────────────────────────────────────────────────────────

fn build_dimension(kind: DimensionKind, signals: Vec<QualitySignal>) -> DimensionScore {
    if signals.is_empty() {
        return DimensionScore {
            kind,
            name: source_quality_dimension_name(kind, true).to_string(),
            score: 0,
            label: source_quality_no_data_label(true),
            signals: vec![],
        };
    }

    // Normalize weights to sum to 1.0
    let total_weight: f32 = signals.iter().map(|s| s.weight).sum();
    let score = if total_weight > 0.0 {
        let raw: f32 = signals
            .iter()
            .map(|s| {
                if s.present {
                    s.weight / total_weight * 100.0
                } else {
                    0.0
                }
            })
            .sum();
        raw.round() as u32
    } else {
        0
    };

    DimensionScore {
        kind,
        name: source_quality_dimension_name(kind, true).to_string(),
        score,
        label: source_quality_dimension_label(score, true),
        signals,
    }
}

fn average_dimensions(dims: &[DimensionScore], kind: DimensionKind) -> DimensionScore {
    if dims.is_empty() {
        return DimensionScore {
            kind,
            name: source_quality_dimension_name(kind, true).to_string(),
            score: 0,
            label: source_quality_no_data_label(true),
            signals: vec![],
        };
    }

    let avg = dims.iter().map(|d| d.score).sum::<u32>() / dims.len() as u32;

    // Merge signals: take the first report's signals as template, show coverage
    let signals = dims.first().map(|d| d.signals.clone()).unwrap_or_default();

    DimensionScore {
        kind,
        name: source_quality_dimension_name(kind, true).to_string(),
        score: avg,
        label: source_quality_dimension_label(avg, true),
        signals,
    }
}

fn weighted_average(items: &[(u32, u32)]) -> u32 {
    let total_weight: u32 = items.iter().map(|(_, w)| w).sum();
    if total_weight == 0 {
        return 0;
    }
    let sum: u32 = items.iter().map(|(s, w)| s * w).sum();
    (sum as f64 / total_weight as f64).round() as u32
}

fn empty_analysis() -> SourceQualityAnalysis {
    let empty = |kind: DimensionKind| DimensionScore {
        kind,
        name: source_quality_dimension_name(kind, true).to_string(),
        score: 0,
        label: source_quality_no_data_label(true),
        signals: vec![],
    };
    SourceQualityAnalysis {
        score: 0,
        grade: "F".into(),
        substance: empty(DimensionKind::Substance),
        consistency: empty(DimensionKind::Consistency),
        authority: empty(DimensionKind::Authority),
        disclaimer: source_quality_disclaimer(true),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::audit::normalized::InteractiveFinding;
    use crate::audit::AuditReport;
    use crate::audit::ViolationStatistics;
    use crate::cli::WcagLevel;
    use crate::taxonomy::Severity;
    use crate::wcag::WcagResults;

    fn minimal_report() -> AuditReport {
        AuditReport {
            url: "https://example.com".into(),
            wcag_level: WcagLevel::AA,
            timestamp: chrono::Utc::now(),
            accessibility: crate::audit::AccessibilitySection {
                wcag_results: WcagResults::new(),
                score: 95.0,
                grade: "A".into(),
                certificate: "SEHR GUT".into(),
                statistics: ViolationStatistics {
                    critical: 0,
                    high: 0,
                    medium: 0,
                    low: 0,
                    total: 0,
                },
                nodes_analyzed: 100,
            },
            duration_ms: 1000,
            performance: None,
            security: None,
            experience: crate::audit::ExperienceSection::default(),
            ux: None,
            journey: None,
            discoverability: crate::audit::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![],
            patterns: None,
            screenshot_status: Default::default(),
            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,
        }
    }

    #[test]
    fn test_minimal_report_produces_scores() {
        let report = minimal_report();
        let analysis = analyze_source_quality(&report);
        assert!(analysis.score <= 100);
        assert!(!analysis.disclaimer.is_empty());
        assert!(!analysis.grade.is_empty());
    }

    #[test]
    fn test_empty_batch_returns_zero() {
        let analysis = analyze_source_quality_batch(&[]);
        assert_eq!(analysis.score, 0);
    }

    #[test]
    fn test_batch_with_reports() {
        let reports = vec![minimal_report(), minimal_report()];
        let analysis = analyze_source_quality_batch(&reports);
        assert!(analysis.score <= 100);
        // Canonical English in the struct.
        assert_eq!(analysis.consistency.name, "Consistency");
        assert_eq!(analysis.consistency.kind, DimensionKind::Consistency);
    }

    #[test]
    fn test_grade_mapping() {
        assert_eq!(module_score_grade(95), "A");
        assert_eq!(module_score_grade(80), "B");
        assert_eq!(module_score_grade(65), "C");
        assert_eq!(module_score_grade(45), "D");
        assert_eq!(module_score_grade(20), "F");
    }

    #[test]
    fn ax_missing_main_prevents_positive_landmark_signal() {
        let mut report = minimal_report();
        report.interactive_findings.push(InteractiveFinding {
            category: "Landmark".to_string(),
            maps_to_finding: None,
            severity: Severity::Medium,
            journey: "link_inventory".to_string(),
            before_snapshot_label: None,
            after_snapshot_label: None,
            message: "Kein <main>-Landmark gefunden.".to_string(),
            fix_suggestion: None,
        });

        let analysis = analyze_source_quality(&report);
        let signal = analysis
            .substance
            .signals
            .iter()
            .find(|s| s.kind == QualitySignalKind::SemanticStructure)
            .expect("semantic structure signal");
        assert!(!signal.present);
        // Canonical English detail in the struct.
        assert!(signal.detail.contains("accessibility tree"));
        // PDF re-derivation yields German.
        let (_name, detail) =
            source_quality_signal_text(signal.kind, signal.present, &signal.values, false);
        assert!(detail.contains("Accessibility Tree"));
    }

    #[test]
    fn test_weighted_average() {
        assert_eq!(weighted_average(&[(100, 50), (0, 50)]), 50);
        assert_eq!(weighted_average(&[(100, 100)]), 100);
        assert_eq!(weighted_average(&[]), 0);
    }

    #[test]
    fn canonical_struct_has_no_german_chars() {
        use crate::seo::{
            HeadingStructure, MetaTags, SeoAnalysis, SocialTags, StructuredData, TechnicalSeo,
        };
        // A bare SEO profile so every "missing"/"weak" branch contributes a string.
        let mut report = minimal_report();
        report.accessibility.score = 50.0;
        report.discoverability.seo = Some(SeoAnalysis {
            meta: MetaTags::default(),
            headings: HeadingStructure::default(),
            technical: TechnicalSeo::default(),
            social: SocialTags::default(),
            structured_data: StructuredData::default(),
            score: 40,
            content_profile: None,
            robots: None,
            page_health: None,
            serp: None,
            meta_issues: vec![],
            image_efficiency: None,
        });

        // The struct (and thus JSON) is always canonical English now.
        let analysis = analyze_source_quality(&report);
        let dims = [
            &analysis.substance,
            &analysis.consistency,
            &analysis.authority,
        ];
        for dim in dims {
            let mut texts = vec![dim.name.clone(), dim.label.clone()];
            for s in &dim.signals {
                texts.push(s.name.clone());
                texts.push(s.detail.clone());
            }
            for t in texts {
                assert!(
                    !t.contains(['ä', 'ö', 'ü', 'Ä', 'Ö', 'Ü', 'ß']),
                    "German characters in canonical struct: {t:?}"
                );
            }
        }
        assert!(!analysis
            .disclaimer
            .contains(['ä', 'ö', 'ü', 'Ä', 'Ö', 'Ü', 'ß']));
    }

    #[test]
    fn signal_text_german_for_pdf_derivation() {
        // PDF re-derivation must yield real German for at least one variant.
        let (name, detail) = source_quality_signal_text(
            QualitySignalKind::ContentVolume,
            false,
            &SignalValues {
                word_count: Some(120),
                ..Default::default()
            },
            false,
        );
        assert_eq!(name, "Inhaltsumfang");
        assert!(detail.contains("Wörter"));
        assert!(detail.contains("Heuristik"));

        // Dimension label + disclaimer localize too.
        assert_eq!(
            source_quality_dimension_name(DimensionKind::Authority, false),
            "Autorität"
        );
        assert_eq!(source_quality_dimension_label(95, false), "Sehr gut");
        assert!(source_quality_disclaimer(false).contains("ausschließlich"));
    }
}