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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
#![allow(dead_code)]
//! Common Crawl module for IntentForge v2
//!
//! Implements CDX-based URL discovery with live verification, deduplication,
//! and quality scoring. Supports persistent state for restart detection.

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::io::{BufRead, BufReader, Read};
use std::path::Path;
use std::time::{Duration, Instant};

/// CDX API response entry
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CdxEntry {
    pub urlkey: String,
    pub timestamp: String,
    pub url: String,
    pub mime: String,
    pub status: String,
    pub digest: String,
    pub length: String,
}

/// A single WET record (extracted text)
#[derive(Debug, Clone)]
pub struct WetRecord {
    pub url: String,
    pub date: String,
    pub content: String,
    pub content_length: usize,
}

/// Persistent state for CC delta to detect restarts
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CrawlState {
    pub crawl_id: String,
    pub completed_at: String,
    pub urls_enqueued: u64,
    pub urls_verified: u64,
    pub urls_total: u64,
}

impl CrawlState {
    /// Load state from disk, returns None if not found
    pub fn load(data_dir: &str) -> Option<Self> {
        let path = Path::new(data_dir).join("delta_state.json");
        if !path.exists() {
            return None;
        }
        let content = std::fs::read_to_string(path).ok()?;
        serde_json::from_str(&content).ok()
    }

    /// Save state to disk
    pub fn save(&self, data_dir: &str) -> Result<()> {
        let path = Path::new(data_dir).join("delta_state.json");
        std::fs::create_dir_all(data_dir)
            .with_context(|| format!("Failed to create data dir: {}", data_dir))?;
        let content = serde_json::to_string_pretty(self)?;
        std::fs::write(path, content).with_context(|| "Failed to write delta state")?;
        Ok(())
    }
}

/// Quality score result for a URL
#[derive(Debug, Clone)]
pub struct UrlQuality {
    pub url: String,
    pub score: f32,
    pub is_live: bool,
    pub status_code: u16,
}

/// Compute a quality score for a URL based on domain heuristics
pub fn compute_url_quality(url: &str) -> f32 {
    let mut score: f32 = 0.5;

    let Ok(parsed) = url::Url::parse(url) else {
        return 0.1;
    };

    // HTTPS bonus
    if parsed.scheme() == "https" {
        score += 0.1;
    }

    let host = parsed.host_str().unwrap_or_default().to_lowercase();

    // Trusted TLD bonus
    let trusted_tlds = [".edu", ".gov", ".org"];
    for tld in &trusted_tlds {
        if host.ends_with(tld) {
            score += 0.2;
            break;
        }
    }

    // Known high-quality domains
    let quality_domains = [
        "github.com",
        "arxiv.org",
        "stackoverflow.com",
        "medium.com",
        "wikipedia.org",
        "arstechnica.com",
        "wired.com",
        "techcrunch.com",
        "theverge.com",
        "news.ycombinator.com",
        "reddit.com",
        "dev.to",
        "docs.rs",
    ];
    for domain in &quality_domains {
        if host == *domain || host.ends_with(&format!(".{}", domain)) {
            score += 0.2;
            break;
        }
    }

    // Spam penalties
    let path = parsed.path().to_lowercase();
    let spam_signals = [
        "click",
        "offer",
        "promo",
        "deal",
        "coupon",
        "casino",
        "viagra",
        "buy-now",
        "free-trial",
        "signup?ref=",
        "/ads/",
    ];
    for signal in &spam_signals {
        if path.contains(signal) {
            score -= 0.3;
            break;
        }
    }

    // Short clean paths bonus
    let segment_count = path.split('/').filter(|s| !s.is_empty()).count();
    if segment_count <= 2 {
        score += 0.05;
    }

    score.clamp(0.0, 1.0)
}

/// CDX API client for domain-filtered content discovery
pub struct CdxClient {
    client: reqwest::Client,
    base_url: String,
}

impl CdxClient {
    pub fn new() -> Self {
        let client = reqwest::Client::builder()
            .timeout(Duration::from_secs(30))
            .build()
            .expect("Failed to create CDX HTTP client");

        Self {
            client,
            base_url: "https://index.commoncrawl.org".to_string(),
        }
    }

    /// Query CDX index for URLs matching a domain pattern
    pub async fn query_domain(
        &self,
        domain: &str,
        crawl_id: Option<&str>,
        limit: usize,
    ) -> Result<Vec<CdxEntry>> {
        let index = crawl_id.unwrap_or("CC-MAIN-2024-51");
        let url = format!(
            "{}/{}-index?url={}&output=json&limit={}",
            self.base_url, index, domain, limit
        );

        tracing::info!("Querying CDX index: {}", url);

        let response = self
            .client
            .get(&url)
            .send()
            .await
            .with_context(|| format!("Failed to query CDX index for domain: {}", domain))?;

        if !response.status().is_success() {
            anyhow::bail!("CDX API returned status: {}", response.status());
        }

        let text = response.text().await?;
        let mut entries = Vec::new();

        for line in text.lines() {
            if let Ok(entry) = serde_json::from_str::<CdxEntry>(line) {
                entries.push(entry);
            }
        }

        Ok(entries)
    }

    /// Query CDX for multiple domains
    pub async fn query_domains(
        &self,
        domains: &[&str],
        crawl_id: Option<&str>,
        limit_per_domain: usize,
    ) -> Result<Vec<CdxEntry>> {
        let mut all_entries = Vec::new();

        for domain in domains {
            match self.query_domain(domain, crawl_id, limit_per_domain).await {
                Ok(entries) => {
                    tracing::info!("Found {} entries for {}", entries.len(), domain);
                    all_entries.extend(entries);
                }
                Err(e) => {
                    tracing::warn!("Failed to query CDX for {}: {}", domain, e);
                }
            }
        }

        Ok(all_entries)
    }
}

/// WET file downloader and parser
pub struct WetProcessor {
    client: reqwest::Client,
    base_url: String,
}

impl WetProcessor {
    pub fn new() -> Self {
        let client = reqwest::Client::builder()
            .timeout(Duration::from_secs(120))
            .build()
            .expect("Failed to create WET HTTP client");

        Self {
            client,
            base_url: "https://data.commoncrawl.org".to_string(),
        }
    }

    /// Download and parse a WET file by its path
    pub async fn process_wet_file(&self, wet_path: &str) -> Result<Vec<WetRecord>> {
        let url = format!("{}/{}", self.base_url, wet_path);
        tracing::info!("Downloading WET file: {}", url);

        let response = self
            .client
            .get(&url)
            .send()
            .await
            .with_context(|| format!("Failed to download WET file: {}", url))?;

        if !response.status().is_success() {
            anyhow::bail!("WET download failed with status: {}", response.status());
        }

        let bytes = response
            .bytes()
            .await
            .with_context(|| "Failed to read WET file body")?;

        self.parse_wet_gzipped(&bytes)
    }

    /// Parse gzipped WET content
    fn parse_wet_gzipped(&self, gzipped: &[u8]) -> Result<Vec<WetRecord>> {
        use std::io::Cursor;

        let cursor = Cursor::new(gzipped);
        let decoder = flate2::read::GzDecoder::new(cursor);
        let reader = BufReader::new(decoder);

        self.parse_wet_records(reader)
    }

    /// Parse WET format records from a reader
    fn parse_wet_records<R: Read>(&self, reader: BufReader<R>) -> Result<Vec<WetRecord>> {
        let mut records = Vec::new();
        let mut lines = reader.lines();

        let mut current_url = String::new();
        let mut current_date = String::new();
        let mut current_length: usize = 0;
        let mut in_record = false;
        let mut content_buffer = String::new();

        while let Some(Ok(line)) = lines.next() {
            if line.starts_with("WARC/1.0") {
                // Save previous record if exists
                if in_record && !content_buffer.is_empty() {
                    records.push(WetRecord {
                        url: current_url.clone(),
                        date: current_date.clone(),
                        content: content_buffer.clone(),
                        content_length: current_length,
                    });
                }

                // Reset for new record
                in_record = false;
                content_buffer.clear();
                current_url.clear();
                current_date.clear();
                current_length = 0;
            } else if line.starts_with("WARC-Type: conversion") {
                in_record = true;
            } else if let Some(stripped) = line.strip_prefix("WARC-Target-URI:") {
                current_url = stripped.trim().to_string();
            } else if let Some(stripped) = line.strip_prefix("WARC-Date:") {
                current_date = stripped.trim().to_string();
            } else if let Some(stripped) = line.strip_prefix("Content-Length:") {
                current_length = stripped.trim().parse().unwrap_or(0);
            } else if in_record && !line.is_empty() {
                content_buffer.push_str(&line);
                content_buffer.push('\n');
            }
        }

        // Don't forget the last record
        if in_record && !content_buffer.is_empty() {
            records.push(WetRecord {
                url: current_url,
                date: current_date,
                content: content_buffer,
                content_length: current_length,
            });
        }

        Ok(records)
    }

    /// List available WET file paths for a crawl
    pub async fn list_wet_files(&self, crawl_id: &str) -> Result<Vec<String>> {
        let url = format!("{}/crawl-data/{}/wat.paths.gz", self.base_url, crawl_id);

        tracing::info!("Listing WET files for crawl: {}", crawl_id);

        let response = self.client.get(&url).send().await;

        match response {
            Ok(resp) if resp.status().is_success() => {
                // This is a gzipped file listing - parse it
                let bytes = resp.bytes().await?;
                let mut decoder = flate2::read::GzDecoder::new(&bytes[..]);
                let mut content = String::new();
                decoder.read_to_string(&mut content)?;

                // Convert WAT paths to WET paths
                let wet_paths: Vec<String> = content
                    .lines()
                    .filter(|l| !l.is_empty())
                    .map(|l| {
                        l.replace("/wat/", "/wet/")
                            .replace(".wat.gz", ".warc.wet.gz")
                    })
                    .collect();

                Ok(wet_paths)
            }
            _ => {
                tracing::warn!("Could not list WET files, returning empty list");
                Ok(Vec::new())
            }
        }
    }
}

/// Configuration for Common Crawl processing
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommonCrawlConfig {
    pub crawl_id: String,
    pub domains: Vec<String>,
    pub max_entries_per_domain: usize,
    pub max_wet_files: usize,
    pub min_content_length: usize,
}

impl Default for CommonCrawlConfig {
    fn default() -> Self {
        Self {
            crawl_id: "CC-MAIN-2024-51".to_string(),
            domains: vec![
                "github.com".to_string(),
                "arxiv.org".to_string(),
                "news.ycombinator.com".to_string(),
                "stackoverflow.com".to_string(),
            ],
            max_entries_per_domain: 100,
            max_wet_files: 5,
            min_content_length: 200,
        }
    }
}

/// Main Common Crawl pipeline
pub struct CommonCrawlPipeline {
    config: CommonCrawlConfig,
    cdx_client: CdxClient,
    wet_processor: WetProcessor,
}

impl CommonCrawlPipeline {
    pub fn new(config: CommonCrawlConfig) -> Self {
        Self {
            config,
            cdx_client: CdxClient::new(),
            wet_processor: WetProcessor::new(),
        }
    }

    /// Run the full pipeline: CDX query -> WET download -> parse
    pub async fn run(&self) -> Result<Vec<WetRecord>> {
        let start = Instant::now();
        tracing::info!(
            "Starting Common Crawl pipeline for {} domains",
            self.config.domains.len()
        );

        // Step 1: Query CDX for domain-filtered entries
        let domain_refs: Vec<&str> = self.config.domains.iter().map(|s| s.as_str()).collect();
        let cdx_entries = self
            .cdx_client
            .query_domains(
                &domain_refs,
                Some(&self.config.crawl_id),
                self.config.max_entries_per_domain,
            )
            .await?;

        tracing::info!("Found {} CDX entries", cdx_entries.len());

        // Step 2: Filter by content type
        let html_entries: Vec<_> = cdx_entries
            .into_iter()
            .filter(|e| e.mime.contains("html") || e.mime.contains("text"))
            .collect();

        tracing::info!("Filtered to {} HTML/text entries", html_entries.len());

        // Step 3: Filter by minimum content length
        let filtered_entries: Vec<_> = html_entries
            .into_iter()
            .filter(|e| {
                e.length
                    .parse::<usize>()
                    .unwrap_or(0)
                    .ge(&self.config.min_content_length)
            })
            .collect();

        tracing::info!("After length filter: {} entries", filtered_entries.len());

        // For now, return CDX metadata as WetRecord summaries
        // Full WET processing would be done in a background job
        let records: Vec<WetRecord> = filtered_entries
            .into_iter()
            .map(|e| WetRecord {
                url: e.url,
                date: e.timestamp,
                content: String::new(),
                content_length: e.length.parse().unwrap_or(0),
            })
            .take(self.config.max_entries_per_domain * self.config.domains.len())
            .collect();

        tracing::info!(
            "Common Crawl pipeline completed in {:.2}s, {} records",
            start.elapsed().as_secs_f64(),
            records.len()
        );

        Ok(records)
    }
}

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

    #[test]
    fn test_common_crawl_config_default() {
        let config = CommonCrawlConfig::default();
        assert!(!config.domains.is_empty());
        assert!(config.max_entries_per_domain > 0);
        assert!(config.min_content_length > 0);
    }

    #[test]
    fn test_cdx_client_creation() {
        let client = CdxClient::new();
        assert!(!client.base_url.is_empty());
    }

    #[test]
    fn test_wet_processor_creation() {
        let processor = WetProcessor::new();
        assert!(!processor.base_url.is_empty());
    }

    #[test]
    fn test_pipeline_creation() {
        let config = CommonCrawlConfig::default();
        let pipeline = CommonCrawlPipeline::new(config);
        assert_eq!(pipeline.config.domains.len(), 4);
    }

    #[test]
    fn test_url_quality_https_bonus() {
        let https_score = compute_url_quality("https://example.com/page");
        let http_score = compute_url_quality("http://example.com/page");
        assert!(https_score > http_score);
    }

    #[test]
    fn test_url_quality_trusted_tld() {
        let org_score = compute_url_quality("https://example.org/article");
        let com_score = compute_url_quality("https://example.com/article");
        assert!(org_score > com_score);
    }

    #[test]
    fn test_url_quality_known_domain() {
        let gh_score = compute_url_quality("https://github.com/user/repo");
        let random_score = compute_url_quality("https://random-site.com/page");
        assert!(gh_score > random_score);
    }

    #[test]
    fn test_url_quality_spam_penalty() {
        let normal = compute_url_quality("https://example.com/article");
        let spam = compute_url_quality("https://example.com/click-here-casino");
        assert!(normal > spam);
    }

    #[test]
    fn test_url_quality_invalid_url() {
        let score = compute_url_quality("not-a-url");
        assert_eq!(score, 0.1);
    }

    #[test]
    fn test_url_quality_clamped() {
        let score = compute_url_quality("https://github.com/org/repo");
        assert!((0.0..=1.0).contains(&score));
    }

    #[test]
    fn test_crawl_state_roundtrip() {
        let state = CrawlState {
            crawl_id: "CC-MAIN-2025-08".to_string(),
            completed_at: "2025-03-26T00:00:00Z".to_string(),
            urls_enqueued: 42,
            urls_verified: 100,
            urls_total: 200,
        };
        let dir = std::env::temp_dir().join("intentforge_test_cc");
        let dir_str = dir.to_str().unwrap();
        state.save(dir_str).unwrap();
        let loaded = CrawlState::load(dir_str).unwrap();
        assert_eq!(loaded.crawl_id, "CC-MAIN-2025-08");
        assert_eq!(loaded.urls_enqueued, 42);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_crawl_state_missing() {
        let loaded = CrawlState::load("/nonexistent/path");
        assert!(loaded.is_none());
    }
}