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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
use crate::intent_classifier::QueryIntent;
use crate::meta_search::models::{SearchResponse, SearchResult};
use crate::meta_search::providers::{SearchContext, SearchProvider};
use crate::meta_search::proxy_manager::ProxyManager;
use crate::meta_search::tor::TorManager;
use anyhow::Result;
use futures::stream::{FuturesUnordered, StreamExt};
use reqwest::Client;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use tokio::time::{timeout, Duration};
use tracing::info;

struct ProviderHealth {
    successes: AtomicU64,
    failures: AtomicU64,
    consecutive_failures: AtomicU64,
    last_success_epoch: AtomicU64,
}

impl ProviderHealth {
    fn new() -> Self {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        Self {
            successes: AtomicU64::new(0),
            failures: AtomicU64::new(0),
            consecutive_failures: AtomicU64::new(0),
            last_success_epoch: AtomicU64::new(now),
        }
    }

    fn record_success(&self) {
        self.successes.fetch_add(1, Ordering::Relaxed);
        self.consecutive_failures.store(0, Ordering::Relaxed);
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        self.last_success_epoch.store(now, Ordering::Relaxed);
    }

    fn record_failure(&self) {
        self.failures.fetch_add(1, Ordering::Relaxed);
        self.consecutive_failures.fetch_add(1, Ordering::Relaxed);
    }

    fn is_healthy(&self) -> bool {
        let consec = self.consecutive_failures.load(Ordering::Relaxed);
        if consec < 3 {
            return true;
        }
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        let last = self.last_success_epoch.load(Ordering::Relaxed);
        now.saturating_sub(last) > 60
    }
}

fn freshness_boost(published_at: &Option<String>) -> f32 {
    let Some(date_str) = published_at else {
        return 0.0;
    };
    let trimmed = date_str.trim();
    if trimmed.len() < 10 {
        return 0.0;
    }
    let date_part = match trimmed.get(..10) {
        Some(s) => s,
        None => return 0.0,
    };
    let parts: Vec<&str> = date_part.split('-').collect();
    if parts.len() != 3 {
        return 0.0;
    }
    let year: u64 = parts[0].parse().unwrap_or(0);
    let month: u64 = parts[1].parse().unwrap_or(6);
    let day: u64 = parts[2].parse().unwrap_or(15);
    if !(2000..=2035).contains(&year) {
        return 0.0;
    }
    let pub_days = (year - 1970) * 365 + (year - 1970) / 4 + (month - 1) * 30 + day;
    let now_days = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
        / 86400;
    let days_ago = now_days.saturating_sub(pub_days) as f64;
    (0.2 * (-days_ago / 120.0).exp()) as f32
}

pub struct MetaSearchAggregator {
    pub providers: Vec<Arc<dyn SearchProvider>>,
    pub news_providers: Vec<Arc<dyn SearchProvider>>,
    pub timeout_ms: u64,
    pub proxy_manager: Arc<ProxyManager>,
    pub tor_manager: Option<Arc<TorManager>>,
    pub client: Arc<Client>,
    provider_health: HashMap<String, Arc<ProviderHealth>>,
}

impl MetaSearchAggregator {
    pub fn new(
        proxy_manager: Arc<ProxyManager>,
        tor_manager: Option<Arc<TorManager>>,
        _whoogle_url: Option<&str>,
        _librex_url: Option<&str>,
        searxng_url: Option<&str>,
    ) -> Self {
        let client = Arc::new(
            Client::builder()
                .user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 IntentForge/0.1")
                .timeout(Duration::from_secs(10))
                .tcp_keepalive(Duration::from_secs(60))
                .pool_idle_timeout(Duration::from_secs(90))
                .build()
                .unwrap_or_default(),
        );

        let mut providers: Vec<Arc<dyn SearchProvider>> = vec![
            // Tier 1: Self-hosted SearXNG (70+ engines via Tor - highest priority)
            // Tier 2: Direct engine providers (API-based, reliable via Tor)
            Arc::new(crate::meta_search::providers::duckduckgo::DuckDuckGoProvider),
            Arc::new(crate::meta_search::providers::bing::BingProvider),
            // Tier 3: Domain-specific providers (all work through Tor)
            Arc::new(crate::meta_search::providers::github::GitHubProvider),
            Arc::new(crate::meta_search::providers::arxiv::ArxivProvider),
            Arc::new(crate::meta_search::providers::reddit::RedditProvider),
            Arc::new(crate::meta_search::providers::gdelt::GDELTProvider),
            Arc::new(crate::meta_search::providers::invidious::InvidiousProvider),
        ];

        // Add self-hosted SearXNG at front for highest priority (works through Tor)
        if let Some(url) = searxng_url {
            if !url.is_empty() {
                providers.insert(
                    0,
                    Arc::new(crate::meta_search::providers::searx::SearxProvider::new(
                        client.clone(),
                        url,
                    )),
                );
            }
        }

        // Skip Whoogle and LibreX - they don't work through Tor (Google CAPTCHAs Tor exit nodes)

        let news_providers: Vec<Arc<dyn SearchProvider>> = vec![
            Arc::new(crate::meta_search::providers::google_news::GoogleNewsProvider),
            Arc::new(crate::meta_search::providers::ddg_news::DuckDuckGoNewsProvider),
            Arc::new(crate::meta_search::providers::gdelt::GDELTProvider),
        ];

        let mut provider_health: HashMap<String, Arc<ProviderHealth>> = HashMap::new();
        for p in &providers {
            provider_health
                .entry(p.name().to_string())
                .or_insert_with(|| Arc::new(ProviderHealth::new()));
        }
        for p in &news_providers {
            provider_health
                .entry(p.name().to_string())
                .or_insert_with(|| Arc::new(ProviderHealth::new()));
        }

        Self {
            providers,
            news_providers,
            timeout_ms: 10000,
            proxy_manager,
            tor_manager,
            client,
            provider_health,
        }
    }

    pub async fn search(&self, query: &str) -> SearchResponse {
        self.search_with_providers_weighted(query, &self.providers, None)
            .await
    }

    pub async fn search_news(&self, query: &str) -> SearchResponse {
        self.search_with_providers_weighted(query, &self.news_providers, None)
            .await
    }

    pub async fn search_news_geo(&self, query: &str, location: &str) -> SearchResponse {
        let start = std::time::Instant::now();
        let mut all_results = Vec::new();
        let news_resp = self.search_news(query).await;
        all_results.push(news_resp.results);
        let enriched_query = format!("{} {}", query, location);
        let enriched_resp = self.search_news(&enriched_query).await;
        all_results.push(enriched_resp.results);

        let ctx = Arc::new(SearchContext {
            proxy_manager: self.proxy_manager.clone(),
            tor_manager: self.tor_manager.clone(),
        });

        for provider in &self.news_providers {
            if provider.name() == "google_news" {
                if let Some(gn_provider) = provider.as_any().downcast_ref::<crate::meta_search::providers::google_news::GoogleNewsProvider>() {
                    if let Ok(res) = gn_provider.get_geo_news(location, "en-US", "US", "US:en", ctx.clone()).await {
                        all_results.push(res);
                    }
                }
            }
        }

        let merged = self.merge_results(all_results);
        let unique = self.deduplicate_results(merged);

        SearchResponse {
            query: query.to_string(),
            results: unique.into_iter().take(100).collect(),
            took_ms: start.elapsed().as_millis() as u64,
        }
    }

    fn merge_results(&self, all_results: Vec<Vec<SearchResult>>) -> Vec<SearchResult> {
        let mut rrf_scores: HashMap<String, (f32, SearchResult)> = HashMap::new();
        let k = 60.0;
        for engine_results in all_results {
            for (rank, result) in engine_results.into_iter().enumerate() {
                let fresh = freshness_boost(&result.published_at);
                let entry = rrf_scores
                    .entry(result.url.clone())
                    .or_insert((0.0, result.clone()));
                entry.0 += (1.0 / (k + rank as f32)) * (1.0 + fresh);
            }
        }
        let mut merged: Vec<SearchResult> = rrf_scores
            .into_iter()
            .map(|(_, (s, mut r))| {
                r.score = s;
                r
            })
            .collect();
        merged.sort_by(|a, b| {
            b.score
                .partial_cmp(&a.score)
                .unwrap_or(std::cmp::Ordering::Equal)
        });
        merged
    }

    fn deduplicate_results(&self, results: Vec<SearchResult>) -> Vec<SearchResult> {
        let mut unique: Vec<SearchResult> = Vec::with_capacity(results.len());
        for result in results {
            let hash =
                crate::utils::compute_simhash(&format!("{} {}", result.title, result.description));
            if !unique.iter().any(|e| {
                crate::utils::simhash_distance(
                    hash,
                    crate::utils::compute_simhash(&format!("{} {}", e.title, e.description)),
                ) <= 3
            }) {
                unique.push(result);
            }
        }
        unique
    }

    pub async fn search_with_intent(
        &self,
        query: &str,
        intent: Option<&QueryIntent>,
    ) -> SearchResponse {
        self.search_with_providers_weighted(query, &self.providers, intent)
            .await
    }

    fn get_provider_weight(&self, provider_name: &str, intent: Option<&QueryIntent>) -> f32 {
        let intent = match intent {
            Some(i) => i,
            None => return 1.0,
        };

        // Base weight for all providers
        let mut weight = 1.0;

        match intent {
            QueryIntent::Programming
            | QueryIntent::DevOps
            | QueryIntent::WebDevelopment
            | QueryIntent::Database => match provider_name {
                "github" => weight = 2.5,
                "stackoverflow" | "searxng" => weight = 2.0,
                "reddit" => weight = 1.5,
                "arxiv" => weight = 1.3,
                "medium" => weight = 1.2,
                _ => {}
            },
            QueryIntent::AIML | QueryIntent::DataScience | QueryIntent::Academic => {
                match provider_name {
                    "arxiv" => weight = 3.0,
                    "github" => weight = 2.0,
                    "searxng" => weight = 1.5,
                    "reddit" => weight = 1.2,
                    _ => {}
                }
            }
            QueryIntent::Cooking
            | QueryIntent::Travel
            | QueryIntent::Fitness
            | QueryIntent::Gardening => match provider_name {
                "searxng" => weight = 2.5,
                "reddit" => weight = 2.0,
                "duckduckgo" | "bing" => weight = 1.3,
                _ => {}
            },
            QueryIntent::News | QueryIntent::Sports | QueryIntent::Finance => match provider_name {
                "gdelt" => weight = 2.5,
                "searxng" => weight = 2.0,
                "bing" => weight = 1.5,
                "reddit" => weight = 1.3,
                _ => {}
            },
            QueryIntent::Gaming => match provider_name {
                "reddit" => weight = 2.5,
                "searxng" => weight = 2.0,
                _ => {}
            },
            _ => {
                // For other intents, boost general-purpose providers
                match provider_name {
                    "searxng" => weight = 1.5,
                    "duckduckgo" => weight = 1.2,
                    _ => {}
                }
            }
        }

        weight
    }

    pub async fn search_with_providers_weighted(
        &self,
        query: &str,
        providers: &[Arc<dyn SearchProvider>],
        intent: Option<&QueryIntent>,
    ) -> SearchResponse {
        let start = std::time::Instant::now();
        let query_owned = query.to_string();
        let query_lower = query.to_lowercase();

        let is_code = query_lower.contains("repo")
            || query_lower.contains("github")
            || query_lower.contains("rust");
        let is_news = query_lower.contains("news") || query_lower.contains("breaking");
        let is_video = query_lower.contains("video") || query_lower.contains("watch");

        let ctx = Arc::new(SearchContext {
            proxy_manager: self.proxy_manager.clone(),
            tor_manager: self.tor_manager.clone(),
        });

        let mut futures = FuturesUnordered::new();
        for provider in providers {
            let name = provider.name();

            let health = self.provider_health.get(name).cloned();
            if let Some(ref h) = health {
                if !h.is_healthy() {
                    info!(
                        "Provider {} skipped (unhealthy — {} consecutive failures)",
                        name,
                        h.consecutive_failures.load(Ordering::Relaxed)
                    );
                    continue;
                }
            }

            let provider = provider.clone();
            let query = query_owned.clone();
            let ctx = ctx.clone();

            let mut priority_boost = 0.0;
            if is_code && name == "github" {
                priority_boost = 0.5;
            }
            if is_news && (name == "gdelt" || name.contains("news")) {
                priority_boost = 0.8;
            }
            if is_video && name == "invidious" {
                priority_boost = 0.8;
            }

            let weight = self.get_provider_weight(name, intent);

            futures.push(async move {
                let name = provider.name();
                // Dynamic timeout: Meta-engines get more time, direct engines are faster
                let provider_timeout = match name {
                    "searxng" => 10000,
                    "whoogle" | "librex" => 8000,
                    "duckduckgo" | "bing" | "reddit" | "github" | "arxiv" | "gdelt" => 8000,
                    _ => 6000,
                };
                match timeout(
                    Duration::from_millis(provider_timeout),
                    provider.search(&query, ctx),
                )
                .await
                {
                    Ok(Ok(mut results)) => {
                        if let Some(h) = &health {
                            h.record_success();
                        }
                        info!(
                            "Provider {} returned {} results (weight={})",
                            name,
                            results.len(),
                            weight
                        );
                        for r in &mut results {
                            r.score += priority_boost;
                        }
                        (name, results, weight)
                    }
                    Ok(Err(e)) => {
                        if let Some(h) = &health {
                            h.record_failure();
                        }
                        info!("Provider {} error: {}", name, e);
                        (name, vec![], weight)
                    }
                    Err(_) => {
                        if let Some(h) = &health {
                            h.record_failure();
                        }
                        info!("Provider {} timed out", name);
                        (name, vec![], weight)
                    }
                }
            });
        }

        let mut all_results: Vec<(Vec<SearchResult>, f32)> = Vec::new();
        let mut total_count = 0;
        let mut high_quality_engines_responded = 0;
        let target_count = 20;
        let fast_threshold = 8;
        let fast_deadline_ms = 1200;

        let deadline = tokio::time::sleep(Duration::from_millis(self.timeout_ms));
        let fast_deadline = tokio::time::sleep(Duration::from_millis(fast_deadline_ms));
        tokio::pin!(deadline);
        tokio::pin!(fast_deadline);

        loop {
            tokio::select! {
                res = futures.next() => {
                    match res {
                        Some((name, results, weight)) => {
                            let is_hq = name == "searxng" || name == "whoogle" || name == "librex";

                            // If an HQ engine returned zero results (likely blocked), we don't increment HQ count
                            // but we keep going to allow other providers to fill the gap.
                            if is_hq && !results.is_empty() {
                                high_quality_engines_responded += 1;
                            }

                            if !results.is_empty() {
                                total_count += results.len();
                                all_results.push((results, weight));
                            }

                            // Dynamic Early Exit Strategy:
                            // 1. If we have at least one HQ engine and met the target count
                            if high_quality_engines_responded >= 1 && total_count >= target_count {
                                info!("Target reached with HQ engine ({}): Early exit in {}ms", total_count, start.elapsed().as_millis());
                                break;
                            }
                            // 2. If we have results from multiple engines and it's taking too long
                            if total_count >= 50 {
                                info!("High result count ({}): Early exit in {}ms", total_count, start.elapsed().as_millis());
                                break;
                            }
                        }
                        None => break,
                    }
                }
                _ = &mut fast_deadline => {
                    // If we already have a decent number of results after the fast deadline, don't wait for slow ones
                    if total_count >= fast_threshold && high_quality_engines_responded >= 1 {
                        info!("Fast deadline hit with results ({}): Early exit in {}ms", total_count, start.elapsed().as_millis());
                        break;
                    }
                }
                _ = &mut deadline => {
                    info!("Global timeout hit ({}ms). Returning {} results, HQ_engines={}", self.timeout_ms, total_count, high_quality_engines_responded);
                    break;
                }
            }
        }

        let query_clone = query.to_string();
        let unique = tokio::task::spawn_blocking(move || {
            let mut rrf_scores: HashMap<String, (f32, SearchResult)> = HashMap::new();
            let k = 60.0;
            for (engine_results, weight) in all_results {
                for (rank, result) in engine_results.into_iter().enumerate() {
                    let fresh = freshness_boost(&result.published_at);
                    let entry = rrf_scores
                        .entry(result.url.clone())
                        .or_insert((0.0, result.clone()));
                    entry.0 += (weight / (k + rank as f32)) * (1.0 + fresh);
                }
            }
            let mut merged: Vec<SearchResult> = rrf_scores
                .into_iter()
                .map(|(_, (s, mut r))| {
                    r.score = s;
                    r
                })
                .collect();
            merged.sort_by(|a, b| {
                b.score
                    .partial_cmp(&a.score)
                    .unwrap_or(std::cmp::Ordering::Equal)
            });

            let mut unique: Vec<SearchResult> = Vec::with_capacity(merged.len());
            for result in merged {
                let text = format!("{} {}", result.title, result.description);
                let hash = crate::utils::compute_simhash(&text);

                let mut is_dup = false;
                for u in &unique {
                    let utext = format!("{} {}", u.title, u.description);
                    let uhash = crate::utils::compute_simhash(&utext);
                    if crate::utils::simhash_distance(hash, uhash) <= 3 {
                        is_dup = true;
                        break;
                    }
                }
                if !is_dup {
                    unique.push(result);
                }
            }
            unique
        })
        .await
        .unwrap_or_default();

        SearchResponse {
            query: query_clone,
            results: unique.into_iter().take(100).collect(),
            took_ms: start.elapsed().as_millis() as u64,
        }
    }

    pub async fn search_results(&self, query: &str) -> Result<Vec<SearchResult>> {
        let response = self.search(query).await;
        Ok(response.results)
    }

    pub async fn fast_search_results(
        &self,
        query: &str,
        timeout_ms: u64,
    ) -> Result<Vec<SearchResult>> {
        let start = std::time::Instant::now();
        let results = match timeout(
            Duration::from_millis(timeout_ms),
            self.search_results(query),
        )
        .await
        {
            Ok(Ok(res)) => res,
            _ => vec![],
        };
        tracing::info!(
            "Fast meta-search for '{}' took {}ms",
            query,
            start.elapsed().as_millis()
        );
        Ok(results)
    }
}