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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
//! Discovery service for IntentForge v2
//!
//! Continuously discovers new content via sitemaps, RSS, and link following.

pub mod enhanced;

use anyhow::{Context, Result};
use async_recursion::async_recursion;
use redis::aio::ConnectionManager;
use redis::AsyncCommands;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tokio::time::Duration;
use tracing::{info, warn};

use crate::config::Config;
use crate::inference::FastIntentScorer;
use crate::trending::{DomainSource, SourcesConfig};

/// Results from sitemap parsing
#[derive(Debug, Clone)]
pub enum SitemapResult {
    Urls(Vec<String>),
    Indices(Vec<String>),
    Empty,
}

/// Redis keys for discovery
const DISCOVERY_QUEUE: &str = "crawl:queue";
const DISCOVERY_SEEN: &str = "crawl:seen";

/// Discovery service
pub struct DiscoveryService {
    config: Arc<Config>,
    sources: Arc<SourcesConfig>,
    redis: ConnectionManager,
    client: reqwest::Client,
    meili: Option<meilisearch_sdk::client::Client>,
    last_cycle: std::sync::Mutex<Option<std::time::Instant>>,
    fast_scorer: FastIntentScorer,
}

impl DiscoveryService {
    /// Create a new discovery service
    pub async fn new(
        config: Arc<Config>,
        sources: Arc<SourcesConfig>,
        fast_scorer: FastIntentScorer,
    ) -> Result<Self> {
        let client = redis::Client::open(config.redis.url.clone())
            .with_context(|| "Failed to connect to Redis for DiscoveryService")?;

        let redis = ConnectionManager::new(client)
            .await
            .with_context(|| "Failed to create Redis ConnectionManager")?;

        let mut headers = reqwest::header::HeaderMap::new();
        headers.insert("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7".parse().unwrap());
        headers.insert("Accept-Language", "en-US,en;q=0.9".parse().unwrap());
        headers.insert("Cache-Control", "max-age=0".parse().unwrap());
        headers.insert(
            "Sec-Ch-Ua",
            "\"Not A(Brand\";v=\"99\", \"Google Chrome\";v=\"121\", \"Chromium\";v=\"121\""
                .parse()
                .unwrap(),
        );
        headers.insert("Sec-Ch-Ua-Mobile", "?0".parse().unwrap());
        headers.insert("Sec-Ch-Ua-Platform", "\"Windows\"".parse().unwrap());
        headers.insert("Sec-Fetch-Dest", "document".parse().unwrap());
        headers.insert("Sec-Fetch-Mode", "navigate".parse().unwrap());
        headers.insert("Sec-Fetch-Site", "none".parse().unwrap());
        headers.insert("Sec-Fetch-User", "?1".parse().unwrap());
        headers.insert("Upgrade-Insecure-Requests", "1".parse().unwrap());

        let client = reqwest::Client::builder()
            .user_agent(&config.crawler.user_agent)
            .default_headers(headers)
            .timeout(Duration::from_secs(config.crawler.timeout_secs))
            .build()
            .with_context(|| "Failed to create HTTP client for DiscoveryService")?;

        let meili = if config.meilisearch.enabled
            && !config.meilisearch.url.is_empty()
            && !config.meilisearch.master_key.is_empty()
        {
            let client = meilisearch_sdk::client::Client::new(
                &config.meilisearch.url,
                Some(&config.meilisearch.master_key),
            )
            .with_context(|| "Failed to create Meilisearch client for DiscoveryService")?;
            Some(client)
        } else {
            tracing::info!("Meilisearch disabled in config - outbound link discovery will be disabled");
            None
        };

        Ok(Self {
            config,
            sources,
            redis,
            client,
            meili,
            last_cycle: std::sync::Mutex::new(None),
            fast_scorer,
        })
    }

    /// Run the discovery loop
    pub async fn run(self: Arc<Self>) {
        info!("Starting DiscoveryService with aggressive continuous mode...");
        let mut interval =
            tokio::time::interval(Duration::from_secs(self.config.discovery.interval_secs));

        // Track consecutive successful cycles
        let mut success_count = 0usize;

        loop {
            interval.tick().await;

            // Adaptive interval: run more frequently when queue is empty
            // Clone redis connection manager for thread-safe access
            let mut redis_clone = self.redis.clone();
            let queue_size: usize = redis_clone.zcard(DISCOVERY_QUEUE).await.unwrap_or_default();

            // 0. Check backpressure: Pause if Redis queue is too large
            if queue_size > self.config.discovery.max_queue_size {
                info!(
                    "Discovery paused: crawl queue size ({}) exceeds threshold ({}). Waiting for next cycle.",
                    queue_size, self.config.discovery.max_queue_size
                );
                // Reset interval to a longer wait when full to avoid frequent polling
                interval = tokio::time::interval(Duration::from_secs(300)); // Wait 5 mins
                interval.tick().await; // Consume the immediate tick
                continue;
            }

            // Adjust interval based on queue size
            if queue_size < 50 {
                // Queue is small, run more aggressively
                interval = tokio::time::interval(Duration::from_secs(30));
            } else if queue_size < 200 {
                // Moderate queue
                interval = tokio::time::interval(Duration::from_secs(60));
            } else {
                // Large queue, slow down
                interval =
                    tokio::time::interval(Duration::from_secs(self.config.discovery.interval_secs));
            }

            info!("Running discovery cycle (queue: {})...", queue_size);

            match self.run_cycle().await {
                Ok(_) => {
                    success_count += 1;
                    if success_count.is_multiple_of(10) {
                        info!("Discovery: {} consecutive successful cycles", success_count);
                    }
                }
                Err(e) => {
                    success_count = 0;
                    warn!("Discovery cycle failed: {}", e);
                }
            }
        }
    }

    /// Run a single discovery cycle
    async fn run_cycle(&self) -> Result<()> {
        // Record cycle start time
        {
            let mut last = self.last_cycle.lock().unwrap_or_else(|e| e.into_inner());
            *last = Some(std::time::Instant::now());
        }

        // 1. Process domain sitemaps
        for domain in &self.sources.domains {
            if let Err(e) = self.process_sitemap(domain).await {
                tracing::debug!("Could not process sitemap for {}: {}", domain.name, e);
            }
        }

        // 1b. Process additional sitemaps for more tech content
        for (name, sitemap_url, category) in enhanced::get_additional_sitemaps() {
            let domain = DomainSource {
                name: name.clone(),
                base_url: sitemap_url.clone(),
                category: category.clone(),
                priority: 7,
                sitemap: Some(sitemap_url.clone()),
            };
            if let Err(e) = self.process_sitemap(&domain).await {
                tracing::debug!("Could not process additional sitemap for {}: {}", name, e);
            }
        }

        // 1c. Process additional domains with potential sitemaps
        for (name, base_url, category, sitemap) in enhanced::get_additional_domains() {
            let domain = DomainSource {
                name: name.clone(),
                base_url: base_url.clone(),
                category: category.clone(),
                priority: 6,
                sitemap,
            };
            if let Err(e) = self.process_sitemap(&domain).await {
                tracing::debug!("Could not process additional domain for {}: {}", name, e);
            }
        }

        // 2. (Optional) Outbound link discovery from Meilisearch
        if self.config.discovery.follow_links {
            if let Err(e) = self.discover_outbound_links().await {
                warn!("Outbound link discovery failed: {}", e);
            }
        }

        Ok(())
    }

    /// Process a domain's sitemap
    async fn process_sitemap(&self, domain: &DomainSource) -> Result<()> {
        let sitemap_url = domain
            .sitemap
            .clone()
            .unwrap_or_else(|| format!("{}/sitemap.xml", domain.base_url));

        self.process_sitemap_recursive(domain, &sitemap_url, 0)
            .await
    }

    /// Recursively process sitemaps and indices
    #[async_recursion]
    async fn process_sitemap_recursive(
        &self,
        domain: &DomainSource,
        url: &str,
        depth: u32,
    ) -> Result<()> {
        if depth > 3 {
            return Ok(());
        }

        info!("Fetching sitemap/feed for {}: {}", domain.name, url);

        let response = self.client.get(url).send().await?;
        if !response.status().is_success() {
            anyhow::bail!("Fetch failed for {} with status {}", url, response.status());
        }

        let content_type = response
            .headers()
            .get(reqwest::header::CONTENT_TYPE)
            .and_then(|v| v.to_str().ok())
            .unwrap_or("")
            .to_string();

        let bytes = response.bytes().await?;

        // 1. Try parsing as RSS/Atom first if it looks like a feed or if it's a known feed URL
        if url.contains("/feed")
            || url.contains("rss.xml")
            || url.contains("atom.xml")
            || content_type.contains("xml")
        {
            if let Ok(urls) = self.parse_rss_as_sitemap(&bytes) {
                if !urls.is_empty() {
                    info!(
                        "Discovered {} URLs from feed of {}",
                        urls.len(),
                        domain.name
                    );
                    let mut redis = self.redis.clone();
                    for u in urls {
                        self.enqueue_url(&mut redis, &u, domain.priority, &domain.category)
                            .await?;
                    }
                    return Ok(());
                }
            }
        }

        // 2. Try parsing as Sitemap XML
        let body = String::from_utf8_lossy(&bytes);
        let result = self.parse_sitemap_advanced(&body)?;

        match result {
            SitemapResult::Urls(urls) => {
                info!(
                    "Discovered {} URLs from sitemap of {}",
                    urls.len(),
                    domain.name
                );
                let mut redis = self.redis.clone();
                for u in urls {
                    self.enqueue_url(&mut redis, &u, domain.priority, &domain.category)
                        .await?;
                }
            }
            SitemapResult::Indices(indices) => {
                info!(
                    "Found {} nested sitemaps in index for {}",
                    indices.len(),
                    domain.name
                );
                for index_url in indices {
                    // Avoid self-recursion if index points to itself
                    if index_url != url {
                        let _ = self
                            .process_sitemap_recursive(domain, &index_url, depth + 1)
                            .await;
                    }
                }
            }
            SitemapResult::Empty => {
                info!("No URLs discovered from {}", url);
            }
        }

        Ok(())
    }

    /// Parse RSS/Atom as a list of URLs
    fn parse_rss_as_sitemap(&self, bytes: &[u8]) -> Result<Vec<String>> {
        let feed = feed_rs::parser::parse(bytes)?;
        let mut urls = Vec::new();
        for entry in feed.entries {
            if let Some(link) = entry.links.first() {
                urls.push(link.href.clone());
            }
        }
        Ok(urls)
    }

    /// Parse sitemap XML into URLs or Nested Indices
    fn parse_sitemap_advanced(&self, body: &str) -> Result<SitemapResult> {
        let is_index = body.contains("<sitemapindex");

        let re = regex::Regex::new(r"<loc>(.*?)</loc>")?;
        let mut urls = Vec::new();
        let mut indices = Vec::new();

        for cap in re.captures_iter(body) {
            if let Some(m) = cap.get(1) {
                let url = m.as_str().to_string();
                if is_index
                    || url.ends_with(".xml")
                    || url.ends_with(".xml.gz")
                    || url.contains("sitemap")
                {
                    indices.push(url);
                } else {
                    urls.push(url);
                }
            }
        }

        if !urls.is_empty() {
            Ok(SitemapResult::Urls(urls))
        } else if !indices.is_empty() {
            Ok(SitemapResult::Indices(indices))
        } else {
            Ok(SitemapResult::Empty)
        }
    }

    /// Enqueue a URL for crawling
    /// Returns true if URL is new, false if already seen
    async fn enqueue_url(
        &self,
        redis: &mut ConnectionManager,
        url: &str,
        priority: u32,
        category: &str,
    ) -> Result<bool> {
        // Fast Intent Scorer Pre-filter
        if !self.fast_scorer.passes(url) {
            tracing::debug!(
                "FastIntentScorer rejected URL (score={:.2} < {:.2}): {}",
                self.fast_scorer.score(url),
                self.fast_scorer.threshold(),
                url
            );
            return Ok(false);
        }

        // Check if seen (using SADD as a set-based seen list)
        let is_new: bool = redis.sadd(DISCOVERY_SEEN, url).await?;
        if !is_new {
            return Ok(false);
        }

        // Add to sorted set queue
        // Score: priority * 1000000 + timestamp (wrapped to fit in score)
        // Using 1,000,000 for priority spacing to ensure it dominates the timestamp
        let now = chrono::Utc::now().timestamp();
        let score = (priority as i64 * 1000000) + (now % 1000000);

        let member = serde_json::to_string(&QueuedUrl {
            url: url.to_string(),
            category: category.to_string(),
            priority,
        })?;

        redis
            .zadd::<_, _, _, ()>(DISCOVERY_QUEUE, member, score)
            .await?;
        Ok(true)
    }

    /// Extract outbound links from high-signal indexed pages
    async fn discover_outbound_links(&self) -> Result<()> {
        let meili = match &self.meili {
            Some(client) => client,
            None => {
                tracing::debug!("Outbound link discovery skipped: Meilisearch is disabled");
                return Ok(());
            }
        };

        info!("Starting outbound link discovery...");
        use crate::crawler::find_links;
        use crate::indexer::IntentDocument;

        // Query Meilisearch for high-quality pages
        let index = meili.index(&self.config.meilisearch.index_name);

        // Search for documents with relevance_score > threshold
        let threshold = self.config.discovery.link_threshold;
        let results = index
            .search()
            .with_filter(&format!("relevance_score > {}", threshold))
            .with_limit(20)
            .execute::<IntentDocument>()
            .await?;

        info!(
            "Found {} high-quality pages for link extraction",
            results.hits.len()
        );

        let mut conn = self.redis.clone();
        for hit in results.hits {
            let doc = hit.result;

            // Re-fetch the page to get HTML for link extraction
            // (Budgeted by rate limiter in enqueue_url or if we added it here)
            let response = match self.client.get(&doc.url).send().await {
                Ok(res) if res.status().is_success() => res,
                _ => continue,
            };

            let html = response.text().await.unwrap_or_default();
            let links = find_links(&html, &doc.url);

            info!("Extracted {} links from {}", links.len(), doc.url);

            for link in links.iter().take(5) {
                // Be conservative with discovered links
                self.enqueue_url(&mut conn, link, 3, &doc.category).await?;
            }
        }

        Ok(())
    }

    /// Pop the highest priority URL from the queue
    pub async fn pop_url(&self) -> Result<Option<QueuedUrl>> {
        let mut redis = self.redis.clone();

        // ZPOPMIN/ZPOPMAX returns [member, score]
        // We use ZPOPMAX because higher score = higher priority
        let results: Vec<(String, f64)> = redis.zpopmax(DISCOVERY_QUEUE, 1).await?;

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

        let (json, _) = &results[0];
        let queued: QueuedUrl = serde_json::from_str(json)
            .with_context(|| "Failed to deserialize QueuedUrl from Redis")?;

        Ok(Some(queued))
    }

    /// Get current queue size
    pub async fn queue_size(&self) -> Result<usize> {
        let mut redis = self.redis.clone();
        let size: usize = redis.zcard(DISCOVERY_QUEUE).await?;
        Ok(size)
    }

    /// Get seconds since last discovery cycle, if any
    pub fn last_cycle_secs(&self) -> Option<u64> {
        let last = self.last_cycle.lock().unwrap_or_else(|e| e.into_inner());
        last.map(|t| t.elapsed().as_secs())
    }

    /// Enqueue a URL for crawling (public API for manual enqueue and CC delta)
    pub async fn enqueue_url_public(
        &self,
        url: &str,
        priority: u32,
        category: &str,
    ) -> Result<bool> {
        let mut redis = self.redis.clone();
        self.enqueue_url(&mut redis, url, priority, category).await
    }

    /// Check if a URL has already been seen (without adding it)
    pub async fn is_url_seen(&self, url: &str) -> Result<bool> {
        let mut redis = self.redis.clone();
        let seen: bool = redis.sismember(DISCOVERY_SEEN, url).await?;
        Ok(seen)
    }
}

/// URL in the crawl queue
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueuedUrl {
    pub url: String,
    pub category: String,
    pub priority: u32,
}