fetchium-core 1.0.0

Fetchium core library โ€” search, extract, rank, validate, cache
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
//! HyperFusion 8-signal implementations (PRD ยง8.1).
//!
//! Each signal returns f64 in [0.0, 1.0].
//! Used by the fusion module to compute weighted combined scores.

use crate::types::ResultItem;
use chrono::Datelike;
use std::collections::{HashMap, HashSet};
use tracing::trace;

/// Context maintained across scoring all results in a batch.
///
/// Shared mutable state needed by diversity and consensus signals.
pub struct ScoringContext {
    /// Lowercase query terms (2+ chars, alphanumeric).
    pub query_terms: Vec<String>,
    /// Domains already seen in the output (for diversity penalty).
    pub seen_domains: HashSet<String>,
    /// All snippets/titles from the result set (for consensus scoring).
    pub all_text: Vec<String>,
    /// URL โ†’ index into `all_text` for zero-copy per-result text lookup.
    pub result_text_index: HashMap<String, usize>,
    /// Pre-tokenized and lowercased words for each result.
    pub result_words: Vec<Vec<String>>,
    /// Word frequencies for each result (word -> count).
    pub result_term_freqs: Vec<HashMap<String, u32>>,
    /// Pre-computed query embedding.
    pub query_embedding: Option<Vec<f32>>,
    /// Pre-computed result embeddings, keyed by URL.
    pub result_embeddings: std::collections::HashMap<String, Vec<f32>>,
}

impl ScoringContext {
    pub fn new(query: &str, results: &[ResultItem]) -> Self {
        let query_terms: Vec<String> = query
            .to_lowercase()
            .split(|c: char| !c.is_alphanumeric())
            .filter(|t| t.len() >= 2)
            .map(|t| t.to_string())
            .collect();

        let all_text: Vec<String> = results
            .iter()
            .map(|r| format!("{} {}", r.title, r.snippet).to_lowercase())
            .collect();

        let mut result_words = Vec::with_capacity(results.len());
        let mut result_term_freqs = Vec::with_capacity(results.len());

        for text in &all_text {
            let words: Vec<String> = text.split_whitespace().map(|s| s.to_string()).collect();
            let mut freqs = HashMap::new();
            for word in &words {
                *freqs.entry(word.clone()).or_insert(0) += 1;
            }
            result_words.push(words);
            result_term_freqs.push(freqs);
        }

        let result_text_index: HashMap<String, usize> = results
            .iter()
            .enumerate()
            .map(|(i, r)| (r.url.clone(), i))
            .collect();

        // Lazily compute query embedding when embeddings feature is enabled
        #[cfg(feature = "embeddings")]
        let query_embedding = crate::embeddings::embed(query).ok();

        #[cfg(not(feature = "embeddings"))]
        let query_embedding: Option<Vec<f32>> = None;

        // Batch-embed all results in a single inference pass (Nร—15ms โ†’ 1ร—20ms).
        #[cfg(feature = "embeddings")]
        let result_embeddings = {
            let full_texts: Vec<String> = results
                .iter()
                .map(|r| format!("{} {}", r.title, r.snippet))
                .collect();
            let text_refs: Vec<&str> = full_texts.iter().map(|s| s.as_str()).collect();
            match crate::embeddings::embed_batch(&text_refs) {
                Ok(embs) => results
                    .iter()
                    .zip(embs)
                    .map(|(r, e)| (r.url.clone(), e))
                    .collect(),
                Err(_) => std::collections::HashMap::new(),
            }
        };

        #[cfg(not(feature = "embeddings"))]
        let result_embeddings: std::collections::HashMap<String, Vec<f32>> =
            std::collections::HashMap::new();

        Self {
            query_terms,
            seen_domains: HashSet::new(),
            all_text,
            result_text_index,
            result_words,
            result_term_freqs,
            query_embedding,
            result_embeddings,
        }
    }
}

// โ”€โ”€โ”€ Signal 1: BM25 โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// BM25 relevance of title+snippet against the query.
/// Uses local TF with IDF=1 (no corpus), k1=1.2, b=0.75, avg_dl=80.
pub fn bm25_score(result: &ResultItem, ctx: &ScoringContext) -> f64 {
    const K1: f64 = 1.2;
    const B: f64 = 0.75;
    const AVG_DL: f64 = 80.0;

    if ctx.query_terms.is_empty() {
        return 0.0;
    }

    let idx = match ctx.result_text_index.get(&result.url) {
        Some(&i) => i,
        None => return 0.0,
    };

    let doc_len = ctx.result_words[idx].len() as f64;
    let freqs = &ctx.result_term_freqs[idx];

    let mut score = 0.0f64;
    for term in &ctx.query_terms {
        let tf = freqs.get(term).copied().unwrap_or(0) as f64;
        if tf == 0.0 {
            // Half-weight for substring match (still O(N) but better than before)
            let partial = ctx.result_words[idx]
                .iter()
                .filter(|w| w.contains(term))
                .count() as f64;
            if partial > 0.0 {
                let denom = partial * 0.5 + K1 * (1.0 - B + B * doc_len / AVG_DL);
                score += 0.5 * (partial * 0.5 * (K1 + 1.0)) / denom;
            }
            continue;
        }
        let num = tf * (K1 + 1.0);
        let den = tf + K1 * (1.0 - B + B * doc_len / AVG_DL);
        score += num / den;
    }

    let max_possible = ctx.query_terms.len() as f64 * (K1 + 1.0);
    (score / max_possible).clamp(0.0, 1.0)
}

// โ”€โ”€โ”€ Signal 2: Semantic โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// Semantic similarity between query and result.
///
/// Looks up the pre-computed batch embedding for this result from `ctx.result_embeddings`
/// (populated in `ScoringContext::new()` via a single `embed_batch()` call).
/// Falls back to Jaccard term overlap when embeddings are unavailable.
pub fn semantic_score(result: &ResultItem, ctx: &ScoringContext) -> f64 {
    // Feature-gated: real cosine similarity via pre-computed batch embeddings
    #[cfg(feature = "embeddings")]
    {
        if let (Some(ref query_emb), Some(result_emb)) =
            (&ctx.query_embedding, ctx.result_embeddings.get(&result.url))
        {
            let cosine = crate::embeddings::cosine_similarity(query_emb, result_emb);
            return (cosine.max(0.0) as f64).min(1.0);
        }
    }

    // Fallback: Jaccard term overlap
    jaccard_semantic(result, ctx)
}

/// Jaccard overlap of query terms vs document terms (lexical proxy).
fn jaccard_semantic(result: &ResultItem, ctx: &ScoringContext) -> f64 {
    if ctx.query_terms.is_empty() {
        return 0.5;
    }

    let idx = match ctx.result_text_index.get(&result.url) {
        Some(&i) => i,
        None => return 0.0,
    };

    let doc_words = &ctx.result_words[idx];
    if doc_words.is_empty() {
        return 0.0;
    }

    let query_set: HashSet<&str> = ctx.query_terms.iter().map(|s| s.as_str()).collect();
    let doc_set: HashSet<&str> = doc_words.iter().map(|s| s.as_str()).collect();

    let intersection = query_set.intersection(&doc_set).count();
    let union = query_set.len() + doc_set.len() - intersection;

    if union == 0 {
        return 0.0;
    }

    (intersection as f64 / union as f64).min(1.0)
}

// โ”€โ”€โ”€ Signal 3: Temporal โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// Temporal freshness score with EDF domain-calibrated exponential decay.
///
/// Formula: `exp(-freshness_need ร— ฮป ร— days_old)` where `ฮป = ln(2) / half_life`
/// and `half_life` is the domain-appropriate half-life from EDF (e.g. 7 days
/// for social media, 36 500 days for mathematics).
///
/// - freshness_need=0: temporal doesn't matter โ†’ 1.0
/// - freshness_need=1, days_old=half_life: score โ‰ˆ 0.5
/// - Unknown date โ†’ 0.5 (neutral)
pub fn temporal_score(result: &ResultItem, freshness_need: f64) -> f64 {
    let Some(ref date_str) = result.published_date else {
        return 0.5; // Unknown date = neutral
    };

    let days_old = match parse_days_old(date_str) {
        Some(d) => d,
        None => return 0.5,
    };

    // Look up domain-specific half-life via EDF instead of using a hardcoded 365 days.
    let half_life = crate::intelligence::edf::domain_half_life(&result.url);
    let lambda = std::f64::consts::LN_2 / half_life;
    let score = (-freshness_need * lambda * days_old as f64).exp();
    score.clamp(0.0, 1.0)
}

/// Parse a date string and return days since publication.
fn parse_days_old(date_str: &str) -> Option<u64> {
    // Try ISO 8601 formats (YYYY-MM-DD or YYYY-MM-DDTHH:MM:SSZ)
    let date_part = date_str.split('T').next()?;
    let parts: Vec<&str> = date_part.split('-').collect();
    if parts.len() < 3 {
        // Try just year
        if let Ok(year) = parts.first()?.parse::<i32>() {
            let now = chrono::Utc::now().year();
            let years_old = (now - year).max(0) as u64;
            return Some(years_old * 365);
        }
        return None;
    }

    let year: i32 = parts[0].parse().ok()?;
    let month: u32 = parts[1].parse().ok()?;
    let day: u32 = parts[2].parse().ok()?;

    let pub_date = chrono::NaiveDate::from_ymd_opt(year, month, day)?;
    let today = chrono::Utc::now().naive_utc().date();
    let duration = today.signed_duration_since(pub_date);
    Some(duration.num_days().max(0) as u64)
}

// โ”€โ”€โ”€ Signal 4: Authority โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// Domain authority score based on known authoritative domains + citation count.
///
/// Tier scoring:
/// - High (0.9): wikipedia, github, arxiv, nature, nih.gov, .gov, .edu
/// - Medium (0.7): stackoverflow, medium, bbc, nytimes, reuters
/// - Default (0.5): everything else
pub fn authority_score(result: &ResultItem) -> f64 {
    let domain = extract_domain(&result.url);

    let base = domain_tier_score(&domain);

    // Boost from citation count if encoded in snippet (Scholar results)
    // "Cited by N" โ†’ ln(N) / ln(10000) bonus (capped at 0.3)
    let citation_boost = if let Some(n) = extract_citation_count(&result.snippet) {
        (n as f64).ln().min((10000f64).ln()) / (10000f64).ln() * 0.3
    } else {
        0.0
    };

    (base + citation_boost).min(1.0)
}

/// Zero-allocation subdomain check โ€” avoids `format!(".{domain}")` heap allocation.
#[inline]
fn domain_ends_with_dot(host: &str, domain: &str) -> bool {
    host.len() > domain.len()
        && host.ends_with(domain)
        && host.as_bytes()[host.len() - domain.len() - 1] == b'.'
}

fn domain_tier_score(domain: &str) -> f64 {
    const HIGH_AUTHORITY: &[&str] = &[
        // Knowledge & reference
        "wikipedia.org",
        "britannica.com",
        // Academic & scientific
        "arxiv.org",
        "nature.com",
        "nih.gov",
        "pubmed.ncbi.nlm.nih.gov",
        "scholar.google.com",
        "sciencedirect.com",
        "springer.com",
        // Developer
        "github.com",
        "docs.rs",
        "crates.io",
        "rust-lang.org",
        "python.org",
        "developer.mozilla.org",
        "docs.microsoft.com",
        "learn.microsoft.com",
        "kubernetes.io",
        "docs.docker.com",
        "cloud.google.com",
        "w3.org",
        "tc39.es",
        "whatwg.org",
        "docs.python.org",
        "cppreference.com",
        "devdocs.io",
        // AI/ML research
        "huggingface.co",
        "paperswithcode.com",
        "openai.com",
        "deepmind.google",
        "research.google",
        "ai.meta.com",
        // Standards bodies (missed previously)
        "rfc-editor.org",
        "ietf.org",
        "iso.org",
        "acm.org",
        "ieee.org",
        // Major news
        "nytimes.com",
        "bbc.com",
        "reuters.com",
        "apnews.com",
    ];
    const MEDIUM_AUTHORITY: &[&str] = &[
        // Tech & developer
        "stackoverflow.com",
        "medium.com",
        "dev.to",
        "techcrunch.com",
        "arstechnica.com",
        "wired.com",
        "theverge.com",
        "hackernoon.com",
        "realpython.com",
        "digitalocean.com",
        "css-tricks.com",
        "smashingmagazine.com",
        "baeldung.com",
        "testdriven.io",
        "digital-trends.com",
        "techradar.com",
        "tomsguide.com",
        "pcmag.com",
        "cnet.com",
        "zdnet.com",
        "theregister.com",
        "infoq.com",
        "cisco.com",
        "owasp.org",
        "sans.org",
        "hbr.org",
        "reddit.com",
        "npr.org",
        "ft.com",
        "wsj.com",
        "statista.com",
        "ourworldindata.org",
        "law.cornell.edu",
        // News & journalism
        "theguardian.com",
        "washingtonpost.com",
        "forbes.com",
        "bloomberg.com",
        "cnbc.com",
        // Consumer & lifestyle
        "healthline.com",
        "webmd.com",
        "mayoclinic.org",
        "investopedia.com",
        "nerdwallet.com",
        "wirecutter.com",
        "consumerreports.org",
        "tripadvisor.com",
        "yelp.com",
        "allrecipes.com",
        "epicurious.com",
        "kayak.com",
        "skyscanner.com",
        "timeout.com",
        "eater.com",
        "tastingtable.com",
        "seriouseats.com",
        "theinfatuation.com",
        // HowTo brand authorities
        "tide.com",
        "maytag.com",
        "familyhandyman.com",
        "thisoldhouse.com",
        "instructables.com",
        "wikihow.com",
        "howtocleanstuff.net",
        // Finance
        "bankrate.com",
        "fool.com",
        "kiplinger.com",
        "morningstar.com",
        // Security
        "krebsonsecurity.com",
        "darkreading.com",
        // Academic/learning
        "khanacademy.org",
        "coursera.org",
        "edx.org",
        "mit.edu",
        "stanford.edu",
        // Finance & investment
        "vanguard.com",
        "fidelity.com",
        "schwab.com",
        "investor.gov",
        "sec.gov",
        "federalreserve.gov",
        // Consumer tech reviews
        "soundguys.com",
        "rtings.com",
        "tomsguide.com",
        "anandtech.com",
        "gsmarena.com",
        // Cooking & dining
        "seriouseats.com",
        "bonappetit.com",
        "foodnetwork.com",
        "guide.michelin.com",
        // Travel & local
        "lonelyplanet.com",
        "frommers.com",
        "fodors.com",
        // Multilingual / international news
        "lemonde.fr",
        "lefigaro.fr",
        "tv5monde.com",
        "spektrum.de",
        "spiegel.de",
        "elpais.com",
        "bbc.co.uk",
        "theguardian.com",
        // Medical
        "cdc.gov",
        "who.int",
        "medlineplus.gov",
        "clevelandclinic.org",
        // Developer docs
        "docs.github.com",
        "developer.apple.com",
        "developer.android.com",
    ];

    if HIGH_AUTHORITY
        .iter()
        .any(|h| domain == *h || domain_ends_with_dot(domain, h))
    {
        return 0.9;
    }
    if domain.ends_with(".gov") || domain.ends_with(".edu") {
        return 0.9;
    }
    if MEDIUM_AUTHORITY
        .iter()
        .any(|m| domain == *m || domain_ends_with_dot(domain, m))
    {
        return 0.7;
    }
    0.5
}

fn extract_domain(url: &str) -> String {
    url::Url::parse(url)
        .ok()
        .and_then(|u| u.host_str().map(|h| h.to_lowercase()))
        .unwrap_or_default()
}

fn extract_citation_count(snippet: &str) -> Option<u64> {
    // Match "Cited by 1234" pattern from Google Scholar
    let lower = snippet.to_lowercase();
    let cited_pos = lower.find("cited by ")?;
    let after = &snippet[cited_pos + 9..];
    let num_str: String = after.chars().take_while(|c| c.is_ascii_digit()).collect();
    num_str.parse().ok()
}

// โ”€โ”€โ”€ Signal 5: Evidence โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// Evidence quality score: detects statistical data, citations, measurements.
///
/// Higher score = more evidence-dense content.
pub fn evidence_score(result: &ResultItem) -> f64 {
    let text = format!("{} {}", result.title, result.snippet);
    let text_lower = text.to_lowercase();

    let mut score = 0.0f64;
    let word_count = text.split_whitespace().count().max(1) as f64;

    // Count evidence indicators
    let indicators: &[(&str, f64)] = &[
        ("%", 0.1),
        ("study", 0.08),
        ("research", 0.08),
        ("according to", 0.1),
        ("et al", 0.15),
        ("doi:", 0.15),
        ("abstract", 0.08),
        ("published", 0.05),
        ("journal", 0.1),
        ("experiment", 0.1),
        ("data shows", 0.1),
        ("findings", 0.08),
    ];

    for (indicator, weight) in indicators {
        if text_lower.contains(indicator) {
            score += weight;
        }
    }

    // Count numbers/statistics (words containing digits)
    let stat_count = text
        .split_whitespace()
        .filter(|w| w.chars().any(|c| c.is_ascii_digit()))
        .count() as f64;
    let stat_density = (stat_count / word_count).min(0.3);
    score += stat_density;

    score.clamp(0.0, 1.0)
}

// โ”€โ”€โ”€ Signal 6: Diversity โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// Diversity score: 1.0 for new domain, 0.2 for already-seen domain.
///
/// Context tracks seen domains; call this in result order.
pub fn diversity_score(result: &ResultItem, ctx: &mut ScoringContext) -> f64 {
    let domain = extract_domain(&result.url);
    if domain.is_empty() {
        return 0.5;
    }
    if ctx.seen_domains.contains(&domain) {
        0.2
    } else {
        ctx.seen_domains.insert(domain);
        1.0
    }
}

// โ”€โ”€โ”€ Signal 7: Depth โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// Content depth score: min(word_count / 100, 1.0).
///
/// A snippet of 100+ words scores 1.0.
pub fn depth_score(result: &ResultItem) -> f64 {
    let word_count = result.snippet.split_whitespace().count() as f64;
    (word_count / 100.0).min(1.0)
}

// โ”€โ”€โ”€ Signal 8: Consensus โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// Consensus score: how much this result's content overlaps with other results.
///
/// High consensus = multiple sources confirm the same information.
/// Uses Jaccard similarity against concatenated text of all other results.
pub fn consensus_score(result: &ResultItem, ctx: &ScoringContext) -> f64 {
    if ctx.all_text.len() <= 1 {
        return 0.5;
    }

    // Use pre-computed lowercased text from context index (zero-copy).
    let owned;
    let my_text: &str = if let Some(&idx) = ctx.result_text_index.get(&result.url) {
        &ctx.all_text[idx]
    } else {
        owned = format!("{} {}", result.title, result.snippet).to_lowercase();
        &owned
    };
    let my_terms: HashSet<&str> = my_text.split_whitespace().collect();

    if my_terms.is_empty() {
        return 0.0;
    }

    // Count how many other results share at least 30% of query terms
    let query_set: HashSet<&str> = ctx.query_terms.iter().map(|s| s.as_str()).collect();

    let mut agreement_count = 0usize;
    let others = ctx
        .all_text
        .iter()
        .filter(|t| t.as_str() != my_text)
        .count();

    if others == 0 {
        return 0.5;
    }

    for other_text in &ctx.all_text {
        if other_text.as_str() == my_text {
            continue;
        }
        let other_terms: HashSet<&str> = other_text.split_whitespace().collect();
        // Overlap with query terms
        let shared_query_terms = query_set.intersection(&other_terms).count();
        let my_query_terms = query_set.intersection(&my_terms).count();
        if my_query_terms > 0 && shared_query_terms as f64 / my_query_terms as f64 >= 0.3 {
            agreement_count += 1;
        }
    }

    trace!(
        "consensus: {}/{} agreement for {:?}",
        agreement_count,
        others,
        result.title
    );
    (agreement_count as f64 / others as f64).min(1.0)
}

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

    fn make_result(title: &str, url: &str, snippet: &str) -> ResultItem {
        ResultItem {
            title: title.into(),
            url: url.into(),
            snippet: snippet.into(),
            rank: 1,
            backend: BackendId::DuckDuckGo,
            score: None,
            published_date: None,
        }
    }

    fn make_ctx(query: &str, results: &[ResultItem]) -> ScoringContext {
        ScoringContext::new(query, results)
    }

    #[test]
    fn bm25_scores_relevant_higher() {
        let results = vec![
            make_result(
                "Rust Language",
                "https://rust-lang.org",
                "systems programming language",
            ),
            make_result("Python", "https://python.org", "dynamic scripting language"),
        ];
        let ctx = make_ctx("rust programming", &results);
        let rust_score = bm25_score(&results[0], &ctx);
        let py_score = bm25_score(&results[1], &ctx);
        assert!(
            rust_score > py_score,
            "rust={rust_score}, python={py_score}"
        );
    }

    #[test]
    fn bm25_in_range() {
        let results = vec![make_result("test", "https://example.com", "foo bar baz")];
        let ctx = make_ctx("foo bar", &results);
        let s = bm25_score(&results[0], &ctx);
        assert!((0.0..=1.0).contains(&s));
    }

    #[test]
    fn temporal_unknown_date_is_neutral() {
        let r = make_result("test", "https://x.com", "content");
        assert_eq!(temporal_score(&r, 1.0), 0.5);
    }

    #[test]
    fn temporal_recent_higher_than_old() {
        let today = chrono::Utc::now().format("%Y-%m-%d").to_string();
        let old = "2000-01-01".to_string();

        let mut recent = make_result("recent", "https://x.com", "x");
        recent.published_date = Some(today);
        let mut aged = make_result("old", "https://x.com", "x");
        aged.published_date = Some(old);

        let recent_score = temporal_score(&recent, 1.0);
        let old_score = temporal_score(&aged, 1.0);
        assert!(
            recent_score > old_score,
            "recent={recent_score}, old={old_score}"
        );
    }

    #[test]
    fn authority_wikipedia_high() {
        let r = make_result(
            "Rust",
            "https://en.wikipedia.org/wiki/Rust",
            "A systems language",
        );
        let score = authority_score(&r);
        assert!(score >= 0.9, "score={score}");
    }

    #[test]
    fn authority_random_blog_default() {
        let r = make_result(
            "Blog Post",
            "https://my-random-blog.xyz/post",
            "some content",
        );
        let score = authority_score(&r);
        assert!((0.4..=0.6).contains(&score), "score={score}");
    }

    #[test]
    fn authority_in_range() {
        let r = make_result("test", "https://stackoverflow.com/q/1", "How to use Rust?");
        let s = authority_score(&r);
        assert!((0.0..=1.0).contains(&s));
    }

    #[test]
    fn evidence_statistical_content() {
        let r = make_result(
            "Study",
            "https://nature.com/study",
            "According to research, 47% of users showed improvement. Study published in Nature et al. with doi:10.1234.",
        );
        let score = evidence_score(&r);
        assert!(score > 0.3, "score={score}");
    }

    #[test]
    fn evidence_plain_content_low() {
        let r = make_result("Home", "https://example.com", "Welcome to our website.");
        let score = evidence_score(&r);
        assert!(score < 0.5, "score={score}");
    }

    #[test]
    fn diversity_penalizes_same_domain() {
        let results = vec![
            make_result("A", "https://example.com/1", "content"),
            make_result("B", "https://example.com/2", "content"),
            make_result("C", "https://other.com/1", "content"),
        ];
        let mut ctx = make_ctx("test", &results);
        let s1 = diversity_score(&results[0], &mut ctx);
        let s2 = diversity_score(&results[1], &mut ctx);
        let s3 = diversity_score(&results[2], &mut ctx);
        assert_eq!(s1, 1.0);
        assert_eq!(s2, 0.2);
        assert_eq!(s3, 1.0);
    }

    #[test]
    fn depth_long_snippet_max() {
        let long_snippet = "word ".repeat(200);
        let r = make_result("test", "https://x.com", &long_snippet);
        assert_eq!(depth_score(&r), 1.0);
    }

    #[test]
    fn depth_empty_snippet_zero() {
        let r = make_result("test", "https://x.com", "");
        assert_eq!(depth_score(&r), 0.0);
    }

    #[test]
    fn consensus_scores_in_range() {
        let results = vec![
            make_result(
                "Rust safety",
                "https://a.com",
                "rust is safe and fast systems language",
            ),
            make_result(
                "Rust performance",
                "https://b.com",
                "rust systems language with zero cost",
            ),
            make_result(
                "Python basics",
                "https://c.com",
                "python is dynamic and easy scripting",
            ),
        ];
        let ctx = make_ctx("rust systems", &results);
        for r in &results {
            let s = consensus_score(r, &ctx);
            assert!((0.0..=1.0).contains(&s), "consensus out of range: {s}");
        }
    }
}