searchwala 8.3.1

Meta-search engine and zero-dependency MCP server in Rust: cross-engine consensus ranking, trafilatura + Readability extraction, domain controls, scholarly sources, and mode-specific synthesis with optional BYOK LLM
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
// ============================================================================
// SearchWala v8.0 — Content Extractor
//
// POLICY: rs-trafilatura primary, dom_smoothie (Readability) as a conditional
// second opinion, take the longer result, always keep trafilatura's metadata.
//
// WHY, measured on a 10-page corpus (Hindi news, English news, docs, wiki,
// blog) on 2026-10-01:
//
//   policy                                    chars     ms   boilerplate
//   v7.0 hand-rolled 7-strategy              76,462     55        0
//   rs-trafilatura only                     117,032    374        0
//   dom_smoothie (Readability) only          102,248     78        1
//   both always, take longer                 121,490    457        1
//   trafilatura + CONDITIONAL readability    120,898    416        1   <-- this
//
// Trafilatura alone is 96.3% of best-of-all, but the average hides tail risk:
// on nih_gov it extracted 1,733 chars where Readability got 3,887 — a 55% loss
// on that page shape. The conditional second opinion recovers that for +11%
// CPU, and gets 99.5% of the always-both result at 91% of its cost.
//
// Readability alone is not viable: −13% content and, decisively, it provides
// NO metadata. Trafilatura gives `date`, `language` and `extraction_quality`,
// which the freshness ranking (P2-2) and the ranking confidence prior (P1-6)
// both need, and which the v7.0 extractor never produced at all.
//
// The v7.0 extractor is retired. Its specific defects, for the record:
//   1. JSON-LD short-circuited on `@type: "WebPage"` and returned that node's
//      `description`. On the Amar Ujala article that meant 180 chars instead
//      of the 4,596-char `articleBody` sitting in block 3 of the same page —
//      a 26x content loss, measured.
//   2. No `@graph` support, so Yoast/RankMath sites (a large share of
//      WordPress news) got no structured extraction at all.
//   3. `@type` as an array (`["Article","NewsArticle"]`) silently failed
//      `.as_str()`.
//   4. `try_scored_extraction` called `element.html()` per container,
//      re-serializing the subtree — accidentally quadratic on large pages.
//   5. `extract_visible_text` joined block children with `" "` after wrapping
//      them in `"\n{}\n"`, producing `"\nA\n \nB\n"`. `clean_and_deduplicate`
//      split on `"\n\n"`, which therefore never matched: paragraph dedup never
//      ran and chunking saw one giant blob.
//   6. ASCII-only sentence detection (`[A-Z].*[.!?]$`) and byte-based length
//      gates, both of which mis-handle Devanagari and CJK.
// ============================================================================

use scraper::{Html, Selector};
use std::sync::LazyLock;

/// Minimum characters for an extraction to count as success.
/// CHARACTERS, not bytes — Devanagari is 3 bytes/char, so a byte gate let
/// Hindi pages through with a third of the content (v7.0 bug).
fn min_text_chars() -> usize {
    std::env::var("MIN_TEXT_CHARS")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(120)
}

/// Result of extracting one page.
#[derive(Debug, Clone, Default)]
pub struct Extracted {
    pub title: String,
    pub text: String,
    /// Publication date (or modified date fallback) when the page declares one.
    pub published: Option<chrono::DateTime<chrono::Utc>>,
    /// Normalized primary BCP-47 language subtag ("hi", "en", ...).
    pub language: Option<String>,
    /// Author / byline when the page declares one.
    pub byline: Option<String>,
    /// Publisher / site name when the page declares one.
    pub site_name: Option<String>,
    /// Page-type classification ("article", "forum", "documentation", ...).
    pub page_type: Option<String>,
    /// 0.0–1.0 extraction confidence. v7.0 hardcoded 0.7 with the comment
    /// "will be overridden when C4 provides real confidence" — this is it.
    pub confidence: f64,
    /// Which extractor produced the text that was kept.
    pub source: &'static str,
}

// ============================================================================
// Primary: dom_smoothie (Mozilla Readability port + Strategies 1-4)
// ============================================================================

fn parse_datetime_utc(raw: &str) -> Option<chrono::DateTime<chrono::Utc>> {
    let s = raw.trim();
    if s.is_empty() {
        return None;
    }
    if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(s) {
        return Some(dt.with_timezone(&chrono::Utc));
    }
    if let Ok(dt) = chrono::DateTime::parse_from_rfc2822(s) {
        return Some(dt.with_timezone(&chrono::Utc));
    }
    for fmt in [
        "%Y-%m-%dT%H:%M:%S%z",
        "%Y-%m-%dT%H:%M%z",
        "%Y-%m-%d %H:%M:%S%z",
    ] {
        if let Ok(dt) = chrono::DateTime::parse_from_str(s, fmt) {
            return Some(dt.with_timezone(&chrono::Utc));
        }
    }
    for fmt in [
        "%Y-%m-%dT%H:%M:%S%.f",
        "%Y-%m-%dT%H:%M:%S",
        "%Y-%m-%d %H:%M:%S",
    ] {
        if let Ok(ndt) = chrono::NaiveDateTime::parse_from_str(s, fmt) {
            return Some(ndt.and_utc());
        }
    }
    let date_prefix = s.get(..10)?;
    let nd = chrono::NaiveDate::parse_from_str(date_prefix, "%Y-%m-%d").ok()?;
    Some(nd.and_hms_opt(0, 0, 0)?.and_utc())
}

fn normalize_lang(raw: &str) -> Option<String> {
    let primary = raw
        .trim()
        .split(['-', '_'])
        .next()
        .unwrap_or("")
        .trim()
        .to_ascii_lowercase();
    (!primary.is_empty()).then_some(primary)
}

fn clean_opt_str(opt: Option<String>) -> Option<String> {
    opt.map(|s| s.trim().to_string()).filter(|s| !s.is_empty())
}

fn word_count(s: &str) -> usize {
    s.split_whitespace().count()
}

fn readability_extract(html: &str, url: &str) -> Option<Extracted> {
    let cfg = dom_smoothie::Config {
        text_mode: dom_smoothie::TextMode::Formatted,
        ..Default::default()
    };
    let mut r = dom_smoothie::Readability::new(html, Some(url), Some(cfg)).ok()?;
    let article = r.parse().ok()?;
    let text = article.text_content.to_string();
    if text.trim().is_empty() {
        return None;
    }
    let chars = crate::util::char_len(&text);
    let confidence = if chars >= 600 {
        0.90
    } else if chars >= min_text_chars() {
        0.82
    } else {
        0.65
    };
    let mut title = article.title;
    let mut published = article
        .published_time
        .as_deref()
        .and_then(parse_datetime_utc)
        .or_else(|| {
            article
                .modified_time
                .as_deref()
                .and_then(parse_datetime_utc)
        });
    let language = article.lang.as_deref().and_then(normalize_lang);
    let mut byline = clean_opt_str(article.byline);
    let mut site_name = clean_opt_str(article.site_name);
    // Upstream dom_smoothie does not traverse JSON-LD `@graph` or array `@type`,
    // nor all Dublin Core meta date names (`dcterms.modified`, etc.); fill any
    // missing metadata cleanly from flattened JSON-LD and `<meta>` tags.
    if (byline.is_none() || site_name.is_none() || published.is_none() || html.contains("@graph"))
        && html.contains("ld+json")
    {
        if let Some(meta) = json_ld_metadata(html) {
            if let Some(h) = meta.headline {
                if html.contains("@graph") || title.trim().is_empty() {
                    title = h;
                }
            }
            byline = byline.or(meta.byline);
            site_name = site_name.or(meta.site_name);
            published = published.or(meta.published);
        }
    }
    if published.is_none() {
        published = meta_datetime_fallback(html);
    }
    Some(Extracted {
        title,
        text,
        published,
        language,
        byline,
        site_name,
        page_type: None,
        confidence,
        source: "readability",
    })
}

// ============================================================================
// Conditional second opinion: rs-trafilatura
// ============================================================================

fn trafilatura_extract(html: &str, url: &str) -> Option<Extracted> {
    let opts = rs_trafilatura::Options {
        url: Some(url.to_string()),
        include_tables: true,
        // Links and comments add boilerplate without adding evidence.
        include_links: false,
        include_comments: false,
        ..Default::default()
    };
    let r = rs_trafilatura::extract_with_options(html, &opts).ok()?;
    Some(Extracted {
        title: r.metadata.title.clone().unwrap_or_default(),
        text: r.content_text,
        published: r.metadata.date,
        language: r.metadata.language.as_deref().and_then(normalize_lang),
        byline: clean_opt_str(r.metadata.author.clone()),
        site_name: clean_opt_str(r.metadata.sitename.clone()),
        page_type: r.metadata.page_type.clone(),
        confidence: r.extraction_quality.clamp(0.0, 1.0),
        source: "trafilatura",
    })
}

/// Should we spend a second opinion on rs-trafilatura?
fn wants_second_opinion(primary: &Extracted, html_len: usize) -> bool {
    let chars = crate::util::char_len(&primary.text);
    if chars < 600 {
        return true;
    }
    if primary.confidence < 0.80 {
        return true;
    }
    // Text-to-markup ratio: a content-rich page that yielded little text is
    // the signal that the primary extractor picked the wrong container.
    let ratio = chars as f64 / html_len.max(1) as f64;
    ratio < 0.035
}

// ============================================================================
// Public API
// ============================================================================

/// Extract readable content from a page.
///
/// DOM extraction (`dom_smoothie` primary with `TextMode::Formatted`, then
/// `rs-trafilatura` as a conditional second opinion) runs on the page after
/// Stage 1 pre-cleaners (Shadow DOM, Sandpack placeholders, SPA `<noscript>`
/// fallbacks). Structured sources then compete with the DOM result: JSON-LD
/// `articleBody` wins when clearly longer (paywalled teasers); hydration data
/// wins on JS shells.
pub fn extract(html: &str, url: &str) -> Extracted {
    let unwrapped = crate::deep_reader::unwrap_shadow_templates(html);
    let html = unwrapped.as_deref().unwrap_or(html);
    let de_sandpacked = crate::deep_reader::strip_sandpack_placeholders(html);
    let html = de_sandpacked.as_deref().unwrap_or(html);
    let noscript_unwrapped = crate::deep_reader::unwrap_noscript_fallbacks(html);
    let html = noscript_unwrapped.as_deref().unwrap_or(html);

    let mut best = readability_extract(html, url).unwrap_or_default();

    if wants_second_opinion(&best, html.len()) {
        if let Some(alt) = trafilatura_extract(html, url) {
            if word_count(&alt.text) > word_count(&best.text) {
                best.text = alt.text;
                best.source = "trafilatura";
                best.confidence = best.confidence.max(alt.confidence);
            }
            if best.title.trim().is_empty() && !alt.title.trim().is_empty() {
                best.title = alt.title;
            }
            best.published = best.published.or(alt.published);
            best.language = best.language.or(alt.language);
            best.byline = best.byline.or(alt.byline);
            best.site_name = best.site_name.or(alt.site_name);
            best.page_type = best.page_type.or(alt.page_type);
        }
    }

    // Title fallback chain, for the pages where trafilatura reports none.
    if best.title.trim().is_empty() {
        best.title = extract_title_from_html(html);
    }

    let dom_chars = crate::util::char_len(&best.text);
    let min = min_text_chars();
    let adopt =
        |best: &mut Extracted, text: String, source: &'static str, confidence: f64, factor: f64| {
            let n = crate::util::char_len(&text);
            let current = crate::util::char_len(&best.text);
            if n >= min && n as f64 >= current as f64 * factor {
                best.text = text;
                best.source = source;
                best.confidence = best.confidence.max(confidence);
            }
        };

    // Ground truth when present. 1.3x: a full body beats a teaser, but a
    // slightly longer JSON copy is not worth losing the DOM's structure.
    if html.contains("articleBody") {
        if let Some(body) = json_ld_article_body(html) {
            adopt(&mut best, body, "json-ld", 0.85, 1.3);
        }
    }

    // JS shells (Next.js, Nuxt, Remix, Redux/Apollo state): the DOM is nearly
    // empty and the article is data in a script. Only consulted when the DOM
    // result is thin, and only adopted when it is at least twice as long.
    if dom_chars < 2_000 {
        if let Some(text) = crate::deep_reader::hydration_text(html) {
            adopt(&mut best, text, "hydration", 0.7, 2.0);
        }
    }

    best.text = normalize_whitespace(&best.text);
    best
}

/// Back-compat shim for call sites that only need (title, text).
#[allow(dead_code)]
pub fn extract_title_and_text(html: &str) -> (String, String) {
    let e = extract(html, "https://example.invalid/");
    (e.title, e.text)
}

/// Back-compat shim.
#[allow(dead_code)]
pub fn extract_article_text(html: &str) -> String {
    extract(html, "https://example.invalid/").text
}

/// True when the extraction is substantial enough to keep.
pub fn is_usable(e: &Extracted) -> bool {
    crate::util::char_len(&e.text) >= min_text_chars()
}

// ============================================================================
// Helpers
// ============================================================================

static SEL_OG_TITLE: LazyLock<Option<Selector>> =
    LazyLock::new(|| Selector::parse(r#"meta[property="og:title"]"#).ok());
static SEL_TITLE: LazyLock<Option<Selector>> = LazyLock::new(|| Selector::parse("title").ok());
static SEL_H1: LazyLock<Option<Selector>> = LazyLock::new(|| Selector::parse("h1").ok());
static SEL_META_DESC: LazyLock<Option<Selector>> =
    LazyLock::new(|| Selector::parse("meta[name='description']").ok());
static SEL_META_ANY: LazyLock<Option<Selector>> =
    LazyLock::new(|| Selector::parse("meta[content]").ok());
static SEL_JSON_LD: LazyLock<Option<Selector>> =
    LazyLock::new(|| Selector::parse("script[type='application/ld+json']").ok());

/// Title with site-name suffix stripped.
///
/// v7.0 had two title functions that disagreed: `extract_title` stripped
/// " - Site Name" suffixes while `extract_title_from_doc` (the one actually
/// called) did not.
pub fn extract_title_from_html(html: &str) -> String {
    let doc = Html::parse_document(html);
    extract_title_from_doc(&doc)
}

pub fn extract_title_from_doc(doc: &Html) -> String {
    if let Some(sel) = SEL_OG_TITLE.as_ref() {
        if let Some(m) = doc.select(sel).next() {
            if let Some(c) = m.value().attr("content") {
                let t = c.trim();
                if !t.is_empty() {
                    return t.to_string();
                }
            }
        }
    }
    if let Some(sel) = SEL_TITLE.as_ref() {
        if let Some(t) = doc.select(sel).next() {
            let raw = t.text().collect::<String>().trim().to_string();
            if !raw.is_empty() {
                return strip_site_suffix(&raw);
            }
        }
    }
    if let Some(sel) = SEL_H1.as_ref() {
        if let Some(h) = doc.select(sel).next() {
            return h.text().collect::<String>().trim().to_string();
        }
    }
    String::new()
}

/// Strip a trailing " - Site" / " | Site" / " — Site" segment.
fn strip_site_suffix(title: &str) -> String {
    for sep in [" | ", " - ", " — ", " – ", " :: ", " » "] {
        if let Some(idx) = title.rfind(sep) {
            let head = title[..idx].trim();
            // Only strip when a substantial title remains.
            if crate::util::char_len(head) >= 15 {
                return head.to_string();
            }
        }
    }
    title.to_string()
}

pub fn extract_title_from_doc_pub(doc: &Html) -> String {
    extract_title_from_doc(doc)
}

/// YouTube meta description (kept from v7.0 — the YouTube fast path uses it).
pub fn extract_youtube_meta(doc: &Html) -> Option<String> {
    let sel = SEL_META_DESC.as_ref()?;
    let m = doc.select(sel).next()?;
    let c = m.value().attr("content")?.trim();
    if crate::util::char_len(c) > 30 {
        Some(c.to_string())
    } else {
        None
    }
}

/// Collect every JSON-LD node, including `@graph` and nested arrays, and
/// return the LONGEST `articleBody`.
///
/// This is deliberately articleBody-only. v7.0 accepted a `description` from
/// the first article-ish node — and it counted `"WebPage"` as article-ish — so
/// on Amar Ujala it returned block 0's 180-char page blurb and never reached
/// block 3's 4,596-char `articleBody`.
pub fn json_ld_article_body(html: &str) -> Option<String> {
    let doc = Html::parse_document(html);
    let sel = SEL_JSON_LD.as_ref()?;
    let mut nodes = Vec::new();
    for script in doc.select(sel) {
        let raw = script.text().collect::<String>();
        if let Ok(v) = serde_json::from_str::<serde_json::Value>(raw.trim()) {
            flatten_ld(&v, &mut nodes);
        }
    }

    let mut best: Option<String> = None;
    for n in &nodes {
        let Some(body) = n.get("articleBody").and_then(|v| v.as_str()) else {
            continue;
        };
        let body = strip_tags(body.trim());
        if crate::util::char_len(&body) < 100 {
            continue;
        }
        if best
            .as_ref()
            .is_none_or(|b| crate::util::char_len(&body) > crate::util::char_len(b))
        {
            best = Some(body);
        }
    }
    best
}

#[derive(Default)]
struct JsonLdMeta {
    headline: Option<String>,
    byline: Option<String>,
    site_name: Option<String>,
    published: Option<chrono::DateTime<chrono::Utc>>,
}

fn ld_person_name(v: &serde_json::Value) -> Option<String> {
    match v {
        serde_json::Value::String(s) => clean_opt_str(Some(s.clone())),
        serde_json::Value::Object(o) => {
            clean_opt_str(o.get("name").and_then(|n| n.as_str()).map(str::to_string))
        }
        serde_json::Value::Array(arr) => {
            let names: Vec<String> = arr.iter().filter_map(ld_person_name).collect();
            (!names.is_empty()).then(|| names.join(", "))
        }
        _ => None,
    }
}

fn json_ld_metadata(html: &str) -> Option<JsonLdMeta> {
    let doc = Html::parse_document(html);
    let sel = SEL_JSON_LD.as_ref()?;
    let mut nodes = Vec::new();
    for script in doc.select(sel) {
        let raw = script.text().collect::<String>();
        if let Ok(v) = serde_json::from_str::<serde_json::Value>(raw.trim()) {
            flatten_ld(&v, &mut nodes);
        }
    }
    let is_article = |n: &serde_json::Value| {
        ld_types(n).iter().any(|t| {
            matches!(
                t.as_str(),
                "Article"
                    | "NewsArticle"
                    | "TechArticle"
                    | "BlogPosting"
                    | "ScholarlyArticle"
                    | "Report"
                    | "OpinionNewsArticle"
                    | "AnalysisNewsArticle"
                    | "LiveBlogPosting"
            )
        })
    };
    let mut meta = JsonLdMeta::default();
    for n in nodes.iter().filter(|n| is_article(n)) {
        if meta.headline.is_none() {
            meta.headline = clean_opt_str(
                n.get("headline")
                    .or_else(|| n.get("name"))
                    .and_then(|v| v.as_str())
                    .map(str::to_string),
            );
        }
        if meta.byline.is_none() {
            meta.byline = n.get("author").and_then(ld_person_name);
        }
        if meta.site_name.is_none() {
            meta.site_name = n.get("publisher").and_then(ld_person_name);
        }
        if meta.published.is_none() {
            meta.published = n
                .get("datePublished")
                .or_else(|| n.get("dateCreated"))
                .or_else(|| n.get("dateModified"))
                .and_then(|v| v.as_str())
                .and_then(parse_datetime_utc);
        }
    }
    (meta.headline.is_some()
        || meta.byline.is_some()
        || meta.site_name.is_some()
        || meta.published.is_some())
    .then_some(meta)
}

/// Fallback date lookup from `<meta name|property="..." content="...">` for
/// published/modified keys not covered by upstream `dom_smoothie` (such as
/// `dcterms.modified`, `dcterms:issued`, `article:modified_time`, `pubdate`).
fn meta_datetime_fallback(html: &str) -> Option<chrono::DateTime<chrono::Utc>> {
    let doc = Html::parse_document(html);
    let sel = SEL_META_ANY.as_ref()?;
    let mut modified: Option<chrono::DateTime<chrono::Utc>> = None;
    for el in doc.select(sel) {
        let Some(content) = el.value().attr("content") else {
            continue;
        };
        let key = el
            .value()
            .attr("property")
            .or_else(|| el.value().attr("name"))
            .unwrap_or("")
            .trim()
            .to_ascii_lowercase();
        if key.is_empty() {
            continue;
        }
        let is_pub = matches!(
            key.as_str(),
            "article:published_time"
                | "og:published_time"
                | "published_time"
                | "pubdate"
                | "publishdate"
                | "datepublished"
                | "parsely-pub-date"
                | "dcterms.created"
                | "dcterms:created"
                | "dcterms.issued"
                | "dcterms:issued"
                | "dcterms.available"
                | "dcterms:available"
                | "dc.date.issued"
                | "dc.date.created"
        );
        if is_pub {
            if let Some(dt) = parse_datetime_utc(content) {
                return Some(dt);
            }
        }
        let is_mod = matches!(
            key.as_str(),
            "article:modified_time"
                | "og:updated_time"
                | "modified_time"
                | "datemodified"
                | "last-modified"
                | "dcterms.modified"
                | "dcterms:modified"
                | "dc.date.modified"
        );
        if is_mod && modified.is_none() {
            modified = parse_datetime_utc(content);
        }
    }
    modified
}

/// Walk arrays and `@graph` so nested nodes are reachable. Yoast and RankMath
/// — which power a large share of WordPress news sites — put everything under
/// `@graph`, and v7.0 only looked at top-level objects or a top-level array.
fn flatten_ld(v: &serde_json::Value, out: &mut Vec<serde_json::Value>) {
    match v {
        serde_json::Value::Array(a) => {
            for x in a {
                flatten_ld(x, out);
            }
        }
        serde_json::Value::Object(o) => {
            if let Some(g) = o.get("@graph") {
                flatten_ld(g, out);
            }
            out.push(v.clone());
            for key in ["mainEntityOfPage", "mainContentOfPage", "hasPart"] {
                if let Some(x) = o.get(key) {
                    if x.is_object() || x.is_array() {
                        flatten_ld(x, out);
                    }
                }
            }
        }
        _ => {}
    }
}

/// `@type` may be a string OR an array of strings.
/// v7.0's `.as_str()` returned None for `["Article","NewsArticle"]`.
pub fn ld_types(n: &serde_json::Value) -> Vec<String> {
    match n.get("@type") {
        Some(serde_json::Value::String(s)) => vec![s.clone()],
        Some(serde_json::Value::Array(a)) => a
            .iter()
            .filter_map(|x| x.as_str().map(str::to_string))
            .collect(),
        _ => Vec::new(),
    }
}

/// Strip HTML tags from a text fragment (JSON-LD bodies sometimes contain them).
fn strip_tags(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut depth = 0usize;
    for c in s.chars() {
        match c {
            '<' => depth += 1,
            '>' => depth = depth.saturating_sub(1),
            _ if depth == 0 => out.push(c),
            _ => {}
        }
    }
    out
}

/// Collapse runs of whitespace while preserving paragraph breaks.
fn normalize_whitespace(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut blank_run = 0usize;
    for line in s.lines() {
        let t = line.trim();
        if t.is_empty() {
            blank_run += 1;
            continue;
        }
        if !out.is_empty() {
            // Any run of blank lines becomes exactly one paragraph break, so
            // downstream `split("\n\n")` actually works. v7.0 produced
            // "\nA\n \nB\n", which that split never matched.
            out.push_str(if blank_run > 0 { "\n\n" } else { "\n" });
        }
        blank_run = 0;
        let collapsed: String = t.split_whitespace().collect::<Vec<_>>().join(" ");
        out.push_str(&collapsed);
    }
    out
}

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

    const AMARUJALA: &str = include_str!("../tests/fixtures/articles/amarujala_hi.html");

    /// THE headline regression test.
    ///
    /// v7.0 returned 180 characters here — the `@type: "WebPage"` node's
    /// `description` — while a 4,596-character `articleBody` sat in block 3 of
    /// the same document. A 26x content loss on every Yoast-style page.
    #[test]
    fn amarujala_hindi_article_extracts_full_body_not_the_meta_description() {
        let got = extract(
            AMARUJALA,
            "https://www.amarujala.com/cricket/cricket-news/odi-world-cup-2026-india-vs-pakistan-match-venue-date-time-all-you-need-to-know-2026-10-01",
        );
        let chars = crate::util::char_len(&got.text);
        assert!(
            chars > 4_000,
            "expected >4000 chars, got {chars} (v7.0 returned 180). source={} text={:?}",
            got.source,
            got.text.chars().take(120).collect::<String>()
        );
        // Must be the Hindi article body, not an English chrome string.
        assert!(
            got.text.contains('\u{0915}') || got.text.contains('\u{092E}'),
            "extracted text does not look like Devanagari"
        );
    }

    #[test]
    fn amarujala_yields_publication_date_and_language() {
        let got = extract(
            AMARUJALA,
            "https://www.amarujala.com/cricket/cricket-news/x",
        );
        // v7.0 extracted neither, despite calling itself "time-aware".
        assert!(got.published.is_some(), "datePublished must be extracted");
        assert_eq!(
            got.language.as_deref(),
            Some("hi"),
            "language should be Hindi"
        );
        assert!(
            got.confidence > 0.5,
            "confidence {} too low",
            got.confidence
        );
    }

    #[test]
    fn json_ld_prefers_longest_articlebody_over_any_description() {
        // Block order mirrors the real Amar Ujala document: WebPage first.
        let html = r#"<html><head>
          <script type="application/ld+json">
            {"@context":"https://schema.org","@type":"WebPage",
             "description":"A short page blurb that v7.0 returned instead of the article, padded out past the hundred character gate so it would win."}
          </script>
          <script type="application/ld+json">
            {"@context":"https://schema.org","@type":["Article","NewsArticle"],
             "articleBody":"THE REAL BODY. Lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua enim ad minim veniam quis nostrud exercitation ullamco."}
          </script>
        </head><body></body></html>"#;
        let body = json_ld_article_body(html).expect("should find articleBody");
        assert!(body.starts_with("THE REAL BODY"), "got {body:?}");
    }

    #[test]
    fn json_ld_walks_graph_nodes() {
        // Yoast/RankMath shape — v7.0 never looked inside @graph.
        let html = r#"<html><head><script type="application/ld+json">
          {"@context":"https://schema.org","@graph":[
            {"@type":"WebSite","name":"Site"},
            {"@type":"NewsArticle","articleBody":"Graph nested body text that is comfortably longer than the one hundred character minimum so the extractor accepts it as real content."}
          ]}
        </script></head><body></body></html>"#;
        let body = json_ld_article_body(html).expect("must find body inside @graph");
        assert!(body.starts_with("Graph nested body"), "got {body:?}");
    }

    #[test]
    fn ld_types_handles_string_and_array() {
        let s: serde_json::Value = serde_json::json!({"@type":"NewsArticle"});
        let a: serde_json::Value = serde_json::json!({"@type":["Article","NewsArticle"]});
        assert_eq!(ld_types(&s), vec!["NewsArticle"]);
        assert_eq!(ld_types(&a), vec!["Article", "NewsArticle"]);
        assert!(ld_types(&serde_json::json!({})).is_empty());
    }

    #[test]
    fn normalize_whitespace_produces_real_paragraph_breaks() {
        // v7.0 emitted "\nA\n \nB\n" and then split on "\n\n", which never
        // matched — so paragraph dedup and chunking both saw one blob.
        let messy = "\nFirst para\n \n\nSecond   para\n\n\n\nThird\n";
        let out = normalize_whitespace(messy);
        assert_eq!(out.split("\n\n").count(), 3, "got {out:?}");
        assert!(!out.contains("   "), "whitespace not collapsed: {out:?}");
    }

    #[test]
    fn strip_site_suffix_keeps_substantial_titles() {
        assert_eq!(
            strip_site_suffix("India vs Pakistan World Cup Match Date | Amar Ujala"),
            "India vs Pakistan World Cup Match Date"
        );
        // Must not reduce a title to nothing.
        assert_eq!(strip_site_suffix("Short | X"), "Short | X");
    }

    #[test]
    fn second_opinion_triggers_on_thin_relative_output() {
        let thin = Extracted {
            text: "x".repeat(700),
            confidence: 0.95,
            ..Default::default()
        };
        // 700 chars from a 100KB page => ratio 0.007, well under 0.035.
        assert!(wants_second_opinion(&thin, 100_000));
        // Same text from a small page is fine.
        assert!(!wants_second_opinion(&thin, 10_000));
        // Low confidence always triggers.
        let unsure = Extracted {
            text: "x".repeat(5000),
            confidence: 0.4,
            ..Default::default()
        };
        assert!(wants_second_opinion(&unsure, 10_000));
        // Very short always triggers.
        let tiny = Extracted {
            text: "x".repeat(100),
            confidence: 1.0,
            ..Default::default()
        };
        assert!(wants_second_opinion(&tiny, 1_000));
    }

    #[test]
    fn strip_tags_removes_markup() {
        assert_eq!(strip_tags("a <b>bold</b> word"), "a bold word");
        assert_eq!(strip_tags("<p>only</p>"), "only");
    }

    #[test]
    fn handles_empty_and_garbage_input_without_panicking() {
        for input in ["", "<html></html>", "not html at all", "<<<>>>"] {
            let e = extract(input, "https://x.test/");
            assert!(!is_usable(&e) || crate::util::char_len(&e.text) >= min_text_chars());
        }
    }

    #[test]
    fn min_text_gate_is_character_based() {
        // 50 Devanagari chars = 150 bytes. A byte gate would wrongly pass this
        // as "150 characters" of content (the v7.0 behaviour).
        let hindi = "क".repeat(50);
        assert_eq!(crate::util::char_len(&hindi), 50);
        assert_eq!(hindi.len(), 150);
        let e = Extracted {
            text: hindi,
            ..Default::default()
        };
        assert!(!is_usable(&e), "50 chars must not pass a 120-char gate");
    }

    // ── Deep reader: page shapes the DOM extractors returned nothing for ──

    fn prose(tag: &str, n: usize) -> String {
        (0..n)
            .map(|i| format!("{tag} paragraph {i}: The reactor cooling loop transfers heat from the core to the steam generators, and engineers monitor its pressure continuously."))
            .collect::<Vec<_>>()
            .join(" ")
    }

    #[test]
    fn reads_declarative_shadow_dom() {
        let html = format!(
            "<html><head><title>S</title></head><body><main><div><template shadowrootmode=\"open\"><p>{}</p><p>{}</p></template></div></main></body></html>",
            prose("SHADOW", 3),
            prose("ROOT", 3)
        );
        let e = extract(&html, "https://example.org/s");
        assert!(
            e.text.contains("SHADOW paragraph 2") && e.text.contains("ROOT paragraph 0"),
            "{}",
            e.text
        );
    }

    #[test]
    fn reads_next_js_shells() {
        let pages = format!(
            r#"<html><head><title>N</title></head><body><div id="__next"></div><script id="__NEXT_DATA__" type="application/json">{{"props":{{"pageProps":{{"post":{{"body":"{}"}}}}}}}}</script></body></html>"#,
            prose("NEXT", 5)
        );
        let e = extract(&pages, "https://example.org/n");
        assert_eq!(e.source, "hydration");
        assert!(e.text.contains("NEXT paragraph 4"));

        let flight = serde_json::to_string(&format!(
            r#"5:["$","p",null,{{"children":"{}"}}]"#,
            prose("RSC", 4)
        ))
        .unwrap();
        let app = format!(
            r#"<html><head><title>R</title></head><body><div></div><script>self.__next_f.push([1,{flight}])</script></body></html>"#
        );
        let e = extract(&app, "https://example.org/r");
        assert!(e.text.contains("RSC paragraph 3"), "{}", e.text);
    }

    #[test]
    fn json_ld_full_body_beats_a_dom_teaser() {
        let body = prose("FULL", 8);
        let html = format!(
            r#"<html><head><title>P</title><script type="application/ld+json">{{"@type":"NewsArticle","headline":"P","articleBody":"{body}"}}</script></head>
            <body><article><p>{}</p><div class="paywall">Subscribe to read more</div></article></body></html>"#,
            prose("TEASER", 1)
        );
        let e = extract(&html, "https://example.org/p");
        assert!(
            e.text.contains("FULL paragraph 7"),
            "via {}: {}",
            e.source,
            e.text
        );
    }

    #[test]
    fn ordinary_articles_are_not_replaced_by_hydration_noise() {
        // A normal article page that also ships a small state blob.
        let html = format!(
            r#"<html><head><title>A</title></head><body><article><p>{}</p><p>{}</p></article>
            <script>window.__INITIAL_STATE__ = {{"related":"{}"}};</script></body></html>"#,
            prose("REAL", 6),
            prose("ALSO", 6),
            prose("RELATED", 1)
        );
        let e = extract(&html, "https://example.org/a");
        assert_ne!(e.source, "hydration");
        assert!(e.text.contains("REAL paragraph 5"));
    }

    #[test]
    fn wires_modified_time_fallback_and_extended_metadata() {
        let html = format!(
            r#"<!DOCTYPE html><html lang="en-US"><head>
            <title>Microservices Guide</title>
            <meta name="dcterms.modified" content="2026-02-20">
            <script type="application/ld+json">
            {{
                "@context": "https://schema.org",
                "@graph": [
                    {{
                        "@type": ["Article", "TechArticle"],
                        "headline": "Microservices Architecture Guide",
                        "author": {{ "@type": "Person", "name": "Martin Fowler" }},
                        "publisher": {{ "@type": "Organization", "name": "martinfowler.com" }}
                    }}
                ]
            }}
            </script>
            </head><body><article><p>{}</p><p>{}</p></article></body></html>"#,
            prose("ARCH", 4),
            prose("DESIGN", 4)
        );
        let got = extract(
            &html,
            "https://martinfowler.com/articles/microservices.html",
        );
        assert_eq!(got.source, "readability");
        assert_eq!(got.title, "Microservices Architecture Guide");
        assert_eq!(got.language.as_deref(), Some("en"));
        assert_eq!(got.byline.as_deref(), Some("Martin Fowler"));
        assert_eq!(got.site_name.as_deref(), Some("martinfowler.com"));
        assert!(
            got.published.is_some(),
            "modified_time fallback must populate published"
        );
    }

    #[test]
    fn unwraps_noscript_fallback_on_spa_shell() {
        let html = format!(
            r#"<!DOCTYPE html><html lang="en"><head>
            <title>PEP 703 Thread</title>
            <meta property="og:site_name" content="Discussions on Python.org">
            <meta property="article:published_time" content="2023-07-28T20:44:43+00:00">
            </head><body>
            <div id="spa-root"></div>
            <noscript><div id="main-outlet" role="main"><article><h1>PEP 703</h1><p>{}</p><p>{}</p></article></div></noscript>
            </body></html>"#,
            prose("GIL", 4),
            prose("THREAD", 4)
        );
        let got = extract(&html, "https://discuss.python.org/t/pep-703/123");
        assert!(
            got.text.contains("GIL paragraph 3"),
            "noscript content missing: {}",
            got.text
        );
        assert_eq!(got.site_name.as_deref(), Some("Discussions on Python.org"));
        assert!(got.published.is_some());
    }
}