auditmysite 1.2.0

Resource-efficient WCAG 2.1 Accessibility Checker in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
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
#[allow(clippy::module_inception)]
#[cfg(all(test, feature = "pdf_test"))]
mod tests {
    use super::super::*;
    use crate::audit::{AuditReport, BatchReport, PageScreenshots, ScreenshotStatus};
    use crate::cli::{ReportLevel, WcagLevel};
    use crate::util::truncate_url;
    use crate::wcag::{Severity, Violation, WcagResults};
    use std::path::PathBuf;
    use std::process::Command;

    #[test]
    fn test_truncate_url() {
        assert_eq!(
            truncate_url("https://example.com/very/long/path/that/exceeds/limit", 30),
            "https://example.com/very/lo..."
        );
        assert_eq!(
            truncate_url("https://example.com", 30),
            "https://example.com"
        );
    }

    #[test]
    fn test_single_pdf_smoke_renders_valid_pdf() {
        let report = pdf_fixture_report();
        let config = ReportConfig {
            level: ReportLevel::Standard,
            ..ReportConfig::default()
        };

        let pdf = generate_pdf(&report, &config).expect("PDF should render");

        assert_pdf_smoke(&pdf, 20_000);
    }

    #[test]
    fn test_single_pdf_smoke_renders_all_report_levels() {
        for level in [
            ReportLevel::Executive,
            ReportLevel::Standard,
            ReportLevel::Technical,
        ] {
            let report = pdf_fixture_report();
            let config = ReportConfig {
                level,
                ..ReportConfig::default()
            };

            let pdf = generate_pdf(&report, &config).expect("PDF should render");
            assert_pdf_smoke(&pdf, 15_000);
        }
    }

    #[test]
    fn test_batch_pdf_smoke_renders_valid_pdf() {
        let batch = BatchReport::from_reports(
            vec![
                pdf_fixture_report_for_url("https://example.com"),
                pdf_fixture_report_for_url("https://example.com/about"),
            ],
            vec![],
            2_400,
        );

        let pdf = generate_batch_pdf(&batch, &ReportConfig::default()).expect("PDF should render");
        assert_pdf_smoke(&pdf, 20_000);
    }

    #[test]
    fn test_cover_logo_asset_prefers_existing_custom_logo() {
        let logo = tempfile::NamedTempFile::new().expect("custom logo fixture should be writable");
        let config = ReportConfig {
            logo_path: Some(logo.path().to_path_buf()),
            ..ReportConfig::default()
        };

        assert_eq!(cover_logo_asset(&config), CUSTOM_COVER_LOGO_ASSET);
    }

    #[test]
    fn test_cover_logo_asset_falls_back_for_missing_custom_logo() {
        let temp_dir = tempfile::tempdir().expect("temp dir should be created");
        let missing_logo = temp_dir.path().join("missing-logo.svg");
        let config = ReportConfig {
            logo_path: Some(missing_logo),
            ..ReportConfig::default()
        };

        assert_eq!(cover_logo_asset(&config), WORDMARK_ASSET);
    }

    #[test]
    fn test_single_pdf_renders_in_english_locale() {
        let report = pdf_fixture_report();
        let config = ReportConfig {
            level: ReportLevel::Standard,
            locale: "en".to_string(),
            ..ReportConfig::default()
        };

        let pdf = generate_pdf(&report, &config).expect("English PDF should render");
        assert_pdf_smoke(&pdf, 15_000);
    }

    /// Regression test for a class of localization leak the existing
    /// "no umlauts/ß" guard tests structurally cannot catch: hardcoded German
    /// table labels/words that happen to contain no umlaut or ß (e.g.
    /// "Vorkommen", "Sprache", "Interne Links"). `pdf_fixture_report()` alone
    /// carries no SEO data, so `build_seo_details`'s whole English-locale
    /// code path (identity_facts, page_profile_facts, technical_summary,
    /// tracking_summary) was previously never exercised by any EN-locale
    /// test at all.
    ///
    /// Note on methodology: a string's presence in `--debug-typ` output does
    /// NOT by itself prove it renders onto a page — the dump embeds every
    /// registered renderreport component template verbatim (`include_str!`),
    /// including ones this report never instantiates. Only assert against
    /// strings actually reachable through this report's own content-building
    /// code (as verified here against `build_seo_details`), not raw
    /// substring presence in the dump.
    #[test]
    fn test_seo_details_english_locale_has_no_known_german_leaks() {
        let report = pdf_fixture_report().with_seo(crate::seo::SeoAnalysis {
            score: 80,
            ..Default::default()
        });
        let typ = generate_typ(
            &report,
            &ReportConfig {
                level: ReportLevel::Technical,
                locale: "en".to_string(),
                ..ReportConfig::default()
            },
        )
        .expect("English Typst source should render");

        // Confirms the English-only branches actually fire (not just "no
        // German leaked", but "the intended English text is present").
        for expected in [
            "Page title",
            "Content type",
            "Topic hints",
            "Page type",
            "Characteristics",
            "Classification",
            "Recommendation",
            "Language tag",
            "Word count",
            "Internal links",
        ] {
            assert!(
                typ.contains(expected),
                "expected English label {expected:?} in EN-locale Typst source"
            );
        }

        // The specific hardcoded-German strings confirmed and fixed in this
        // session (#511-style regression corpus candidates). Deliberately
        // excludes "Empfehlung": it also happens to be the unrelated default
        // fallback text of the (unused) renderreport `dominant-issue-spotlight`
        // component, which is always present in any --debug-typ dump per the
        // methodology note above, regardless of this fix.
        for leaked in [
            "Seitentitel",
            "Inhaltstyp",
            "Themenhinweise",
            "Seitentyp",
            "Merkmale",
            "Einordnung",
            "Sprachangabe",
            "Wortanzahl",
            "Interne Links",
            "Externe Links",
            "Vollständigkeit",
        ] {
            assert!(
                !typ.contains(leaked),
                "German string {leaked:?} leaked into EN-locale Typst source"
            );
        }
    }

    /// Regression test for the tech-stack findings-severity localization fix
    /// in `detail_modules/indicators.rs::render_tech_stack` — the severity
    /// column used to call `finding.severity.label()` unconditionally, always
    /// emitting the German label ("Hoch"/"Kritisch") even in the EN-locale
    /// report.
    #[test]
    fn test_tech_stack_findings_english_locale_uses_english_severity_label() {
        let report = pdf_fixture_report().with_tech_stack(crate::tech_stack::TechStackAnalysis {
            detected: vec![],
            findings: vec![crate::tech_stack::StackFinding {
                tech: "jQuery".to_string(),
                title: "Outdated jQuery version".to_string(),
                detail: "jQuery 1.x has known vulnerabilities.".to_string(),
                severity: Severity::Critical,
                fix: None,
                url_checked: None,
            }],
            score: 60,
            grade: "C".to_string(),
        });
        let typ = generate_typ(
            &report,
            &ReportConfig {
                level: ReportLevel::Technical,
                locale: "en".to_string(),
                ..ReportConfig::default()
            },
        )
        .expect("English Typst source should render");

        assert!(
            typ.contains("CRITICAL"),
            "expected English severity label \"CRITICAL\" in EN-locale Typst source"
        );
        assert!(
            !typ.contains("Kritisch"),
            "German severity label \"Kritisch\" leaked into EN-locale Typst source"
        );
    }

    #[test]
    fn test_single_pdf_places_json_ld_status_before_schema_inventory() {
        let structured_data = crate::seo::schema::analyze_structured_data_payloads(
            &[
                serde_json::json!({
                    "@context": "https://schema.org",
                    "@type": "WebPage",
                    "name": "Example",
                    "url": "https://example.com"
                })
                .to_string(),
                r#"{"@context":"https://schema.org","@type":"Product""#.to_string(),
            ],
            false,
            false,
        );
        let seo = crate::seo::SeoAnalysis {
            structured_data,
            score: 73,
            ..Default::default()
        };
        let report = pdf_fixture_report().with_seo(seo);
        let typ = generate_typ(
            &report,
            &ReportConfig {
                level: ReportLevel::Technical,
                locale: "de".to_string(),
                ..ReportConfig::default()
            },
        )
        .expect("Typst source should render");

        let status = typ.find("JSON-LD-Status").expect("JSON-LD status missing");
        let inventory = typ
            .find("Strukturierte Daten (1 Schema)")
            .expect("schema inventory missing");
        assert!(status < inventory, "status must precede schema inventory");
        assert!(typ.contains("ungültiges JSON"));
    }

    #[test]
    fn test_single_pdf_places_page_fit_and_feature_rules_before_inventory() {
        let mut structured_data = crate::seo::schema::analyze_structured_data_payloads(
            &[serde_json::json!({
                "@context": "https://schema.org",
                "@type": "Product",
                "name": "Example product",
                "offers": {"@type": "Offer", "price": "19.99"}
            })
            .to_string()],
            false,
            false,
        );
        let fit = crate::seo::schema_fit::assess_schema_fit(
            "https://example.com/produkt/example",
            crate::journey::PageIntent::Shop,
            &structured_data,
        );
        crate::seo::schema::refresh_rule_assessments(&mut structured_data, fit.product_context());
        structured_data.rule_assessments[0]
            .manual_review
            .push("Confirm that marked-up details are visible.".to_string());
        structured_data.content_parity = vec![crate::seo::schema_parity::ContentParityAssessment {
            node_index: 0,
            schema_type: "Product".to_string(),
            property: "name".to_string(),
            status: crate::seo::schema_parity::ContentParityStatus::Mismatch,
            schema_value: Some("Example product".to_string()),
            visible_value: Some("Different visible title".to_string()),
            evidence: "Schema and visible title differ".to_string(),
        }];
        structured_data.fit_assessment = Some(fit);

        let report = pdf_fixture_report().with_seo(crate::seo::SeoAnalysis {
            structured_data,
            score: 73,
            ..Default::default()
        });
        let typ = generate_typ(
            &report,
            &ReportConfig {
                level: ReportLevel::Technical,
                locale: "de".to_string(),
                ..ReportConfig::default()
            },
        )
        .expect("Typst source should render");

        let status = typ.find("JSON-LD-Status").expect("JSON-LD status missing");
        let fit = typ
            .find("Seitentyp und Schema-Eignung")
            .expect("schema fit missing");
        let rules = typ
            .find("Funktionsbezogene Schema-Anforderungen")
            .expect("feature rules missing");
        let inventory = typ
            .find("Strukturierte Daten (1 Schema)")
            .expect("schema inventory missing");
        let manual_review = typ
            .find("Kontext- und Inhaltsprüfung")
            .expect("manual-review table missing");
        let content_parity = typ
            .find("Abgleich mit sichtbaren Inhalten")
            .expect("content-parity table missing");

        assert!(
            status < fit
                && fit < rules
                && rules < manual_review
                && manual_review < content_parity
                && content_parity < inventory
        );
        assert!(typ.contains("Merchant Listing"));
        assert!(typ.contains("Pflichtangaben fehlen"));
        assert!(typ.contains("Schema: Example product; sichtbar: Different visible title"));
    }

    #[test]
    fn test_pdf_german_and_english_outputs_differ() {
        // Locale-aware narrative must produce different PDF bytes.
        let report = pdf_fixture_report();
        let de = generate_pdf(
            &report,
            &ReportConfig {
                level: ReportLevel::Standard,
                locale: "de".to_string(),
                ..ReportConfig::default()
            },
        )
        .expect("German PDF should render");
        let en = generate_pdf(
            &report,
            &ReportConfig {
                level: ReportLevel::Standard,
                locale: "en".to_string(),
                ..ReportConfig::default()
            },
        )
        .expect("English PDF should render");
        assert_ne!(de, en, "German and English PDFs should differ in content");
    }

    #[test]
    fn test_pdf_with_custom_logo_differs_from_default() {
        // A custom logo asset registered on the cover must change PDF bytes.
        let temp_dir = tempfile::tempdir().expect("temp dir should be created");
        let logo_path = temp_dir.path().join("custom-logo.svg");
        // Minimal valid SVG so Typst can decode it.
        std::fs::write(
            &logo_path,
            r##"<svg xmlns="http://www.w3.org/2000/svg" width="120" height="32" viewBox="0 0 120 32"><rect width="120" height="32" fill="#ff00ff"/></svg>"##,
        )
        .expect("write logo");

        let report = pdf_fixture_report();
        let default_pdf =
            generate_pdf(&report, &ReportConfig::default()).expect("default PDF should render");
        let custom_pdf = generate_pdf(
            &report,
            &ReportConfig {
                logo_path: Some(logo_path),
                ..ReportConfig::default()
            },
        )
        .expect("custom logo PDF should render");

        assert_ne!(
            default_pdf, custom_pdf,
            "PDF with custom logo should differ from default cover"
        );
    }

    #[test]
    fn test_single_pdf_technical_renders_multiple_pages_when_pdftoppm_is_available() {
        let Some(pdftoppm) = find_executable("pdftoppm") else {
            return;
        };

        let report = pdf_fixture_report();
        let config = ReportConfig {
            level: ReportLevel::Technical,
            ..ReportConfig::default()
        };
        let pdf = generate_pdf(&report, &config).expect("PDF should render");

        let temp_dir = tempfile::tempdir().expect("temp dir should be created");
        let pdf_path = temp_dir.path().join("auditmysite-pages.pdf");
        let png_prefix = temp_dir.path().join("auditmysite-pages");
        std::fs::write(&pdf_path, pdf).expect("PDF fixture should be writable");

        let status = Command::new(pdftoppm)
            .arg("-png")
            .arg("-r")
            .arg("72")
            .arg(&pdf_path)
            .arg(&png_prefix)
            .status()
            .expect("pdftoppm should run");
        assert!(status.success(), "pdftoppm failed with {status}");

        let mut produced_pages = 0;
        for entry in std::fs::read_dir(temp_dir.path()).expect("temp dir should be readable") {
            let entry = entry.expect("dir entry should be readable");
            let name = entry.file_name();
            let name_str = name.to_string_lossy();
            if name_str.starts_with("auditmysite-pages-") && name_str.ends_with(".png") {
                produced_pages += 1;
            }
        }

        assert!(
            produced_pages >= 3,
            "Technical report should render at least 3 pages, got {produced_pages}"
        );
    }

    #[test]
    fn test_single_pdf_first_page_can_be_rasterized_when_pdftoppm_is_available() {
        let Some(pdftoppm) = find_executable("pdftoppm") else {
            return;
        };

        let report = pdf_fixture_report();
        let config = ReportConfig {
            level: ReportLevel::Executive,
            ..ReportConfig::default()
        };
        let pdf = generate_pdf(&report, &config).expect("PDF should render");
        let temp_dir = tempfile::tempdir().expect("temp dir should be created");
        let pdf_path = temp_dir.path().join("auditmysite-smoke.pdf");
        let png_prefix = temp_dir.path().join("auditmysite-smoke-page");
        std::fs::write(&pdf_path, pdf).expect("PDF fixture should be writable");

        let status = Command::new(pdftoppm)
            .arg("-png")
            .arg("-f")
            .arg("1")
            .arg("-singlefile")
            .arg(&pdf_path)
            .arg(&png_prefix)
            .status()
            .expect("pdftoppm should run");

        assert!(status.success(), "pdftoppm failed with {status}");

        let png_path = png_prefix.with_extension("png");
        let png = std::fs::read(&png_path).expect("first page PNG should exist");
        assert!(png.starts_with(b"\x89PNG\r\n\x1a\n"), "PNG header missing");
        assert!(
            png.len() > 10_000,
            "PNG too small to represent a rendered report page: {} bytes",
            png.len()
        );
    }

    /// Standard deviation of grayscale pixel values, as a cheap "is there
    /// real content here" signal. A blank/degenerate page (missing font or
    /// asset causing empty content) renders as a near-solid color and scores
    /// close to 0; real report content (text, tables, charts) always has
    /// substantial variance. Deliberately not an exact pixel-diff — those are
    /// too flaky across environments (font hinting/anti-aliasing differ by
    /// machine); this only asks "is content there", not "is it pixel-identical".
    fn png_luma_std_dev(png_path: &std::path::Path) -> f64 {
        let bytes = std::fs::read(png_path).expect("rasterized page PNG should be readable");
        let image =
            image::load_from_memory(&bytes).expect("rasterized page should be a valid image");
        let luma = image.to_luma8();
        let pixels: Vec<f64> = luma.pixels().map(|p| p.0[0] as f64).collect();
        let mean = pixels.iter().sum::<f64>() / pixels.len() as f64;
        let variance = pixels.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / pixels.len() as f64;
        variance.sqrt()
    }

    /// Rasterizes `pdf` to one PNG per page under `temp_dir` (via `pdftoppm`)
    /// and returns the produced paths in page order.
    fn rasterize_pages(
        pdftoppm: &std::path::Path,
        pdf: &[u8],
        temp_dir: &std::path::Path,
    ) -> Vec<PathBuf> {
        let pdf_path = temp_dir.join("auditmysite-visual.pdf");
        let png_prefix = temp_dir.join("auditmysite-visual");
        std::fs::write(&pdf_path, pdf).expect("PDF fixture should be writable");

        let status = Command::new(pdftoppm)
            .arg("-png")
            .arg("-r")
            .arg("72")
            .arg(&pdf_path)
            .arg(&png_prefix)
            .status()
            .expect("pdftoppm should run");
        assert!(status.success(), "pdftoppm failed with {status}");

        let mut pages: Vec<PathBuf> = std::fs::read_dir(temp_dir)
            .expect("temp dir should be readable")
            .filter_map(|entry| entry.ok())
            .map(|entry| entry.path())
            .filter(|path| {
                path.file_name()
                    .and_then(|n| n.to_str())
                    .map(|n| n.starts_with("auditmysite-visual-") && n.ends_with(".png"))
                    .unwrap_or(false)
            })
            .collect();
        pages.sort();
        pages
    }

    #[test]
    fn test_single_pdf_technical_pages_are_not_blank_when_pdftoppm_is_available() {
        let Some(pdftoppm) = find_executable("pdftoppm") else {
            return;
        };

        let report = pdf_fixture_report();
        let config = ReportConfig {
            level: ReportLevel::Technical,
            ..ReportConfig::default()
        };
        let pdf = generate_pdf(&report, &config).expect("PDF should render");

        let temp_dir = tempfile::tempdir().expect("temp dir should be created");
        let pages = rasterize_pages(&pdftoppm, &pdf, temp_dir.path());
        assert!(
            pages.len() >= 3,
            "expected at least 3 pages, got {}",
            pages.len()
        );

        for page in &pages {
            let std_dev = png_luma_std_dev(page);
            assert!(
                std_dev > 5.0,
                "page {} looks blank/degenerate (grayscale std dev {std_dev:.2})",
                page.display()
            );
        }
    }

    #[test]
    fn test_batch_pdf_pages_are_not_blank_when_pdftoppm_is_available() {
        let Some(pdftoppm) = find_executable("pdftoppm") else {
            return;
        };

        let batch = BatchReport::from_reports(
            vec![
                pdf_fixture_report_for_url("https://example.com"),
                pdf_fixture_report_for_url("https://example.com/about"),
            ],
            vec![],
            2_400,
        );
        let pdf = generate_batch_pdf(&batch, &ReportConfig::default()).expect("batch PDF");

        let temp_dir = tempfile::tempdir().expect("temp dir should be created");
        let pages = rasterize_pages(&pdftoppm, &pdf, temp_dir.path());
        assert!(
            pages.len() >= 3,
            "expected at least 3 pages, got {}",
            pages.len()
        );

        for page in &pages {
            let std_dev = png_luma_std_dev(page);
            assert!(
                std_dev > 5.0,
                "page {} looks blank/degenerate (grayscale std dev {std_dev:.2})",
                page.display()
            );
        }
    }

    /// Builds the mobile `PerformanceResults` (for `report.performance`) and
    /// the desktop counterpart wrapped in `DualViewportResults` (for
    /// `report.dual_viewport`), so `build_performance_details` populates both
    /// `PerformancePresentation.desktop` and `.mobile` and `render_performance`
    /// takes the two-gauge branch (`score_gauge_grid`) instead of the
    /// single-viewport fallback.
    fn dual_viewport_performance(
        desktop_score: u32,
        mobile_score: u32,
    ) -> (
        crate::audit::PerformanceResults,
        crate::audit::DualViewportResults,
    ) {
        use crate::audit::{DualViewportResults, PerformanceResults, ViewportAuditData};
        use crate::performance::{PerformanceGrade, PerformanceScore, WebVitals};

        fn perf(score: u32) -> PerformanceResults {
            PerformanceResults {
                vitals: WebVitals::default(),
                score: PerformanceScore {
                    overall: score,
                    grade: if score >= 75 {
                        PerformanceGrade::Gold
                    } else {
                        PerformanceGrade::NeedsImprovement
                    },
                    lcp_score: None,
                    fcp_score: None,
                    cls_score: None,
                    interactivity_score: None,
                    si_score: None,
                    metrics_available: 0,
                    size_penalty: None,
                    js_penalty: None,
                    request_penalty: None,
                    dom_penalty: None,
                    is_capped: None,
                },
                render_blocking: None,
                content_weight: None,
                third_party: None,
                critical_chain: None,
                minification: None,
                animations: None,
                coverage: None,
                measurement_warnings: vec![],
            }
        }

        let empty_viewport = |performance: Option<PerformanceResults>| ViewportAuditData {
            wcag_results: WcagResults::new(),
            accessibility_score: 0.0,
            performance,
            seo: None,
            mobile: None,
            ux: None,
            journey: None,
            screenshot: None,
            module_runs: vec![],
        };

        (
            perf(mobile_score),
            DualViewportResults {
                desktop: empty_viewport(Some(perf(desktop_score))),
                mobile: empty_viewport(None),
            },
        )
    }

    /// Regression guard for the historical "flat metric strip" bug named in
    /// issue #510 (the wrapped dual-viewport cell): the Desktop/Mobile
    /// performance comparison must render as two distinct gauge components
    /// inside a 2-column `Grid`, not collapse back into a single combined
    /// text line. This is a structural check on the Typst source (reliable,
    /// no rasterization needed) rather than a pixel judgment — it can't
    /// detect *every* possible bad-wrap regression, but it directly locks in
    /// the fix for the one concrete case #510 names. `to_typst_dict`
    /// (renderreport) turns each component's JSON into a Typst dict literal
    /// (`type: "gauge"`, `label: "Desktop"`), not raw JSON text.
    #[test]
    fn test_dual_viewport_performance_renders_two_gauges_not_a_flat_strip() {
        let (mobile_perf, dual_viewport) = dual_viewport_performance(85, 40);
        let mut report = pdf_fixture_report_rich().with_performance(mobile_perf);
        report.dual_viewport = Some(dual_viewport);

        let typ =
            unescape_typ(&generate_typ(&report, &ReportConfig::default()).expect("Typst source"));

        let gauge_occurrences = typ.matches("type: \"gauge\"").count();
        assert!(
            gauge_occurrences >= 2,
            "expected at least 2 gauge components (Desktop + Mobile) in the Typst source, found {gauge_occurrences}"
        );
        assert!(
            typ.contains("label: \"Desktop\"") && typ.contains("label: \"Mobile\""),
            "expected distinct \"Desktop\" and \"Mobile\" gauge labels in the Typst source"
        );
    }

    /// Renders a fixture that exercises every fixture category issue #510's
    /// acceptance criteria names (cover, scorecards, tables, findings,
    /// methodology, technical metrics) in one report — WCAG findings table,
    /// dual-viewport performance gauges, detected-technology/findings tables,
    /// throttled-network table, lab-data methodology callout — rasterizes
    /// every page, and checks each is non-blank (as the existing blank-page
    /// tests do) plus that the page count stays within a generous, explicit
    /// budget. The budget catches genuine Typst-reflow blowups (a component
    /// stuck re-wrapping runaway content across dozens of pages); it does not
    /// attempt to judge subjective layout quality, which is out of reach for
    /// a pixel/page-count heuristic and stays the `report-critic` skill's job
    /// (#509).
    ///
    /// On failure, rasterized pages are copied to a stable, gitignored
    /// `target/pdf-visual-debug/` directory (tempdir contents are otherwise
    /// deleted before a human could inspect them) — CI uploads that
    /// directory as a build artifact on failure (see `.github/workflows/ci.yml`'s
    /// `pdf-smoke` job) so a red run is diagnosable without a local re-run.
    #[test]
    fn test_representative_fixture_pages_are_not_blank_and_stay_within_page_budget() {
        let Some(pdftoppm) = find_executable("pdftoppm") else {
            return;
        };

        let (mobile_perf, dual_viewport) = dual_viewport_performance(85, 40);
        let mut report = pdf_fixture_report_rich().with_performance(mobile_perf);
        report.dual_viewport = Some(dual_viewport);
        report.throttled_performance = vec![crate::audit::ThrottledPerfResult {
            profile: crate::browser::ThrottleProfile::Slow3G,
            lcp_ms: Some(3200.0),
            tbt_ms: Some(180.0),
            cls: Some(0.03),
            score: 72,
        }];
        report = report.with_tech_stack(crate::tech_stack::TechStackAnalysis {
            detected: vec![crate::tech_stack::DetectedTech {
                name: "jQuery".to_string(),
                category: crate::tech_stack::TechCategory::JsLibrary,
                version: Some("1.12.4".to_string()),
                confidence: crate::tech_stack::Confidence::High,
                signals: vec!["window.jQuery".to_string()],
            }],
            findings: vec![crate::tech_stack::StackFinding {
                tech: "jQuery".to_string(),
                title: "Outdated jQuery version".to_string(),
                detail: "jQuery 1.x has known vulnerabilities.".to_string(),
                severity: Severity::Critical,
                fix: None,
                url_checked: None,
            }],
            score: 60,
            grade: "C".to_string(),
        });

        let config = ReportConfig {
            level: ReportLevel::Technical,
            ..ReportConfig::default()
        };
        let pdf = generate_pdf(&report, &config).expect("PDF should render");

        let temp_dir = tempfile::tempdir().expect("temp dir should be created");
        let pages = rasterize_pages(&pdftoppm, &pdf, temp_dir.path());

        const MAX_EXPECTED_PAGES: usize = 60;
        if pages.len() > MAX_EXPECTED_PAGES {
            let debug_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
                .join("target/pdf-visual-debug/page-budget-exceeded");
            let _ = std::fs::create_dir_all(&debug_dir);
            for page in &pages {
                if let Some(name) = page.file_name() {
                    let _ = std::fs::copy(page, debug_dir.join(name));
                }
            }
            panic!(
                "representative fixture rendered {} pages (budget: {MAX_EXPECTED_PAGES}) — \
                 likely a reflow regression; rasterized pages copied to {}",
                pages.len(),
                debug_dir.display()
            );
        }

        let mut blank_pages = Vec::new();
        for page in &pages {
            if png_luma_std_dev(page) <= 5.0 {
                blank_pages.push(page.clone());
            }
        }
        if !blank_pages.is_empty() {
            let debug_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
                .join("target/pdf-visual-debug/blank-pages");
            let _ = std::fs::create_dir_all(&debug_dir);
            for page in &pages {
                if let Some(name) = page.file_name() {
                    let _ = std::fs::copy(page, debug_dir.join(name));
                }
            }
            panic!(
                "{} of {} pages look blank/degenerate: {:?} — all rasterized pages copied to {}",
                blank_pages.len(),
                pages.len(),
                blank_pages,
                debug_dir.display()
            );
        }
    }

    #[test]
    fn test_pdf_technical_contains_violation_criteria() {
        // Every WCAG criterion from the input must appear as text in the rendered PDF.
        // This catches silent information loss between builder and renderer.
        let Some(pdftotext) = find_executable("pdftotext") else {
            return;
        };

        let report = pdf_fixture_report_rich();
        let criteria = [
            "1.4.3", "1.1.1", "4.1.2", "2.4.4", "1.3.1", "2.4.1", "2.4.6", "3.1.1",
        ];
        let config = ReportConfig {
            level: ReportLevel::Technical,
            ..ReportConfig::default()
        };
        let pdf = generate_pdf(&report, &config).expect("PDF should render");

        let temp_dir = tempfile::tempdir().expect("temp dir");
        let pdf_path = temp_dir.path().join("criteria-check.pdf");
        let txt_path = temp_dir.path().join("criteria-check.txt");
        std::fs::write(&pdf_path, &pdf).expect("write pdf");
        Command::new(pdftotext)
            .arg(&pdf_path)
            .arg(&txt_path)
            .status()
            .expect("pdftotext should run");
        let text = std::fs::read_to_string(&txt_path).expect("read extracted text");

        for criterion in criteria {
            assert!(
                text.contains(criterion),
                "Criterion {criterion} missing from PDF text — information lost in renderer"
            );
        }
    }

    #[test]
    fn test_pdf_renders_positive_signals_from_patterns() {
        // When the report carries recognized patterns, the PDF text should
        // include a localized pattern title (e.g. "Skip-Link").
        let Some(pdftotext) = find_executable("pdftotext") else {
            return;
        };

        let mut report = pdf_fixture_report_rich();
        report.patterns = Some(crate::patterns::PatternAnalysis {
            recognized: vec![crate::patterns::RecognizedPattern {
                pattern: "SkipLink".to_string(),
                message: "Skip link recognized and correctly positioned.".to_string(),
                confidence: crate::patterns::PatternConfidence::Strong,
            }],
            violations: vec![],
            journey_candidates: vec![],
        });

        let config = ReportConfig {
            level: ReportLevel::Standard,
            ..ReportConfig::default()
        };
        let pdf = generate_pdf(&report, &config).expect("PDF should render");

        let temp_dir = tempfile::tempdir().expect("temp dir");
        let pdf_path = temp_dir.path().join("patterns-check.pdf");
        let txt_path = temp_dir.path().join("patterns-check.txt");
        std::fs::write(&pdf_path, &pdf).expect("write pdf");
        Command::new(pdftotext)
            .arg(&pdf_path)
            .arg(&txt_path)
            .status()
            .expect("pdftotext should run");
        let text = std::fs::read_to_string(&txt_path).expect("read text");

        assert!(
            text.contains("Skip-Link"),
            "Expected localized pattern title 'Skip-Link' in PDF text"
        );
    }

    #[test]
    fn test_pdf_renders_throttled_performance_table() {
        let Some(pdftotext) = find_executable("pdftotext") else {
            return;
        };

        let mut report =
            pdf_fixture_report_rich().with_performance(crate::audit::PerformanceResults {
                vitals: crate::performance::WebVitals::default(),
                score: crate::performance::PerformanceScore {
                    overall: 80,
                    grade: crate::performance::PerformanceGrade::Gold,
                    lcp_score: None,
                    fcp_score: None,
                    cls_score: None,
                    interactivity_score: None,
                    si_score: None,
                    metrics_available: 0,
                    size_penalty: None,
                    js_penalty: None,
                    request_penalty: None,
                    dom_penalty: None,
                    is_capped: None,
                },
                render_blocking: None,
                content_weight: None,
                third_party: None,
                critical_chain: None,
                minification: None,
                animations: None,
                coverage: None,
                measurement_warnings: vec![],
            });
        report.throttled_performance = vec![crate::audit::ThrottledPerfResult {
            profile: crate::browser::ThrottleProfile::Slow3G,
            lcp_ms: Some(3200.0),
            tbt_ms: Some(180.0),
            cls: Some(0.03),
            score: 72,
        }];

        let config = ReportConfig {
            level: ReportLevel::Standard,
            ..ReportConfig::default()
        };
        let pdf = generate_pdf(&report, &config).expect("PDF should render");

        let temp_dir = tempfile::tempdir().expect("temp dir");
        let pdf_path = temp_dir.path().join("throttled-perf-check.pdf");
        let txt_path = temp_dir.path().join("throttled-perf-check.txt");
        std::fs::write(&pdf_path, &pdf).expect("write pdf");
        Command::new(pdftotext)
            .arg(&pdf_path)
            .arg(&txt_path)
            .status()
            .expect("pdftotext should run");
        let text = std::fs::read_to_string(&txt_path).expect("read text");

        assert!(
            text.contains("Performance unter gedrosselten Bedingungen"),
            "Expected throttled-performance section title in PDF text"
        );
        assert!(
            text.contains("Slow3G") && text.contains("3200 ms") && text.contains("180 ms"),
            "Expected throttled-performance values in PDF text"
        );
    }

    #[test]
    fn test_pdf_interprets_performance_resources_and_bottlenecks() {
        let Some(pdftotext) = find_executable("pdftotext") else {
            return;
        };
        let report = pdf_fixture_report_rich().with_performance(crate::audit::PerformanceResults {
            vitals: crate::performance::WebVitals {
                dom_nodes: Some(12_485),
                load_time: Some(7_280.0),
                dom_content_loaded: Some(4_756.0),
                js_heap_size: Some(9_961_472),
                ..crate::performance::WebVitals::default()
            },
            score: crate::performance::PerformanceScore {
                overall: 38,
                grade: crate::performance::PerformanceGrade::NeedsImprovement,
                lcp_score: None,
                fcp_score: None,
                cls_score: None,
                interactivity_score: None,
                si_score: None,
                metrics_available: 0,
                size_penalty: None,
                js_penalty: None,
                request_penalty: None,
                dom_penalty: None,
                is_capped: None,
            },
            render_blocking: None,
            content_weight: None,
            third_party: None,
            critical_chain: None,
            minification: Some(crate::performance::MinificationAnalysis {
                unminified_scripts: vec![crate::performance::UnminifiedAsset {
                    url: "https://www.inros-lackner.de/assets/app/build/index-noncritical.js"
                        .to_string(),
                    kind: "script".to_string(),
                    decoded_bytes: 305_818,
                    transfer_bytes: 80_000,
                    savings_bytes: 203_878,
                }],
                unminified_styles: vec![crate::performance::UnminifiedAsset {
                    url: "https://www.inros-lackner.de/assets/app/build/index.css?v=1".to_string(),
                    kind: "css".to_string(),
                    decoded_bytes: 454_810,
                    transfer_bytes: 110_000,
                    savings_bytes: 303_514,
                }],
                total_savings_bytes: 507_392,
                total_unminified_count: 2,
                legacy_scripts: vec![],
                total_legacy_wasted_bytes: 0,
            }),
            animations: None,
            coverage: Some(crate::performance::CoverageAnalysis {
                unused_js: crate::performance::UnusedJsAnalysis {
                    scripts: vec![],
                    total_bytes: 760_628,
                    unused_bytes: 0,
                    used_pct: 100.0,
                },
                unused_css: crate::performance::UnusedCssAnalysis {
                    total_rules: 0,
                    used_rules: 0,
                    used_pct: None,
                    measurement: "not_available".to_string(),
                },
                measurement_warnings: vec![],
            }),
            measurement_warnings: vec![],
        });
        let pdf = generate_pdf(
            &report,
            &ReportConfig {
                level: ReportLevel::Standard,
                ..ReportConfig::default()
            },
        )
        .expect("performance preview PDF");
        let temp_dir = tempfile::tempdir().expect("temp dir");
        let pdf_path = temp_dir.path().join("performance-interpretation.pdf");
        let text_path = temp_dir.path().join("performance-interpretation.txt");
        std::fs::write(&pdf_path, pdf).expect("write performance PDF");
        Command::new(pdftotext)
            .arg(&pdf_path)
            .arg(&text_path)
            .status()
            .expect("pdftotext should run");
        let text = std::fs::read_to_string(text_path).expect("read PDF text");
        for expected in [
            "Größter direkt nutzbarer Hebel",
            "Code-Nutzung unauffällig",
            "Ziel: max. 800",
            "Priorisierte Maßnahmen",
        ] {
            assert!(
                text.contains(expected),
                "missing PDF interpretation: {expected}"
            );
        }
    }

    #[test]
    fn test_pdf_score_present_in_extracted_text() {
        // The overall score computed by normalize() must appear as a number in the rendered PDF.
        let Some(pdftotext) = find_executable("pdftotext") else {
            return;
        };

        let report = pdf_fixture_report_rich();
        let normalized = crate::audit::normalize(&report);
        let expected_score = normalized.normalized.score.to_string();
        let config = ReportConfig {
            level: ReportLevel::Standard,
            ..ReportConfig::default()
        };
        let pdf = generate_pdf(&report, &config).expect("PDF should render");

        let temp_dir = tempfile::tempdir().expect("temp dir");
        let pdf_path = temp_dir.path().join("score-check.pdf");
        let txt_path = temp_dir.path().join("score-check.txt");
        std::fs::write(&pdf_path, &pdf).expect("write pdf");
        Command::new(pdftotext)
            .arg(&pdf_path)
            .arg(&txt_path)
            .status()
            .expect("pdftotext should run");
        let text = std::fs::read_to_string(&txt_path).expect("read extracted text");

        assert!(
            text.contains(&expected_score),
            "Score {expected_score} missing from PDF text — score not rendered on page"
        );
    }

    fn assert_pdf_smoke(pdf: &[u8], min_size: usize) {
        assert!(pdf.starts_with(b"%PDF-"), "PDF header missing");
        assert!(
            pdf.windows(5).any(|window| window == b"%%EOF"),
            "PDF EOF marker missing"
        );
        assert!(
            pdf.len() > min_size,
            "PDF too small to contain the expected report layout: {} bytes",
            pdf.len()
        );
    }

    fn pdf_fixture_report() -> AuditReport {
        pdf_fixture_report_for_url("https://example.com")
    }

    fn pdf_fixture_report_for_url(url: &str) -> AuditReport {
        let mut results = WcagResults::new();
        results.nodes_checked = 42;
        results.passes = 8;
        results.add_violation(
            Violation::new(
                "1.1.1",
                "Non-text Content",
                WcagLevel::A,
                Severity::High,
                "Image missing alternative text",
                "node-hero-image",
            )
            .with_selector("img.hero")
            .with_html_snippet("<img class=\"hero\" src=\"hero.jpg\">")
            .with_fix("Add a meaningful alt attribute"),
        );

        AuditReport::new(url.to_string(), WcagLevel::AA, results, 1_200)
    }

    /// Richer fixture with multiple violations across severities — closer to a real-world report.
    fn pdf_fixture_report_rich() -> AuditReport {
        let mut results = WcagResults::new();
        results.nodes_checked = 320;
        results.passes = 48;

        let violations = [
            (
                "1.4.3",
                "Contrast (Minimum)",
                WcagLevel::AA,
                Severity::Critical,
                "Text has insufficient color contrast ratio",
                "node-body-text",
            ),
            (
                "1.1.1",
                "Non-text Content",
                WcagLevel::A,
                Severity::Critical,
                "Image missing alternative text on hero banner",
                "node-hero-1",
            ),
            (
                "4.1.2",
                "Name, Role, Value",
                WcagLevel::A,
                Severity::High,
                "Button has no accessible name",
                "node-cta-btn",
            ),
            (
                "2.4.4",
                "Link Purpose",
                WcagLevel::A,
                Severity::High,
                "Link text is not descriptive enough",
                "node-read-more",
            ),
            (
                "1.3.1",
                "Info and Relationships",
                WcagLevel::A,
                Severity::High,
                "Form field missing label",
                "node-email-input",
            ),
            (
                "2.4.1",
                "Bypass Blocks",
                WcagLevel::A,
                Severity::Medium,
                "Skip navigation link missing",
                "node-skip",
            ),
            (
                "2.4.6",
                "Headings and Labels",
                WcagLevel::AA,
                Severity::Medium,
                "Heading hierarchy skips levels",
                "node-h3",
            ),
            (
                "3.1.1",
                "Language of Page",
                WcagLevel::A,
                Severity::Low,
                "HTML lang attribute not set",
                "node-html",
            ),
        ];

        for (criterion, rule_name, level, severity, msg, node_id) in violations {
            results.add_violation(
                Violation::new(criterion, rule_name, level, severity, msg, node_id)
                    .with_selector(format!("#{node_id}"))
                    .with_fix(format!("Fix required for {rule_name}")),
            );
        }

        AuditReport::new(
            "https://example.com".to_string(),
            WcagLevel::AA,
            results,
            3_800,
        )
    }

    fn tiny_png_bytes() -> &'static [u8] {
        &[
            0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48,
            0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00,
            0x00, 0x1f, 0x15, 0xc4, 0x89, 0x00, 0x00, 0x00, 0x0a, 0x49, 0x44, 0x41, 0x54, 0x78,
            0x9c, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0d, 0x0a, 0x2d, 0xb4, 0x00,
            0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
        ]
    }

    fn find_executable(name: &str) -> Option<PathBuf> {
        let paths = std::env::var_os("PATH")?;
        std::env::split_paths(&paths)
            .map(|path| path.join(name))
            .find(|path| path.is_file())
    }

    /// Count PDF pages by scanning for `/Type /Page` objects (not `/Type /Pages`).
    fn count_pdf_pages(pdf: &[u8]) -> usize {
        let needle = b"/Type /Page";
        let mut count = 0;
        let mut i = 0;
        while i + needle.len() <= pdf.len() {
            if pdf[i..i + needle.len()] == *needle {
                // Exclude /Type /Pages (the catalogue node)
                if pdf.get(i + needle.len()).copied() != Some(b's') {
                    count += 1;
                }
            }
            i += 1;
        }
        count
    }

    /// Count PDF `/Annot` entries — proxy for callout boxes / links.
    fn count_pdf_annotations(pdf: &[u8]) -> usize {
        let doc = match lopdf::Document::load_mem(pdf) {
            Ok(d) => d,
            Err(_) => return 0,
        };
        doc.objects
            .values()
            .filter(|o| {
                if let Ok(d) = o.as_dict() {
                    return d
                        .get(b"Type")
                        .ok()
                        .and_then(|v| v.as_name().ok())
                        .map(|n| n == b"Annot")
                        .unwrap_or(false);
                }
                false
            })
            .count()
    }

    /// Read PDF outline (bookmark) titles in tree order. Empty when there
    /// is no outline.
    fn pdf_outline_titles(pdf: &[u8]) -> Vec<String> {
        let doc = match lopdf::Document::load_mem(pdf) {
            Ok(d) => d,
            Err(_) => return vec![],
        };
        let mut titles = Vec::new();
        let catalog = match doc.catalog() {
            Ok(c) => c,
            Err(_) => return titles,
        };
        let outlines_ref = match catalog.get(b"Outlines") {
            Ok(v) => v,
            Err(_) => return titles,
        };
        let outlines_id = match outlines_ref.as_reference() {
            Ok(id) => id,
            Err(_) => return titles,
        };
        let outlines = match doc.get_dictionary(outlines_id) {
            Ok(d) => d,
            Err(_) => return titles,
        };
        let mut current = outlines
            .get(b"First")
            .ok()
            .and_then(|v| v.as_reference().ok());
        while let Some(id) = current {
            let dict = match doc.get_dictionary(id) {
                Ok(d) => d,
                Err(_) => break,
            };
            if let Ok(title) = dict.get(b"Title").and_then(|v| v.as_str()) {
                titles.push(String::from_utf8_lossy(title).trim().to_string());
            }
            current = dict.get(b"Next").ok().and_then(|v| v.as_reference().ok());
        }
        titles
    }

    #[test]
    fn test_standard_pdf_larger_than_executive() {
        let report = pdf_fixture_report_rich();
        let exec_pdf = generate_pdf(
            &report,
            &ReportConfig {
                level: ReportLevel::Executive,
                ..ReportConfig::default()
            },
        )
        .expect("executive PDF should render");
        let std_pdf = generate_pdf(
            &report,
            &ReportConfig {
                level: ReportLevel::Standard,
                ..ReportConfig::default()
            },
        )
        .expect("standard PDF should render");
        assert!(
            std_pdf.len() > exec_pdf.len(),
            "Standard PDF ({} bytes) should be larger than Executive ({} bytes)",
            std_pdf.len(),
            exec_pdf.len()
        );
    }

    #[test]
    fn test_batch_pdf_page_count_reasonable() {
        let batch = BatchReport::from_reports(
            vec![
                pdf_fixture_report_for_url("https://example.com"),
                pdf_fixture_report_for_url("https://example.com/about"),
            ],
            vec![],
            2_400,
        );
        let pdf = generate_batch_pdf(&batch, &ReportConfig::default()).expect("batch PDF");
        let pages = count_pdf_pages(&pdf);
        assert!(
            pages >= 3,
            "Batch PDF must have at least 3 pages, got {}",
            pages
        );
    }

    #[test]
    fn test_pdf_has_annotations() {
        // Renderreport emits annotations for some interactive constructs
        // (links, etc.). This is a smoke check that lopdf can parse the PDF
        // and the structural pipeline is intact.
        let report = pdf_fixture_report_rich();
        let pdf = generate_pdf(&report, &ReportConfig::default()).expect("standard PDF");
        let _ = count_pdf_annotations(&pdf); // result not asserted; counts may be 0
        let _ = pdf_outline_titles(&pdf);
        assert!(
            lopdf::Document::load_mem(&pdf).is_ok(),
            "PDF must parse via lopdf"
        );
    }

    #[test]
    fn test_executive_pdf_page_count_within_target() {
        // Use the richer fixture (8 violations across severities) to validate
        // that executive stays compact even with a realistic finding load.
        let report = pdf_fixture_report_rich();
        let config = ReportConfig {
            level: ReportLevel::Executive,
            ..ReportConfig::default()
        };
        let pdf = generate_pdf(&report, &config).expect("Executive PDF should render");
        let pages = count_pdf_pages(&pdf);
        assert!(
            pages <= 8,
            "Executive PDF must be ≤ 8 pages per target, got {} pages",
            pages
        );
    }

    #[test]
    fn test_standard_pdf_page_count_reasonable() {
        let report = pdf_fixture_report();
        let config = ReportConfig {
            level: ReportLevel::Standard,
            ..ReportConfig::default()
        };
        let pdf = generate_pdf(&report, &config).expect("Standard PDF should render");
        let pages = count_pdf_pages(&pdf);
        assert!(
            pages >= 3,
            "Standard PDF must have at least 3 pages, got {}",
            pages
        );
        assert!(
            pages <= 35,
            "Standard PDF must not exceed 35 pages, got {} pages",
            pages
        );
    }

    #[test]
    fn test_pdf_contains_no_raw_typst_syntax() {
        // Regression test for #239: raw Typst source code must never appear in the
        // rendered PDF text (e.g. "block( width: 100%, fill: accent, radius: 8pt )").
        // If renderreport fails to compile a section, it may emit the raw template
        // string into the output instead of a compiled result.
        //
        // Text extraction uses `lopdf` so no external tool (pdftotext) is required.
        for level in [
            ReportLevel::Executive,
            ReportLevel::Standard,
            ReportLevel::Technical,
        ] {
            let report = pdf_fixture_report_rich();
            let config = ReportConfig {
                level,
                ..ReportConfig::default()
            };
            let pdf = generate_pdf(&report, &config).expect("PDF should render");

            let doc = lopdf::Document::load_mem(&pdf).expect("lopdf parse");
            let page_ids: Vec<u32> = doc.get_pages().keys().copied().collect();
            let text = doc.extract_text(&page_ids).unwrap_or_default();

            for (pattern, description) in forbidden_typst_patterns() {
                assert!(
                    !text.contains(pattern),
                    "Raw Typst syntax found in {:?} PDF — {description} ({pattern:?} in extracted text). Issue #239.",
                    level,
                );
            }
        }
    }

    /// Fast smoke test for #239 using `Engine::render_typ()` — verifies that the
    /// intermediate Typst source for every report level assembles without errors
    /// and that templates we depend on are present in the source. Much faster
    /// than the full PDF round-trip; runs in <1s.
    #[test]
    fn test_typ_source_smoke_for_all_report_levels() {
        for level in [
            ReportLevel::Executive,
            ReportLevel::Standard,
            ReportLevel::Technical,
        ] {
            let report = pdf_fixture_report_rich();
            let config = ReportConfig {
                level,
                ..ReportConfig::default()
            };
            let typ = generate_typ(&report, &config).expect("typ source should assemble");

            assert!(
                typ.len() > 5_000,
                "typ source for {:?} suspiciously short ({} bytes)",
                level,
                typ.len()
            );

            // Sanity: source must contain the template token boundary marker.
            assert!(
                typ.contains("#let "),
                "typ source for {:?} must include at least one `#let` (template definitions)",
                level
            );
        }
    }

    #[test]
    fn test_typ_renders_device_preview_when_screenshots_are_available() {
        use crate::audit::{ViewportScoreSet, ViewportScores};

        let mut report = pdf_fixture_report_rich();
        report.page_screenshots = Some(PageScreenshots {
            desktop: tiny_png_bytes().to_vec(),
            mobile: tiny_png_bytes().to_vec(),
        });
        report.screenshot_status = ScreenshotStatus::Captured;
        report.viewport_scores = Some(ViewportScores {
            desktop: ViewportScoreSet {
                accessibility: 20,
                performance: None,
                overall: 20,
            },
            mobile: ViewportScoreSet {
                accessibility: 20,
                performance: None,
                overall: 20,
            },
            weighted_overall: 20,
        });

        let ts = report.timestamp.timestamp_nanos_opt().unwrap_or(0);
        let desktop_path = std::env::temp_dir().join(format!("ams-desktop-{}.png", ts));
        let mobile_path = std::env::temp_dir().join(format!("ams-mobile-{}.png", ts));

        let typ = unescape_typ(&generate_typ(&report, &ReportConfig::default()).expect("typ"));

        assert!(typ.contains("device-preview"));
        assert!(typ.contains(PAGE_DESKTOP_SCREENSHOT_ASSET));
        assert!(typ.contains(PAGE_MOBILE_SCREENSHOT_ASSET));
        // With viewport scores available, the compact strip contains the three
        // score values while the captured images provide the visual preview.
        assert!(typ.contains("Barrierefreiheit"));
        assert!(typ.contains("Desktop"));
        assert!(typ.contains("Mobile"));
        assert!(typ.contains("Barrierefreiheit - Gesamt"));
        assert!(typ.contains("70/30 gewichtet"));
        assert!(typ.contains("Barrierefreiheits-Gesamtwert"));
        assert!(
            !desktop_path.exists() && !mobile_path.exists(),
            "temporary screenshot assets should be removed after Typst rendering"
        );
    }

    // ── Typst ⇄ JSON consistency per report part (3 internal areas) ─────────
    //
    // The single report is split into three parts (TEIL 1/2/3). For each part we
    // decide which aggregated audit value belongs there and assert that the value
    // is (a) present in that part of the Typst source and (b) identical to the
    // value the JSON report exposes. We deliberately test the *number as a value*
    // (the way the figure is represented, e.g. `73` / `73/100`), NOT the visual
    // formatting (fonts, colors, spacing) — those are not part of the contract.
    //
    //   Teil 1 (Executive)      → overall score (headline aggregate)
    //   Teil 2 (Accessibility)  → accessibility score + every module score
    //                             (the aggregated module overview lives here)
    //   Teil 3 (Tech & Quality) → every non-accessibility module score (detail)

    /// Unescape the embedded component JSON so values read as plain `"value":"73"`.
    fn unescape_typ(typ: &str) -> String {
        typ.replace("\\\"", "\"")
    }

    /// True if `n` appears as a *value* (not a color/spacing/font literal).
    /// Matches both JSON-in-string (renderreport ≤0.2.20) and Typst-dict
    /// (renderreport ≥0.2.21) representations:
    ///   JSON: `"value":"73"`  `"value":"73/100"`  `"score":73`
    ///   Typst: `value: "73"`  `value: "73/100"`  `score: 73,`
    fn part_has_value(part: &str, n: u32) -> bool {
        let s = n.to_string();
        [
            // JSON-in-string format (renderreport ≤0.2.20)
            format!(":\"{s}\""),
            format!(":\"{s}/100\""),
            format!(":\"{s}/"),
            format!(":{s},"),
            format!(":{s}}}"),
            // Typst dict format (renderreport ≥0.2.21): `key: "value"` or `key: number`
            format!(": \"{s}\""),
            format!(": \"{s}/"),
            format!(": {s},"),
            format!(": {s})"),
            format!(": {s}.0,"),
            format!(": {s}.0)"),
        ]
        .iter()
        .any(|needle| part.contains(needle))
    }

    /// Split the (unescaped) Typst source into the 3 report parts on the
    /// "TEIL 2 / TEIL 3" dividers. Part 1 covers the cover + executive front matter.
    fn split_parts(typ: &str) -> (String, String, String) {
        let i2 = typ.find("TEIL 2 VON 3").expect("Teil 2 divider present");
        let i3 = typ.find("TEIL 3 VON 3").expect("Teil 3 divider present");
        assert!(i2 < i3, "part dividers must appear in order");
        (
            typ[..i2].to_string(),
            typ[i2..i3].to_string(),
            typ[i3..].to_string(),
        )
    }

    #[test]
    fn test_typ_aggregates_consistent_with_json_per_part() {
        // Rich WCAG fixture + one module (SEO = 73) so all three parts render.
        let seo = crate::seo::SeoAnalysis {
            score: 73,
            ..Default::default()
        };
        let report = pdf_fixture_report_rich().with_seo(seo);

        let config = ReportConfig {
            level: ReportLevel::Technical,
            locale: "de".to_string(),
            ..ReportConfig::default()
        };

        // JSON holds the aggregated values that MUST also appear in the PDF.
        let normalized = crate::audit::normalize(&report);
        let unified = crate::output::UnifiedReport::single(&normalized, &report);
        let json: serde_json::Value =
            serde_json::from_str(&unified.to_json(true).expect("json")).expect("parse json");
        let page = &json["pages"][0];

        let overall = page["overall_score"].as_u64().expect("overall_score") as u32;
        let a11y = page["accessibility_score"]
            .as_u64()
            .expect("accessibility_score") as u32;
        let module_scores: Vec<(String, u32)> = page["module_scores"]
            .as_array()
            .expect("module_scores")
            .iter()
            .map(|m| {
                (
                    m["name"].as_str().unwrap_or_default().to_string(),
                    m["score"].as_u64().unwrap_or_default() as u32,
                )
            })
            .collect();
        assert!(
            module_scores.iter().any(|(n, _)| n == "SEO"),
            "fixture must expose an SEO module score"
        );

        let typ = unescape_typ(&generate_typ(&report, &config).expect("typ"));
        let (p1, p2, p3) = split_parts(&typ);

        // Teil 1 — Executive: the overall score is the headline aggregate.
        assert!(
            part_has_value(&p1, overall),
            "overall score {overall} (JSON) must appear in Teil 1"
        );

        // Teil 2 — Accessibility: a11y score + every module score (overview).
        assert!(
            part_has_value(&p2, a11y),
            "accessibility score {a11y} (JSON) must appear in Teil 2"
        );
        for (name, score) in &module_scores {
            assert!(
                part_has_value(&p2, *score),
                "module '{name}' score {score} (JSON) must appear in the Teil 2 overview"
            );
        }

        // Teil 3 — Tech & Quality: non-accessibility module scores (detail).
        for (name, score) in &module_scores {
            if name == "Accessibility" {
                continue;
            }
            assert!(
                part_has_value(&p3, *score),
                "module '{name}' score {score} (JSON) must appear in the Teil 3 detail"
            );
        }
    }

    #[test]
    fn test_dual_viewport_accessibility_score_is_identical_in_json_and_pdf() {
        use crate::audit::{ViewportScoreSet, ViewportScores};

        let mut report = pdf_fixture_report_rich();
        // Simulate the former bug: a score recomputed from the merged finding
        // union differed from the two viewport scores shown later in the PDF.
        report.accessibility.score = 12.0;
        report.viewport_scores = Some(ViewportScores {
            desktop: ViewportScoreSet {
                accessibility: 80,
                performance: None,
                overall: 80,
            },
            mobile: ViewportScoreSet {
                accessibility: 20,
                performance: None,
                overall: 20,
            },
            weighted_overall: 38,
        });

        let normalized = crate::audit::normalize(&report);
        let unified = crate::output::UnifiedReport::single(&normalized, &report);
        assert_eq!(unified.summary.accessibility_score, 38);
        assert_eq!(unified.pages[0].accessibility_score, 38);
        assert_eq!(
            unified.pages[0]
                .module_scores
                .iter()
                .find(|module| module.name == "Accessibility")
                .map(|module| module.score),
            Some(38)
        );

        let typ =
            unescape_typ(&generate_typ(&report, &ReportConfig::default()).expect("Typst source"));
        assert!(typ.contains("Barrierefreiheit - Gesamt"));
        assert!(part_has_value(&typ, 38));
        assert!(typ.contains("70/30 gewichtet"));
    }

    #[test]
    fn test_screen_reader_quality_numbers_explain_scale_and_counts() {
        let mut report = pdf_fixture_report_rich();
        report.screen_reader_audit = Some(crate::screen_reader::build_sr_audit_report(
            &report.url,
            report.timestamp,
            &crate::AXTree::new(),
            "de",
            None,
        ));

        let typ =
            unescape_typ(&generate_typ(&report, &ReportConfig::default()).expect("Typst source"));
        assert!(typ.contains("Heading-Qualität"));
        assert!(typ.contains("Qualitätswerte nutzen eine Skala von 0–100"));
        assert!(typ.contains("reine Anzahlen, keine Qualitätswerte"));
    }

    fn forbidden_typst_patterns() -> &'static [(&'static str, &'static str)] {
        &[
            ("block( width:", "Typst block() call with params"),
            ("block(width:", "Typst block() call (no space)"),
            ("v(spacing-", "Typst v() vertical-space call"),
            ("box(height:", "Typst box() call with height"),
            ("fill: accent", "Typst fill: accent token"),
            ("#pagebreak()", "Typst page-break call"),
            ("#colbreak()", "Typst column-break call"),
        ]
    }
}