auditmysite 1.7.2

Resource-efficient WCAG 2.2 AA Accessibility Checker in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
//! 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;

// ─── 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,
    /// Qualitative band for `score`, canonical English (#406). This module
    /// carries no weight in the overall score, so it gets a band word rather
    /// than a letter grade (plan 29, D2).
    pub band: 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,
    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>,
    /// Whether the first heading in document order is the H1 (HeadingStructure)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub starts_with_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>,
    /// A UX score (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. Pass/fail marker for display only —
    /// the score uses `fulfilment`.
    pub present: bool,
    /// How much of this signal is met, 0.0–1.0.
    ///
    /// Coverage signals are proportions, and scoring them as a bool made 94 %
    /// HSTS coverage count exactly as 0 % while the report printed "94 %" next
    /// to a failed marker — a visible contradiction, and a cliff where one
    /// page in twenty flipped a whole dimension (plan 43). For genuinely
    /// binary signals this is 1.0 or 0.0 and nothing changes.
    #[serde(default = "default_fulfilment")]
    pub fulfilment: f32,
    /// 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,
}

/// Signals recorded before `fulfilment` existed are read back as fully met or
/// not met, matching the old binary behaviour.
fn default_fulfilment() -> f32 {
    1.0
}

impl QualitySignal {
    /// Build a binary signal — met or not, nothing in between.
    fn new(kind: QualitySignalKind, present: bool, weight: f32, values: SignalValues) -> Self {
        Self::graded(
            kind,
            present,
            if present { 1.0 } else { 0.0 },
            weight,
            values,
        )
    }

    /// Build a signal that is met proportionally. `present` remains the
    /// pass/fail marker the report shows; `fulfilment` is what scores.
    fn graded(
        kind: QualitySignalKind,
        present: bool,
        fulfilment: f32,
        weight: f32,
        values: SignalValues,
    ) -> Self {
        let (name, detail) = source_quality_signal_text(kind, present, &values, true);
        QualitySignal {
            kind,
            name,
            present,
            fulfilment: fulfilment.clamp(0.0, 1.0),
            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 {
    crate::registry::FIVE_BAND
        .label(score as f32, en)
        .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(),
        (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);
            let h1_count = count;
            let starts_with_h1 = values.starts_with_h1.unwrap_or(true);
            if !has_h1 {
                if en {
                    "No H1 heading present".into()
                } else {
                    "Keine H1-Überschrift vorhanden".into()
                }
            } else if h1_count != 1 {
                if en {
                    format!("{h1_count} H1 headings found (should be exactly one)")
                } else {
                    format!("{h1_count} H1-Überschriften gefunden (sollte genau eine sein)")
                }
            } else if !starts_with_h1 {
                if en {
                    "Exactly one H1, but it is not the first heading in the document".into()
                } else {
                    "Genau eine H1, aber nicht die erste Überschrift im Dokument".into()
                }
            } else if depth >= 3 {
                if en {
                    format!("Structured outline down to H{}", depth)
                } else {
                    format!("Strukturierte Gliederung bis H{}", depth)
                }
            } 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 && !values.schema_types.is_empty() {
                format!("Schema.org: {}", values.schema_types.join(", "))
            } else if present {
                // has_structured_data is true via microdata/RDFa, but
                // schema_types only tracks JSON-LD @type values — a bare
                // "Schema.org:" with nothing after the colon would read as
                // broken rather than as "detected, just not via JSON-LD".
                if en {
                    "Schema.org: structured data detected (microdata/RDFa, no JSON-LD types)".into()
                } else {
                    "Schema.org: strukturierte Daten erkannt (Microdata/RDFa, keine JSON-LD-Typen)"
                        .into()
                }
            } 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()
            }
        }
        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,
        band: crate::registry::FIVE_BAND
            .label(score as f32, true)
            .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,
        band: crate::registry::FIVE_BAND
            .label(score as f32, true)
            .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 h1_count = seo.headings.h1_count;
        let has_h1 = h1_count > 0;
        // A single H1 that isn't the first heading in the document (e.g. a
        // page opening with H2/H3 content before its H1) is just as much of
        // a broken outline as having none or several — `h1_count > 0` alone
        // used to call that "structured", contradicting the separately
        // reported `multiple_h1`/reading-order findings for the same page.
        let starts_with_h1 = seo
            .headings
            .headings
            .first()
            .map(|h| h.level == 1)
            .unwrap_or(false);
        let well_formed_h1 = h1_count == 1 && starts_with_h1;
        let depth = seo
            .headings
            .headings
            .iter()
            .map(|h| h.level)
            .max()
            .unwrap_or(0);
        let good_depth = depth >= 3;

        signals.push(QualitySignal::new(
            HeadingStructure,
            well_formed_h1 && good_depth,
            0.20,
            SignalValues {
                depth: Some(depth as u32),
                has_h1: Some(has_h1),
                starts_with_h1: Some(starts_with_h1),
                count: Some(h1_count as u32),
                ..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. Reads the same canonical
    // WCAG 1.1.1 violation count the report's findings surface elsewhere
    // (see `WcagResults::count_by_rule`, #574) rather than re-deriving it.
    let image_violations = report.accessibility.wcag_results.count_by_rule("1.1.1");
    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(),
        ));
    }

    // The accessibility score used to be signal 6 here. It is reported by the
    // Accessibility module, and folding it in again made a single finding move
    // both numbers, so the report read as two independent assessments that
    // happened to agree (plan 29, D3).

    // 6. 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: violations whose taxonomy rule is a
    // missing name or role, mapped the way the normalization maps them
    // (#574: one definition, not a second filter). Counting all of 4.1.2 and
    // 1.1.1 also counted duplicate IDs and images, and the JSON findings,
    // which carry 4.1.2 for `aria-hidden-focus` since plan 61, then
    // contradicted a "present" signal (report-lint on 5 rankinglab reports).
    let unnamed_interactive = report
        .accessibility
        .wcag_results
        .violations
        .iter()
        .filter(|v| {
            crate::taxonomy::RuleLookup::by_legacy_wcag_id(
                crate::audit::normalized::wcag_group_key(v),
            )
            .is_some_and(|rule| crate::taxonomy::is_missing_name_or_role(rule.id))
        })
        .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();
    // Tapers from fully met at a standard deviation of 15 to nothing at 30,
    // rather than falling off a cliff at 15.
    signals.push(QualitySignal::graded(
        ScoreStability,
        std_dev < 15.0,
        ((30.0 - std_dev) / 15.0).clamp(0.0, 1.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::graded(
        MetaDescriptionCoverage,
        meta_pct >= 90,
        meta_pct as f32 / 100.0,
        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::graded(
        StructuredDataCoverage,
        schema_pct >= 80,
        schema_pct as f32 / 100.0,
        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::graded(
        LanguageDeclarationCoverage,
        lang_pct >= 95,
        lang_pct as f32 / 100.0,
        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::graded(
        HstsCoverage,
        hsts_pct >= 95,
        hsts_pct as f32 / 100.0,
        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;
    // `clean_pct` was computed and then discarded in favour of the bool.
    signals.push(QualitySignal::graded(
        ErrorFreePages,
        pages_with_critical == 0,
        clean_pct as f32 / 100.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| s.weight / total_weight * 100.0 * s.fulfilment)
            .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,
        band: crate::registry::FIVE_BAND.label(0.0, true).to_string(),
        substance: empty(DimensionKind::Substance),
        consistency: empty(DimensionKind::Consistency),
        authority: empty(DimensionKind::Authority),
        disclaimer: source_quality_disclaimer(true),
    }
}

#[cfg(test)]
mod tests {

    /// Plan 43: coverage signals are proportions. Scoring them as a bool made
    /// 94 % count exactly as 0 %, while the report printed "94 %" beside a
    /// failed marker — a visible contradiction and a cliff where one page in
    /// twenty flipped a dimension.
    #[test]
    fn coverage_signals_score_proportionally_not_at_a_cliff() {
        use QualitySignalKind::*;

        let at = |pct: u32| {
            QualitySignal::graded(
                HstsCoverage,
                pct >= 95,
                pct as f32 / 100.0,
                0.15,
                SignalValues {
                    percent: Some(pct),
                    ..Default::default()
                },
            )
        };

        let just_below = build_dimension(DimensionKind::Consistency, vec![at(94)]);
        let none = build_dimension(DimensionKind::Consistency, vec![at(0)]);
        let just_above = build_dimension(DimensionKind::Consistency, vec![at(95)]);

        assert!(
            just_below.score > none.score,
            "94 % coverage must not score like 0 %: {} vs {}",
            just_below.score,
            none.score,
        );
        assert!(
            just_above.score - just_below.score <= 2,
            "the threshold must not be a cliff: {} vs {}",
            just_below.score,
            just_above.score,
        );

        // `present` stays the pass/fail marker the report shows.
        assert!(!at(94).present);
        assert!(at(95).present);
    }

    /// Genuinely binary signals must behave exactly as before.
    #[test]
    fn binary_signals_are_unchanged() {
        let met = QualitySignal::new(
            QualitySignalKind::HstsCoverage,
            true,
            0.5,
            SignalValues::default(),
        );
        let unmet = QualitySignal::new(
            QualitySignalKind::HstsCoverage,
            false,
            0.5,
            SignalValues::default(),
        );
        assert_eq!(met.fulfilment, 1.0);
        assert_eq!(unmet.fulfilment, 0.0);
        assert_eq!(
            build_dimension(DimensionKind::Consistency, vec![met]).score,
            100,
        );
        assert_eq!(
            build_dimension(DimensionKind::Consistency, vec![unmet]).score,
            0,
        );
    }

    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,
                execution: Default::default(),
            },
            duration_ms: 1000,
            performance: None,
            security: None,
            html_conform: 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.band.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 band_replaces_the_letter_grade_this_module_no_longer_carries() {
        // Plan 29, D2: an indicator of weight 0 gets a band word, not A-F.
        let band = |s: f32| crate::registry::FIVE_BAND.label(s, true);
        assert_eq!(band(95.0), "Excellent");
        assert_eq!(band(80.0), "Good");
        assert_eq!(band(65.0), "Needs improvement");
        assert_eq!(band(45.0), "Inadequate");
        assert_eq!(band(20.0), "Critical");
    }

    #[test]
    fn ax_missing_main_prevents_positive_landmark_signal() {
        let mut report = minimal_report();
        report.interactive_findings.push(InteractiveFinding {
            category: "Landmark".to_string(),
            kind: crate::audit::normalized::InteractiveFindingKind::LandmarkMissingMain,
            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,
            values: crate::audit::normalized::InteractiveFindingValues::default(),
            uncertainty: 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"));
    }

    /// Regression test for a real report-critique finding: a page with two
    /// H1 headings, where the document opens with H2 content before the
    /// first H1, used to be labeled a "structured outline" here because the
    /// old check only asked `h1_count > 0` — directly contradicting this
    /// same report's own SEO `multiple_h1` finding and reading-order
    /// findings for the identical page.
    #[test]
    fn heading_structure_signal_flags_multiple_h1_as_not_well_formed() {
        use crate::seo::{HeadingInfo, HeadingStructure, MetaTags, SeoAnalysis};

        let mut report = minimal_report();
        report.discoverability.seo = Some(SeoAnalysis {
            meta: MetaTags::default(),
            headings: HeadingStructure {
                h1_count: 2,
                h1_text: Some("First".into()),
                headings: vec![
                    HeadingInfo {
                        level: 2,
                        text: "Intro".into(),
                        length: 5,
                        is_question: false,
                        in_faq_context: false,
                        word_count_after: 10,
                    },
                    HeadingInfo {
                        level: 1,
                        text: "First".into(),
                        length: 5,
                        is_question: false,
                        in_faq_context: false,
                        word_count_after: 10,
                    },
                    HeadingInfo {
                        level: 3,
                        text: "Sub".into(),
                        length: 3,
                        is_question: false,
                        in_faq_context: false,
                        word_count_after: 5,
                    },
                    HeadingInfo {
                        level: 1,
                        text: "Second".into(),
                        length: 6,
                        is_question: false,
                        in_faq_context: false,
                        word_count_after: 5,
                    },
                ],
                issues: vec![],
                total_count: 4,
            },
            ..Default::default()
        });

        let analysis = analyze_source_quality(&report);
        let signal = analysis
            .substance
            .signals
            .iter()
            .find(|s| s.kind == QualitySignalKind::HeadingStructure)
            .expect("heading structure signal");

        assert!(
            !signal.present,
            "two H1 headings with content before the first one must not count as well-formed"
        );
        assert!(
            signal.detail.contains('2') && signal.detail.to_lowercase().contains("h1"),
            "detail should name the actual H1 count, got {:?}",
            signal.detail
        );
        assert!(
            !signal.detail.contains("Structured outline"),
            "must not claim a structured outline when H1 usage is broken: {:?}",
            signal.detail
        );
    }

    /// Finds a signal by kind in the `Substance` dimension of a freshly
    /// analyzed report — shared helper for the threshold tests below.
    fn substance_signal(report: &AuditReport, kind: QualitySignalKind) -> QualitySignal {
        analyze_source_quality(report)
            .substance
            .signals
            .into_iter()
            .find(|s| s.kind == kind)
            .unwrap_or_else(|| panic!("{kind:?} signal must be present in the substance dimension"))
    }

    #[test]
    fn content_volume_signal_requires_at_least_300_words() {
        use crate::seo::{SeoAnalysis, TechnicalSeo};

        let mut report = minimal_report();
        report.discoverability.seo = Some(SeoAnalysis {
            technical: TechnicalSeo {
                word_count: 299,
                ..Default::default()
            },
            ..Default::default()
        });
        assert!(
            !substance_signal(&report, QualitySignalKind::ContentVolume).present,
            "299 words must not count as sufficient content volume"
        );

        report.discoverability.seo = Some(SeoAnalysis {
            technical: TechnicalSeo {
                word_count: 300,
                ..Default::default()
            },
            ..Default::default()
        });
        assert!(
            substance_signal(&report, QualitySignalKind::ContentVolume).present,
            "300 words must count as sufficient content volume"
        );
    }

    #[test]
    fn structured_data_signal_reflects_has_structured_data_flag() {
        use crate::seo::SeoAnalysis;
        use crate::seo::StructuredData;

        let mut report = minimal_report();
        report.discoverability.seo = Some(SeoAnalysis {
            structured_data: StructuredData {
                has_structured_data: false,
                ..Default::default()
            },
            ..Default::default()
        });
        assert!(
            !substance_signal(&report, QualitySignalKind::StructuredData).present,
            "no structured data must not be flagged present"
        );

        report.discoverability.seo = Some(SeoAnalysis {
            structured_data: StructuredData {
                has_structured_data: true,
                ..Default::default()
            },
            ..Default::default()
        });
        let signal = substance_signal(&report, QualitySignalKind::StructuredData);
        assert!(
            signal.present,
            "has_structured_data=true must be flagged present even without JSON-LD types"
        );
        assert!(
            signal.detail.contains("microdata/RDFa"),
            "detail should explain structured data was detected via microdata/RDFa, not JSON-LD: {:?}",
            signal.detail
        );
    }

    #[test]
    fn meta_description_signal_requires_at_least_50_characters() {
        use crate::seo::{MetaTags, SeoAnalysis};

        let mut report = minimal_report();
        report.discoverability.seo = Some(SeoAnalysis {
            meta: MetaTags {
                description: Some("x".repeat(49)),
                ..Default::default()
            },
            ..Default::default()
        });
        assert!(
            !substance_signal(&report, QualitySignalKind::MetaDescription).present,
            "a 49-character meta description must not count as meaningful"
        );

        report.discoverability.seo = Some(SeoAnalysis {
            meta: MetaTags {
                description: Some("x".repeat(50)),
                ..Default::default()
            },
            ..Default::default()
        });
        assert!(
            substance_signal(&report, QualitySignalKind::MetaDescription).present,
            "a 50-character meta description must count as meaningful"
        );
    }

    #[test]
    fn language_declaration_signal_reflects_has_lang_flag() {
        use crate::seo::{SeoAnalysis, TechnicalSeo};

        let mut report = minimal_report();
        report.discoverability.seo = Some(SeoAnalysis {
            technical: TechnicalSeo {
                has_lang: false,
                lang: None,
                ..Default::default()
            },
            ..Default::default()
        });
        assert!(
            !substance_signal(&report, QualitySignalKind::LanguageDeclaration).present,
            "missing lang attribute must not be flagged present"
        );

        report.discoverability.seo = Some(SeoAnalysis {
            technical: TechnicalSeo {
                has_lang: true,
                lang: Some("de-DE".to_string()),
                ..Default::default()
            },
            ..Default::default()
        });
        let signal = substance_signal(&report, QualitySignalKind::LanguageDeclaration);
        assert!(
            signal.present,
            "declared lang attribute must be flagged present"
        );
        assert!(
            signal.detail.contains("de-DE"),
            "detail should name the declared language: {:?}",
            signal.detail
        );
    }

    #[test]
    fn image_descriptions_signal_requires_zero_missing_alt_text_violations() {
        let mut report = minimal_report();
        report
            .accessibility
            .wcag_results
            .add_violation(crate::wcag::Violation::new(
                "1.1.1",
                "Non-text Content",
                WcagLevel::A,
                Severity::High,
                "Image missing alternative text",
                "img.hero",
            ));
        assert!(
            !substance_signal(&report, QualitySignalKind::ImageDescriptions).present,
            "any 1.1.1 violation must not be flagged present"
        );

        let clean_report = minimal_report();
        assert!(
            substance_signal(&clean_report, QualitySignalKind::ImageDescriptions).present,
            "zero 1.1.1 violations must be flagged present"
        );
    }

    #[test]
    fn semantic_structure_signal_requires_zero_landmark_violations() {
        let mut report = minimal_report();
        report
            .accessibility
            .wcag_results
            .add_violation(crate::wcag::Violation::new(
                "1.3.1",
                "Landmark Uniqueness",
                WcagLevel::A,
                Severity::Medium,
                "Multiple landmarks share the same accessible name",
                "header.site-header",
            ));
        let signal = substance_signal(&report, QualitySignalKind::SemanticStructure);
        assert!(
            !signal.present,
            "a landmark-rule violation must not be flagged present"
        );
        assert!(
            signal.detail.contains('1'),
            "detail should name the actual violation count: {:?}",
            signal.detail
        );

        let clean_report = minimal_report();
        assert!(
            substance_signal(&clean_report, QualitySignalKind::SemanticStructure).present,
            "zero landmark violations (and no missing <main>) must be flagged present"
        );
    }
}