jev-seo 0.4.0

Free Rust SEO and GEO toolkit powered by TypeSafe Jev: 64-rule audits, site crawls, AI citation checks, rank drift, CI gates, 19-tool MCP. Zero cost.
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
use anyhow::{Context, Result};
use gray_matter::engine::YAML;
use gray_matter::Matter;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::path::Path;
use std::sync::LazyLock;

static SLOP_RE: LazyLock<Regex> = LazyLock::new(|| {
    let mut alts: Vec<String> = AI_SLOP_PHRASES.iter().map(|p| regex::escape(p)).collect();
    alts.sort_by_key(|a| std::cmp::Reverse(a.len()));
    Regex::new(&format!("(?i)\\b(?:{})\\b", alts.join("|"))).expect("slop regex")
});
static TAG_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?is)<(script|style|head)\b[^>]*>.*?</(script|style|head)\s*>").expect("tag regex")
});
static MD_HTML_H_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r#"(?i)<h([1-6])\b[^>]*>"#).expect("md html heading regex"));
static MD_FENCE_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?s)```.*?```").expect("fence regex"));
static CLAIM_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\b\d+(?:\.\d+)?%?|\b(?:19|20)\d{2}\b").expect("claim regex"));
static CITE_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?i)https?://|source|study|studies|research|according to|figure|fig\.|report|survey|data shows|\[\d+\]").expect("cite regex")
});
static SCRIPT_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?is)<script\b[^>]*>(.*?)</script>").expect("script regex"));

pub(crate) fn js_shell_for(raw: &str, word_count: usize) -> bool {
    if word_count >= 300 {
        return false;
    }
    // ponytail: bytes ratio only, no headless render until --features js
    let script_bytes: usize = SCRIPT_RE.captures_iter(raw).map(|c| c[1].len()).sum();
    let text = crate::fetch::readable_text(raw, 200_000);
    let text_bytes = text.len().max(1);
    word_count < 300 && script_bytes > 2 * text_bytes
}

pub(crate) fn schema_missing_for(content: &str, label: &str) -> Vec<String> {
    let Ok(rep) = crate::schema::validate_content(label, content) else {
        return Vec::new();
    };
    let mut out = Vec::new();
    for d in &rep.details {
        for m in &d.missing_required {
            out.push(format!("{}: {}", d.schema_type, m));
        }
    }
    out
}

/// Claims (statistics, quantities, years) with no citation signal within
/// 200 chars either side: the cheapest trust gap a rule can measure.
pub fn count_uncited_claims(text: &str) -> usize {
    let mut n = 0;
    for m in CLAIM_RE.find_iter(text) {
        let lo = text.floor_char_boundary(m.start().saturating_sub(200));
        let hi = text.floor_char_boundary((m.end() + 200).min(text.len()));
        if hi > lo && !CITE_RE.is_match(&text[lo..hi]) {
            n += 1;
        }
    }
    n
}
static MD_LINK_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"!\[([^\]]*)\]\([^)]+\)|\[([^\]]*)\]\([^)]+\)").expect("md link regex")
});

/// Attribute value from a single HTML tag, any attribute order.
fn tag_attr(tag: &str, attr: &str) -> Option<String> {
    let pat = format!(
        r#"(?i)\b{}\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)"#,
        regex::escape(attr)
    );
    let re = Regex::new(&pat).ok()?;
    re.captures(tag).and_then(|c| {
        c.get(1).map(|m| {
            m.as_str()
                .trim_matches(|c: char| c == '"' || c == '\'')
                .to_string()
        })
    })
}

/// Distinct AI-slop markers with word boundaries: "robust" no longer fires
/// inside "robustness", but multi-word tells like "in summary" still match.
fn slop_hits(text: &str) -> Vec<String> {
    let mut found: Vec<String> = SLOP_RE
        .find_iter(text)
        .map(|m| m.as_str().to_lowercase())
        .collect::<std::collections::BTreeSet<_>>()
        .into_iter()
        .collect();
    found.sort();
    found
}

/// Markdown body stripped of fences, code spans, and link markup for honest
/// word counts: syntax characters are not prose.
pub fn md_plain_text(body: &str) -> String {
    md_prose_words(body).0
}

fn md_prose_words(body: &str) -> (String, usize) {
    let no_fence = MD_FENCE_RE.replace_all(body, " ");
    let no_links = MD_LINK_RE.replace_all(&no_fence, "$1$2");
    let no_code: String = no_links
        .split('`')
        .enumerate()
        .filter(|(i, _)| i % 2 == 0)
        .map(|(_, s)| s)
        .collect::<Vec<_>>()
        .join(" ");
    let words: Vec<&str> = no_code
        .split_whitespace()
        .filter(|w| {
            let t = w.trim_matches(|c: char| {
                c == '#' || c == '*' || c == '_' || c == '-' || c == '>' || c == '|'
            });
            !t.is_empty()
        })
        .collect();
    let n = words.len();
    (words.join(" "), n)
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditReport {
    pub file_path: String,
    pub title: Option<String>,
    pub title_len: usize,
    pub description: Option<String>,
    pub description_len: usize,
    pub h1_count: usize,
    pub h2_count: usize,
    pub h3_count: usize,
    pub word_count: usize,
    pub image_count: usize,
    pub images_missing_alt: usize,
    pub internal_links: usize,
    pub external_links: usize,
    pub schema_found: bool,
    pub canonical_found: bool,
    pub og_tags_found: bool,
    pub geo_opening_words: usize,
    pub heading_skipped_levels: Vec<String>,
    pub em_dash_count: usize,
    pub ai_slop_words_found: Vec<String>,
    pub internal_link_targets: Vec<String>,
    /// Right-hand side alternates: (hreflang code, href target) pairs parsed
    /// from `<link rel="alternate" hreflang=...>` head markup.
    #[serde(default)]
    pub hreflang_alternates: Vec<(String, String)>,
    /// Page self-declares noindex via meta robots. hreflang pointing at such
    /// a page is a silent multilingual failure (R58).
    #[serde(default)]
    pub noindex: bool,
    /// Statistics/quantities with no citation signal within 200 chars.
    #[serde(default)]
    pub uncited_claims: usize,
    /// False only when an ld+json block failed to parse. Defaults true so
    /// reports saved before validation existed do not newly fail R33.
    #[serde(default = "schema_valid_default")]
    pub schema_json_valid: bool,
    /// Missing required rich-result props (R32) extracted from ld+json.
    #[serde(default)]
    pub schema_missing_required: Vec<String>,
    /// JS-only shell heuristic: readable_text <300w && script bytes >2× text (R08).
    #[serde(default)]
    pub js_shell: bool,
    pub checks: Vec<CheckItem>,
}

fn schema_valid_default() -> bool {
    true
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CheckItem {
    pub name: String,
    pub passed: bool,
    pub message: String,
}

/// Display windows match the R10/R12 rule windows exactly: a page never
/// passes the badge while firing the rule, or vice versa.
pub const MIN_TITLE_CHARS: usize = 30;
pub const MAX_TITLE_CHARS: usize = 60;
pub const MIN_DESC_CHARS: usize = 120;
pub const MAX_DESC_CHARS: usize = 160;
pub const MIN_CONTENT_WORDS: usize = 300;
pub const GEO_MIN_WORDS: usize = 100;
pub const GEO_MAX_WORDS: usize = 200;

pub const AI_SLOP_PHRASES: &[&str] = &[
    "delve",
    "leverage",
    "testament",
    "bolster",
    "foster",
    "seamless",
    "seamlessly",
    "crucial",
    "robust",
    "landscape",
    "furthermore",
    "moreover",
    "underscores",
    "unveil",
    "tapestry",
    "beacon",
    "in summary",
    "in today's",
];

pub fn check_heading_hierarchy(skipped: &[String]) -> CheckItem {
    let passed = skipped.is_empty();
    CheckItem {
        name: "Heading Hierarchy".into(),
        passed,
        message: if passed {
            "Logical heading progression (no skipped levels)".into()
        } else {
            format!("Skipped levels detected: [{}]", skipped.join(", "))
        },
    }
}

pub fn check_ai_slop(em_dash_count: usize, slop_words: &[String], word_count: usize) -> CheckItem {
    let em_dash_density = if word_count > 0 {
        (em_dash_count as f64 / word_count as f64) * 500.0
    } else {
        0.0
    };
    let is_excessive_dashes = em_dash_density > 2.0 && em_dash_count >= 2;
    let is_excessive_words = slop_words.len() >= 3;
    let passed = !is_excessive_dashes && !is_excessive_words;

    let message = if passed {
        format!(
            "Natural writing tone ({} em-dashes, {} AI crutches)",
            em_dash_count,
            slop_words.len()
        )
    } else {
        format!(
            "Helpful Content risk: {} em-dashes ({:.1}/500w) and {} AI tells [{}]",
            em_dash_count,
            em_dash_density,
            slop_words.len(),
            slop_words.join(", ")
        )
    };

    CheckItem {
        name: "Helpful Content (AI Slop)".into(),
        passed,
        message,
    }
}

pub fn check_title_length(title_len: usize) -> CheckItem {
    let passed = (MIN_TITLE_CHARS..=MAX_TITLE_CHARS).contains(&title_len);
    CheckItem {
        name: "Title Tag Length".into(),
        passed,
        message: format!(
            "Length: {} chars (Optimal: {}-{} chars)",
            title_len, MIN_TITLE_CHARS, MAX_TITLE_CHARS
        ),
    }
}

pub fn check_meta_description(description_len: usize) -> CheckItem {
    let passed = (MIN_DESC_CHARS..=MAX_DESC_CHARS).contains(&description_len);
    CheckItem {
        name: "Meta Description".into(),
        passed,
        message: if description_len == 0 {
            "Missing description metadata".into()
        } else {
            format!(
                "Length: {} chars (Optimal: {}-{} chars)",
                description_len, MIN_DESC_CHARS, MAX_DESC_CHARS
            )
        },
    }
}

pub fn check_h1_uniqueness(h1_count: usize) -> CheckItem {
    CheckItem {
        name: "H1 Uniqueness".into(),
        passed: h1_count == 1,
        message: format!("Found {} H1 headings (Expected: exactly 1)", h1_count),
    }
}

pub fn check_content_depth(word_count: usize) -> CheckItem {
    CheckItem {
        name: "Content Depth".into(),
        passed: word_count >= MIN_CONTENT_WORDS,
        message: format!(
            "Word count: {} (Recommended min: {} words)",
            word_count, MIN_CONTENT_WORDS
        ),
    }
}

pub fn check_image_alt_tags(image_count: usize, images_missing_alt: usize) -> CheckItem {
    CheckItem {
        name: "Image Alt Tags".into(),
        passed: images_missing_alt == 0,
        message: format!(
            "Images: {}, Missing Alt: {}",
            image_count, images_missing_alt
        ),
    }
}

pub fn check_geo_citation_density(words: usize) -> CheckItem {
    let passed = (GEO_MIN_WORDS..=GEO_MAX_WORDS).contains(&words);
    CheckItem {
        name: "GEO Citation Density".into(),
        passed,
        message: format!(
            "Opening passage: {} words (Optimal AI citation block: 134-167 words)",
            words
        ),
    }
}

pub fn check_schema_markup(schema_found: bool) -> CheckItem {
    CheckItem {
        name: "Schema Markup".into(),
        passed: schema_found,
        message: if schema_found {
            "Structured data present".into()
        } else {
            "No JSON-LD/schema markup defined".into()
        },
    }
}

pub fn check_canonical_reference(canonical_found: bool) -> CheckItem {
    CheckItem {
        name: "Canonical Reference".into(),
        passed: canonical_found,
        message: if canonical_found {
            "Canonical tag configured".into()
        } else {
            "Missing canonical URL definition".into()
        },
    }
}

pub fn check_opengraph_metadata(og_found: bool) -> CheckItem {
    CheckItem {
        name: "OpenGraph Metadata".into(),
        passed: og_found,
        message: if og_found {
            "OpenGraph meta tags found".into()
        } else {
            "Missing og:title, og:description, or og:image tags".into()
        },
    }
}

pub fn audit_file(path_str: &str) -> Result<AuditReport> {
    let path = Path::new(path_str);
    let content = std::fs::read_to_string(path)
        .with_context(|| format!("Failed to read file: {}", path_str))?;

    let is_markdown = path
        .extension()
        .is_some_and(|ext| ext == "md" || ext == "mdx" || ext == "markdown");

    if is_markdown {
        audit_markdown(path_str, &content)
    } else {
        audit_html(path_str, &content)
    }
}

fn audit_markdown(path_str: &str, content: &str) -> Result<AuditReport> {
    let matter = Matter::<YAML>::new();
    let parsed = matter.parse(content);

    let mut title: Option<String> = None;
    let mut description: Option<String> = None;
    let mut canonical_found = false;
    let mut schema_found = false;
    let mut og_tags_found = false;

    if let Some(data) = parsed.data {
        if let Ok(val) = data.as_hashmap() {
            if let Some(t) = val.get("title") {
                title = t.as_string().ok();
            }
            if let Some(d) = val.get("description") {
                description = d.as_string().ok();
            }
            if val.contains_key("canonical") || val.contains_key("canonical_url") {
                canonical_found = true;
            }
            if val.contains_key("schema") || val.contains_key("json_ld") {
                schema_found = true;
            }
            if val.contains_key("og_image") || val.contains_key("image") {
                og_tags_found = true;
            }
        }
    }

    let body = parsed.content;
    // Inline HTML in markdown bodies counts: layout tags the author wrote
    // by hand satisfy canonical/schema/OG the same as frontmatter keys.
    let mut schema_json_valid = true;
    let mut hreflang_alternates: Vec<(String, String)> = Vec::new();
    let mut noindex = false;
    {
        let link_tag_re = Regex::new(r#"(?is)<link\b[^>]*>"#)?;
        for cap in link_tag_re.captures_iter(&body) {
            let tag = &cap[0];
            if tag_attr(tag, "rel").is_some_and(|v| v.eq_ignore_ascii_case("canonical")) {
                canonical_found = true;
            }
            if let (Some(lang), Some(href)) = (tag_attr(tag, "hreflang"), tag_attr(tag, "href")) {
                hreflang_alternates.push((lang.to_ascii_lowercase(), href));
            }
        }
        let script_re = Regex::new(
            r#"(?is)<script\b[^>]*type=["']application/ld\+json["'][^>]*>(.*?)</script>"#,
        )?;
        for cap in script_re.captures_iter(&body) {
            schema_found = true;
            if serde_json::from_str::<serde_json::Value>(&cap[1]).is_err() {
                schema_json_valid = false;
            }
        }
        let meta_tag_re = Regex::new(r#"(?is)<meta\b[^>]*>"#)?;
        let mut og_seen = std::collections::BTreeSet::new();
        for cap in meta_tag_re.captures_iter(&body) {
            let tag = &cap[0];
            if let Some(prop) = tag_attr(tag, "property") {
                let p = prop.to_ascii_lowercase();
                if p == "og:title" || p == "og:description" || p == "og:image" {
                    og_seen.insert(p);
                }
            }
            if tag_attr(tag, "name").is_some_and(|n| n.eq_ignore_ascii_case("robots")) {
                if let Some(robots) = tag_attr(tag, "content") {
                    if robots.to_ascii_lowercase().contains("noindex") {
                        noindex = true;
                    }
                }
            }
        }
        if og_seen.len() == 3 {
            og_tags_found = true;
        }
    }
    let mut h1_count = 0;
    let mut h2_count = 0;
    let mut h3_count = 0;
    let mut image_count = 0;
    let mut images_missing_alt = 0;
    let mut internal_links = 0;
    let mut external_links = 0;
    let mut internal_link_targets = Vec::new();
    let mut prev_heading_level: Option<usize> = None;
    let mut heading_skipped_levels = Vec::new();

    let mut first_section_words = 0;
    let mut past_first_heading = false;

    let link_re = Regex::new(r#"\[([^\]]*)\]\(([^)]+)\)"#)?;

    for line in body.lines() {
        let trimmed = line.trim();
        // Inline HTML headings count too: docs often mix <h2> into markdown.
        let mut html_heading: Option<usize> = None;
        if !trimmed.starts_with('#') {
            if let Some(cap) = MD_HTML_H_RE.captures(trimmed) {
                if let Ok(lvl) = cap[1].parse::<usize>() {
                    html_heading = Some(lvl);
                    match lvl {
                        1 => h1_count += 1,
                        2 => h2_count += 1,
                        3 => h3_count += 1,
                        _ => {}
                    }
                    past_first_heading = true;
                }
            }
        }
        let heading_lvl = if let Some(stripped) = trimmed.strip_prefix("# ") {
            h1_count += 1;
            past_first_heading = true;
            if title.is_none() {
                title = Some(stripped.trim().to_string());
            }
            Some(1)
        } else if trimmed.starts_with("## ") {
            h2_count += 1;
            past_first_heading = true;
            Some(2)
        } else if trimmed.starts_with("### ") {
            h3_count += 1;
            Some(3)
        } else if trimmed.starts_with("#### ") {
            Some(4)
        } else if trimmed.starts_with("##### ") {
            Some(5)
        } else if trimmed.starts_with("###### ") {
            Some(6)
        } else {
            html_heading
        };

        if let Some(lvl) = heading_lvl {
            if let Some(prev) = prev_heading_level {
                if lvl > prev + 1 {
                    heading_skipped_levels.push(format!("H{} -> H{}", prev, lvl));
                }
            } else if lvl > 2 {
                // Leading jump with no prior heading: H3-first skips H1+H2.
                // H2-first is covered by the missing-H1 check instead.
                heading_skipped_levels.push(format!("H1 -> H{}", lvl));
            }
            prev_heading_level = Some(lvl);
        } else if !past_first_heading || h2_count == 0 {
            first_section_words += trimmed.split_whitespace().count();
        }

        if trimmed.contains("![") {
            image_count += 1;
            if trimmed.contains("![](") {
                images_missing_alt += 1;
            }
        }

        for cap in link_re.captures_iter(trimmed) {
            let target = cap[2].trim().split('#').next().unwrap_or("").trim();
            if target.starts_with("http://") || target.starts_with("https://") {
                external_links += 1;
            } else if !target.is_empty()
                && !target.starts_with('#')
                && !target.starts_with("mailto:")
            {
                internal_links += 1;
                internal_link_targets.push(target.to_string());
            }
        }
    }

    let word_count = md_prose_words(&body).1;
    let title_len = title.as_ref().map(|s| s.chars().count()).unwrap_or(0);
    let description_len = description.as_ref().map(|s| s.chars().count()).unwrap_or(0);

    let em_dash_count = content.chars().filter(|&c| c == '\u{2014}').count();
    let ai_slop_words_found = slop_hits(&body);

    let checks = vec![
        check_title_length(title_len),
        check_meta_description(description_len),
        check_h1_uniqueness(h1_count),
        check_heading_hierarchy(&heading_skipped_levels),
        check_content_depth(word_count),
        check_image_alt_tags(image_count, images_missing_alt),
        check_geo_citation_density(first_section_words),
        check_ai_slop(em_dash_count, &ai_slop_words_found, word_count),
        check_schema_markup(schema_found),
        check_canonical_reference(canonical_found),
        check_opengraph_metadata(og_tags_found),
    ];

    Ok(AuditReport {
        file_path: path_str.to_string(),
        title,
        title_len,
        description,
        description_len,
        h1_count,
        h2_count,
        h3_count,
        word_count,
        image_count,
        images_missing_alt,
        internal_links,
        external_links,
        schema_found,
        schema_json_valid,
        schema_missing_required: schema_missing_for(&body, path_str),
        js_shell: js_shell_for(content, word_count),
        canonical_found,
        og_tags_found,
        geo_opening_words: first_section_words,
        heading_skipped_levels,
        em_dash_count,
        ai_slop_words_found,
        internal_link_targets,
        hreflang_alternates,
        noindex,
        uncited_claims: count_uncited_claims(&body),
        checks,
    })
}

fn audit_html(path_str: &str, content: &str) -> Result<AuditReport> {
    let title_re = Regex::new(r#"(?is)<title[^>]*>(.*?)</title>"#)?;
    let tag_re = Regex::new(r#"(?is)<(meta|link)\b[^>]*>"#)?;
    let img_re = Regex::new(r#"(?is)<img\b([^>]*)>"#)?;
    let alt_attr_re = Regex::new(r#"(?is)\balt\s*="#)?;
    let a_re = Regex::new(r#"(?is)<a\b[^>]*href=["']([^"']*)["']"#)?;
    let schema_block_re =
        Regex::new(r#"(?is)<script\b[^>]*type=["']application/ld\+json["'][^>]*>(.*?)</script>"#)?;
    let strip_html = Regex::new(r#"<[^>]+>"#)?;

    let title = title_re.captures(content).map(|c| c[1].trim().to_string());
    // Attribute order must not matter: find the tag by one attribute,
    // read the value from the other.
    let mut description: Option<String> = None;
    let mut canonical_found = false;
    let mut og_seen = std::collections::BTreeSet::new();
    let mut hreflang_alternates: Vec<(String, String)> = Vec::new();
    let mut noindex = false;
    for cap in tag_re.captures_iter(content) {
        let tag = &cap[0];
        let is_meta = cap[1].eq_ignore_ascii_case("meta");
        if is_meta {
            if let Some(name) = tag_attr(tag, "name") {
                if name.eq_ignore_ascii_case("description") && description.is_none() {
                    description = tag_attr(tag, "content").map(|s| s.trim().to_string());
                }
                if name.eq_ignore_ascii_case("robots") {
                    if let Some(robots) = tag_attr(tag, "content") {
                        if robots.to_ascii_lowercase().contains("noindex") {
                            noindex = true;
                        }
                    }
                }
            }
            if let Some(prop) = tag_attr(tag, "property") {
                let p = prop.to_ascii_lowercase();
                if p == "og:title" || p == "og:description" || p == "og:image" {
                    og_seen.insert(p);
                }
            }
        } else if tag_attr(tag, "rel").is_some_and(|v| {
            if v.eq_ignore_ascii_case("canonical") {
                true
            } else {
                tag_attr(tag, "hreflang").is_some()
            }
        }) {
            if let (Some(lang), Some(href)) = (tag_attr(tag, "hreflang"), tag_attr(tag, "href")) {
                hreflang_alternates.push((lang.to_ascii_lowercase(), href));
            } else {
                canonical_found = true;
            }
        }
    }
    // All three OG tags required: one of three passing hid partial markup.
    let og_tags_found = og_seen.len() == 3;

    let h1_count = Regex::new(r#"(?is)<h1\b[^>]*>.*?</h1>"#)?
        .find_iter(content)
        .count();
    let h2_count = Regex::new(r#"(?is)<h2\b[^>]*>.*?</h2>"#)?
        .find_iter(content)
        .count();
    let h3_count = Regex::new(r#"(?is)<h3\b[^>]*>.*?</h3>"#)?
        .find_iter(content)
        .count();

    let heading_seq_re = Regex::new(r#"(?is)<(h[1-6])\b[^>]*>"#)?;
    let mut prev_heading_level: Option<usize> = None;
    let mut heading_skipped_levels = Vec::new();
    for cap in heading_seq_re.captures_iter(content) {
        let tag = &cap[1];
        if let Some(lvl_char) = tag.chars().nth(1) {
            if let Some(lvl) = lvl_char.to_digit(10).map(|d| d as usize) {
                if let Some(prev) = prev_heading_level {
                    if lvl > prev + 1 {
                        heading_skipped_levels.push(format!("H{} -> H{}", prev, lvl));
                    }
                } else if lvl > 2 {
                    heading_skipped_levels.push(format!("H1 -> H{}", lvl));
                }
                prev_heading_level = Some(lvl);
            }
        }
    }

    let mut schema_found = false;
    let mut schema_json_valid = true;
    for cap in schema_block_re.captures_iter(content) {
        schema_found = true;
        if serde_json::from_str::<serde_json::Value>(&cap[1]).is_err() {
            schema_json_valid = false;
        }
    }

    let mut image_count = 0;
    let mut images_missing_alt = 0;
    for cap in img_re.captures_iter(content) {
        image_count += 1;
        // Missing means no alt attribute at all. Empty alt is valid:
        // it marks decorative images screen readers should skip.
        if !alt_attr_re.is_match(&cap[1]) {
            images_missing_alt += 1;
        }
    }

    let mut internal_links = 0;
    let mut external_links = 0;
    let mut internal_link_targets = Vec::new();
    for cap in a_re.captures_iter(content) {
        let href = cap[1].trim();
        let target = href.split('#').next().unwrap_or("").trim();
        if target.starts_with("http://") || target.starts_with("https://") {
            external_links += 1;
        } else if !target.is_empty() && !target.starts_with('#') && !target.starts_with("mailto:") {
            internal_links += 1;
            internal_link_targets.push(target.to_string());
        }
    }

    // Word count runs on body copy only: head, scripts, and styles are not
    // prose, and counting them inflated depth passes.
    let copy = TAG_RE.replace_all(content, " ");
    let plain_text = strip_html.replace_all(&copy, " ");
    let words: Vec<&str> = plain_text.split_whitespace().collect();
    let word_count = words.len();

    // Opening passage for the GEO window: words before the first H2, which
    // approximates the lede. The old 30%-of-total metric failed every real
    // page by construction.
    let h2_at = Regex::new(r#"(?is)<h2\b"#)
        .ok()
        .and_then(|re| re.find(content))
        .map(|m| m.start())
        .unwrap_or(content.len());
    let lede_clean = TAG_RE.replace_all(&content[..h2_at], " ");
    let lede_text = strip_html.replace_all(&lede_clean, " ");
    let opening_words = lede_text.split_whitespace().count();

    let title_len = title.as_ref().map(|s| s.chars().count()).unwrap_or(0);
    let description_len = description.as_ref().map(|s| s.chars().count()).unwrap_or(0);

    let em_dash_count = content.chars().filter(|&c| c == '\u{2014}').count();
    let ai_slop_words_found = slop_hits(&plain_text);

    let checks = vec![
        check_title_length(title_len),
        check_meta_description(description_len),
        check_h1_uniqueness(h1_count),
        check_heading_hierarchy(&heading_skipped_levels),
        check_content_depth(word_count),
        check_image_alt_tags(image_count, images_missing_alt),
        check_geo_citation_density(opening_words),
        check_ai_slop(em_dash_count, &ai_slop_words_found, word_count),
        check_schema_markup(schema_found),
        check_canonical_reference(canonical_found),
        check_opengraph_metadata(og_tags_found),
    ];

    Ok(AuditReport {
        file_path: path_str.to_string(),
        title,
        title_len,
        description,
        description_len,
        h1_count,
        h2_count,
        h3_count,
        word_count,
        image_count,
        images_missing_alt,
        internal_links,
        external_links,
        schema_found,
        schema_json_valid,
        schema_missing_required: schema_missing_for(content, path_str),
        js_shell: js_shell_for(content, word_count),
        canonical_found,
        og_tags_found,
        geo_opening_words: opening_words,
        heading_skipped_levels,
        em_dash_count,
        ai_slop_words_found,
        internal_link_targets,
        hreflang_alternates,
        noindex,
        uncited_claims: count_uncited_claims(&plain_text),
        checks,
    })
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CannibalizationItem {
    pub keyword_stem: String,
    pub colliding_files: Vec<String>,
}

/// Two pages fighting for one stem. Winner = more words, then lower path.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CannibalizationPair {
    pub keyword_stem: String,
    pub a: String,
    pub b: String,
    pub winner: String,
    pub a_words: usize,
    pub b_words: usize,
}

/// Expand every multi-file stem into explicit A×B pairs for editors.
pub fn cannibalization_pairs(rep: &DirectoryAuditReport) -> Vec<CannibalizationPair> {
    let words_for = |path: &str| -> usize {
        rep.reports
            .iter()
            .find(|r| r.file_path == path)
            .map(|r| r.word_count)
            .unwrap_or(0)
    };
    let mut out = Vec::new();
    for item in &rep.keyword_cannibalization {
        let files = &item.colliding_files;
        for i in 0..files.len() {
            for j in (i + 1)..files.len() {
                let (a, b) = (files[i].clone(), files[j].clone());
                let (aw, bw) = (words_for(&a), words_for(&b));
                let winner = if aw > bw || (aw == bw && a < b) {
                    a.clone()
                } else {
                    b.clone()
                };
                out.push(CannibalizationPair {
                    keyword_stem: item.keyword_stem.clone(),
                    a,
                    b,
                    winner,
                    a_words: aw,
                    b_words: bw,
                });
            }
        }
    }
    out.sort_by(|x, y| {
        x.keyword_stem
            .cmp(&y.keyword_stem)
            .then(x.a.cmp(&y.a))
            .then(x.b.cmp(&y.b))
    });
    out
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DirectoryAuditReport {
    pub dir_path: String,
    pub total_files: usize,
    pub total_words: usize,
    pub avg_words_per_file: usize,
    pub pass_rate: f64,
    pub reports: Vec<AuditReport>,
    pub duplicate_titles: std::collections::HashMap<String, Vec<String>>,
    pub thin_pages: Vec<(String, usize)>,
    pub missing_canonicals: Vec<String>,
    pub missing_descriptions: Vec<String>,
    pub orphan_pages: Vec<String>,
    pub keyword_cannibalization: Vec<CannibalizationItem>,
    #[serde(default)]
    pub findings: Vec<crate::rules::Finding>,
}

pub fn audit_path(path_str: &str) -> Result<DirectoryAuditReport> {
    let path = Path::new(path_str);
    if !path.exists() {
        anyhow::bail!("Path does not exist: {}", path_str);
    }

    if path.is_file() {
        let single = audit_file(path_str)?;
        let total_words = single.word_count;
        let mut missing_canonicals = Vec::new();
        if !single.canonical_found {
            missing_canonicals.push(path_str.to_string());
        }
        let mut missing_descriptions = Vec::new();
        if single.description.is_none() {
            missing_descriptions.push(path_str.to_string());
        }
        let mut thin_pages = Vec::new();
        if single.word_count < MIN_CONTENT_WORDS {
            thin_pages.push((path_str.to_string(), single.word_count));
        }
        let passed = single.checks.iter().filter(|c| c.passed).count();
        let pass_rate = if !single.checks.is_empty() {
            (passed as f64 / single.checks.len() as f64) * 100.0
        } else {
            100.0
        };

        return Ok(with_findings(DirectoryAuditReport {
            dir_path: path_str.to_string(),
            total_files: 1,
            total_words,
            avg_words_per_file: total_words,
            pass_rate,
            reports: vec![single],
            duplicate_titles: std::collections::HashMap::new(),
            thin_pages,
            missing_canonicals,
            missing_descriptions,
            orphan_pages: Vec::new(),
            keyword_cannibalization: Vec::new(),
            findings: Vec::new(),
        }));
    }

    let mut files = Vec::new();
    collect_audit_files(path, &mut files)?;
    files.sort();

    if files.is_empty() {
        anyhow::bail!(
            "No markdown (.md/.mdx) or HTML files found in directory: {}",
            path_str
        );
    }

    let mut reports = Vec::new();
    let mut total_words = 0;
    let mut total_checks = 0;
    let mut total_passed = 0;
    let mut title_map: std::collections::HashMap<String, Vec<String>> =
        std::collections::HashMap::new();
    let mut thin_pages = Vec::new();
    let mut missing_canonicals = Vec::new();
    let mut missing_descriptions = Vec::new();

    for f in &files {
        let p_str = f.to_string_lossy().to_string();
        if let Ok(rep) = audit_file(&p_str) {
            total_words += rep.word_count;
            for c in &rep.checks {
                total_checks += 1;
                if c.passed {
                    total_passed += 1;
                }
            }

            if let Some(t) = &rep.title {
                let clean_t = t.trim().to_string();
                if !clean_t.is_empty() {
                    title_map.entry(clean_t).or_default().push(p_str.clone());
                }
            }

            if rep.word_count < MIN_CONTENT_WORDS {
                thin_pages.push((p_str.clone(), rep.word_count));
            }
            if !rep.canonical_found {
                missing_canonicals.push(p_str.clone());
            }
            if rep.description.is_none() {
                missing_descriptions.push(p_str.clone());
            }

            reports.push(rep);
        }
    }

    let duplicate_titles: std::collections::HashMap<String, Vec<String>> = title_map
        .into_iter()
        .filter(|(_, paths)| paths.len() > 1)
        .collect();

    // Internal Link Graph & Orphan Page Detection
    let mut inbound_map: std::collections::HashMap<String, usize> =
        std::collections::HashMap::new();
    for rep in &reports {
        let rep_norm = rep.file_path.replace('\\', "/");
        let rep_stem = Path::new(&rep.file_path)
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("")
            .to_string();

        for raw_target in &rep.internal_link_targets {
            let clean = raw_target
                .trim()
                .trim_start_matches("./")
                .replace('\\', "/");
            let clean_stem = clean.split('/').next_back().unwrap_or("").to_string();

            for f in &files {
                let f_norm = f.to_string_lossy().replace('\\', "/");
                let f_name = f.file_name().and_then(|n| n.to_str()).unwrap_or("");
                let f_stem = f.file_stem().and_then(|s| s.to_str()).unwrap_or("");

                if (f_norm.ends_with(&clean) || f_name == clean_stem || f_stem == clean_stem)
                    && f_norm != rep_norm
                    && f_name != rep_stem
                {
                    *inbound_map.entry(f_norm.clone()).or_insert(0) += 1;
                }
            }
        }
    }

    let mut orphan_pages = Vec::new();
    if files.len() > 1 {
        for f in &files {
            let f_norm = f.to_string_lossy().replace('\\', "/");
            let f_name = f
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("")
                .to_lowercase();
            // Skip root index / readme as landing entrypoint
            if f_name.starts_with("readme") || f_name.starts_with("index") {
                continue;
            }
            if inbound_map.get(&f_norm).copied().unwrap_or(0) == 0 {
                orphan_pages.push(f.to_string_lossy().to_string());
            }
        }
    }

    // Keyword Cannibalization Radar
    let stop_words: std::collections::HashSet<&str> = [
        "a", "an", "the", "in", "on", "at", "for", "to", "of", "and", "or", "with", "by", "is",
        "vs", "how",
    ]
    .into_iter()
    .collect();

    let mut stem_to_files: std::collections::HashMap<String, Vec<String>> =
        std::collections::HashMap::new();
    for rep in &reports {
        if let Some(title) = &rep.title {
            let words: Vec<String> = title
                .to_lowercase()
                .split(|c: char| !c.is_alphanumeric())
                .filter(|w| !w.is_empty() && !stop_words.contains(w) && w.len() > 2)
                .map(|s| s.to_string())
                .collect();

            if words.len() >= 2 {
                let stem = words[..words.len().min(3)].join(" ");
                stem_to_files
                    .entry(stem)
                    .or_default()
                    .push(rep.file_path.clone());
            }
        }
    }

    let keyword_cannibalization: Vec<CannibalizationItem> = stem_to_files
        .into_iter()
        .filter(|(_, paths)| paths.len() > 1)
        .map(|(keyword_stem, colliding_files)| CannibalizationItem {
            keyword_stem,
            colliding_files,
        })
        .collect();

    let total_files = reports.len();
    let avg_words_per_file = total_words.checked_div(total_files).unwrap_or(0);
    let pass_rate = if total_checks > 0 {
        (total_passed as f64 / total_checks as f64) * 100.0
    } else {
        100.0
    };

    Ok(DirectoryAuditReport {
        dir_path: path_str.to_string(),
        total_files,
        total_words,
        avg_words_per_file,
        pass_rate,
        reports,
        duplicate_titles,
        thin_pages,
        missing_canonicals,
        missing_descriptions,
        orphan_pages,
        keyword_cannibalization,
        findings: Vec::new(),
    })
}

/// Fill rule findings after construction. Shared by live audits and --rescore.
pub fn with_findings(mut rep: DirectoryAuditReport) -> DirectoryAuditReport {
    rep.findings = crate::rules::check_audit(&rep);
    rep
}

fn collect_audit_files(dir: &Path, files: &mut Vec<std::path::PathBuf>) -> Result<()> {
    if dir.is_dir() {
        for entry in std::fs::read_dir(dir)? {
            let entry = entry?;
            let path = entry.path();
            let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
            if file_name.starts_with('.')
                || file_name == "node_modules"
                || file_name == "target"
                || file_name == "dist"
                || file_name == "build"
            {
                continue;
            }
            if path.is_dir() {
                collect_audit_files(&path, files)?;
            } else if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
                if ext == "md" || ext == "mdx" || ext == "markdown" || ext == "html" || ext == "htm"
                {
                    files.push(path);
                }
            }
        }
    }
    Ok(())
}

fn esc(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
}

/// ASCII-fold a line for PDF standard fonts (WinAnsi only).
fn pdf_text(s: &str) -> String {
    s.chars()
        .map(|c| match c {
            '—' | '–' => '-',
            '“' | '”' => '"',
            '‘' | '’' => '\'',
            '…' => '.',
            '▲' => '^',
            '▼' => 'v',
            '✖' | '⚠' => '!',
            c if c.is_ascii() => c,
            _ => '?',
        })
        .collect::<String>()
        .replace('\\', "\\\\")
        .replace('(', "\\(")
        .replace(')', "\\)")
}

/// Minimal multi-page PDF 1.4 writer, std only. Helvetica, A4, 11pt.
fn pdf_lines(title: &str, lines: &[String]) -> Vec<u8> {
    const PER_PAGE: usize = 48;
    let mut pages: Vec<&[String]> = Vec::new();
    let mut i = 0;
    while i < lines.len().max(1) {
        pages.push(&lines[i..(i + PER_PAGE).min(lines.len())]);
        i += PER_PAGE;
        if lines.is_empty() {
            break;
        }
    }
    // Objects: 1 catalog, 2 pages, 3 font, then per page (page, content).
    let mut objs: Vec<Vec<u8>> = Vec::new();
    objs.push(b"<< /Type /Catalog /Pages 2 0 R >>".to_vec());
    let kids: Vec<String> = (0..pages.len())
        .map(|p| format!("{} 0 R", 4 + p * 2))
        .collect();
    objs.push(
        format!(
            "<< /Type /Pages /Kids [{}] /Count {} >>",
            kids.join(" "),
            pages.len()
        )
        .as_bytes()
        .to_vec(),
    );
    objs.push(b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_vec());
    for (pi, chunk) in pages.iter().enumerate() {
        let content_obj = 5 + pi * 2;
        objs.push(
            format!(
                "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << /Font << /F1 3 0 R >> >> /Contents {} 0 R >>",
                content_obj
            )
            .as_bytes()
            .to_vec(),
        );
        let mut stream = String::from("BT /F1 11 Tf 50 790 Td 14 TL ");
        if pi == 0 {
            stream.push_str(&format!("({}) Tj T* ", pdf_text(title)));
        }
        for line in chunk.iter() {
            stream.push_str(&format!("({}) Tj T* ", pdf_text(line)));
        }
        stream.push_str("ET");
        let bytes = stream.as_bytes();
        let mut obj = format!("<< /Length {} >>\nstream\n", bytes.len())
            .as_bytes()
            .to_vec();
        obj.extend_from_slice(bytes);
        obj.extend_from_slice(b"\nendstream");
        objs.push(obj);
    }
    let mut out = b"%PDF-1.4\n".to_vec();
    let mut offsets = Vec::new();
    for (n, body) in objs.iter().enumerate() {
        offsets.push(out.len());
        out.extend_from_slice(format!("{} 0 obj\n", n + 1).as_bytes());
        out.extend_from_slice(body);
        out.extend_from_slice(b"\nendobj\n");
    }
    let xref_at = out.len();
    out.extend_from_slice(format!("xref\n0 {}\n", objs.len() + 1).as_bytes());
    out.extend_from_slice(b"0000000000 65535 f \n");
    for off in &offsets {
        out.extend_from_slice(format!("{:010} 00000 n \n", off).as_bytes());
    }
    out.extend_from_slice(
        format!(
            "trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{}\n%%EOF",
            objs.len() + 1,
            xref_at
        )
        .as_bytes(),
    );
    out
}

/// Markdown twin of to_html: scorecard, pages, findings, method.
pub fn to_markdown(rep: &DirectoryAuditReport) -> String {
    let score = rep.pass_rate.round().clamp(0.0, 100.0) as u32;
    let mut m = String::new();
    m.push_str(&format!(
        "# SEO audit: {}\n\nScore **{}/100 ({})** across {} files and {} words, pass rate {:.1}%.\n",
        rep.dir_path, score, crate::actions::grade(score), rep.total_files, rep.total_words, rep.pass_rate
    ));
    m.push_str("\n## Pages\n\n| Page | Words | Title | Checks |\n|---|---|---|---|\n");
    for r in &rep.reports {
        let passed = r.checks.iter().filter(|c| c.passed).count();
        m.push_str(&format!(
            "| {} | {} | {} | {}/{} |\n",
            r.file_path,
            r.word_count,
            r.title.as_deref().unwrap_or(""),
            passed,
            r.checks.len()
        ));
    }
    if !rep.duplicate_titles.is_empty() {
        m.push_str(&format!(
            "\n## Duplicate titles ({})\n\n",
            rep.duplicate_titles.len()
        ));
        let mut titles: Vec<&String> = rep.duplicate_titles.keys().collect();
        titles.sort();
        for t in titles {
            m.push_str(&format!(
                "- {} ({} files)\n",
                t,
                rep.duplicate_titles[t].len()
            ));
        }
    }
    if !rep.orphan_pages.is_empty() {
        m.push_str(&format!(
            "\n## Orphan pages ({})\n\n",
            rep.orphan_pages.len()
        ));
        for f in &rep.orphan_pages {
            m.push_str(&format!("- {}\n", f));
        }
    }
    if !rep.thin_pages.is_empty() {
        m.push_str(&format!("\n## Thin pages ({})\n\n", rep.thin_pages.len()));
        for (f, wc) in &rep.thin_pages {
            m.push_str(&format!("- {} ({} words)\n", f, wc));
        }
    }
    if !rep.keyword_cannibalization.is_empty() {
        m.push_str(&format!(
            "\n## Keyword cannibalization ({})\n\n",
            rep.keyword_cannibalization.len()
        ));
        for item in &rep.keyword_cannibalization {
            m.push_str(&format!(
                "- {} ({} pages)\n",
                item.keyword_stem,
                item.colliding_files.len()
            ));
        }
        let pairs = cannibalization_pairs(rep);
        if !pairs.is_empty() {
            m.push_str(&format!("\n### Conflict pairs ({})\n\n", pairs.len()));
            m.push_str(
                "| Stem | A | B | A words | B words | Keep |\n|---|---|---|---:|---:|---|\n",
            );
            for p in pairs.iter().take(20) {
                m.push_str(&format!(
                    "| {} | {} | {} | {} | {} | {} |\n",
                    p.keyword_stem, p.a, p.b, p.a_words, p.b_words, p.winner
                ));
            }
        }
    }
    // Offline rescore hint for agents: same JSON via --rescore.
    m.push_str("\n## Trend\n\nOffline rescore: `jev-seo audit <dir> --rescore audit.json --json`. Per-target GEO history in `geo_history`, sparkline `<svg>` in HTML/PDF.\n");
    m.push_str("\n## Method\n\nOn-page checks per file, duplicate titles, orphan link graph, thin-page and cannibalization radar. Scores rank work; they never predict rankings or traffic.\n");
    m.push_str("\n## How to read this report\n\nFindings marked fact were measured directly (status codes, missing tags, counts). Findings marked heuristic are threshold guesses that can fire on healthy pages: re-check those by hand before acting. Any Jev semantic lines carry their model and confidence; below-confidence answers print as notes, not scores. A recommendation failed when its evidence is missing: that is the falsifiability test. Rule set version rides `run.json`.\n");
    m.push_str("\n## Completeness\n\nLocal file walk only. Jev and live crawl are not part of this report unless run separately. Companion artifacts: `run.json`, `ledger.json`.\n");
    m
}

/// Agent digest: score, top actions each with evidence and a concrete
/// verify line (re-audit shows the action id resolved), watch counts,
/// limits. The handoff an agent loop reads instead of the full report.
pub fn digest(rep: &DirectoryAuditReport, actions: &[crate::actions::Action]) -> String {
    let score = rep.pass_rate.round().clamp(0.0, 100.0) as u32;
    let mut m = String::new();
    m.push_str(&format!(
        "# Digest: {} — {}/100 ({})\n\n{} files, {} words, {} findings.\n",
        rep.dir_path,
        score,
        crate::actions::grade(score),
        rep.total_files,
        rep.total_words,
        rep.findings.len()
    ));
    let top = crate::actions::top(actions, 5);
    if top.is_empty() {
        m.push_str("\n## Do first\n\nNothing: directory is clean.\n");
    } else {
        m.push_str("\n## Do first\n\n");
        for a in top {
            let ev: String = a.evidence.chars().take(200).collect();
            m.push_str(&format!(
                "- [P{}] {} {} (effort {}, impact {}){}\n  evidence: {}\n  verify: re-audit; `{}` absent from findings\n",
                a.priority,
                a.id,
                a.title,
                a.effort,
                a.impact,
                if a.quick_win { " quick-win" } else { "" },
                ev,
                a.id
            ));
        }
    }
    m.push_str(&format!(
        "\n## Watch\n\n- duplicate titles: {}\n- orphan pages: {}\n- thin pages: {}\n- missing canonicals: {}\n",
        rep.duplicate_titles.len(),
        rep.orphan_pages.len(),
        rep.thin_pages.len(),
        rep.missing_canonicals.len()
    ));
    m.push_str("\n## Limits\n\nLocal file walk only. Scores rank work; they never predict rankings or traffic. Fact findings were measured; heuristic ones need a human re-check before acting.\n");
    m
}

/// Canonical close: digest + conflict pairs + drift alerts in one file.
/// The single artifact an audit ends with; agents and owners read the same.
pub fn bundle_markdown(
    rep: &DirectoryAuditReport,
    actions: &[crate::actions::Action],
    drift: &[crate::rank::DriftAlert],
) -> String {
    let mut m = digest(rep, actions);
    let pairs = cannibalization_pairs(rep);
    if !pairs.is_empty() {
        m.push_str(&format!("\n## Merge candidates ({})\n\n", pairs.len()));
        m.push_str("| Stem | A | B | Keep |\n|---|---|---|---|\n");
        for p in pairs.iter().take(20) {
            m.push_str(&format!(
                "| {} | {} | {} | {} |\n",
                p.keyword_stem, p.a, p.b, p.winner
            ));
        }
    }
    if !drift.is_empty() {
        m.push_str("\n## Drift since last check\n\n");
        for d in drift {
            m.push_str(&format!(
                "- {}: {} `{}` ({} → {})\n",
                d.kind, d.target, d.term, d.from, d.to
            ));
        }
    }
    m
}

/// PDF with an embedded narrative block when present.
pub fn to_pdf_with_narrative(
    rep: &DirectoryAuditReport,
    n: &crate::narrative::Narrative,
) -> Vec<u8> {
    to_pdf_opt(rep, Some(n))
}

/// Deck section 1: cover with score and grade.
pub fn pdf_cover(rep: &DirectoryAuditReport) -> Vec<String> {
    let score = rep.pass_rate.round().clamp(0.0, 100.0) as u32;
    vec![
        "jev-seo audit report".to_string(),
        format!("Target: {}", rep.dir_path),
        format!("Score: {}/100 ({})", score, crate::actions::grade(score)),
        format!(
            "Files: {}  Words: {}  Pass rate: {:.1}%",
            rep.total_files, rep.total_words, rep.pass_rate
        ),
    ]
}

/// Deck section 2: scorecard totals plus ranked impact list.
pub fn pdf_scorecard(rep: &DirectoryAuditReport) -> Vec<String> {
    let mut lines = vec!["Scorecard:".to_string()];
    lines.push(format!(
        "Files walked: {}  Words: {}  Avg words/file: {}",
        rep.total_files, rep.total_words, rep.avg_words_per_file
    ));
    lines.push(format!(
        "Findings recorded: {}  Duplicate titles: {}  Orphans: {}  Thin pages: {}",
        rep.findings.len(),
        rep.duplicate_titles.len(),
        rep.orphan_pages.len(),
        rep.thin_pages.len()
    ));
    lines.push(String::new());
    lines.push("Top actions by impact:".to_string());
    let actions = crate::rules::actions_for(&rep.findings);
    if actions.is_empty() {
        lines.push("- none, directory is clean".to_string());
    }
    for a in actions.iter().take(8) {
        lines.push(format!(
            "- [P{}] {}  impact {}  effort {}{}",
            a.priority,
            a.id,
            a.impact,
            a.effort,
            if a.quick_win { "  quick-win" } else { "" }
        ));
    }
    lines
}

/// Deck section 3: findings grouped by area with severity.
pub fn pdf_findings_by_area(rep: &DirectoryAuditReport) -> Vec<String> {
    use std::collections::BTreeMap;
    let mut lines = vec!["Findings by area:".to_string()];
    if rep.findings.is_empty() {
        lines.push("- none".to_string());
        return lines;
    }
    let mut by_area: BTreeMap<String, Vec<&crate::rules::Finding>> = BTreeMap::new();
    for f in &rep.findings {
        by_area
            .entry(crate::rules::label(&f.area).to_string())
            .or_default()
            .push(f);
    }
    for (area, list) in &by_area {
        lines.push(format!("{} ({}):", area, list.len()));
        for f in list.iter().take(8) {
            lines.push(format!("- {} {:?} {}", f.rule_id, f.severity, f.scope));
        }
    }
    lines
}

/// Deck section 4: page inventory with per-page check counts.
pub fn pdf_inventory(rep: &DirectoryAuditReport) -> Vec<String> {
    let mut lines = vec!["Page inventory (path | words | title | checks):".to_string()];
    for r in &rep.reports {
        let passed = r.checks.iter().filter(|c| c.passed).count();
        lines.push(format!(
            "- {} | {}w | {} | {}/{}",
            r.file_path,
            r.word_count,
            r.title.as_deref().unwrap_or(""),
            passed,
            r.checks.len()
        ));
    }
    if !rep.duplicate_titles.is_empty() {
        lines.push(String::new());
        lines.push(format!(
            "Duplicate titles ({}):",
            rep.duplicate_titles.len()
        ));
        let mut titles: Vec<&String> = rep.duplicate_titles.keys().collect();
        titles.sort();
        for t in titles.iter().take(10) {
            lines.push(format!(
                "- {} ({} files)",
                t,
                rep.duplicate_titles[*t].len()
            ));
        }
    }
    if !rep.orphan_pages.is_empty() {
        lines.push(String::new());
        lines.push(format!("Orphan pages ({}):", rep.orphan_pages.len()));
        for f in rep.orphan_pages.iter().take(10) {
            lines.push(format!("- {}", f));
        }
    }
    if !rep.thin_pages.is_empty() {
        lines.push(String::new());
        lines.push(format!("Thin pages ({}):", rep.thin_pages.len()));
        for (f, wc) in rep.thin_pages.iter().take(10) {
            lines.push(format!("- {} ({} words)", f, wc));
        }
    }
    lines
}

/// Deck section 5: narrative block when present.
pub fn pdf_narrative(n: &crate::narrative::Narrative) -> Vec<String> {
    let mut lines = vec!["Narrative:".to_string()];
    if n.automatic {
        lines.push("(automatic evidence-only summary)".to_string());
    }
    for p in &n.executive_summary {
        lines.push(p.clone());
    }
    if !n.risks.is_empty() {
        lines.push("Risks:".to_string());
        for r in &n.risks {
            lines.push(format!("- {}", r));
        }
    }
    if !n.unverified_numbers.is_empty() {
        lines.push(format!(
            "Warning: numbers not in audit: {}",
            n.unverified_numbers.join(", ")
        ));
    }
    lines
}

/// Deck section 6: method appendix, same facts as the Markdown twin.
pub fn pdf_method() -> Vec<String> {
    vec![
        "Method:".to_string(),
        "On-page checks per file, duplicate titles, orphan link graph, thin-page and cannibalization radar.".to_string(),
        "Scores rank work; they never predict rankings or traffic.".to_string(),
        "Completeness: local file walk; Jev and live crawl not in this report.".to_string(),
        "Companion files: run.json, ledger.json.".to_string(),
    ]
}

/// Inline SVG sparkline from integer series. Std only. 0..100 scaled to 20px height.
/// ponytail: no chart dep, <svg> polyline only
pub fn sparkline_svg(values: &[u32], width: u32) -> String {
    if values.len() < 2 {
        return String::new();
    }
    let w = width.max(60) as f64;
    let h = 20.0;
    let max = *values.iter().max().unwrap().max(&1) as f64;
    let min = *values.iter().min().unwrap() as f64;
    let range = (max - min).max(1.0);
    let step = w / (values.len() - 1) as f64;
    let pts: Vec<String> = values
        .iter()
        .enumerate()
        .map(|(i, v)| {
            let x = i as f64 * step;
            let y = h - ((*v as f64 - min) / range * (h - 4.0) + 2.0);
            format!("{:.1},{:.1}", x, y)
        })
        .collect();
    format!("<svg width=\"{width}\" height=\"20\" viewBox=\"0 0 {width} 20\" xmlns=\"http://www.w3.org/2000/svg\"><polyline fill=\"none\" stroke=\"#f386a1\" stroke-width=\"1.5\" points=\"{}\"/></svg>", pts.join(" "))
}

/// Embed GEO/score sparkline in PDF deck when trend history exists.
fn pdf_trend(db_target: &str) -> Vec<String> {
    let Ok(db) = crate::rank::DbStore::open() else {
        return Vec::new();
    };
    let Ok(vals) = db.geo_trend(db_target, 12) else {
        return Vec::new();
    };
    if vals.len() < 2 {
        return Vec::new();
    }
    vec![format!(
        "Trend {}: {}",
        db_target,
        vals.iter()
            .map(|v| v.to_string())
            .collect::<Vec<_>>()
            .join(" → ")
    )]
}

pub(crate) fn to_pdf_opt(
    rep: &DirectoryAuditReport,
    n: Option<&crate::narrative::Narrative>,
) -> Vec<u8> {
    let mut lines = pdf_cover(rep);
    lines.extend(pdf_trend(&rep.dir_path));
    lines.push(String::new());
    lines.extend(pdf_scorecard(rep));
    lines.push(String::new());
    lines.extend(pdf_findings_by_area(rep));
    lines.push(String::new());
    lines.extend(pdf_inventory(rep));
    if let Some(n) = n {
        lines.push(String::new());
        lines.extend(pdf_narrative(n));
    }
    lines.push(String::new());
    lines.extend(pdf_method());
    pdf_lines(&format!("jev-seo audit report: {}", rep.dir_path), &lines)
}

/// Single-file HTML report for humans. Same numbers as the JSON output.
pub fn to_html(rep: &DirectoryAuditReport) -> String {
    let score = rep.pass_rate.round().clamp(0.0, 100.0) as u32;
    let grade = crate::actions::grade(score);
    let mut h = String::new();
    h.push_str("<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\">");
    h.push_str("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
    h.push_str("<title>jev-seo audit report</title>");
    h.push_str("<style>:root{--pink:#f386a1;--ink:#111;--mut:#666;--line:#e2e2e2}body{font-family:system-ui,-apple-system,sans-serif;color:var(--ink);max-width:960px;margin:0 auto;padding:2rem 1rem;line-height:1.55}.hero{background:#111;color:#fff;border-radius:10px;padding:2rem;display:flex;gap:2rem;align-items:center;flex-wrap:wrap}.grade{font-size:4rem;font-weight:800;background:var(--pink);color:#111;border-radius:10px;min-width:6rem;text-align:center}.meta{font-size:.9rem;color:#bbb}table{border-collapse:collapse;width:100%;margin-top:1rem}th,td{border:1px solid var(--line);padding:.45rem .65rem;text-align:left;font-size:.9rem}th{background:#f6f6f6}h2{margin-top:2.2rem;font-size:1.15rem;border-bottom:2px solid var(--pink);display:inline-block}ul{padding-left:1.2rem}.foot{margin-top:2.5rem;font-size:.8rem;color:var(--mut);border-top:1px solid var(--line);padding-top:1rem}code{background:#f1f1f1;padding:.1rem .35rem;border-radius:4px;font-size:.85em}</style>");
    h.push_str("</head><body>");
    h.push_str(&format!(
        "<div class=\"hero\"><div class=\"grade\">{}</div><div><h1 style=\"margin:0;font-size:1.5rem\">SEO audit: {}</h1><p class=\"meta\">{} files | {} words | pass rate {:.1}% | score {}/100</p></div></div>",
        grade,
        esc(&rep.dir_path),
        rep.total_files,
        rep.total_words,
        rep.pass_rate,
        score
    ));
    h.push_str("<h2>Pages</h2><table><tr><th>Page</th><th>Words</th><th>Title</th><th>Checks passed</th></tr>");
    for r in &rep.reports {
        let passed = r.checks.iter().filter(|c| c.passed).count();
        h.push_str(&format!(
            "<tr><td>{}</td><td>{}</td><td>{}</td><td>{}/{}</td></tr>",
            esc(&r.file_path),
            r.word_count,
            esc(r.title.as_deref().unwrap_or("")),
            passed,
            r.checks.len()
        ));
    }
    h.push_str("</table>");
    if !rep.duplicate_titles.is_empty() {
        h.push_str("<h2>Duplicate titles</h2><ul>");
        let mut titles: Vec<&String> = rep.duplicate_titles.keys().collect();
        titles.sort();
        for t in titles {
            h.push_str(&format!(
                "<li>{} ({} files)</li>",
                esc(t),
                rep.duplicate_titles[t].len()
            ));
        }
        h.push_str("</ul>");
    }
    if !rep.orphan_pages.is_empty() {
        h.push_str(&format!(
            "<h2>Orphan pages ({})</h2><ul>",
            rep.orphan_pages.len()
        ));
        for f in &rep.orphan_pages {
            h.push_str(&format!("<li>{}</li>", esc(f)));
        }
        h.push_str("</ul>");
    }
    if !rep.thin_pages.is_empty() {
        h.push_str(&format!(
            "<h2>Thin pages ({})</h2><ul>",
            rep.thin_pages.len()
        ));
        for (f, wc) in &rep.thin_pages {
            h.push_str(&format!("<li>{} ({} words)</li>", esc(f), wc));
        }
        h.push_str("</ul>");
    }
    if !rep.keyword_cannibalization.is_empty() {
        h.push_str("<h2>Keyword cannibalization</h2><ul>");
        for item in &rep.keyword_cannibalization {
            h.push_str(&format!(
                "<li>{} ({} pages)</li>",
                esc(&item.keyword_stem),
                item.colliding_files.len()
            ));
        }
        h.push_str("</ul>");
    }
    if let Ok(db) = crate::rank::DbStore::open() {
        if let Ok(vals) = db.geo_trend(&rep.dir_path, 12) {
            let svg = sparkline_svg(&vals, 320);
            if !svg.is_empty() {
                h.push_str(&format!("<h2>Trend</h2>{}", svg));
            }
        }
    }
    h.push_str("<div class=\"foot\">Generated locally by <code>jev-seo audit --html</code>. Scores rank work; they never predict rankings or traffic. Method: on-page checks per file, duplicate titles, orphan detection via internal link graph, thin-page and cannibalization radar. Completeness: local file walk; Jev and live crawl not part of this report unless run separately. Companion files: <code>run.json</code>, <code>ledger.json</code>. Offline rescore: <code>jev-seo audit &lt;dir&gt; --rescore audit.json</code>.</div>");
    h.push_str("</body></html>");
    h
}