lectito 0.3.0

Article extraction and readability parsing for Lectito.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
use std::collections::HashMap;

use kuchiki::NodeRef;
use kuchiki::traits::TendrilSink;
use scraper::Html;
use url::Url;

use crate::shared;

use super::config::{Article, ExtractFlags, ReadabilityOptions};
use super::diagnostics::{
    AttemptDiagnostic, CandidateDiagnostic, CandidateSelection, CleanupDiagnostic, ContentSelectorDiagnostic,
    ExtractionDiagnostics, ExtractionOutcome, ExtractionReport, FlagDiagnostic, NodeDiagnostic, RecoveryDiagnostic,
    SiteRuleSource,
};
use super::error::{Error, Result};
use super::regexes::RegexPattern;
use super::{cleanup, dom, json_schema, markdown, metadata, normalize, patterns, recovery, rules, scoring, serialize};
use super::{metadata::Metadata, scoring::Candidate};

const KNOWN_CONTENT_SELECTORS: &[&str] = &[
    "#article-body",
    "[itemprop='articleBody']",
    ".article-body",
    ".article__body",
    ".article-content",
    ".article__content",
    ".articleContent",
    ".entry-content",
    ".post-content",
    ".content-wrapper",
];
const USEFUL_WORD_THRESHOLD: usize = 180;
const EXTREMELY_SHORT_WORD_THRESHOLD: usize = 80;
const SUSPICIOUS_SIGNAL_RATIO: usize = 3;
const ENTRY_POINT_SELECTORS: &[&str] = &[
    "article",
    "main",
    r#"[role="main"]"#,
    "#content",
    "#main",
    "#article",
    ".content",
    ".main",
    ".article",
    ".post",
    ".entry-content",
];

pub struct ExtractAttempt {
    pub metadata: Metadata,
    pub content: String,
    pub text_content: String,
    pub text_len: usize,
}

impl From<ExtractAttempt> for Article {
    fn from(attempt: ExtractAttempt) -> Self {
        let mut metadata = attempt.metadata;
        if title_duplicates_site_name(&metadata)
            && let Some(heading) = first_content_heading(&attempt.content)
        {
            metadata.title = Some(heading);
        }

        if metadata.excerpt.as_deref().unwrap_or_default().trim().is_empty() {
            metadata.excerpt = metadata::first_paragraph_excerpt(&attempt.content);
        }

        Article {
            title: metadata.title,
            byline: metadata.byline,
            dir: metadata.dir,
            lang: metadata.lang,
            markdown: markdown::html_to_markdown(&attempt.content),
            content: attempt.content,
            text_content: attempt.text_content,
            length: attempt.text_len,
            excerpt: metadata.excerpt,
            site_name: metadata.site_name,
            published_time: metadata.published_time,
            image: metadata.image,
            domain: metadata.domain,
            favicon: metadata.favicon,
        }
    }
}

impl From<Metadata> for ExtractAttempt {
    fn from(metadata: Metadata) -> Self {
        Self { metadata, content: String::new(), text_content: String::new(), text_len: 0 }
    }
}

struct GrabDiagnostics {
    attempt: AttemptDiagnostic,
    content_selector: Option<ContentSelectorDiagnostic>,
}

impl From<ExtractFlags> for FlagDiagnostic {
    fn from(flags: ExtractFlags) -> Self {
        Self {
            strip_unlikely: flags.strip_unlikely,
            weight_classes: flags.weight_classes,
            clean_conditionally: flags.clean_conditionally,
        }
    }
}

struct EntryPointCandidate {
    node: NodeRef,
    score: f64,
    diagnostic: CandidateDiagnostic,
}

#[derive(Clone, Copy)]
struct AttemptConfig {
    flags: ExtractFlags,
    remove_hidden: bool,
}

/// Extract a readable article from an HTML document.
///
/// `base_url` is optional. Pass it when the document contains relative links,
/// images, or metadata URLs. The function returns `Ok(None)` when the document
/// parses but no useful article content is found.
pub fn extract(html: &str, base_url: Option<&str>, options: &ReadabilityOptions) -> Result<Option<Article>> {
    Ok(extract_with_diagnostics(html, base_url, options)?.article)
}

/// Extract and return only the cleaned article HTML.
///
/// This is a convenience wrapper around [`extract`].
pub fn clean_article_html(html: &str, base_url: Option<&str>, options: &ReadabilityOptions) -> Result<Option<String>> {
    Ok(extract(html, base_url, options)?.map(|article| article.content))
}

/// Extract an article and include diagnostics for root selection and cleanup.
///
/// Diagnostics are intended for fixture work, site-profile tuning, and bug
/// reports. Most application code should call [`extract`].
pub fn extract_with_diagnostics(
    html: &str, base_url: Option<&str>, options: &ReadabilityOptions,
) -> Result<ExtractionReport> {
    let (working_html, source_recovery) = recovery::recover_html_snapshot(html);
    let html = working_html.as_str();
    let base_url = base_url
        .map(|base_url| Url::parse(base_url).map_err(|_| Error::InvalidBaseUrl(base_url.to_string())))
        .transpose()?;

    let document = Html::parse_document(html);
    enforce_element_limit(&document, options.max_elems_to_parse)?;
    let base_url = effective_base_url(&document, base_url.as_ref());

    let metadata = metadata::extract_metadata(&document, html, options, base_url.as_ref());
    let extraction_html = strip_raw_script_blocks(html);
    let mut best_attempt: Option<ExtractAttempt> = None;
    let mut diagnostics = ExtractionDiagnostics::default();

    if options.content_selector.is_none()
        && let Some((mut attempt, attempt_diagnostic)) =
            known_content_attempt(&extraction_html, options, base_url.as_ref(), &metadata)?
    {
        attempt.metadata = metadata;
        diagnostics.selected_attempt = Some(0);
        diagnostics.outcome = ExtractionOutcome::Accepted;
        diagnostics.attempts.push(attempt_diagnostic);
        return Ok(ExtractionReport { article: Some(attempt.into()), diagnostics });
    }

    let schema_text_has_markup = metadata.schema_text.as_deref().is_some_and(schema_text_contains_html);
    if (schema_text_has_markup || !source_has_rich_article_content(&extraction_html))
        && let Some((mut attempt, attempt_diagnostic)) = schema_text_attempt(&metadata, options, base_url.as_ref())?
    {
        attempt.metadata = metadata;
        diagnostics.selected_attempt = Some(0);
        diagnostics.outcome = ExtractionOutcome::Accepted;
        diagnostics.attempts.push(attempt_diagnostic);
        return Ok(ExtractionReport { article: Some(attempt.into()), diagnostics });
    }

    if let Some(mut rule_extraction) = try_site_rule(html, options, base_url.as_ref(), &metadata)?
        && rule_extraction.attempt.text_len > 0
    {
        let attempt_metadata = rule_extraction.attempt.metadata.clone();
        rule_extraction.attempt = json_schema::apply_schema_fallback(
            html,
            rule_extraction.attempt,
            &attempt_metadata,
            options,
            rule_extraction.flags,
            base_url.as_ref(),
        )?;
        rule_extraction.diagnostic.text_len = rule_extraction.attempt.text_len;
        rule_extraction.diagnostic.accepted =
            matches!(rule_extraction.diagnostic.source, SiteRuleSource::CodeExtractor)
                || rule_extraction.attempt.text_len >= options.char_threshold;
        if rule_extraction.diagnostic.accepted {
            diagnostics.site_rule = Some(rule_extraction.diagnostic);
            diagnostics.outcome = ExtractionOutcome::Accepted;
            return Ok(ExtractionReport { article: Some(rule_extraction.attempt.into()), diagnostics });
        }
        rule_extraction.diagnostic.fallback_reason = Some(format!(
            "site rule text_len {} below char_threshold {}",
            rule_extraction.attempt.text_len, options.char_threshold
        ));
        diagnostics.site_rule = Some(rule_extraction.diagnostic);
        best_attempt = Some(rule_extraction.attempt);
    }

    let attempts = [
        AttemptConfig { flags: ExtractFlags::all(), remove_hidden: true },
        AttemptConfig {
            flags: ExtractFlags { strip_unlikely: false, weight_classes: true, clean_conditionally: true },
            remove_hidden: true,
        },
        AttemptConfig {
            flags: ExtractFlags { strip_unlikely: false, weight_classes: false, clean_conditionally: true },
            remove_hidden: true,
        },
        AttemptConfig {
            flags: ExtractFlags { strip_unlikely: false, weight_classes: false, clean_conditionally: false },
            remove_hidden: true,
        },
        AttemptConfig {
            flags: ExtractFlags { strip_unlikely: false, weight_classes: false, clean_conditionally: false },
            remove_hidden: false,
        },
    ];

    for (index, config) in attempts.into_iter().enumerate() {
        let dom = kuchiki::parse_html().one(extraction_html.as_ref());
        let flags = config.flags;
        let mut recovery = prep_document_with_visibility(&dom, options, flags, config.remove_hidden);
        recovery.shadow_roots_flattened += source_recovery.shadow_roots_flattened;

        let Some((mut attempt, attempt_diagnostic)) = grab_article(
            &dom,
            options,
            flags,
            index,
            recovery.clone(),
            base_url.as_ref(),
            &metadata,
        )?
        else {
            diagnostics.attempts.push(AttemptDiagnostic {
                index,
                flags: flags.into(),
                candidate_count: 0,
                candidates: Vec::new(),
                entry_points: Vec::new(),
                selected_root: None,
                cleanup: None,
                recovery,
                text_len: 0,
                accepted: false,
            });
            continue;
        };

        if diagnostics.content_selector.is_none() {
            diagnostics.content_selector = attempt_diagnostic.content_selector.clone();
        }
        diagnostics.attempts.push(attempt_diagnostic.attempt);
        let diagnostic_index = diagnostics.attempts.len() - 1;

        if attempt.text_len >= options.char_threshold
            && !should_retry_short_or_suspicious(
                &attempt,
                &diagnostics.attempts[diagnostic_index],
                flags,
                config.remove_hidden,
                options,
            )
        {
            attempt.metadata = metadata.clone();
            attempt = json_schema::apply_schema_fallback(html, attempt, &metadata, options, flags, base_url.as_ref())?;
            diagnostics.selected_attempt = Some(diagnostic_index);
            diagnostics.outcome = ExtractionOutcome::Accepted;
            return Ok(ExtractionReport { article: Some(attempt.into()), diagnostics });
        }

        if best_attempt
            .as_ref()
            .map(|best| attempt.text_len > best.text_len)
            .unwrap_or(true)
        {
            diagnostics.selected_attempt = Some(diagnostic_index);
            best_attempt = Some(attempt);
        }
    }

    let Some(mut attempt) = best_attempt.filter(|attempt| attempt.text_len > 0) else {
        diagnostics.outcome = ExtractionOutcome::NoContent;
        return Ok(ExtractionReport { article: None, diagnostics });
    };
    attempt.metadata = metadata.clone();
    attempt = json_schema::apply_schema_fallback(
        html,
        attempt,
        &metadata,
        options,
        ExtractFlags { strip_unlikely: false, weight_classes: false, clean_conditionally: false },
        base_url.as_ref(),
    )?;
    diagnostics.outcome = ExtractionOutcome::BestAttempt;
    Ok(ExtractionReport { article: Some(attempt.into()), diagnostics })
}

pub fn prep_document(document: &NodeRef, options: &ReadabilityOptions, flags: ExtractFlags) -> RecoveryDiagnostic {
    prep_document_with_visibility(document, options, flags, true)
}

fn prep_document_with_visibility(
    document: &NodeRef, options: &ReadabilityOptions, flags: ExtractFlags, remove_hidden: bool,
) -> RecoveryDiagnostic {
    let recovery = recovery::recover(document, options.mobile_viewport_width);
    unwrap_noscript_images(document);
    dom::remove_matching(document, "script, style");
    normalize_markup(document);

    if flags.strip_unlikely {
        let nodes = dom::select_nodes(document, "*");
        for node in nodes {
            if (remove_hidden && !dom::is_kuchiki_visible(&node)) || dom::has_unlikely_role(&node) {
                node.detach();
                continue;
            }

            let tag = dom::node_name(&node);
            if tag == "body" || tag == "a" {
                continue;
            }

            let match_string = dom::class_id_string(&node);
            if RegexPattern::UnlikelyCandidates.to_regex().is_match(&match_string)
                && !RegexPattern::MaybeCandidate.to_regex().is_match(&match_string)
                && !dom::has_ancestor_tag(&node, "table", 3)
                && !dom::has_ancestor_tag(&node, "code", 3)
            {
                node.detach();
            }
        }
    } else {
        let nodes = dom::select_nodes(document, "*");
        for node in nodes {
            if remove_hidden && !dom::is_kuchiki_visible(&node) {
                node.detach();
            }
        }
    }
    recovery
}

pub fn serialize_roots(
    roots: Vec<NodeRef>, opts: &ReadabilityOptions, flags: ExtractFlags, base_url: Option<&Url>, metadata: &Metadata,
) -> Result<(ExtractAttempt, CleanupDiagnostic)> {
    let text_len_before = serialize::text_content(&roots).encode_utf16().count();
    let element_count_before = roots.iter().map(element_count).sum();
    let root_selectors = roots.iter().map(node_selector).collect();

    cleanup::cleanup_article(&roots, opts, flags, base_url, metadata);
    normalize::normalize_article(&roots, metadata.title.as_deref());
    let roots = cleanup::remove_trailing_chrome_roots(roots);

    let mut content = String::from(r#"<div id="readability-page-1" class="page">"#);
    for node in &roots {
        if dom::node_name(node) == "body" {
            content.push_str(&serialize::serialize_children(node)?);
        } else {
            content.push_str(&serialize::serialize_node(node)?);
        }
    }
    content.push_str("</div>");
    let text_content = serialize::text_content(&roots);
    let text_len = text_content.encode_utf16().count();
    let element_count_after = roots.iter().map(element_count).sum();

    let attempt = ExtractAttempt { metadata: Metadata::default(), content, text_content, text_len };
    let cleanup = CleanupDiagnostic {
        roots: root_selectors,
        text_len_before,
        text_len_after: text_len,
        element_count_before,
        element_count_after,
        removed_elements: element_count_before.saturating_sub(element_count_after),
    };

    Ok((attempt, cleanup))
}

pub fn element_count(node: &NodeRef) -> usize {
    node.descendants().filter(|node| node.as_element().is_some()).count()
}

fn strip_raw_script_blocks(html: &str) -> String {
    RegexPattern::RawScript.to_regex().replace_all(html, "").into_owned()
}

fn should_retry_short_or_suspicious(
    attempt: &ExtractAttempt, diagnostic: &AttemptDiagnostic, flags: ExtractFlags, remove_hidden: bool,
    options: &ReadabilityOptions,
) -> bool {
    flags != (ExtractFlags { strip_unlikely: false, weight_classes: false, clean_conditionally: false })
        && (short_after_unlikely_stripping(attempt, flags)
            || far_below_best_content_signal(attempt.text_len, diagnostic, options.char_threshold))
        || (remove_hidden && extremely_short(attempt))
}

fn short_after_unlikely_stripping(attempt: &ExtractAttempt, flags: ExtractFlags) -> bool {
    flags.strip_unlikely && shared::word_count(&attempt.text_content) < USEFUL_WORD_THRESHOLD
}

fn extremely_short(attempt: &ExtractAttempt) -> bool {
    shared::word_count(&attempt.text_content) < EXTREMELY_SHORT_WORD_THRESHOLD
}

fn far_below_best_content_signal(text_len: usize, diagnostic: &AttemptDiagnostic, char_threshold: usize) -> bool {
    if text_len >= char_threshold.saturating_mul(4).max(2_000) {
        return false;
    }

    best_content_signal_len(diagnostic) >= char_threshold.saturating_mul(2).max(1)
        && text_len.saturating_mul(SUSPICIOUS_SIGNAL_RATIO) < best_content_signal_len(diagnostic)
}

fn best_content_signal_len(diagnostic: &AttemptDiagnostic) -> usize {
    diagnostic
        .selected_root
        .iter()
        .chain(diagnostic.candidates.iter().map(|candidate| &candidate.node))
        .chain(diagnostic.entry_points.iter().map(|entry_point| &entry_point.node))
        .map(|node| node.text_len)
        .max()
        .unwrap_or(0)
}

fn known_content_attempt(
    html: &str, opts: &ReadabilityOptions, base_url: Option<&Url>, metadata: &Metadata,
) -> Result<Option<(ExtractAttempt, AttemptDiagnostic)>> {
    let document = kuchiki::parse_html().one(html);
    let flags = ExtractFlags { strip_unlikely: false, weight_classes: false, clean_conditionally: false };

    for selector in KNOWN_CONTENT_SELECTORS {
        let roots = dom::select_nodes(&document, selector);
        for root in roots {
            let recovery = recovery::recover(&root, opts.mobile_viewport_width);
            unwrap_noscript_images(&root);
            dom::remove_matching(&root, "script, style");
            normalize_markup(&root);
            let selected_root = node_diagnostic(&root);
            let (attempt, cleanup) = serialize_roots(vec![root], opts, flags, base_url, metadata)?;
            if attempt.text_len < opts.char_threshold {
                continue;
            }

            let diagnostic = AttemptDiagnostic {
                index: 0,
                flags: flags.into(),
                candidate_count: 0,
                candidates: Vec::new(),
                entry_points: Vec::new(),
                selected_root: Some(selected_root),
                cleanup: Some(cleanup),
                recovery,
                text_len: attempt.text_len,
                accepted: true,
            };
            return Ok(Some((attempt, diagnostic)));
        }
    }

    Ok(None)
}

fn schema_text_attempt(
    metadata: &Metadata, opts: &ReadabilityOptions, base_url: Option<&Url>,
) -> Result<Option<(ExtractAttempt, AttemptDiagnostic)>> {
    let Some(schema_text) = metadata.schema_text.as_deref() else {
        return Ok(None);
    };

    let normalized = patterns::normalize_spaces(schema_text.trim());
    if normalized.encode_utf16().count() < opts.char_threshold {
        return Ok(None);
    }

    let document = if schema_text_contains_html(&normalized) {
        kuchiki::parse_html().one(format!("<html><body><article>{normalized}</article></body></html>"))
    } else {
        kuchiki::parse_html().one(format!(
            "<html><body><article><p>{}</p></article></body></html>",
            shared::escape_html(&normalized)
        ))
    };
    let Some(root) = dom::select_nodes(&document, "article").into_iter().next() else {
        return Ok(None);
    };

    let selected_root = node_diagnostic(&root);
    let flags = ExtractFlags { strip_unlikely: false, weight_classes: false, clean_conditionally: false };
    let (attempt, cleanup) = serialize_roots(vec![root], opts, flags, base_url, metadata)?;
    if attempt.text_len < opts.char_threshold {
        return Ok(None);
    }

    let diagnostic = AttemptDiagnostic {
        index: 0,
        flags: flags.into(),
        candidate_count: 0,
        candidates: Vec::new(),
        entry_points: Vec::new(),
        selected_root: Some(selected_root),
        cleanup: Some(cleanup),
        recovery: RecoveryDiagnostic::default(),
        text_len: attempt.text_len,
        accepted: true,
    };

    Ok(Some((attempt, diagnostic)))
}

fn schema_text_contains_html(text: &str) -> bool {
    let lower = text.to_ascii_lowercase();
    ["<p", "<h1", "<h2", "<h3", "<blockquote", "<ul", "<ol", "<div"]
        .iter()
        .any(|tag| lower.contains(tag))
}

fn source_has_rich_article_content(html: &str) -> bool {
    let document = kuchiki::parse_html().one(html);
    !dom::select_nodes(
        &document,
        "article img, article figure, article picture, article table, article video, article iframe,\
         main img, main figure, main picture, main table, main video, main iframe,\
         [role='main'] img, [role='main'] figure, [role='main'] picture, [role='main'] table,\
         [role='main'] video, [role='main'] iframe",
    )
    .is_empty()
}

fn title_duplicates_site_name(metadata: &Metadata) -> bool {
    let title = metadata.title.as_deref().unwrap_or_default().trim();
    let site_name = metadata.site_name.as_deref().unwrap_or_default().trim();
    !title.is_empty() && title.eq_ignore_ascii_case(site_name)
}

fn first_content_heading(content: &str) -> Option<String> {
    dom::select_nodes(
        &kuchiki::parse_html().one(format!("<html><body>{content}</body></html>")),
        "h1, h2, h3",
    )
    .into_iter()
    .map(|heading| patterns::normalize_spaces(dom::inner_text(&heading).trim()))
    .find(|heading| !heading.is_empty())
}

fn try_site_rule(
    html: &str, options: &ReadabilityOptions, base_url: Option<&Url>, metadata: &Metadata,
) -> Result<Option<rules::RuleExtraction>> {
    let doc = kuchiki::parse_html().one(html);
    prep_document(
        &doc,
        options,
        ExtractFlags { strip_unlikely: false, weight_classes: false, clean_conditionally: false },
    );
    rules::extract_with_site_rule(&doc, base_url, options, metadata)
}

fn normalize_markup(document: &NodeRef) {
    for font in dom::select_nodes(document, "font") {
        let _ = dom::retag_node(&font, "span");
    }

    for div in dom::select_nodes(document, "div") {
        if has_single_element_child(&div, "p") && direct_text_is_empty(&div) {
            dom::replace_with_children(&div);
        }
    }

    for div in dom::select_nodes(document, "div") {
        if !has_child_block_element(&div) && !dom::inner_text(&div).is_empty() {
            let _ = dom::retag_node(&div, "p");
        }
    }
}

fn has_single_element_child(node: &NodeRef, tag: &str) -> bool {
    let mut element_children = node.children().filter(|child| child.as_element().is_some());
    let Some(first) = element_children.next() else {
        return false;
    };
    element_children.next().is_none() && dom::node_name(&first) == tag
}

fn direct_text_is_empty(node: &NodeRef) -> bool {
    node.children()
        .filter_map(|child| child.as_text().map(|text| text.borrow().to_string()))
        .all(|text| text.trim().is_empty())
}

fn has_child_block_element(node: &NodeRef) -> bool {
    !dom::select_nodes(
        node,
        "address, article, aside, blockquote, canvas, dd, div, dl, dt, fieldset, figcaption, figure, footer, form, h1, h2, h3, h4, h5, h6, header, hgroup, hr, li, main, nav, noscript, ol, output, p, pre, section, table, tfoot, ul, video",
    )
    .is_empty()
}

fn effective_base_url(document: &Html, base_url: Option<&Url>) -> Option<Url> {
    let base_url = base_url.cloned()?;
    let selector = patterns::selector("base[href]");
    document
        .select(&selector)
        .next()
        .and_then(|base| base.value().attr("href"))
        .and_then(|href| base_url.join(href).ok())
        .or(Some(base_url))
}

fn unwrap_noscript_images(document: &NodeRef) {
    for noscript in dom::select_nodes(document, "noscript") {
        let content = unescape_noscript_markup(&noscript.text_contents());
        let lower_content = content.to_ascii_lowercase();
        if !lower_content.contains("<img") && !lower_content.contains("<picture") {
            continue;
        }

        let fragment = kuchiki::parse_html().one(format!("<html><body>{content}</body></html>"));
        let Some(body) = dom::select_nodes(&fragment, "body").into_iter().next() else {
            continue;
        };
        let children: Vec<_> = body.children().collect();
        if children.is_empty() {
            continue;
        }

        for child in children {
            noscript.insert_before(child);
        }
        noscript.detach();
    }
}

fn unescape_noscript_markup(value: &str) -> String {
    value
        .replace("&lt;", "<")
        .replace("&gt;", ">")
        .replace("&quot;", "\"")
        .replace("&#34;", "\"")
        .replace("&amp;", "&")
}

fn grab_article(
    doc: &NodeRef, opts: &ReadabilityOptions, flags: ExtractFlags, index: usize, recovery: RecoveryDiagnostic,
    base_url: Option<&Url>, metadata: &Metadata,
) -> Result<Option<(ExtractAttempt, GrabDiagnostics)>> {
    if let Some(selector) = opts.content_selector.as_deref()
        && let Some(root) = dom::select_nodes(doc, selector).into_iter().next()
    {
        let selector_diagnostic = ContentSelectorDiagnostic {
            selector: selector.to_string(),
            matched: true,
            selected: Some(node_diagnostic(&root)),
        };
        let (attempt, cleanup) = serialize_roots(vec![root], opts, flags, base_url, metadata)?;
        let attempt_diagnostic = AttemptDiagnostic {
            index,
            flags: flags.into(),
            candidate_count: 0,
            candidates: Vec::new(),
            entry_points: Vec::new(),
            selected_root: selector_diagnostic.selected.clone(),
            cleanup: Some(cleanup),
            recovery,
            text_len: attempt.text_len,
            accepted: attempt.text_len >= opts.char_threshold,
        };
        return Ok(Some((
            attempt,
            GrabDiagnostics { attempt: attempt_diagnostic, content_selector: Some(selector_diagnostic) },
        )));
    }

    let entry_points = entry_point_candidates(doc);
    let mut candidates = scoring::score_candidates(doc, flags);
    if candidates.is_empty() {
        let body = dom::select_nodes(doc, "body").into_iter().next();
        if let Some(body) = body {
            candidates.push(Candidate { node: body, score: 1.0 });
        }
    }

    if candidates.is_empty() {
        return Ok(None);
    }

    for candidate in &mut candidates {
        candidate.score *= 1.0 - scoring::link_density(&candidate.node);
    }

    let max_candidate_score = candidates
        .iter()
        .map(|candidate| candidate.score)
        .max_by(|a, b| a.total_cmp(b))
        .unwrap_or(0.0);
    let selected_entry_id = selected_entry_point(&entry_points).map(|entry_point| {
        let id = dom::node_id(&entry_point.node);
        let preferred_score = entry_point.score.max(max_candidate_score + 25.0);
        if let Some(candidate) = candidates
            .iter_mut()
            .find(|candidate| dom::node_id(&candidate.node) == id)
        {
            candidate.score = candidate.score.max(preferred_score);
        } else {
            candidates.push(Candidate { node: entry_point.node.clone(), score: preferred_score });
        }
        id
    });

    candidates.sort_by(|a, b| b.score.total_cmp(&a.score));

    let candidate_count = candidates.len();

    candidates.truncate(opts.nb_top_candidates.max(1));

    let candidate_diagnostics: Vec<_> = candidates
        .iter()
        .map(|candidate| CandidateDiagnostic {
            node: node_diagnostic(&candidate.node),
            score: round_score(candidate.score),
            selected_by: if selected_entry_id == Some(dom::node_id(&candidate.node)) {
                CandidateSelection::EntryPointPreselection
            } else {
                CandidateSelection::CandidateScoring
            },
        })
        .collect();

    let top_candidate = candidates[0].node.clone();
    let top_score = candidates[0].score;
    let top_id = dom::node_id(&top_candidate);
    let score_by_id: HashMap<usize, f64> = candidates
        .iter()
        .map(|candidate| (dom::node_id(&candidate.node), candidate.score))
        .collect();

    let parent = top_candidate.parent().unwrap_or_else(|| doc.clone());
    let sibling_threshold = 10.0_f64.max(top_score * 0.2);
    let top_class = dom::attr(&top_candidate, "class").unwrap_or_default();

    let mut included = Vec::new();
    for sibling in parent.children().filter(|node| node.as_element().is_some()) {
        let mut append = dom::node_id(&sibling) == top_id;

        if !append {
            let mut content_bonus = 0.0;
            if !top_class.is_empty() && dom::attr(&sibling, "class").as_deref() == Some(top_class.as_str()) {
                content_bonus += top_score * 0.2;
            }

            if score_by_id.get(&dom::node_id(&sibling)).copied().unwrap_or(0.0) + content_bonus >= sibling_threshold {
                append = true;
            } else if dom::node_name(&sibling) == "p" {
                let density = scoring::link_density(&sibling);
                let text = dom::inner_text(&sibling);
                let len = text.chars().count();
                if (len > 80 && density < 0.25) || (len < 80 && len > 0 && density == 0.0 && text.contains(". ")) {
                    append = true;
                }
            }
        }

        if append {
            included.push(sibling);
        }
    }

    if included.is_empty() {
        included.push(top_candidate);
    }
    let included_text_len = serialize::text_content(&included).encode_utf16().count();
    if let Some(focused_root) = larger_focused_subtree(&candidates[0].node, included_text_len, opts.char_threshold) {
        included = vec![focused_root];
    }

    let selected_root = included.first().map(node_diagnostic);
    let (attempt, cleanup) = serialize_roots(included, opts, flags, base_url, metadata)?;
    let content_selector = opts
        .content_selector
        .as_ref()
        .map(|selector| ContentSelectorDiagnostic { selector: selector.clone(), matched: false, selected: None });
    let attempt_diagnostic = AttemptDiagnostic {
        index,
        flags: flags.into(),
        candidate_count,
        candidates: candidate_diagnostics,
        entry_points: entry_points
            .iter()
            .map(|entry_point| entry_point.diagnostic.clone())
            .collect(),
        selected_root,
        cleanup: Some(cleanup),
        recovery,
        text_len: attempt.text_len,
        accepted: attempt.text_len >= opts.char_threshold,
    };

    Ok(Some((
        attempt,
        GrabDiagnostics { attempt: attempt_diagnostic, content_selector },
    )))
}

fn entry_point_candidates(document: &NodeRef) -> Vec<EntryPointCandidate> {
    let mut candidates = Vec::new();
    let mut seen = std::collections::HashSet::new();

    for selector in ENTRY_POINT_SELECTORS {
        for node in dom::select_nodes(document, selector) {
            if !seen.insert(dom::node_id(&node)) {
                continue;
            }
            let text_len = dom::inner_text(&node).chars().count();
            if text_len < 80 {
                continue;
            }
            let link_density = scoring::link_density(&node);
            if link_density > 0.65 {
                continue;
            }
            let score = (text_len as f64 / 25.0) * (1.0 - link_density).max(0.0)
                + scoring::class_weight(&node, ExtractFlags::all()) as f64;
            let diagnostic = CandidateDiagnostic {
                node: node_diagnostic(&node),
                score: round_score(score),
                selected_by: CandidateSelection::EntryPointPreselection,
            };
            candidates.push(EntryPointCandidate { node, score, diagnostic });
        }
    }

    candidates.sort_by(|a, b| b.score.total_cmp(&a.score));
    candidates.truncate(8);
    candidates
}

fn selected_entry_point(entry_points: &[EntryPointCandidate]) -> Option<Candidate> {
    let best = entry_points.first()?;
    if best.diagnostic.node.text_len < 140 || best.score < 8.0 {
        return None;
    }
    let selected = entry_points
        .iter()
        .find(|entry_point| {
            dom::node_name(&entry_point.node) == "article"
                && entry_point.score >= best.score * 0.75
                && entry_point.diagnostic.node.text_len >= 500
        })
        .unwrap_or(best);
    Some(Candidate { node: selected.node.clone(), score: best.score + 25.0 })
}

fn larger_focused_subtree(node: &NodeRef, current_text_len: usize, char_threshold: usize) -> Option<NodeRef> {
    if shared::word_count(&dom::inner_text(node)) >= EXTREMELY_SHORT_WORD_THRESHOLD
        && !looks_like_narrow_non_article(node)
    {
        return None;
    }

    let min_text_len = char_threshold.max(current_text_len.saturating_mul(2)).max(1);
    node.ancestors()
        .filter(|ancestor| ancestor.as_element().is_some())
        .skip(1)
        .take(5)
        .filter(|ancestor| {
            matches!(
                dom::node_name(ancestor).as_str(),
                "article" | "main" | "section" | "div"
            )
        })
        .find(|ancestor| {
            let text = dom::inner_text(ancestor);
            text.encode_utf16().count() >= min_text_len
                && shared::word_count(&text) >= USEFUL_WORD_THRESHOLD
                && scoring::link_density(ancestor) < 0.35
        })
}

fn looks_like_narrow_non_article(node: &NodeRef) -> bool {
    let attrs = dom::class_id_string(node).to_ascii_lowercase();
    ["author-note", "authors-note", "metadata", "meta", "single-step", "step"]
        .iter()
        .any(|needle| attrs.contains(needle))
        || dom::inner_text(node)
            .trim_start()
            .to_ascii_lowercase()
            .starts_with("*****notes*****")
}

fn node_diagnostic(node: &NodeRef) -> NodeDiagnostic {
    let class = dom::attr(node, "class").unwrap_or_default();
    NodeDiagnostic {
        selector: node_selector(node),
        tag: dom::node_name(node),
        id: dom::attr(node, "id"),
        classes: class.split_whitespace().map(str::to_string).collect(),
        text_len: dom::inner_text(node).encode_utf16().count(),
        link_density: round_score(scoring::link_density(node)),
    }
}

fn node_selector(node: &NodeRef) -> String {
    let tag = dom::node_name(node);
    if tag.is_empty() {
        return "<node>".to_string();
    }
    if let Some(id) = dom::attr(node, "id")
        && !id.trim().is_empty()
    {
        return format!("{tag}#{id}");
    }
    if let Some(class) = dom::attr(node, "class") {
        let mut classes = class.split_whitespace().take(3).collect::<Vec<_>>();
        if !classes.is_empty() {
            classes.insert(0, tag.as_str());
            return classes.join(".");
        }
    }
    tag
}

fn round_score(value: f64) -> f64 {
    (value * 1000.0).round() / 1000.0
}

fn enforce_element_limit(document: &Html, limit: Option<usize>) -> Result<()> {
    match limit {
        Some(limit) => {
            let selector = patterns::selector("*");
            let actual = document.select(&selector).count();
            if actual > limit { Err(Error::max_elems_exceeded(actual, limit)) } else { Ok(()) }
        }
        None => Ok(()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::MediaRetention;
    use crate::patterns::normalize_spaces;

    #[test]
    fn returns_article_for_simple_document() {
        let article = extract(
            "<html><head><title>Example Article</title></head><body><article><p>This is a long enough paragraph, with punctuation, to become a readable article body for the MVP extractor.</p></article></body></html>",
            None,
            &ReadabilityOptions { char_threshold: 0, ..Default::default() },
        )
        .unwrap()
        .unwrap();

        assert_eq!(article.title.as_deref(), Some("Example Article"));
        assert!(article.content.contains("readability-page-1"));
        assert!(article.text_content.contains("long enough paragraph"));
        assert!(article.length > 25);
    }

    #[test]
    fn accepts_long_json_ld_article_body_before_candidate_scoring() {
        let schema_text = "This article body comes from JSON-LD before the generic scoring path runs. ".repeat(20);
        let html = format!(
            r#"
            <html><head>
                <title>Schema Article</title>
                <script type="application/ld+json">
                    {{"@type":"NewsArticle","headline":"Schema Article","articleBody":"{schema_text}"}}
                </script>
            </head><body>
                <main>
                    <div class="feed">
                        <p>Navigation, recommendations, and page chrome should not win extraction.</p>
                    </div>
                </main>
            </body></html>
            "#
        );

        let report = extract_with_diagnostics(&html, None, &ReadabilityOptions::default()).unwrap();
        let article = report.article.unwrap();
        assert_eq!(report.diagnostics.outcome, ExtractionOutcome::Accepted);
        assert_eq!(report.diagnostics.selected_attempt, Some(0));
        assert_eq!(report.diagnostics.attempts.len(), 1);
        assert_eq!(report.diagnostics.attempts[0].candidate_count, 0);
        assert!(article.text_content.contains("JSON-LD before the generic scoring path"));
        assert!(!article.text_content.contains("Navigation, recommendations"));
    }

    #[test]
    fn parses_html_json_ld_article_body() {
        let schema_text = "<p>Schema paragraph one has enough useful article prose, punctuation, and detail.</p><p>Schema paragraph two keeps inline <a href=\"https://example.com\">links</a> as markup instead of escaped text.</p>".repeat(4);
        let html = format!(
            r#"
            <html><head>
                <title>Schema HTML Article</title>
                <script type="application/ld+json">
                    {{"@type":"NewsArticle","headline":"Schema HTML Article","articleBody":{}}}
                </script>
            </head><body><main><p>Short fallback.</p></main></body></html>
            "#,
            serde_json::to_string(&schema_text).unwrap()
        );

        let article = extract(&html, Some("https://example.com/story"), &ReadabilityOptions::default())
            .unwrap()
            .unwrap();

        assert!(article.content.contains("<p>Schema paragraph one"));
        assert!(article.content.contains(r#"<a href="https://example.com/">links</a>"#));
        assert!(!article.text_content.contains("<p>"));
    }

    #[test]
    fn accepts_known_article_body_container_before_candidate_scoring() {
        let body = (0..12)
            .map(|index| {
                format!(
                    "<p>This focused article-body container paragraph {index} has useful prose, \
                    concrete detail, and enough punctuation to be accepted before scoring.</p>"
                )
            })
            .collect::<String>();
        let html = format!(
            r#"
            <html><head><title>Known Container</title></head><body>
                <div class="navigation">
                    <p>Navigation, recommendations, and other page chrome.</p>
                </div>
                <div id="article-body" class="text-copy">
                    {body}
                </div>
            </body></html>
            "#
        );

        let report = extract_with_diagnostics(&html, None, &ReadabilityOptions::default()).unwrap();
        let article = report.article.unwrap();

        assert_eq!(report.diagnostics.outcome, ExtractionOutcome::Accepted);
        assert_eq!(report.diagnostics.selected_attempt, Some(0));
        assert_eq!(report.diagnostics.attempts.len(), 1);
        assert_eq!(report.diagnostics.attempts[0].candidate_count, 0);
        assert!(article.text_content.contains("focused article-body container"));
        assert!(!article.text_content.contains("Navigation, recommendations"));
    }

    #[test]
    fn prefers_known_content_dom_over_plain_schema_text() {
        let body = (0..12)
            .map(|index| {
                format!(
                    "<p>Article paragraph {index} has useful prose, concrete detail, \
                    and enough punctuation to be accepted before schema text.</p>"
                )
            })
            .collect::<String>();
        let schema_text = patterns::normalize_spaces(&body.replace(['<', '>'], " "));
        let html = format!(
            r#"
            <html><head>
                <title>Media Story</title>
                <script type="application/ld+json">
                    {{"@type":"NewsArticle","headline":"Media Story","articleBody":{}}}
                </script>
            </head><body>
                <article>
                    <div class="story-body">
                        {body}
                        <figure><img src="/chart.png" alt="Chart"><figcaption>Chart caption.</figcaption></figure>
                    </div>
                </article>
            </body></html>
            "#,
            serde_json::to_string(&schema_text).unwrap()
        );

        let report =
            extract_with_diagnostics(&html, Some("https://example.com/story"), &ReadabilityOptions::default()).unwrap();
        let article = report.article.unwrap();

        assert_eq!(report.diagnostics.outcome, ExtractionOutcome::Accepted);
        assert_eq!(report.diagnostics.selected_attempt, Some(0));
        assert!(article.content.contains("chart.png"));
        assert!(article.text_content.contains("Chart caption."));
    }

    #[test]
    fn accepts_camel_case_article_content_container_before_scoring() {
        let body = (0..10)
            .map(|index| {
                format!(
                    "<p>This camel-case article content paragraph {index} has enough prose, \
                    punctuation, and detail to be the focused story body.</p>"
                )
            })
            .collect::<String>();
        let html = format!(
            r#"
            <html><body>
                <div class="horizontalPostList">
                    <div class="slideShow">
                        <p>A promoted slideshow should not become the article root.</p>
                    </div>
                </div>
                <div class="articleContent">{body}</div>
            </body></html>
            "#
        );

        let report = extract_with_diagnostics(&html, None, &ReadabilityOptions::default()).unwrap();
        let article = report.article.unwrap();

        assert_eq!(report.diagnostics.selected_attempt, Some(0));
        assert!(article.text_content.contains("camel-case article content paragraph 9"));
        assert!(!article.text_content.contains("promoted slideshow"));
    }

    #[test]
    fn reports_invalid_base_url_and_element_limit() {
        let invalid_url = extract(
            "<html><body><p>text</p></body></html>",
            Some("not a url"),
            &Default::default(),
        );
        assert!(matches!(invalid_url, Err(Error::InvalidBaseUrl(_))));

        let too_many_elements = extract(
            "<html><body><main><p>text</p></main></body></html>",
            None,
            &ReadabilityOptions { max_elems_to_parse: Some(2), ..Default::default() },
        );
        assert!(matches!(too_many_elements, Err(Error::MaxElemsExceeded { .. })));
    }

    #[test]
    fn honors_base_element_for_relative_urls() {
        let fixture = lectito_fixtures::load_fixture("base-url-base-element").unwrap();
        let article = extract(
            &fixture.source,
            Some("http://fakehost/test/page.html"),
            &ReadabilityOptions { char_threshold: 0, ..Default::default() },
        )
        .unwrap()
        .unwrap();

        assert!(article.content.contains(r#"href="http://fakehost/foo/bar/baz.html""#));
        assert!(article.content.contains(r#"src="http://fakehost/foo/bar/baz.png""#));
        assert!(
            !article
                .content
                .contains(r#"href="http://fakehost/test/foo/bar/baz.html""#)
        );
    }

    #[test]
    fn repairs_noscript_images_and_scores_br_divs() {
        let noscript_article = extract(
            r#"<html><body><article><p>Enough text, with punctuation, to choose the article body for this regression.</p><noscript>&lt;img src="/image.jpg" alt="fallback"&gt;</noscript></article></body></html>"#,
            Some("https://example.com/story"),
            &ReadabilityOptions { char_threshold: 0, ..Default::default() },
        )
        .unwrap()
        .unwrap();
        assert!(
            noscript_article
                .content
                .contains(r#"src="https://example.com/image.jpg""#)
        );

        let br_article = extract(
            "<html><body><div>First long line with enough words to score well.<br><br>Second long line, also with enough words and punctuation to survive extraction.</div></body></html>",
            None,
            &ReadabilityOptions { char_threshold: 0, ..Default::default() },
        )
        .unwrap()
        .unwrap();
        assert!(br_article.text_content.contains("Second long line"));
    }

    #[test]
    fn content_selector_override_forces_root_and_reports_diagnostics() {
        let report = extract_with_diagnostics(
            r#"
            <html><body>
                <main>
                    <p>Navigation teaser text that should lose when the explicit selector points elsewhere.</p>
                </main>
                <section id="forced">
                    <p>This forced article body has enough punctuation, enough words, and enough detail to become the returned content.</p>
                </section>
            </body></html>
            "#,
            None,
            &ReadabilityOptions {
                char_threshold: 0,
                content_selector: Some("#forced".to_string()),
                ..Default::default()
            },
        )
        .unwrap();

        let article = report.article.unwrap();
        assert!(article.text_content.contains("forced article body"));
        assert!(!article.text_content.contains("Navigation teaser"));

        let selector = report.diagnostics.content_selector.unwrap();
        assert_eq!(selector.selector, "#forced");
        assert!(selector.matched);
        assert_eq!(selector.selected.unwrap().selector, "section#forced");
        assert!(report.diagnostics.attempts[0].cleanup.is_some());
    }

    #[test]
    fn custom_site_profile_can_select_content_root() {
        let profile = r##"
            name = "example profile"
            hosts = ["example.com"]
            content_roots = ["#profiled"]
            remove = [".ad"]

            [metadata]
            title = ["h1"]
            site_name = "Example"
        "##;
        let report = extract_with_diagnostics(
            r#"
            <html><body>
                <main><p>Generic main content that should not be returned.</p></main>
                <article id="profiled">
                    <h1>Profiled Story</h1>
                    <p>This profile-selected article body has enough punctuation, enough words, and enough detail to become the returned content.</p>
                    <p class="ad">Sponsored interruption.</p>
                </article>
            </body></html>
            "#,
            Some("https://example.com/story"),
            &ReadabilityOptions {
                char_threshold: 0,
                site_profiles: vec![profile.to_string()],
                ..Default::default()
            },
        )
        .unwrap();

        let article = report.article.unwrap();
        assert_eq!(article.title.as_deref(), Some("Profiled Story"));
        assert_eq!(article.site_name.as_deref(), Some("Example"));
        assert!(article.text_content.contains("profile-selected article body"));
        assert!(!article.text_content.contains("Generic main content"));
        assert!(!article.text_content.contains("Sponsored interruption"));

        let diagnostic = report.diagnostics.site_rule.unwrap();
        assert_eq!(diagnostic.name, "example profile");
        assert!(diagnostic.accepted);
        assert_eq!(diagnostic.roots, vec!["article#profiled"]);
    }

    #[test]
    fn preserves_link_heavy_article_lists() {
        let links = (0..30)
            .map(|index| format!(r#"<li><a href="https://example.com/api/{index}"><code>Api::{index}</code></a></li>"#))
            .collect::<String>();
        let html = format!(
            r#"<html><body><article><h1>Release notes</h1>
            <p>This release includes new capabilities and enough explanatory prose to be selected as an article candidate.</p>
            <p>The following APIs are now stable and should remain in the extracted content.</p>
            <h2>Stabilized APIs</h2><ul>{links}</ul>
            <p>Other changes include compiler fixes, cargo improvements, and documentation updates for users.</p>
            </article></body></html>"#
        );

        let article = extract(
            &html,
            Some("https://example.com/release"),
            &ReadabilityOptions { char_threshold: 0, ..Default::default() },
        )
        .unwrap()
        .unwrap();

        assert!(article.content.contains("Stabilized APIs"), "{}", article.content);
        assert!(article.content.contains("Api::0"), "{}", article.content);
        assert!(article.content.contains("Api::29"), "{}", article.content);
    }

    #[test]
    fn uses_content_heading_when_metadata_title_is_site_name() {
        let article = extract(
            r#"<html><head>
                <meta property="og:site_name" content="Example Site">
                <meta property="og:title" content="Example Site">
            </head><body>
                <h1>Example Site</h1>
                <article><h2>Short Post</h2><p>This article body has enough prose and punctuation to be selected as readable content.</p></article>
            </body></html>"#,
            Some("https://example.com/post"),
            &ReadabilityOptions { char_threshold: 0, ..Default::default() },
        )
        .unwrap()
        .unwrap();

        assert_eq!(article.title.as_deref(), Some("Short Post"));
    }

    #[test]
    fn article_media_retention_preserves_body_figures() {
        let html = r#"
            <html><body><article>
                <h1>Quality curves</h1>
                <p>This article explains a diagram, with enough punctuation and prose to be extracted as readable content.</p>
                <div class="figure" id="curve.png"><img src="curve.png"><p class="photoCaption"></p></div>
                <p>The paragraph after the figure continues the argument and proves the figure sits inside the article body.</p>
            </article></body></html>
        "#;

        let article = extract(
            html,
            Some("https://example.com/articles/story.html"),
            &ReadabilityOptions { char_threshold: 0, media_retention: MediaRetention::Article, ..Default::default() },
        )
        .unwrap()
        .unwrap();

        assert!(article.content.contains("<img"), "{}", article.content);
        assert!(
            article.content.contains("https://example.com/articles/curve.png"),
            "{}",
            article.content
        );
    }

    #[test]
    fn none_media_retention_removes_body_figures() {
        let html = r#"
            <html><body><article>
                <p>This article explains a diagram, with enough punctuation and prose to be extracted as readable content.</p>
                <div class="figure"><img src="curve.png"></div>
                <p>The paragraph after the figure continues the argument and proves the figure sits inside the article body.</p>
            </article></body></html>
        "#;

        let article = extract(
            html,
            Some("https://example.com/articles/story.html"),
            &ReadabilityOptions { char_threshold: 0, media_retention: MediaRetention::None, ..Default::default() },
        )
        .unwrap()
        .unwrap();

        assert!(!article.content.contains("<img"), "{}", article.content);
    }

    #[test]
    fn weak_site_profile_output_falls_back_to_generic_extraction() {
        let profile = r##"
            name = "weak profile"
            hosts = ["example.com"]
            content_roots = ["#short"]
        "##;
        let report = extract_with_diagnostics(
            r#"
            <html><body>
                <section id="short"><p>Too short.</p></section>
                <article>
                    <p>This generic article body is intentionally much longer than the profiled short node. It has enough punctuation, enough words, and enough detail to pass the configured threshold through normal readability scoring.</p>
                    <p>The second paragraph adds more meaningful article text so fallback clearly selects the generic article instead of the weak site profile.</p>
                </article>
            </body></html>
            "#,
            Some("https://example.com/story"),
            &ReadabilityOptions {
                char_threshold: 160,
                site_profiles: vec![profile.to_string()],
                ..Default::default()
            },
        )
        .unwrap();

        let article = report.article.unwrap();
        assert!(article.text_content.contains("generic article body"));
        assert!(!article.text_content.trim_start().starts_with("Too short."));

        let diagnostic = report.diagnostics.site_rule.unwrap();
        assert_eq!(diagnostic.name, "weak profile");
        assert!(!diagnostic.accepted);
        assert!(diagnostic.fallback_reason.unwrap().contains("below char_threshold"));
    }

    #[test]
    fn retries_relaxed_cleanup_when_result_is_far_below_content_signal() {
        let paragraphs = (0..12)
            .map(|index| {
                format!(
                    "<p>Recovered paragraph {index} has substantial article prose, commas, \
                    concrete detail, and enough punctuation to prove it belongs in the story.</p>"
                )
            })
            .collect::<String>();
        let html = format!(
            r#"
            <html><body>
                <article>
                    <p>This opening paragraph is long enough to pass the minimum threshold, but it is only the beginning of the article and should not be accepted alone.</p>
                    <section class="shopping">
                        {paragraphs}
                    </section>
                </article>
            </body></html>
            "#
        );

        let report = extract_with_diagnostics(&html, None, &ReadabilityOptions::default()).unwrap();
        let article = report.article.unwrap();

        assert_eq!(report.diagnostics.outcome, ExtractionOutcome::Accepted);
        assert_eq!(report.diagnostics.selected_attempt, Some(2));
        assert_eq!(report.diagnostics.attempts.len(), 3);
        assert!(article.text_content.contains("Recovered paragraph 11"));
    }

    #[test]
    fn keeps_substantial_clean_result_instead_of_accepting_page_chrome() {
        let article_paragraphs = (0..24)
            .map(|index| {
                format!(
                    "<p>Article paragraph {index} has useful prose, commas, and enough \
                    detail to make the cleaned result substantial without nearby cards.</p>"
                )
            })
            .collect::<String>();
        let link_cards = (0..30)
            .map(|index| {
                format!(
                    r#"<li><a href="/story-{index}">Related story {index}</a>
                    <p>Teaser copy that should stay out of the readable article.</p></li>"#
                )
            })
            .collect::<String>();
        let html = format!(
            r#"
            <html><body>
                <main>
                    <article>{article_paragraphs}</article>
                    <section class="related"><h2>More stories</h2><ol>{link_cards}</ol></section>
                </main>
            </body></html>
            "#
        );

        let report = extract_with_diagnostics(&html, None, &ReadabilityOptions::default()).unwrap();
        let article = report.article.unwrap();

        assert_eq!(report.diagnostics.selected_attempt, Some(0));
        assert!(article.text_content.contains("Article paragraph 23"));
        assert!(!article.text_content.contains("Teaser copy"));
    }

    #[test]
    fn keeps_cms_content_class_as_article_body() {
        let paragraphs = (0..12)
            .map(|index| {
                format!(
                    "<p>City article paragraph {index} has substantial prose, commas, \
                    and enough detail to survive conditional cleanup.</p>"
                )
            })
            .collect::<String>();
        let html = format!(
            r#"
            <html><body>
                <main id="main-content">
                    <article class="l-article s-cms-content">
                        <header><h1>City Story</h1><p>By Reporter</p></header>
                        <section class="s-article__section o-small-container">
                            {paragraphs}
                        </section>
                    </article>
                </main>
            </body></html>
            "#
        );

        let report = extract_with_diagnostics(&html, None, &ReadabilityOptions::default()).unwrap();
        let article = report.article.unwrap();

        assert_eq!(report.diagnostics.outcome, ExtractionOutcome::Accepted);
        assert_eq!(
            report.diagnostics.attempts[0]
                .selected_root
                .as_ref()
                .map(|root| root.tag.as_str()),
            Some("article")
        );
        assert!(article.text_content.contains("City article paragraph 11"));
    }

    #[test]
    fn retries_without_unlikely_stripping_when_first_result_is_short() {
        let paragraphs = (0..30)
            .map(|index| {
                format!(
                    "<p>Hidden article paragraph {index} has useful prose, commas, \
                    concrete examples, and enough detail to beat the short fallback result.</p>"
                )
            })
            .collect::<String>();
        let html = format!(
            r#"
            <html><body>
                <article>
                    <p>This short fallback paragraph has enough characters to pass the old threshold, but too few words to be a useful extraction.</p>
                    <p>The second short fallback paragraph adds characters while still leaving the extraction well under a useful article word count.</p>
                    <p>The third short fallback paragraph repeats the same problem: enough length for acceptance, not enough substance to stop retrying.</p>
                    <p>The fourth short fallback paragraph keeps the first attempt above the default character threshold without making it useful.</p>
                </article>
                <section class="comments">
                    {paragraphs}
                </section>
            </body></html>
            "#
        );

        let report = extract_with_diagnostics(&html, None, &ReadabilityOptions::default()).unwrap();
        let article = report.article.unwrap();

        assert_eq!(report.diagnostics.outcome, ExtractionOutcome::Accepted);
        assert_eq!(report.diagnostics.selected_attempt, Some(1));
        assert!(report.diagnostics.attempts.len() > 1);
        assert!(article.text_content.contains("Hidden article paragraph 9"));
    }

    #[test]
    fn retries_with_hidden_removal_disabled_when_result_is_extremely_short() {
        let paragraphs = (0..14)
            .map(|index| {
                format!(
                    "<p>Recovered hidden paragraph {index} contains article prose, concrete \
                    examples, clear punctuation, and enough detail to be selected.</p>"
                )
            })
            .collect::<String>();
        let html = format!(
            r#"
            <html><body>
                <article>
                    <p>Brief visible summary.</p>
                    <section style="display: none">
                        {paragraphs}
                    </section>
                </article>
            </body></html>
            "#
        );

        let report = extract_with_diagnostics(&html, None, &ReadabilityOptions::default()).unwrap();
        let article = report.article.unwrap();

        assert_eq!(report.diagnostics.outcome, ExtractionOutcome::Accepted);
        assert_eq!(report.diagnostics.selected_attempt, Some(4));
        assert!(article.text_content.contains("Recovered hidden paragraph 13"));
    }

    #[test]
    fn prefers_larger_focused_subtree_over_single_step() {
        let paragraphs = (0..12)
            .map(|index| {
                format!(
                    "<p>Full article paragraph {index} has useful prose, concrete detail, \
                    commas, and enough punctuation to belong with the larger focused body.</p>"
                )
            })
            .collect::<String>();
        let html = format!(
            r#"
            <html><body>
                <div class="negative-shell">
                    <section class="post author-note">
                        <p>*****Notes***** This long author note has enough words, commas, and punctuation to look readable on its own, but it is still page-adjacent context rather than the whole article. It mentions background details, pronunciation notes, side comments, reader guidance, and other metadata-like material that should not beat the larger focused article subtree.</p>
                    </section>
                    <section>
                        {paragraphs}
                    </section>
                </div>
            </body></html>
            "#
        );

        let report = extract_with_diagnostics(&html, None, &ReadabilityOptions::default()).unwrap();
        let article = report.article.unwrap();

        assert_eq!(report.diagnostics.outcome, ExtractionOutcome::Accepted);
        assert!(article.text_content.contains("Full article paragraph 11"));
    }

    #[test]
    fn removes_trailing_related_card_lists() {
        let cards = (0..4)
            .map(|index| {
                format!(
                    "<li><h3>Related card {index}</h3><p>News &amp; Commentary</p><p>By: Staff Writer</p><p>This is a current site card, not article prose.</p></li>"
                )
            })
            .collect::<String>();
        let html = format!(
            r#"
            <html><body>
                <main id="content">
                    <article>
                        <p>This article body has enough real prose, enough punctuation, and enough concrete detail to be the selected content.</p>
                        <p>The second paragraph keeps the article meaningful before the related content cards begin.</p>
                    </article>
                    <section>
                        <ul>{cards}</ul>
                    </section>
                </main>
            </body></html>
            "#
        );

        let article = extract(
            &html,
            None,
            &ReadabilityOptions { char_threshold: 0, ..Default::default() },
        )
        .unwrap()
        .unwrap();

        assert!(article.text_content.contains("This article body has enough real prose"));
        assert!(!article.text_content.contains("Related card 3"));
    }

    #[test]
    fn code_extractor_output_accepts_short_specialized_pages() {
        let report = extract_with_diagnostics(
            r#"
            <html><head><title>Short Link | Hacker News</title></head><body>
                <table><tbody>
                    <tr class="athing" id="1">
                        <td><span class="titleline"><a href="https://example.com">Short Link</a></span></td>
                    </tr>
                    <tr><td class="subtext"><span class="score">1 point</span> by <a class="hnuser">alice</a> <span class="age" title="2026-05-22T00:00:00"><a href="item?id=1">1 hour ago</a></span></td></tr>
                    <tr class="fatitem"><td></td></tr>
                </tbody></table>
            </body></html>
            "#,
            Some("https://news.ycombinator.com/item?id=1"),
            &ReadabilityOptions::default(),
        )
        .unwrap();

        assert_eq!(report.diagnostics.outcome, ExtractionOutcome::Accepted);
        let diagnostic = report.diagnostics.site_rule.unwrap();
        assert_eq!(diagnostic.source, SiteRuleSource::CodeExtractor);
        assert!(diagnostic.accepted);
        assert!(report.article.unwrap().text_content.contains("Short Link"));
    }

    #[test]
    fn unmatched_content_selector_falls_back_to_scoring_and_reports_candidates() {
        let report = extract_with_diagnostics(
            r#"
            <html><body>
                <article class="story">
                    <p>This article body is long enough, punctuated enough, and clean enough to be selected by normal scoring.</p>
                </article>
            </body></html>
            "#,
            None,
            &ReadabilityOptions {
                char_threshold: 0,
                content_selector: Some(".missing".to_string()),
                ..Default::default()
            },
        )
        .unwrap();

        assert!(
            report
                .article
                .unwrap()
                .text_content
                .contains("selected by normal scoring")
        );
        let selector = report.diagnostics.content_selector.unwrap();
        assert!(!selector.matched);
        assert!(report.diagnostics.attempts[0].candidate_count > 0);
        assert!(!report.diagnostics.attempts[0].entry_points.is_empty());
    }

    #[test]
    fn metadata_expands_image_domain_favicon_and_deduplicated_author() {
        let article = extract(
            r#"
            <html><head>
                <title>Metadata Story</title>
                <link rel="canonical" href="https://www.example.com/story/one">
                <link rel="icon" href="/icon.png">
                <meta property="og:image" content="/lead.jpg">
                <meta name="author" content="Ada Lovelace, Ada Lovelace; Grace Hopper">
            </head><body>
                <article><p>This article has enough text and punctuation to be extracted as the main content.</p></article>
            </body></html>
            "#,
            Some("https://www.example.com/story/one"),
            &ReadabilityOptions { char_threshold: 0, ..Default::default() },
        )
        .unwrap()
        .unwrap();

        assert_eq!(article.byline.as_deref(), Some("Ada Lovelace, Grace Hopper"));
        assert_eq!(article.image.as_deref(), Some("https://www.example.com/lead.jpg"));
        assert_eq!(article.domain.as_deref(), Some("example.com"));
        assert_eq!(article.favicon.as_deref(), Some("https://www.example.com/icon.png"));
    }

    #[test]
    fn prefers_specific_heading_over_generic_site_title_and_cleans_header() {
        let article = extract(
            r#"
            <html><head>
                <title>Example Daily</title>
                <meta property="og:title" content="Example Daily">
                <meta property="og:site_name" content="Example Daily">
            </head><body>
                <article>
                    <header>
                        <h1>Specific Article Headline About Metadata</h1>
                        <div class="byline author-card">
                            <img src="/avatar.jpg" alt="">
                            By Ada Lovelace Published May 1, 2026
                        </div>
                        <time datetime="2026-05-01T12:00:00Z">May 1, 2026</time>
                        <figure class="hero"><img src="/hero.jpg" alt="Lead image"></figure>
                    </header>
                    <p>This article body is long enough, punctuated enough, and concrete enough to be selected without carrying the header chrome into the readable article.</p>
                    <p>The second paragraph should remain as normal body content after metadata and hero cleanup.</p>
                </article>
            </body></html>
            "#,
            Some("https://example.com/story"),
            &ReadabilityOptions { char_threshold: 0, ..Default::default() },
        )
        .unwrap()
        .unwrap();

        assert_eq!(
            article.title.as_deref(),
            Some("Specific Article Headline About Metadata")
        );
        assert_eq!(article.byline.as_deref(), Some("Ada Lovelace"));
        assert_eq!(article.published_time.as_deref(), Some("2026-05-01T12:00:00Z"));
        assert!(article.text_content.contains("This article body is long enough"));
        assert!(
            !article
                .text_content
                .contains("Specific Article Headline About Metadata")
        );
        assert!(!article.text_content.contains("Ada Lovelace"));
        assert!(!article.content.contains("hero.jpg"));
    }

    #[test]
    fn normalization_cleans_common_output_shapes_before_markdown() {
        let article = extract(
            r##"
            <html><head><title>Code Story</title></head><body>
                <article>
                    <h1>Code Story</h1>
                    <h2><a href="#code">Code Samples</a></h2>
                    <p>Alpha<wbr>Beta<br><br><br>Gamma</p>
                    <pre>let value = 1;</pre>
                    <div><span></span></div>
                </article>
            </body></html>
            "##,
            None,
            &ReadabilityOptions { char_threshold: 0, ..Default::default() },
        )
        .unwrap()
        .unwrap();

        assert!(!article.content.contains("<wbr"));
        assert!(!article.content.contains("<br><br><br>"));
        assert!(article.content.contains("<h2>Code Samples</h2>"));
        assert!(article.content.contains("<pre><code>let value = 1;</code></pre>"));
        assert!(article.markdown.contains("## Code Samples"));
        assert!(article.markdown.contains("    let value = 1;"));
    }

    #[test]
    fn removes_trailing_page_chrome_after_article_body() {
        let article = extract(
            r#"
            <html><head><title>Cleanup Story</title></head><body>
                <main>
                    <article>
                        <h1>Cleanup Story</h1>
                        <p>This article opens with enough detail, punctuation, and concrete prose to be selected as readable content.</p>
                        <p>This article continues with a second paragraph, so the following blocks are trailing page chrome.</p>
                        <section class="related-articles">
                            <h2>Related articles</h2>
                            <ul>
                                <li><a href="/a">One related link</a></li>
                                <li><a href="/b">Two related link</a></li>
                                <li><a href="/c">Three related link</a></li>
                            </ul>
                        </section>
                        <section id="comments">
                            <h2>Comments</h2>
                            <p>Join the discussion below.</p>
                        </section>
                    </article>
                </main>
            </body></html>
            "#,
            Some("https://example.com/cleanup"),
            &ReadabilityOptions { char_threshold: 0, ..Default::default() },
        )
        .unwrap()
        .unwrap();

        assert!(
            article
                .text_content
                .contains("following blocks are trailing page chrome")
        );
        assert!(!article.text_content.contains("Related articles"));
        assert!(!article.text_content.contains("Join the discussion"));
    }

    #[test]
    fn removes_jetpack_related_posts_inside_article_body() {
        let article = extract(
            r#"
            <html><body>
                <article>
                    <div class="entry-content" itemprop="articleBody">
                        <p>This article body has enough substance, punctuation, and concrete
                        detail to be selected by the known content selector.</p>
                        <p>The second paragraph keeps the story meaningful before the related
                        module appears at the end of the article body.</p>
                        <div id="jp-relatedposts" class="jp-relatedposts">
                            <h3>Related</h3>
                            <div>
                                <h4><a href="/related">Related story headline</a></h4>
                                <p>Related teaser text should stay out of the article output.</p>
                                <p>In "News"</p>
                            </div>
                        </div>
                    </div>
                </article>
            </body></html>
            "#,
            None,
            &ReadabilityOptions { char_threshold: 0, ..Default::default() },
        )
        .unwrap()
        .unwrap();

        assert!(article.text_content.contains("This article body has enough substance"));
        assert!(!article.text_content.contains("Related story headline"));
        assert!(!article.text_content.contains("Related teaser text"));
    }

    #[test]
    fn keeps_body_list_items_with_short_image_captions() {
        let article = extract(
            r#"
            <html><body>
                <article>
                    <p>This article opens with enough detail, punctuation, and prose to pass
                    extraction before a list of visual updates.</p>
                    <ul>
                        <li>
                            <b>Feature milestone</b> reached a useful state.
                            <ul>
                                <li>
                                    <div class="wp-caption aligncenter">
                                        <a href="/image.png"><img src="/image.png" alt="Feature chart"></a>
                                        <p class="wp-caption-text">The feature chart confirms this milestone.</p>
                                    </div>
                                </li>
                            </ul>
                        </li>
                    </ul>
                    <p>The closing paragraph proves the list sits inside the article body.</p>
                </article>
            </body></html>
            "#,
            None,
            &ReadabilityOptions { char_threshold: 0, ..Default::default() },
        )
        .unwrap()
        .unwrap();

        assert!(article.text_content.contains("Feature milestone"));
        assert!(
            article
                .text_content
                .contains("The feature chart confirms this milestone")
        );
    }

    #[test]
    fn removes_reference_page_table_of_contents_without_url_profile() {
        let article = extract(
            r##"
            <html><head><title>Reference Entry</title></head><body>
                <main>
                    <article>
                        <h1>Reference Entry</h1>
                        <div id="toc">
                            <h2>Contents</h2>
                            <ol>
                                <li><a href="#history">History</a></li>
                                <li><a href="#software">Software</a></li>
                            </ol>
                        </div>
                        <p>This reference entry has enough real article text, punctuation, and detail to pass extraction.</p>
                        <h2 id="history">History</h2>
                        <p>The body explains the topic without keeping the navigation table of contents in reader output.</p>
                    </article>
                </main>
            </body></html>
            "##,
            None,
            &ReadabilityOptions { char_threshold: 0, ..Default::default() },
        )
        .unwrap()
        .unwrap();

        assert!(!article.text_content.contains("Contents"));
        assert!(!article.text_content.contains("Software"));
        assert!(article.text_content.contains("The body explains the topic"));
    }

    #[test]
    fn removes_continue_reading_article_chrome() {
        let article = extract(
            r##"
            <html><head><title>Continue Story</title></head><body>
                <article>
                    <h1>Continue Story</h1>
                    <p>This article has enough substance, punctuation, and detail to pass the extraction threshold.</p>
                    <p>The second paragraph keeps the article body clearly above the minimum length for this regression.</p>
                    <a href="#whats-next">Continue reading the main story</a>
                </article>
            </body></html>
            "##,
            None,
            &ReadabilityOptions { char_threshold: 0, ..Default::default() },
        )
        .unwrap()
        .unwrap();

        assert!(!article.text_content.contains("Continue reading"));
        assert!(article.text_content.contains("second paragraph"));
    }

    #[test]
    fn preserves_read_more_article_continuation() {
        let continuation = (0..8)
            .map(|index| {
                format!(
                    "<p>Continuation paragraph {index} carries article prose, commas, \
                    and enough detail to remain part of the story body.</p>"
                )
            })
            .collect::<String>();
        let related = (0..5)
            .map(|index| {
                format!(
                    r#"<div class="story-block"><h4><a href="/related-{index}">Related story {index}</a></h4>
                    <p>Related teaser {index} should not remain in the article.</p></div>"#
                )
            })
            .collect::<String>();
        let html = format!(
            r##"
            <html><body>
                <div id="content">
                    <div class="story-body">
                        <p>Main story paragraph has enough prose, commas, and detail.</p>
                        <div id="read-more">
                            <div id="read-more-link"><a href="#">Read more</a></div>
                            <div id="read-more-content">{continuation}</div>
                        </div>
                    </div>
                    <div class="group text-g-other-opinion-columns">{related}</div>
                </div>
            </body></html>
            "##
        );

        let article = extract(&html, None, &ReadabilityOptions::default()).unwrap().unwrap();

        assert!(article.text_content.contains("Continuation paragraph 7"));
        assert!(!article.text_content.contains("Related teaser"));
    }

    #[test]
    fn preserves_short_link_text_that_appears_in_byline_metadata() {
        let article = extract(
            r#"
            <html>
                <head>
                    <title>Announcing Rust 1.83.0 | Rust Blog</title>
                    <meta name="author" content="The Rust Release Team">
                </head>
                <body>
                    <article>
                        <p>This article has enough substance, punctuation, and detail to pass the extraction threshold.</p>
                        <p>
                            Check out everything that changed in
                            <a rel="external" href="https://github.com/rust-lang/rust/releases/tag/1.83.0">Rust</a>,
                            <a rel="external" href="https://doc.rust-lang.org/nightly/cargo/CHANGELOG.html">Cargo</a>,
                            and
                            <a rel="external" href="https://github.com/rust-lang/rust-clippy/blob/master/CHANGELOG.md">Clippy</a>.
                        </p>
                    </article>
                </body>
            </html>
            "#,
            None,
            &ReadabilityOptions { char_threshold: 0, ..Default::default() },
        )
        .unwrap()
        .unwrap();

        assert!(article.text_content.contains("changed in Rust, Cargo, and Clippy"));
        assert!(
            article
                .markdown
                .contains("[Rust](https://github.com/rust-lang/rust/releases/tag/1.83.0)")
        );
    }

    #[test]
    fn preserves_footnotes_while_removing_chrome_after_them() {
        let article = extract(
            r##"
            <html><head><title>Notes Story</title></head><body>
                <article>
                    <h1>Notes Story</h1>
                    <p>This article has enough substance, punctuation, and references to keep the body readable.<sup><a href="#fn1">1</a></sup></p>
                    <section class="footnotes">
                        <h2>Footnotes</h2>
                        <ol>
                            <li id="fn1">A legitimate note that should remain attached to the article.</li>
                        </ol>
                    </section>
                    <aside class="partner-offer">
                        <h2>Partner offers</h2>
                        <a href="/deal">Mortgage offer</a>
                        <a href="/card">Finance widget</a>
                        <a href="/jobs">Jobs widget</a>
                    </aside>
                </article>
            </body></html>
            "##,
            Some("https://example.com/notes"),
            &ReadabilityOptions { char_threshold: 0, ..Default::default() },
        )
        .unwrap()
        .unwrap();

        assert!(article.text_content.contains("legitimate note"));
        assert!(!article.text_content.contains("Partner offers"));
        assert!(!article.text_content.contains("Mortgage offer"));
    }

    #[test]
    fn removes_newsletter_category_and_next_article_tail_sections() {
        let article = extract(
            r#"
            <html><head><title>Article Tail</title></head><body>
                <div id="postContent">
                    <div id="postBody">
                        <section>
                            <p>This article body is long enough, punctuated enough, and concrete enough to be selected from a nested article page.</p>
                            <p>The final paragraph should remain as the end of the article.</p>
                        </section>
                        <section id="newsletter">
                            <div>The Daily Newsletter</div>
                            <p><em>Get highlights of the most important news delivered to your email inbox</em></p>
                        </section>
                        <section>
                            <div><h2>Also in <span>Physics</span></h2></div>
                        </section>
                        <div>
                            <section>
                                <div>
                                    <h2>Next article</h2>
                                    <div>Solution: A puzzle teaser</div>
                                </div>
                            </section>
                            <a href="/next"></a>
                        </div>
                    </div>
                </div>
            </body></html>
            "#,
            Some("https://example.com/story"),
            &ReadabilityOptions { char_threshold: 0, ..Default::default() },
        )
        .unwrap()
        .unwrap();

        assert!(article.text_content.contains("final paragraph should remain"));
        assert!(!article.text_content.contains("The Daily Newsletter"));
        assert!(!article.text_content.contains("Also in Physics"));
        assert!(!article.text_content.contains("Next article"));
    }

    #[test]
    fn recovery_hooks_expose_mobile_and_shadow_dom_content() {
        let mobile = extract_with_diagnostics(
            r#"
            <html><head>
                <style>@media (max-width: 600px) { .mobile-article { display: block; } }</style>
            </head><body>
                <article class="mobile-article" style="display: none">
                    <p>This mobile article has enough text, punctuation, and detail to become readable after display recovery.</p>
                </article>
            </body></html>
            "#,
            None,
            &ReadabilityOptions { char_threshold: 0, ..Default::default() },
        )
        .unwrap();
        let mobile_article = mobile.article.unwrap();
        assert!(mobile_article.text_content.contains("mobile article"));
        assert!(mobile.diagnostics.attempts[0].recovery.mobile_rules_applied > 0);

        let shadow = extract_with_diagnostics(
            r#"
            <html><body>
                <x-story>
                    <template shadowrootmode="open">
                        <article><p>This shadow article has enough text and punctuation to become readable after flattening.</p></article>
                    </template>
                </x-story>
            </body></html>
            "#,
            None,
            &ReadabilityOptions { char_threshold: 0, ..Default::default() },
        )
        .unwrap();
        let shadow_article = shadow.article.unwrap();
        assert!(shadow_article.text_content.contains("shadow article"));
        assert!(shadow.diagnostics.attempts[0].recovery.shadow_roots_flattened > 0);
    }

    #[test]
    fn prefers_focused_main_over_body_app_shell() {
        let report = extract_with_diagnostics(
            r#"
            <html><head><title>Focused docs</title></head><body class="antialiased">
                <nav>
                    <a href="/a">Overview</a><a href="/b">SDKs</a><a href="/c">API</a>
                    <a href="/d">Guides</a><a href="/e">Examples</a><a href="/f">Changelog</a>
                </nav>
                <main id="content-container">
                    <h1>Focused docs</h1>
                    <p>This documentation page has enough focused prose, commas, and detail to be selected as the article root.</p>
                    <p>The body also contains an app shell, but this main element is the useful content readers requested.</p>
                </main>
                <footer><a href="/privacy">Privacy</a><a href="/terms">Terms</a></footer>
            </body></html>
            "#,
            Some("https://example.com/docs/code"),
            &ReadabilityOptions { char_threshold: 0, ..Default::default() },
        )
        .unwrap();
        let article = report.article.unwrap();
        let selected = report.diagnostics.attempts[0]
            .selected_root
            .as_ref()
            .map(|node| node.selector.as_str());

        assert_eq!(selected, Some("main#content-container"));
        assert!(article.text_content.contains("useful content readers requested"));
        assert!(!article.text_content.contains("OverviewSDKsAPI"));
    }

    #[test]
    fn removes_doc_controls_without_dropping_code_panels() {
        let article = extract(
            r#"
            <html><head><title>Tabbed code docs</title></head><body>
                <main>
                    <h1>Tabbed code docs</h1>
                    <p>This page explains a code sample with enough prose to be readable and selected correctly.</p>
                    <button aria-label="Copy page"><svg></svg>Copy page</button>
                    <div role="tablist"><button role="tab">JavaScript</button><button role="tab">Python</button></div>
                    <section>
                        <pre data-language="js"><code>client.extract(url)</code></pre>
                    </section>
                    <p>The code panel should remain while toolbar controls and orphan labels are removed.</p>
                </main>
            </body></html>
            "#,
            Some("https://example.com/docs/create/code"),
            &ReadabilityOptions { char_threshold: 0, ..Default::default() },
        )
        .unwrap()
        .unwrap();

        assert!(
            article
                .content
                .contains("<pre data-language=\"js\"><code data-language=\"js\">client.extract(url)</code></pre>")
        );
        assert!(!article.text_content.contains("Copy page"));
        assert!(!article.text_content.contains("JavaScriptPython"));
    }

    #[test]
    fn keeps_docs_landing_list_card_bodies() {
        let article = extract(
            r#"
            <html><head><title>Docs + Quickstarts</title></head><body>
                <main>
                    <article>
                        <h1>Docs + Quickstarts</h1>
                        <p>Start here to create, configure, and operate useful services with Render.</p>
                        <section>
                            <h2>Create</h2>
                            <ul>
                                <li>
                                    <div><svg></svg></div>
                                    <div>
                                        <h3>Deploy services</h3>
                                        <p>Connect your repo and ship with every push.</p>
                                        <ul>
                                            <li><a href="/docs/deploys">How deploys work</a></li>
                                            <li><a href="/docs/service-types">Service types</a></li>
                                            <li><a href="/docs/language-support">Language runtimes</a></li>
                                        </ul>
                                    </div>
                                </li>
                            </ul>
                        </section>
                    </article>
                </main>
            </body></html>
            "#,
            Some("https://render.com/docs"),
            &ReadabilityOptions { char_threshold: 0, ..Default::default() },
        )
        .unwrap()
        .unwrap();

        assert!(article.text_content.contains("Deploy services"));
        assert!(article.text_content.contains("Connect your repo"));
        assert!(article.markdown.contains("How deploys work"), "{}", article.markdown);
    }

    #[test]
    fn removes_live_doc_site_chrome() {
        let article = extract(
            r#"
            <html><head><title>serde - Rust</title></head><body>
                <main>
                    <section id="main-content">
                        <details open>
                            <summary><span>Expand description</span></summary>
                            <div>
                                <p>Serde is a framework for serializing and deserializing Rust data structures efficiently.</p>
                                <p>The description continues with enough prose to remain readable after summary chrome is removed.</p>
                            </div>
                        </details>
                        <dl>
                            <dt>Serialize</dt>
                            <dd>A data structure that can be serialized into any data format supported by Serde.</dd>
                        </dl>
                    </section>
                </main>
            </body></html>
            "#,
            Some("https://docs.rs/serde/latest/serde/"),
            &ReadabilityOptions { char_threshold: 0, ..Default::default() },
        )
        .unwrap()
        .unwrap();

        assert!(article.text_content.contains("Serde is a framework"));
        assert!(article.text_content.contains("Serialize"));
        assert!(!article.text_content.contains("Expand description"));

        let mdn = extract(
            r##"
            <html><head><title>&lt;article&gt;: The Article Contents element</title></head><body>
                <main>
                    <article>
                        <section class="baseline-card">
                            <p>Baseline Widely available</p>
                            <p>This feature is well established and works across many devices.</p>
                            <a href="#browser_compatibility">See full compatibility</a>
                        </section>
                        <p>The article HTML element represents a self-contained composition in a document, page, application, or site.</p>
                        <p>Usage notes explain how nested article elements and publication dates should be represented.</p>
                        <section>
                            <h2>Help improve MDN</h2>
                            <p>This feedback panel belongs to the page shell.</p>
                        </section>
                    </article>
                </main>
            </body></html>
            "##,
            Some("https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/article"),
            &ReadabilityOptions { char_threshold: 0, ..Default::default() },
        )
        .unwrap()
        .unwrap();

        assert!(mdn.text_content.contains("self-contained composition"));
        assert!(!mdn.text_content.contains("Baseline Widely available"));
        assert!(!mdn.text_content.contains("Help improve MDN"));
    }

    #[test]
    fn matches_representative_fixture_metadata() {
        for name in [
            "wikipedia",
            "base-url-base-element",
            "article-author-tag",
            "parsely-metadata",
        ] {
            let fixture = lectito_fixtures::load_fixture(name).unwrap();
            let article = extract(
                &fixture.source,
                Some("http://fakehost/test/page.html"),
                &ReadabilityOptions { char_threshold: 0, ..Default::default() },
            )
            .unwrap()
            .unwrap();

            let expected = fixture.expected_metadata;
            if let Some(title) = expected.get("title").and_then(serde_json::Value::as_str) {
                assert_eq!(article.title.as_deref(), Some(title), "{name} title");
            }
            if let Some(byline) = expected.get("byline").and_then(serde_json::Value::as_str) {
                assert_eq!(article.byline.as_deref(), Some(byline), "{name} byline");
            }
            if let Some(excerpt) = expected.get("excerpt").and_then(serde_json::Value::as_str) {
                assert_eq!(
                    article.excerpt.as_deref().map(normalize_spaces),
                    Some(normalize_spaces(excerpt)),
                    "{name} excerpt"
                );
            }
            assert!(article.length > 0, "{name} should have text");
            assert!(
                article.content.contains("readability-page-1"),
                "{name} should be wrapped"
            );
        }
    }

    #[test]
    fn returns_content_for_representative_fixture_subset() {
        let names = [
            "wikipedia",
            "dropbox-blog",
            "cnet",
            "base-url-base-element",
            "keep-images",
            "replace-brs",
            "article-author-tag",
            "parsely-metadata",
        ];

        for name in names {
            let fixture = lectito_fixtures::load_fixture(name).unwrap();
            let article = extract(
                &fixture.source,
                Some("http://fakehost/test/page.html"),
                &ReadabilityOptions { char_threshold: 0, ..Default::default() },
            )
            .unwrap()
            .unwrap();

            assert!(article.length > 100, "{name} should have meaningful text");
            assert!(
                article.content.contains("readability-page-1"),
                "{name} should be wrapped"
            );
            assert!(
                !fixture.expected_content.trim().is_empty(),
                "{name} fixture should include expected content"
            );
        }
    }
}