auditmysite 1.4.0

Resource-efficient WCAG 2.1 AA (+ select 2.2 criteria) 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
//! Performance scoring and grading
//!
//! Calculates overall performance score and assigns grades.

use serde::{Deserialize, Serialize};

use super::content_weight::ContentWeight;
use super::vitals::WebVitals;

/// Performance grade levels
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PerformanceGrade {
    /// 90-100: Excellent performance
    Platinum,
    /// 75-89: Good performance
    Gold,
    /// 60-74: Average performance
    Silver,
    /// 50-59: Below average
    Bronze,
    /// <50: Needs significant improvement
    NeedsImprovement,
}

impl PerformanceGrade {
    pub fn from_score(score: u32) -> Self {
        match score {
            90..=100 => PerformanceGrade::Platinum,
            75..=89 => PerformanceGrade::Gold,
            60..=74 => PerformanceGrade::Silver,
            50..=59 => PerformanceGrade::Bronze,
            _ => PerformanceGrade::NeedsImprovement,
        }
    }

    pub fn emoji(&self) -> &'static str {
        match self {
            PerformanceGrade::Platinum => "🏆",
            PerformanceGrade::Gold => "🥇",
            PerformanceGrade::Silver => "🥈",
            PerformanceGrade::Bronze => "🥉",
            PerformanceGrade::NeedsImprovement => "⚠️",
        }
    }

    pub fn label(&self) -> &'static str {
        match self {
            PerformanceGrade::Platinum => "SEHR GUT",
            PerformanceGrade::Gold => "GUT",
            PerformanceGrade::Silver => "STABIL",
            PerformanceGrade::Bronze => "AUSBAUFÄHIG",
            PerformanceGrade::NeedsImprovement => "UNGENÜGEND",
        }
    }
}

impl std::fmt::Display for PerformanceGrade {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} {}", self.emoji(), self.label())
    }
}

// Lighthouse v10/v11 weights — SI (Speed Index) is not measured here, so the
// remaining metrics are renormalized over their combined 90-point budget
// (10 + 25 + 30 + 25). When all four are present, `overall = sum * 100 / 90`.
const W_FCP: u32 = 10;
const W_LCP: u32 = 25;
const W_TBT: u32 = 30;
const W_CLS: u32 = 25;
const W_SI: u32 = 10;

/// Performance score with breakdown
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceScore {
    /// Overall score (0-100), normalized to available metrics
    pub overall: u32,
    /// Grade based on score
    pub grade: PerformanceGrade,
    /// LCP score contribution (0-25); None = metric not measured
    pub lcp_score: Option<u32>,
    /// FCP score contribution (0-10); None = metric not measured
    pub fcp_score: Option<u32>,
    /// CLS score contribution (0-25); None = metric not measured
    pub cls_score: Option<u32>,
    /// TBT score contribution (0-30); None = metric not measured
    pub interactivity_score: Option<u32>,
    /// Speed Index score contribution (0-10); None = metric not measured
    #[serde(skip_serializing_if = "Option::is_none")]
    pub si_score: Option<u32>,
    /// Number of metrics that were actually measured (0-5)
    pub metrics_available: u32,
    /// Penalty deducted for page size (transfer/decoded bytes)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub size_penalty: Option<u32>,
    /// Penalty deducted for JavaScript size
    #[serde(skip_serializing_if = "Option::is_none")]
    pub js_penalty: Option<u32>,
    /// Penalty deducted for request count
    #[serde(skip_serializing_if = "Option::is_none")]
    pub request_penalty: Option<u32>,
    /// Penalty deducted for DOM complexity
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dom_penalty: Option<u32>,
    /// Whether the score was capped due to a critical threshold
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_capped: Option<bool>,
}

/// Calculate performance score from Web Vitals and Content Weight.
///
/// Weights follow Lighthouse v10/v11 (FCP 10 %, LCP 25 %, TBT 30 %, CLS 25 %, SI 10 %).
/// The overall score is normalized to the metrics that were actually measured.
/// Then deductions and caps are applied based on content size, request count, and DOM complexity.
pub fn calculate_performance_score(
    vitals: &WebVitals,
    content_weight: Option<&ContentWeight>,
) -> PerformanceScore {
    let lcp_score = vitals.lcp.as_ref().map(|v| score_lcp(v.value));
    let fcp_score = vitals.fcp.as_ref().map(|v| score_fcp(v.value));
    let cls_score = vitals.cls.as_ref().map(|v| score_cls(v.value));
    let interactivity_score = vitals.tbt.as_ref().map(|v| score_interactivity(v.value));
    let si_score = vitals.speed_index.as_ref().map(|v| score_si(v.value));

    let mut total = 0u32;
    let mut max_possible = 0u32;
    let mut metrics_available = 0u32;
    if let Some(s) = lcp_score {
        total += s;
        max_possible += W_LCP;
        metrics_available += 1;
    }
    if let Some(s) = fcp_score {
        total += s;
        max_possible += W_FCP;
        metrics_available += 1;
    }
    if let Some(s) = cls_score {
        total += s;
        max_possible += W_CLS;
        metrics_available += 1;
    }
    if let Some(s) = interactivity_score {
        total += s;
        max_possible += W_TBT;
        metrics_available += 1;
    }
    if let Some(s) = si_score {
        total += s;
        max_possible += W_SI;
        metrics_available += 1;
    }

    let base_overall = (total * 100)
        .checked_div(max_possible)
        .map(|n| n.min(100))
        .unwrap_or(0);

    let mut overall = base_overall;
    let mut size_penalty = None;
    let mut js_penalty = None;
    let mut request_penalty = None;
    let mut dom_penalty = None;
    let mut is_capped = None;

    let mut size_cap = 100u32;
    let mut js_cap = 100u32;
    let mut req_cap = 100u32;

    if let Some(cw) = content_weight {
        // Page Size (Total Bytes): > 2MB starts linear penalty (5 points per MB, max 30)
        let total_mb = cw.total_bytes as f64 / 1_000_000.0;
        if total_mb > 2.0 {
            let penalty = ((total_mb - 2.0) * 5.0).min(30.0).round() as u32;
            size_penalty = Some(penalty);
        }

        // JS Size (Decoded): > 1MB starts linear penalty (5 points per 500KB, max 20)
        let js_mb = cw.breakdown.javascript.bytes as f64 / 1_000_000.0;
        if js_mb > 1.0 {
            let penalty = (((js_mb - 1.0) / 0.5) * 5.0).min(20.0).round() as u32;
            js_penalty = Some(penalty);
        }

        // Request Count: > 60 requests starts linear penalty (2 points per 10 requests, max 15)
        if cw.request_count > 60 {
            let penalty =
                ((((cw.request_count - 60) as f64 / 10.0).round() * 2.0).min(15.0)) as u32;
            request_penalty = Some(penalty);
        }

        // Caps
        // Page Size caps: > 10MB -> max 39, > 5MB -> max 59, > 3MB -> max 74
        if cw.total_bytes > 10_000_000 {
            size_cap = 39;
        } else if cw.total_bytes > 5_000_000 {
            size_cap = 59;
        } else if cw.total_bytes > 3_000_000 {
            size_cap = 74;
        }

        // JS caps: > 3MB -> max 59, > 1.5MB -> max 74
        if cw.breakdown.javascript.bytes > 3_000_000 {
            js_cap = 59;
        } else if cw.breakdown.javascript.bytes > 1_500_000 {
            js_cap = 74;
        }

        // Request count cap: > 120 -> max 74
        if cw.request_count > 120 {
            req_cap = 74;
        }
    }

    // DOM Nodes (WebVitals): a degressive penalty, NOT a hard cap. A base
    // linear penalty (2 points per 100 nodes from 1000, up to 15) covers
    // moderate bloat; a logarithmic surcharge above 6000 nodes keeps very large
    // DOMs costing more, bounded at 35 points total. Modelling DOM size as a
    // hard cap (→ 59) flattened pages with perfect Core Web Vitals to a fixed
    // score below a janky-CLS page, inverting the ranking (#455).
    if let Some(nodes) = vitals.dom_nodes {
        if nodes > 1000 {
            let base = (((nodes - 1000) as f64 / 100.0).round() * 2.0).min(15.0);
            let excess = nodes.saturating_sub(6000) as f64;
            let surcharge = if excess > 0.0 {
                (excess / 1000.0).ln_1p() * 4.0
            } else {
                0.0
            };
            let penalty = (base + surcharge).round().min(35.0) as u32;
            dom_penalty = Some(penalty);
        }
    }

    // Apply the weight/complexity penalties as a *bounded aggregate* rather than
    // stacking each one additively. Individually capped (size 30, JS 20, requests
    // 15, DOM 35) they can sum past 80 and wipe a page with good Core Web Vitals
    // (perfect CLS/TBT, fast FCP) down to 0 purely on heaviness — flattening
    // every heavy site to the same zero and losing all discrimination (#461).
    // Capping the combined deduction keeps the vitals-based score the dominant
    // signal and spreads heavy sites across a low band instead of collapsing them.
    // The cap is both absolute (max 45) and relative (at most 70 % of the
    // vitals-based score): a page that actually measured its vitals must never
    // be driven to 0 by weight alone. Without the relative bound a mediocre but
    // very heavy page (base ≈ cap) still collapsed to exactly 0, losing it
    // against worse-but-lighter pages (#461 follow-up; e.g. bundestag base 45 −
    // cap 45 = 0 despite good TBT/FCP).
    const MAX_WEIGHT_PENALTY: u32 = 45;
    let raw_weight_penalty = size_penalty.unwrap_or(0)
        + js_penalty.unwrap_or(0)
        + request_penalty.unwrap_or(0)
        + dom_penalty.unwrap_or(0);
    let relative_cap = (base_overall as f64 * 0.7).round() as u32;
    let weight_penalty = raw_weight_penalty.min(MAX_WEIGHT_PENALTY).min(relative_cap);
    overall = overall.saturating_sub(weight_penalty);

    // Apply caps
    let min_cap = size_cap.min(js_cap).min(req_cap);
    if overall > min_cap {
        overall = min_cap;
        is_capped = Some(true);
    }

    let grade = PerformanceGrade::from_score(overall);

    PerformanceScore {
        overall,
        grade,
        lcp_score,
        fcp_score,
        cls_score,
        interactivity_score,
        si_score,
        metrics_available,
        size_penalty,
        js_penalty,
        request_penalty,
        dom_penalty,
        is_capped,
    }
}

/// Lighthouse-style log-normal score in [0, max_points].
///
/// Matches the Lighthouse v10/v11 formulation: the cumulative log-normal
/// distribution with median = p50 and a sigma calibrated so that the score
/// at p10 is exactly 0.9. score = 1 − Φ((ln(value) − ln(p50)) / σ).
fn log_normal_score(value: f64, p10: f64, p50: f64, max_points: u32) -> u32 {
    if value <= 0.0 {
        return max_points;
    }
    // Z-score for the 90th percentile of the standard normal (≈ 1.2816).
    const Z90: f64 = 1.2815515655446004;
    let p10_log = p10.ln();
    let p50_log = p50.ln();
    let value_log = value.ln();
    let sigma = (p50_log - p10_log).abs() / Z90;
    let z = (value_log - p50_log) / sigma;
    let s = (1.0 - standard_normal_cdf(z)).clamp(0.0, 1.0);
    (s * max_points as f64).round() as u32
}

/// Standard normal CDF Φ(x) = ½·(1 + erf(x/√2)).
fn standard_normal_cdf(x: f64) -> f64 {
    0.5 * (1.0 + erf(x / std::f64::consts::SQRT_2))
}

/// Abramowitz & Stegun 7.1.26 approximation of erf — accurate enough for
/// Lighthouse-style scoring, no external dependency required.
fn erf(x: f64) -> f64 {
    let sign = if x < 0.0 { -1.0 } else { 1.0 };
    let x = x.abs();
    let a1 = 0.254829592;
    let a2 = -0.284496736;
    let a3 = 1.421413741;
    let a4 = -1.453152027;
    let a5 = 1.061405429;
    let p = 0.3275911;
    let t = 1.0 / (1.0 + p * x);
    let y = 1.0 - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * (-x * x).exp();
    sign * y
}

/// Score LCP (0-25). Lighthouse curve: p10=2500 ms, p50=4000 ms.
fn score_lcp(ms: f64) -> u32 {
    log_normal_score(ms, 2500.0, 4000.0, W_LCP)
}

/// Score FCP (0-10). Lighthouse curve: p10=1800 ms, p50=3000 ms.
fn score_fcp(ms: f64) -> u32 {
    log_normal_score(ms, 1800.0, 3000.0, W_FCP)
}

/// Score CLS (0-25). Lighthouse curve: p10=0.1, p50=0.25.
/// CLS above 0.5 is capped to zero independent of the curve.
fn score_cls(value: f64) -> u32 {
    if value > 0.5 {
        return 0;
    }
    log_normal_score(value.max(0.0001), 0.1, 0.25, W_CLS)
}

/// Score TBT (0-30). Lighthouse curve: p10=200 ms, p50=600 ms.
fn score_interactivity(ms: f64) -> u32 {
    log_normal_score(ms.max(1.0), 200.0, 600.0, W_TBT)
}

/// Score Speed Index (0-10). Lighthouse curve: p10=3400 ms, p50=5800 ms.
fn score_si(ms: f64) -> u32 {
    log_normal_score(ms, 3400.0, 5800.0, W_SI)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::performance::vitals::VitalMetric;
    use crate::performance::ResourceBreakdown;

    #[test]
    fn test_performance_grade_from_score() {
        assert_eq!(PerformanceGrade::from_score(95), PerformanceGrade::Platinum);
        assert_eq!(PerformanceGrade::from_score(80), PerformanceGrade::Gold);
        assert_eq!(PerformanceGrade::from_score(65), PerformanceGrade::Silver);
        assert_eq!(PerformanceGrade::from_score(55), PerformanceGrade::Bronze);
        assert_eq!(
            PerformanceGrade::from_score(30),
            PerformanceGrade::NeedsImprovement
        );
    }

    #[test]
    fn test_score_lcp_good() {
        // p10 = 2500 ms → ~90 % of max → ~22-23 out of 25.
        assert!(score_lcp(2500.0) >= 22);
        assert_eq!(score_lcp(1000.0), 25);
    }

    #[test]
    fn test_score_lcp_poor() {
        // p50 = 4000 ms → ~50 % of max → ~12-13 out of 25.
        let s_p50 = score_lcp(4000.0);
        assert!((10..=14).contains(&s_p50), "p50 score was {}", s_p50);
        // Lighthouse-parity expectation: LCP > 6 s yields a tiny score (≤ 5/25).
        assert!(score_lcp(7000.0) <= 5);
        assert!(score_lcp(10000.0) <= 1);
    }

    #[test]
    fn test_score_cls_lighthouse_parity() {
        // p10 = 0.1 → ~90 % → ~22-23 / 25
        assert!(score_cls(0.1) >= 22);
        // p50 = 0.25 → ~50 % → ~12-13 / 25
        let s_p50 = score_cls(0.25);
        assert!((10..=14).contains(&s_p50));
        // Extreme CLS (> 0.5) must hard-cap to zero.
        assert_eq!(score_cls(1.7), 0);
    }

    #[test]
    fn test_overall_caps_when_lcp_is_extreme() {
        // amazon.de-like profile: LCP = 7432, CLS = 0.04, FCP ≈ 2400, TBT ≈ 800.
        let vitals = WebVitals {
            lcp: Some(VitalMetric::new(7432.0, 2500.0, 4000.0)),
            fcp: Some(VitalMetric::new(2400.0, 1800.0, 3000.0)),
            cls: Some(VitalMetric::new(0.04, 0.1, 0.25)),
            tbt: Some(VitalMetric::new(800.0, 200.0, 600.0)),
            ..Default::default()
        };
        let s = calculate_performance_score(&vitals, None);
        // Issue #248: a profile with LCP > 7 s should land well below 50,
        // not in the 70s as the old weighting allowed.
        assert!(s.overall < 50, "overall was {}", s.overall);
    }

    #[test]
    fn test_calculate_performance_score() {
        let vitals = WebVitals {
            lcp: Some(VitalMetric::new(1500.0, 2500.0, 4000.0)),
            fcp: Some(VitalMetric::new(1200.0, 1800.0, 3000.0)),
            cls: Some(VitalMetric::new(0.05, 0.1, 0.25)),
            tbt: Some(VitalMetric::new(150.0, 200.0, 600.0)),
            ..Default::default()
        };

        let score = calculate_performance_score(&vitals, None);
        assert!(score.overall >= 80);
        assert!(matches!(
            score.grade,
            PerformanceGrade::Gold | PerformanceGrade::Platinum
        ));
    }

    #[test]
    fn test_partial_vitals_scores_on_available_metrics_only() {
        // Only LCP and CLS present; FCP/TBT/SI absent.
        // Score must be computed against the available weight budget (W_LCP + W_CLS = 50),
        // not the full 100-point budget — otherwise missing vitals would silently deflate scores.
        let vitals = WebVitals {
            lcp: Some(VitalMetric::new(1000.0, 2500.0, 4000.0)), // → score_lcp = 25 (max)
            cls: Some(VitalMetric::new(0.0, 0.1, 0.25)),         // → score_cls = 25 (max)
            ..Default::default()
        };
        let score = calculate_performance_score(&vitals, None);
        assert_eq!(score.overall, 100, "all available metrics perfect → 100");
        assert_eq!(score.metrics_available, 2);
    }

    #[test]
    fn test_no_vitals_returns_zero() {
        let vitals = WebVitals::default();
        let score = calculate_performance_score(&vitals, None);
        assert_eq!(score.overall, 0, "no vitals available → 0");
        assert_eq!(score.metrics_available, 0);
    }

    #[test]
    fn test_page_weight_capping_and_penalties() {
        let vitals = WebVitals {
            lcp: Some(VitalMetric::new(1000.0, 2500.0, 4000.0)),
            fcp: Some(VitalMetric::new(800.0, 1800.0, 3000.0)),
            cls: Some(VitalMetric::new(0.01, 0.1, 0.25)),
            tbt: Some(VitalMetric::new(50.0, 200.0, 600.0)),
            ..Default::default()
        };

        // 1. Size = 2.5 MB (no cap, minor penalty)
        // size_penalty: (2.5 - 2.0) * 5 = 2.5 -> round to 3
        let cw_light = ContentWeight {
            total_bytes: 2_500_000,
            transfer_bytes: 1_800_000,
            breakdown: ResourceBreakdown::default(),
            request_count: 30,
            carbon: crate::performance::CarbonEstimate::default(),
            recommendations: vec![],
        };
        let s_light = calculate_performance_score(&vitals, Some(&cw_light));
        assert_eq!(s_light.size_penalty, Some(3));
        assert_eq!(s_light.overall, 97);
        assert_eq!(s_light.is_capped, None);

        // 2. Size = 4.5 MB (cap 74)
        let cw_medium = ContentWeight {
            total_bytes: 4_500_000,
            transfer_bytes: 3_000_000,
            breakdown: ResourceBreakdown::default(),
            request_count: 50,
            carbon: crate::performance::CarbonEstimate::default(),
            recommendations: vec![],
        };
        let s_medium = calculate_performance_score(&vitals, Some(&cw_medium));
        assert_eq!(s_medium.overall, 74);
        assert_eq!(s_medium.is_capped, Some(true));

        // 3. Size = 12 MB (cap 39 - "geht gar nicht")
        let cw_heavy = ContentWeight {
            total_bytes: 12_000_000,
            transfer_bytes: 9_000_000,
            breakdown: ResourceBreakdown::default(),
            request_count: 80,
            carbon: crate::performance::CarbonEstimate::default(),
            recommendations: vec![],
        };
        let s_heavy = calculate_performance_score(&vitals, Some(&cw_heavy));
        assert_eq!(s_heavy.overall, 39);
        assert_eq!(s_heavy.is_capped, Some(true));
    }

    #[test]
    fn test_js_weight_capping_and_penalties() {
        let vitals = WebVitals {
            lcp: Some(VitalMetric::new(1000.0, 2500.0, 4000.0)),
            fcp: Some(VitalMetric::new(800.0, 1800.0, 3000.0)),
            cls: Some(VitalMetric::new(0.01, 0.1, 0.25)),
            tbt: Some(VitalMetric::new(50.0, 200.0, 600.0)),
            ..Default::default()
        };

        // JS size = 1.6 MB decoded -> capped at 74
        let mut breakdown = ResourceBreakdown::default();
        breakdown.javascript.bytes = 1_600_000;
        let cw = ContentWeight {
            total_bytes: 2_500_000,
            transfer_bytes: 1_800_000,
            breakdown,
            request_count: 30,
            carbon: crate::performance::CarbonEstimate::default(),
            recommendations: vec![],
        };

        let s = calculate_performance_score(&vitals, Some(&cw));
        assert_eq!(s.overall, 74);
        assert_eq!(s.is_capped, Some(true));
        assert_eq!(s.js_penalty, Some(6)); // (1.6 - 1.0)/0.5 * 5 = 6
    }

    #[test]
    fn test_weight_penalties_do_not_zero_out_good_vitals() {
        // Regression for #461: a heavy page (large size + JS + many requests +
        // huge DOM) with mostly good Core Web Vitals (perfect CLS/TBT, fast FCP,
        // only LCP poor) must not collapse to 0. The aggregate weight penalty is
        // bounded so the vitals stay the dominant signal and heavy sites spread
        // across a low band instead of all clustering at zero.
        let vitals = WebVitals {
            lcp: Some(VitalMetric::new(7500.0, 2500.0, 4000.0)), // poor
            fcp: Some(VitalMetric::new(200.0, 1800.0, 3000.0)),  // good
            cls: Some(VitalMetric::new(0.003, 0.1, 0.25)),       // good
            tbt: Some(VitalMetric::new(0.0, 200.0, 600.0)),      // good
            dom_nodes: Some(30000),
            ..Default::default()
        };
        let mut breakdown = ResourceBreakdown::default();
        breakdown.javascript.bytes = 2_000_000;
        let cw = ContentWeight {
            total_bytes: 2_900_000, // size penalty, but below the 3MB cap
            transfer_bytes: 2_200_000,
            breakdown,
            request_count: 120,
            carbon: crate::performance::CarbonEstimate::default(),
            recommendations: vec![],
        };

        let s = calculate_performance_score(&vitals, Some(&cw));
        // Individual penalties sum to ~55; without the cap this would zero a
        // base of ~72. Bounded at 45, the page stays in a low-but-nonzero band.
        assert!(
            s.overall >= 20,
            "heavy page with good CLS/TBT must not collapse to ~0, got {}",
            s.overall
        );
        assert!(
            s.overall < 50,
            "still clearly penalised for weight, got {}",
            s.overall
        );
    }

    #[test]
    fn test_weight_penalty_relative_cap_keeps_low_base_above_zero() {
        // Regression for #461 follow-up: a mediocre page (base ≈ 45) that is
        // also very heavy must not be canceled to exactly 0 — the relative cap
        // (<=70% of base) leaves some of the measured vitals intact.
        let vitals = WebVitals {
            lcp: Some(VitalMetric::new(9400.0, 2500.0, 4000.0)), // poor -> ~0
            fcp: Some(VitalMetric::new(1600.0, 1800.0, 3000.0)), // good
            cls: Some(VitalMetric::new(0.346, 0.1, 0.25)),       // poor
            tbt: Some(VitalMetric::new(282.0, 200.0, 600.0)),    // needs-improvement
            dom_nodes: Some(178000),                             // huge -> dom penalty 35
            ..Default::default()
        };
        let mut breakdown = ResourceBreakdown::default();
        breakdown.javascript.bytes = 2_500_000;
        let cw = ContentWeight {
            total_bytes: 2_900_000,
            transfer_bytes: 2_200_000,
            breakdown,
            request_count: 90,
            carbon: crate::performance::CarbonEstimate::default(),
            recommendations: vec![],
        };

        let s = calculate_performance_score(&vitals, Some(&cw));
        assert!(
            s.overall > 0,
            "measured-but-mediocre heavy page must not hit exactly 0, got {}",
            s.overall
        );
    }

    #[test]
    fn test_dom_nodes_penalty_for_common_sizes() {
        // 2500 nodes is common for modern content sites: the base linear penalty
        // applies (no surcharge below 6000 nodes), and DOM size never caps.
        let vitals = WebVitals {
            lcp: Some(VitalMetric::new(1000.0, 2500.0, 4000.0)),
            fcp: Some(VitalMetric::new(800.0, 1800.0, 3000.0)),
            cls: Some(VitalMetric::new(0.01, 0.1, 0.25)),
            tbt: Some(VitalMetric::new(50.0, 200.0, 600.0)),
            dom_nodes: Some(2500),
            ..Default::default()
        };

        let s = calculate_performance_score(&vitals, None);
        assert_eq!(s.dom_penalty, Some(15)); // (2500-1000)/100 * 2 = 30 -> max 15
        assert_eq!(s.is_capped, None);
        assert_eq!(s.overall, 85); // 100 - 15 penalty
    }

    #[test]
    fn test_dom_penalty_is_degressive_not_a_hard_cap() {
        let base = WebVitals {
            lcp: Some(VitalMetric::new(1000.0, 2500.0, 4000.0)),
            fcp: Some(VitalMetric::new(800.0, 1800.0, 3000.0)),
            cls: Some(VitalMetric::new(0.01, 0.1, 0.25)),
            tbt: Some(VitalMetric::new(50.0, 200.0, 600.0)),
            ..Default::default()
        };
        let score_at = |nodes| {
            calculate_performance_score(
                &WebVitals {
                    dom_nodes: Some(nodes),
                    ..base.clone()
                },
                None,
            )
            .overall
        };
        // Monotonic: more nodes -> lower score, but never a fixed hard cap.
        assert!(score_at(7000) > score_at(20000));
        assert!(score_at(20000) >= score_at(250000));
        // Bounded: even a 250k-node DOM with perfect vitals stays well above the
        // old hard floor of 59 (penalty capped at 35 points) (#455).
        assert!(
            score_at(250000) >= 65,
            "huge DOM scored {}",
            score_at(250000)
        );
    }

    #[test]
    fn test_perfect_vitals_huge_dom_outranks_janky_cls() {
        // Regression for #455: perfect Core Web Vitals + a huge DOM must not
        // score below a page with poor CLS.
        let perfect_big_dom = WebVitals {
            lcp: Some(VitalMetric::new(1200.0, 2500.0, 4000.0)),
            fcp: Some(VitalMetric::new(1200.0, 1800.0, 3000.0)),
            cls: Some(VitalMetric::new(0.0, 0.1, 0.25)),
            tbt: Some(VitalMetric::new(0.0, 200.0, 600.0)),
            dom_nodes: Some(20000),
            ..Default::default()
        };
        let janky_cls = WebVitals {
            lcp: Some(VitalMetric::new(900.0, 2500.0, 4000.0)),
            fcp: Some(VitalMetric::new(800.0, 1800.0, 3000.0)),
            cls: Some(VitalMetric::new(0.616, 0.1, 0.25)),
            tbt: Some(VitalMetric::new(0.0, 200.0, 600.0)),
            dom_nodes: Some(2000),
            ..Default::default()
        };
        let a = calculate_performance_score(&perfect_big_dom, None).overall;
        let b = calculate_performance_score(&janky_cls, None).overall;
        assert!(a > b, "perfect+bigDOM {a} must outrank jankyCLS {b}");
    }
}