auditmysite 1.7.3

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
use std::collections::{BTreeMap, HashSet};

use serde::{Deserialize, Serialize};

use crate::taxonomy::{
    criterion_for_rule, principle_for_criterion, RuleLookup, Scaling, ScoreImpact, WcagPrinciple,
};
use crate::wcag::coverage::automated_criteria;
use crate::wcag::types::{Severity, Violation};

/// Number of automatically-checked WCAG criteria belonging to a principle.
fn checked_criteria_count(principle: WcagPrinciple) -> usize {
    automated_criteria()
        .iter()
        .filter(|(c, _)| principle_for_criterion(c) == Some(principle))
        .count()
}

/// Calculates accessibility scores and grades based on WCAG violations
pub struct AccessibilityScorer;

/// Below this raw score the hard `clamp(0)` is replaced by an asymptotic
/// curve, so that semantically different catastrophic states (score 0 vs 5)
/// remain distinguishable instead of collapsing onto a single value.
const SOFT_FLOOR_START: f32 = 15.0;

/// Penalty above which the square-root compression curve engages. Below it the
/// raw `100 - penalty` passes through unchanged (scores ≥30 are untouched).
const COMPRESSION_KNEE: f32 = 70.0;

/// Diversity factor for `unique_criteria` violated WCAG success criteria.
///
/// A focused failure (≤3 criteria) gets no surcharge; broad, systemic
/// failure is penalised, with logarithmic — bounded — growth.
fn diversity_factor(unique_criteria: usize) -> f32 {
    if unique_criteria <= 3 {
        1.0
    } else {
        (1.0 + 0.15 * (1.0 + (unique_criteria as f32 / 5.0).ln())).min(1.5)
    }
}

/// Soft floor: above `SOFT_FLOOR_START` the raw score passes through
/// unchanged; below it, an exponential curve approaches zero asymptotically.
fn apply_soft_floor(raw_score: f32) -> f32 {
    if raw_score >= SOFT_FLOOR_START {
        raw_score
    } else {
        SOFT_FLOOR_START * ((raw_score - SOFT_FLOOR_START) / 8.0).exp()
    }
}

/// Default penalty for rules not found in the taxonomy registry.
///
/// `pub(crate)` so the JSON score breakdown attributes penalties with the
/// exact same per-rule cost the scorer uses, instead of a second severity
/// weighting of its own (plan 37).
pub(crate) fn default_impact(severity: Severity) -> ScoreImpact {
    match severity {
        Severity::Critical => ScoreImpact {
            base_penalty: 5.0,
            max_penalty: 15.0,
            occurrence_scaling: Scaling::Logarithmic,
        },
        Severity::High => ScoreImpact {
            base_penalty: 3.0,
            max_penalty: 10.0,
            occurrence_scaling: Scaling::Logarithmic,
        },
        Severity::Medium => ScoreImpact {
            base_penalty: 1.5,
            max_penalty: 5.0,
            occurrence_scaling: Scaling::Logarithmic,
        },
        Severity::Low => ScoreImpact {
            base_penalty: 0.5,
            max_penalty: 2.0,
            occurrence_scaling: Scaling::Fixed,
        },
    }
}

/// The global half of the accessibility score: everything applied *after*
/// the per-rule penalties are summed.
///
/// Extracted so the JSON score breakdown can score a single area with the
/// exact same pipeline instead of inventing a second model (plan 37). Every
/// step here is non-linear and depends on the finding set as a whole, which is
/// why per-area scores produced by this function do not add up to the score of
/// the whole set — that reconciliation is carried by
/// `estimated_lost_points`, not by the per-area scores.
pub(crate) fn score_from_penalties(
    raw_penalty: f32,
    unique_criteria: usize,
    critical_occurrences: usize,
    urgent_occurrences: usize,
    level_a_urgent_occurrences: usize,
) -> f32 {
    if raw_penalty <= 0.0 {
        return 100.0;
    }

    // Diversity factor: failing many distinct WCAG criteria is a broader,
    // more systemic problem than failing one criterion repeatedly.
    let total_penalty = raw_penalty * diversity_factor(unique_criteria);

    // Compression for high penalties: scores with total_penalty ≤ 70 (i.e.
    // ≥30) pass through unchanged. Above the knee a square-root curve grows
    // the effective penalty — slower than linear (so a few thousand
    // violations don't all hit absolute zero) but far faster than the
    // previous logarithmic curve, which crushed every large site into a
    // 4–9 cluster. A site failing 30 distinct critical criteria now scores
    // visibly lower than one failing 8, instead of being indistinguishable.
    let effective_penalty = if total_penalty > COMPRESSION_KNEE {
        COMPRESSION_KNEE + (total_penalty - COMPRESSION_KNEE).sqrt() * 2.0
    } else {
        total_penalty
    };
    // Soft floor instead of a hard clamp(0): keeps the 1–15 band usable
    // for distinguishing degrees of catastrophic failure.
    let raw_score = apply_soft_floor(100.0 - effective_penalty).min(100.0);

    // Semantic score cap: a site with open critical/high issues cannot be
    // reported as near-perfect even if penalties are individually small.
    //
    // A High failure of a Level A criterion keeps the page below the top band
    // (90 = SEHR GUT): Level A is the conformance floor, a page failing it is
    // not conformant. Before, one missing alt text on an otherwise clean page
    // scored 92 (plan 47, calibration decision 2026-09-26).
    let score_cap: f32 = if critical_occurrences >= 1 {
        49.0
    } else if level_a_urgent_occurrences >= 1 {
        89.0
    } else if urgent_occurrences >= 5 {
        92.0
    } else {
        100.0
    };

    raw_score.min(score_cap)
}

impl AccessibilityScorer {
    /// Calculate accessibility score (0-100) based on violations
    ///
    /// Uses the taxonomy rule registry for per-rule score impacts.
    /// Groups violations by rule, looks up ScoreImpact, and applies
    /// occurrence-based penalty scaling.
    pub fn calculate_score(violations: &[Violation]) -> f32 {
        if violations.is_empty() {
            return 100.0;
        }

        // Group violations by rule ID and track severity
        let mut rule_counts: BTreeMap<&str, (usize, Severity)> = BTreeMap::new();
        for v in violations {
            let entry = rule_counts.entry(&v.rule).or_insert((0, v.severity));
            entry.0 += 1;
            // Keep highest severity if same rule has mixed severities
            if v.severity > entry.1 {
                entry.1 = v.severity;
            }
        }

        let mut total_penalty = 0.0f32;

        for (rule_id, (count, severity)) in &rule_counts {
            // Look up rule in taxonomy (by legacy WCAG ID)
            let impact = RuleLookup::by_legacy_wcag_id(rule_id)
                .map(|r| r.score_impact)
                .unwrap_or_else(|| default_impact(*severity));

            total_penalty += impact.calculate_penalty(*count);
        }

        let unique_criteria: HashSet<String> = rule_counts
            .keys()
            .map(|rule_id| criterion_for_rule(rule_id).unwrap_or_else(|| (*rule_id).to_string()))
            .collect();

        let critical_count = violations
            .iter()
            .filter(|v| matches!(v.severity, Severity::Critical))
            .count();
        let urgent_count = critical_count
            + violations
                .iter()
                .filter(|v| matches!(v.severity, Severity::High))
                .count();
        let level_a_urgent_count = violations
            .iter()
            .filter(|v| {
                v.level == crate::cli::WcagLevel::A
                    && matches!(v.severity, Severity::High | Severity::Critical)
            })
            .count();

        score_from_penalties(
            total_penalty,
            unique_criteria.len(),
            critical_count,
            urgent_count,
            level_a_urgent_count,
        )
    }

    /// Calculate letter grade (A-F) based on score
    pub fn calculate_grade(score: f32) -> &'static str {
        crate::registry::LETTER_GRADE.label(score, false)
    }

    /// Calculate certificate level based on score.
    ///
    /// Thresholds follow the official grade bands (#449). The returned value is
    /// the canonical German token used as the lookup key for badge/colour; the
    /// display label is localized at render time (see
    /// `registry::certificate_label_localized`).
    ///
    /// - SEHR GUT: ≥90 (platinum)
    /// - GUT: ≥75 (gold)
    /// - STABIL: ≥60 (silver)
    /// - AUSBAUFÄHIG: ≥40 (bronze)
    /// - UNGENÜGEND: <40 (failed)
    pub fn calculate_certificate(score: f32) -> &'static str {
        crate::registry::CERTIFICATE.label(score, false)
    }

    /// Calculate WCAG principle coverage — a purely informative secondary
    /// indicator that does *not* feed into the numeric score.
    ///
    /// For each of the four WCAG principles it reports how many of the
    /// criteria the tool checks passed (had no violation).
    pub fn calculate_coverage(violations: &[Violation]) -> PrincipleCoverage {
        let failed: HashSet<String> = violations
            .iter()
            .filter_map(|v| criterion_for_rule(&v.rule))
            .collect();

        let ratio_for = |principle: WcagPrinciple| -> CoverageRatio {
            let total = checked_criteria_count(principle) as u32;
            let failed_in_principle = failed
                .iter()
                .filter(|c| principle_for_criterion(c) == Some(principle))
                .count() as u32;
            let passed = total.saturating_sub(failed_in_principle);
            CoverageRatio {
                passed,
                total,
                ratio: if total == 0 {
                    1.0
                } else {
                    let r = passed as f32 / total as f32;
                    (r * 10000.0).round() / 10000.0
                },
            }
        };

        PrincipleCoverage {
            perceivable: ratio_for(WcagPrinciple::Perceivable),
            operable: ratio_for(WcagPrinciple::Operable),
            understandable: ratio_for(WcagPrinciple::Understandable),
            robust: ratio_for(WcagPrinciple::Robust),
        }
    }

    /// Calculate detailed statistics for a set of violations
    pub fn calculate_statistics(violations: &[Violation]) -> ViolationStatistics {
        let total = violations.len();
        let critical = violations
            .iter()
            .filter(|v| matches!(v.severity, Severity::Critical))
            .count();
        let high = violations
            .iter()
            .filter(|v| matches!(v.severity, Severity::High))
            .count();
        let medium = violations
            .iter()
            .filter(|v| matches!(v.severity, Severity::Medium))
            .count();
        let low = violations
            .iter()
            .filter(|v| matches!(v.severity, Severity::Low))
            .count();

        ViolationStatistics {
            total,
            critical,
            high,
            medium,
            low,
        }
    }
}

/// Pass/total ratio of checked WCAG criteria for one principle.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CoverageRatio {
    pub passed: u32,
    pub total: u32,
    /// 0.0 – 1.0
    pub ratio: f32,
}

/// WCAG principle coverage — informative secondary indicator (#99).
///
/// Shows *where* a site fails: a deep failure in one area versus a broad
/// failure across all four principles. Does not affect the numeric score.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PrincipleCoverage {
    pub perceivable: CoverageRatio,
    pub operable: CoverageRatio,
    pub understandable: CoverageRatio,
    pub robust: CoverageRatio,
}

/// Detailed statistics about violations
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ViolationStatistics {
    pub total: usize,
    pub critical: usize,
    pub high: usize,
    pub medium: usize,
    pub low: usize,
}

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

    #[test]
    fn test_perfect_score() {
        let violations = vec![];
        let score = AccessibilityScorer::calculate_score(&violations);
        assert_eq!(score, 100.0);
        assert_eq!(AccessibilityScorer::calculate_grade(score), "A");
        assert_eq!(
            AccessibilityScorer::calculate_certificate(score),
            "SEHR GUT"
        );
    }

    #[test]
    fn test_score_with_errors() {
        use crate::cli::WcagLevel;

        let violations = vec![
            Violation::new(
                "1.1.1",
                "Non-text Content",
                WcagLevel::A,
                Severity::High,
                "Image missing alt",
                "img1",
            ),
            Violation::new(
                "1.1.1",
                "Non-text Content",
                WcagLevel::A,
                Severity::High,
                "Image missing alt",
                "img2",
            ),
        ];

        // Rule 1.1.1: base=3.0, max=10.0, Logarithmic
        // 2 occurrences: 3.0 * (1 + ln(2)) ≈ 5.08 → 95 before the cap. A High
        // failure of a Level A criterion caps at 89: not conformant, so not
        // the top band (plan 47).
        let score = AccessibilityScorer::calculate_score(&violations);
        assert_eq!(score, 89.0);
        assert_eq!(AccessibilityScorer::calculate_grade(score), "B");
    }

    #[test]
    fn test_score_with_warnings() {
        use crate::cli::WcagLevel;

        let violations = vec![Violation::new(
            "2.4.4",
            "Link Purpose",
            WcagLevel::A,
            Severity::Medium,
            "Link text not descriptive",
            "link1",
        )];

        // Rule 2.4.4: base=1.0, max=5.0, Logarithmic
        // 1 occurrence: 1.0 * (1 + ln(1)) = 1.0
        let score = AccessibilityScorer::calculate_score(&violations);
        assert_eq!(score, 99.0);
    }

    #[test]
    fn test_critical_penalty_no_headings() {
        use crate::cli::WcagLevel;

        let violations = vec![Violation::new(
            "2.4.6",
            "Headings and Labels",
            WcagLevel::AA,
            Severity::High,
            "No headings found",
            "document",
        )];

        // Rule 2.4.6: base=20.0, max=20.0, Fixed
        // 1 occurrence: 20.0
        let score = AccessibilityScorer::calculate_score(&violations);
        assert_eq!(score, 80.0);
        assert_eq!(AccessibilityScorer::calculate_grade(score), "B");
        assert_eq!(AccessibilityScorer::calculate_certificate(score), "GUT");
    }

    #[test]
    fn test_score_floor_at_zero() {
        use crate::cli::WcagLevel;

        // Create many violations across ALL mapped rules to exceed 100 penalty
        let rules = [
            ("1.1.1", "Non-text Content"),
            ("1.3.1", "Info and Relationships"),
            ("1.4.3", "Contrast"),
            ("2.1.1", "Keyboard"),
            ("2.4.1", "Bypass Blocks"),
            ("2.4.2", "Page Titled"),
            ("2.4.6", "Headings"),
            ("2.4.7", "Focus Visible"),
            ("3.1.1", "Language"),
            ("3.3.2", "Labels"),
            ("4.1.2", "Name Role Value"),
            ("2.4.4", "Link Purpose"),
            ("2.4.3", "Focus Order"),
            ("1.4.4", "Resize Text"),
        ];
        let mut violations = Vec::new();
        for (rule, name) in &rules {
            for i in 0..20 {
                violations.push(Violation::new(
                    *rule,
                    *name,
                    WcagLevel::A,
                    Severity::Critical,
                    "Error",
                    format!("n{}", i),
                ));
            }
        }

        let score = AccessibilityScorer::calculate_score(&violations);
        // With log compression, catastrophic failure scores 3–5 (not ~1).
        assert!(score < 10.0, "score was {}", score);
        assert_eq!(AccessibilityScorer::calculate_grade(score), "F");
        assert_eq!(
            AccessibilityScorer::calculate_certificate(score),
            "UNGENÜGEND"
        );
    }

    #[test]
    fn test_catastrophic_band_stays_discriminating() {
        use crate::cli::WcagLevel;

        let rules = [
            ("1.1.1", "Non-text Content"),
            ("1.3.1", "Info and Relationships"),
            ("1.4.3", "Contrast"),
            ("2.1.1", "Keyboard"),
            ("2.4.1", "Bypass Blocks"),
            ("2.4.2", "Page Titled"),
            ("2.4.6", "Headings"),
            ("2.4.7", "Focus Visible"),
            ("3.1.1", "Language"),
            ("3.3.2", "Labels"),
            ("4.1.2", "Name Role Value"),
            ("2.4.4", "Link Purpose"),
            ("2.4.3", "Focus Order"),
            ("1.4.4", "Resize Text"),
        ];
        let build = |criteria: usize, occ: usize| -> Vec<Violation> {
            let mut v = Vec::new();
            for (rule, name) in rules.iter().take(criteria) {
                for i in 0..occ {
                    v.push(Violation::new(
                        *rule,
                        *name,
                        WcagLevel::A,
                        Severity::Critical,
                        "Error",
                        format!("n{}", i),
                    ));
                }
            }
            v
        };

        // A moderately failing site (4 critical criteria) and a catastrophic one
        // (14 critical criteria, many occurrences each). Both score below the
        // critical cap, but the catastrophic site must score meaningfully lower
        // rather than collapsing into the same 4–9 cluster.
        let moderate = AccessibilityScorer::calculate_score(&build(4, 3));
        let catastrophic = AccessibilityScorer::calculate_score(&build(14, 30));
        assert!(
            moderate - catastrophic >= 8.0,
            "moderate {} should outscore catastrophic {} by a clear margin",
            moderate,
            catastrophic
        );
        assert!(catastrophic > 0.0);
    }

    #[test]
    fn test_diversity_penalises_breadth() {
        use crate::cli::WcagLevel;

        // 5× the same High violation — a focused failure.
        let same: Vec<Violation> = (0..5)
            .map(|i| {
                Violation::new(
                    "1.1.1",
                    "Non-text Content",
                    WcagLevel::A,
                    Severity::High,
                    "Image missing alt",
                    format!("n{}", i),
                )
            })
            .collect();

        // 5 distinct High violations — a broader failure.
        let diverse_rules = [
            ("1.1.1", "Non-text Content"),
            ("1.3.1", "Info and Relationships"),
            ("2.4.3", "Focus Order"),
            ("3.3.2", "Labels"),
            ("1.4.4", "Resize Text"),
        ];
        let diverse: Vec<Violation> = diverse_rules
            .iter()
            .map(|(rule, name)| {
                Violation::new(*rule, *name, WcagLevel::A, Severity::High, "Error", "node")
            })
            .collect();

        let score_same = AccessibilityScorer::calculate_score(&same);
        let score_diverse = AccessibilityScorer::calculate_score(&diverse);
        assert!(
            score_diverse < score_same,
            "diverse {} should score lower than same {}",
            score_diverse,
            score_same
        );
    }

    #[test]
    fn test_diversity_factor_growth() {
        // ≤3 criteria: no surcharge.
        assert_eq!(diversity_factor(1), 1.0);
        assert_eq!(diversity_factor(3), 1.0);
        // Logarithmic, bounded growth.
        assert!(diversity_factor(5) > 1.0);
        assert!(diversity_factor(20) > diversity_factor(5));
        assert!(diversity_factor(40) <= 1.5);
    }

    #[test]
    fn test_soft_floor_curve() {
        // Above the floor start: unchanged.
        assert_eq!(apply_soft_floor(20.0), 20.0);
        assert_eq!(apply_soft_floor(50.0), 50.0);
        // Below: approaches 0 but never hard-clamps to it.
        assert!(apply_soft_floor(0.0) > 0.0);
        assert!(apply_soft_floor(-30.0) > 0.0);
        assert!(apply_soft_floor(-30.0) < apply_soft_floor(0.0));
        // Catastrophic penalties drop below 1.0.
        assert!(apply_soft_floor(-60.0) < 1.0);
    }

    #[test]
    fn test_coverage_all_pass_when_no_violations() {
        let coverage = AccessibilityScorer::calculate_coverage(&[]);
        for ratio in [
            &coverage.perceivable,
            &coverage.operable,
            &coverage.understandable,
            &coverage.robust,
        ] {
            assert_eq!(ratio.passed, ratio.total);
            assert!(ratio.total > 0);
            assert_eq!(ratio.ratio, 1.0);
        }
    }

    #[test]
    fn test_coverage_reflects_violations() {
        use crate::cli::WcagLevel;

        let violations = vec![Violation::new(
            "1.1.1",
            "Non-text Content",
            WcagLevel::A,
            Severity::High,
            "Missing alt",
            "n1",
        )];
        let coverage = AccessibilityScorer::calculate_coverage(&violations);
        // One Perceivable criterion failed.
        assert_eq!(coverage.perceivable.passed, coverage.perceivable.total - 1);
        // Other principles untouched.
        assert_eq!(coverage.operable.passed, coverage.operable.total);
        assert_eq!(coverage.robust.passed, coverage.robust.total);
    }

    #[test]
    fn test_statistics_calculation() {
        use crate::cli::WcagLevel;

        let violations = vec![
            Violation::new(
                "1.1.1",
                "Non-text Content",
                WcagLevel::A,
                Severity::Critical,
                "Error",
                "1",
            ),
            Violation::new(
                "2.4.6",
                "Headings and Labels",
                WcagLevel::AA,
                Severity::Medium,
                "Warning",
                "2",
            ),
            Violation::new(
                "3.1.1",
                "Language of Page",
                WcagLevel::A,
                Severity::Low,
                "Notice",
                "3",
            ),
            Violation::new(
                "4.1.2",
                "Name, Role, Value",
                WcagLevel::A,
                Severity::High,
                "Error",
                "4",
            ),
        ];

        let stats = AccessibilityScorer::calculate_statistics(&violations);
        assert_eq!(stats.total, 4);
        assert_eq!(stats.critical, 1);
        assert_eq!(stats.high, 1);
        assert_eq!(stats.medium, 1);
        assert_eq!(stats.low, 1);
    }
}

/// Properties the score must have regardless of how its constants are tuned
/// (plan 47). None of them says what a page *should* score — that needs an
/// outside reference — but each one is something no tuning may break, and a
/// break would mean the score contradicts its own findings.
#[cfg(test)]
mod score_invariants {
    use super::*;
    use crate::cli::WcagLevel;

    /// Rule ids mixing catalogued criteria (taxonomy score impacts) with ids
    /// the taxonomy doesn't know (severity-based `default_impact`).
    const RULES: &[&str] = &[
        "1.1.1", "1.3.1", "1.4.3", "2.1.1", "2.4.2", "2.4.4", "3.1.1", "4.1.2", "x.1", "x.2",
        "x.3", "x.4",
    ];
    const SEVERITIES: &[Severity] = &[
        Severity::Low,
        Severity::Medium,
        Severity::High,
        Severity::Critical,
    ];

    /// Deterministic generator — no dependency, reproducible failures.
    struct Lcg(u64);
    impl Lcg {
        fn next(&mut self, n: usize) -> usize {
            self.0 = self
                .0
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            ((self.0 >> 33) as usize) % n
        }
    }

    fn violation(rule: &str, level: WcagLevel, severity: Severity, i: usize) -> Violation {
        Violation::new(rule, rule, level, severity, "m", format!("n{i}"))
    }

    fn random_violation(rng: &mut Lcg, i: usize) -> Violation {
        let level = if rng.next(2) == 0 {
            WcagLevel::A
        } else {
            WcagLevel::AA
        };
        violation(
            RULES[rng.next(RULES.len())],
            level,
            SEVERITIES[rng.next(4)],
            i,
        )
    }

    fn random_set(rng: &mut Lcg) -> Vec<Violation> {
        (0..rng.next(25))
            .map(|i| random_violation(rng, i))
            .collect()
    }

    fn score(v: &[Violation]) -> f32 {
        AccessibilityScorer::calculate_score(v)
    }

    /// Per-rule penalties are summed in rule-id order, so adding a rule can
    /// change the summation order and the sixth decimal. The report shows
    /// whole points.
    const EPS: f32 = 1e-3;

    #[test]
    fn score_stays_within_bounds() {
        let mut rng = Lcg(1);
        for _ in 0..2000 {
            let s = score(&random_set(&mut rng));
            assert!((0.0..=100.0).contains(&s), "score {s} out of bounds");
        }
    }

    /// Another finding — a new rule or one more occurrence of a known one —
    /// never makes the page score better.
    #[test]
    fn adding_a_finding_never_raises_the_score() {
        let mut rng = Lcg(2);
        for _ in 0..2000 {
            let mut set = random_set(&mut rng);
            let before = score(&set);
            let i = set.len();
            set.push(random_violation(&mut rng, i));
            let after = score(&set);
            assert!(
                after <= before + EPS,
                "adding {:?} raised the score {before} -> {after}",
                set.last().map(|v| (&v.rule, v.severity))
            );
        }
    }

    /// Raising the severity of one finding never makes the page score better.
    #[test]
    fn raising_a_severity_never_raises_the_score() {
        let mut rng = Lcg(3);
        for _ in 0..2000 {
            let mut set = random_set(&mut rng);
            if set.is_empty() {
                continue;
            }
            let before = score(&set);
            let i = rng.next(set.len());
            let raised = SEVERITIES
                .iter()
                .copied()
                .find(|s| *s > set[i].severity)
                .unwrap_or(set[i].severity);
            set[i].severity = raised;
            let after = score(&set);
            assert!(
                after <= before + EPS,
                "raising severity raised the score {before} -> {after}"
            );
        }
    }

    /// The caps the report text relies on: any Critical keeps a page out of
    /// the upper half, five or more Critical/High out of the top band.
    #[test]
    fn caps_hold_for_any_set() {
        let mut rng = Lcg(4);
        for _ in 0..2000 {
            let set = random_set(&mut rng);
            let s = score(&set);
            let critical = set
                .iter()
                .filter(|v| v.severity == Severity::Critical)
                .count();
            let urgent = critical + set.iter().filter(|v| v.severity == Severity::High).count();
            let level_a_urgent = set
                .iter()
                .filter(|v| v.level == WcagLevel::A && v.severity >= Severity::High)
                .count();
            if critical > 0 {
                assert!(s <= 49.0, "{s} with {critical} critical");
            } else if level_a_urgent > 0 {
                assert!(s <= 89.0, "{s} with {level_a_urgent} Level A high");
            } else if urgent >= 5 {
                assert!(s <= 92.0, "{s} with {urgent} critical/high");
            }
        }
    }

    /// No finding, full score — and only then: a single Low finding already
    /// costs something.
    #[test]
    fn only_an_empty_set_scores_100() {
        assert_eq!(score(&[]), 100.0);
        for rule in RULES {
            assert!(
                score(&[violation(rule, WcagLevel::AA, Severity::Low, 0)]) < 100.0,
                "{rule}"
            );
        }
    }
}