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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
#![allow(clippy::too_many_arguments, dead_code)]
//! Crawler module for IntentForge v2
//!
//! High-performance web crawler with robots.txt compliance,
//! static-first fetching, adaptive rate limiting, and Trafilatura integration.

pub mod extractor;

use crate::crawler::extractor::FastExtractor;
use anyhow::{Context, Result};
use reqwest::Client;
use robotstxt::DefaultMatcher;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::{Mutex, Semaphore};

/// Pre-fetch information from HTTP HEAD request
#[derive(Debug, Clone)]
pub struct PreFetchInfo {
    pub content_type: String,
    pub content_length: u64,
    pub etag: Option<String>,
}

/// Crawl result with extracted content
#[derive(Debug, Clone)]
pub struct CrawlResult {
    pub url: String,
    pub title: String,
    pub content: String,
    pub html: Option<String>,
    pub status: u16,
    pub fetch_time_ms: u64,
    pub is_dynamic: bool,
}

/// Cached robots.txt entry
#[derive(Debug, Clone)]
struct RobotsEntry {
    body: String,
    fetched_at: Instant,
}

/// Robots.txt cache with TTL-based expiration
pub struct RobotsCache {
    cache: HashMap<String, RobotsEntry>,
    ttl: Duration,
    client: Client,
}

impl RobotsCache {
    pub fn new(ttl_secs: u64, client: Client) -> Self {
        Self {
            cache: HashMap::new(),
            ttl: Duration::from_secs(ttl_secs),
            client,
        }
    }

    /// Get robots.txt body for a domain, fetching if not cached or expired
    async fn get_robots_body(&mut self, domain: &str, scheme: &str) -> String {
        // Check cache validity
        if let Some(entry) = self.cache.get(domain) {
            if entry.fetched_at.elapsed() < self.ttl {
                return entry.body.clone();
            }
        }

        // Fetch robots.txt
        let robots_url = format!("{}://{}/robots.txt", scheme, domain);
        let body = match self.client.get(&robots_url).send().await {
            Ok(resp) if resp.status().is_success() => resp.text().await.unwrap_or_default(),
            _ => String::new(),
        };

        self.cache.insert(
            domain.to_string(),
            RobotsEntry {
                body: body.clone(),
                fetched_at: Instant::now(),
            },
        );

        body
    }

    /// Check if URL is allowed by robots.txt
    pub async fn is_allowed(&mut self, url: &str, user_agent: &str) -> Result<bool> {
        let parsed_url = url::Url::parse(url).with_context(|| format!("Invalid URL: {}", url))?;

        let domain = parsed_url.host_str().unwrap_or("").to_string();
        let scheme = parsed_url.scheme();

        if domain.is_empty() {
            return Ok(true);
        }

        let robots_body = self.get_robots_body(&domain, scheme).await;

        if robots_body.is_empty() {
            return Ok(true);
        }

        let mut matcher = DefaultMatcher::default();
        Ok(matcher.one_agent_allowed_by_robots(&robots_body, user_agent, url))
    }
}

/// Adaptive rate limiter using token bucket
#[derive(Debug)]
pub struct RateLimiter {
    tokens: f64,
    max_tokens: f64,
    refill_rate: f64,
    last_refill: Instant,
}

impl RateLimiter {
    pub fn new(requests_per_sec: u32) -> Self {
        let rate = requests_per_sec as f64;
        Self {
            tokens: rate,
            max_tokens: rate,
            refill_rate: rate,
            last_refill: Instant::now(),
        }
    }

    /// Acquire a token, waiting if necessary
    pub async fn acquire(&mut self) {
        loop {
            self.refill();
            if self.tokens >= 1.0 {
                self.tokens -= 1.0;
                return;
            }
            let wait = Duration::from_secs_f64((1.0 - self.tokens) / self.refill_rate);
            tokio::time::sleep(wait).await;
        }
    }

    fn refill(&mut self) {
        let now = Instant::now();
        let elapsed = now.duration_since(self.last_refill).as_secs_f64();
        self.tokens = (self.tokens + elapsed * self.refill_rate).min(self.max_tokens);
        self.last_refill = now;
    }
}

/// Trafilatura microservice client
#[derive(Debug, Clone)]
pub struct TrafilaturaClient {
    client: Client,
    base_url: String,
    batch_size: usize,
    timeout: Duration,
}

/// Single extraction request
#[derive(Debug, Clone, serde::Serialize)]
pub struct ExtractRequest {
    pub url: String,
    pub html: String,
}

/// Single extraction response
#[derive(Debug, Clone, serde::Deserialize)]
pub struct ExtractResponse {
    pub url: String,
    pub title: Option<String>,
    pub content: Option<String>,
    pub success: bool,
    pub error: Option<String>,
}

impl TrafilaturaClient {
    pub fn new(base_url: &str, batch_size: usize, timeout_secs: u64) -> Result<Self> {
        let client = Client::builder()
            .timeout(Duration::from_secs(timeout_secs))
            .build()
            .with_context(|| "Failed to create Trafilatura HTTP client")?;

        Ok(Self {
            client,
            base_url: base_url.to_string(),
            batch_size,
            timeout: Duration::from_secs(timeout_secs),
        })
    }

    /// Extract content from a batch of HTML documents
    pub async fn extract_batch(
        &self,
        requests: Vec<ExtractRequest>,
    ) -> Result<Vec<ExtractResponse>> {
        if requests.is_empty() {
            return Ok(Vec::new());
        }

        let mut all_results = Vec::new();

        // Process in chunks matching batch_size
        for chunk in requests.chunks(self.batch_size) {
            let url = format!("{}/extract-batch", self.base_url);
            let resp = self
                .client
                .post(&url)
                .json(chunk)
                .timeout(self.timeout)
                .send()
                .await
                .with_context(|| "Failed to send extraction request to Trafilatura")?;

            if !resp.status().is_success() {
                let status = resp.status();
                let body = resp.text().await.unwrap_or_default();
                tracing::warn!("Trafilatura returned {}: {}", status, body);
                // Return partial results with error info
                for req in chunk {
                    all_results.push(ExtractResponse {
                        url: req.url.clone(),
                        title: None,
                        content: None,
                        success: false,
                        error: Some(format!("HTTP {}: {}", status, body)),
                    });
                }
                continue;
            }

            let results: Vec<ExtractResponse> = resp
                .json()
                .await
                .with_context(|| "Failed to parse Trafilatura response")?;
            all_results.extend(results);
        }

        Ok(all_results)
    }

    /// Health check for Trafilatura service
    pub async fn health_check(&self) -> bool {
        let url = format!("{}/health", self.base_url);
        self.client
            .get(&url)
            .send()
            .await
            .map(|r| r.status().is_success())
            .unwrap_or(false)
    }
}

/// Web crawler with rate limiting, robots.txt, and Trafilatura integration
#[derive(Clone)]
pub struct Crawler {
    client: Client,
    robots_cache: Arc<Mutex<RobotsCache>>,
    rate_limiter: Arc<Mutex<RateLimiter>>,
    semaphore: Arc<Semaphore>,
    user_agent: String,
    respect_robots: bool,
    static_first: bool,
    max_retries: u32,
    js_whitelist: Vec<String>,
    trafilatura: Option<TrafilaturaClient>,
    // Content deduplication cache (SHA-256 hashes)
    seen_content_hashes: Arc<dashmap::DashSet<String>>,
}

impl Crawler {
    /// Create a new crawler instance
    pub fn new(
        rate_limit: u32,
        timeout_secs: u64,
        user_agent: String,
        respect_robots: bool,
        static_first: bool,
        max_concurrent: usize,
        max_retries: u32,
        robots_cache_ttl: u64,
        js_whitelist: Vec<String>,
        trafilatura_url: Option<&str>,
        trafilatura_batch: usize,
        trafilatura_timeout: u64,
    ) -> Result<Self> {
        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());

        // Optimized HTTP client with connection pooling and HTTP/2
        let client = Client::builder()
            .user_agent(&user_agent)
            .default_headers(headers)
            .timeout(Duration::from_secs(timeout_secs))
            .pool_max_idle_per_host(max_concurrent * 4) // Increased pooling
            .pool_idle_timeout(Duration::from_secs(90))
            .http2_keep_alive_interval(Duration::from_secs(30))
            .http2_keep_alive_timeout(Duration::from_secs(20))
            .http2_keep_alive_while_idle(true)
            .tcp_keepalive(Duration::from_secs(30))
            .build()
            .with_context(|| "Failed to create HTTP client")?;

        let robots_cache = RobotsCache::new(robots_cache_ttl, client.clone());
        let rate_limiter = RateLimiter::new(rate_limit);
        let semaphore = Arc::new(Semaphore::new(max_concurrent));

        let trafilatura = trafilatura_url
            .map(|url| TrafilaturaClient::new(url, trafilatura_batch, trafilatura_timeout))
            .transpose()?;

        Ok(Self {
            client,
            robots_cache: Arc::new(Mutex::new(robots_cache)),
            rate_limiter: Arc::new(Mutex::new(rate_limiter)),
            semaphore,
            user_agent,
            respect_robots,
            static_first,
            max_retries,
            js_whitelist,
            trafilatura,
            seen_content_hashes: Arc::new(dashmap::DashSet::new()),
        })
    }

    /// Check if content type is fetchable (HTML or unknown)
    fn should_fetch_content_type(content_type: &str) -> bool {
        if content_type.is_empty() {
            return true; // Unknown, fetch and check
        }
        content_type.starts_with("text/html")
            || content_type.starts_with("application/xhtml")
            || content_type.starts_with("application/xml")
    }

    /// Pre-fetch check using HTTP HEAD request
    async fn pre_fetch_check(&self, url: &str) -> Result<PreFetchInfo> {
        let resp = self.client.head(url).send().await?;

        Ok(PreFetchInfo {
            content_type: resp
                .headers()
                .get("Content-Type")
                .and_then(|h| h.to_str().ok())
                .unwrap_or("")
                .to_string(),
            content_length: resp
                .headers()
                .get("Content-Length")
                .and_then(|h| h.to_str().ok())
                .and_then(|s| s.parse::<u64>().ok())
                .unwrap_or(0),
            etag: resp
                .headers()
                .get("ETag")
                .and_then(|h| h.to_str().ok())
                .map(|s| s.to_string()),
        })
    }

    /// Check if content is a duplicate using SHA-256 hash
    fn is_duplicate_content(&self, html: &str) -> bool {
        use sha2::{Digest, Sha256};
        let mut hasher = Sha256::new();
        hasher.update(html.as_bytes());
        let hash = format!("{:x}", hasher.finalize());

        // Check if we've seen this hash before
        if self.seen_content_hashes.contains(&hash) {
            return true;
        }

        // Add to seen hashes
        self.seen_content_hashes.insert(hash);
        false
    }

    /// Check if a domain requires JS rendering
    fn requires_js(&self, url: &str) -> bool {
        if !self.static_first {
            return false;
        }
        for domain in &self.js_whitelist {
            if url.contains(domain) {
                return true;
            }
        }
        false
    }

    /// Fetch a URL with head-only peek for intent gating
    async fn fetch_head_only(&self, url: &str) -> Result<String> {
        let resp = self
            .client
            .get(url)
            .header("Range", "bytes=0-10240")
            .send()
            .await?;

        let status = resp.status();
        if !status.is_success() && status != reqwest::StatusCode::PARTIAL_CONTENT {
            return Err(anyhow::anyhow!("Head fetch failed with status: {}", status));
        }

        Ok(resp.text().await?)
    }

    /// Fetch a single URL with full intent gating
    pub async fn fetch(&self, url: &str) -> Result<CrawlResult> {
        let start = Instant::now();

        // Check robots.txt
        if self.respect_robots {
            let allowed = self
                .robots_cache
                .lock()
                .await
                .is_allowed(url, &self.user_agent)
                .await?;
            if !allowed {
                anyhow::bail!("Blocked by robots.txt: {}", url);
            }
        }

        // Phase 1: Pre-fetch check (HTTP HEAD)
        let pre_fetch = self.pre_fetch_check(url).await?;

        // Skip non-HTML content types
        if !Self::should_fetch_content_type(&pre_fetch.content_type) {
            anyhow::bail!("Skipping non-HTML content type: {}", pre_fetch.content_type);
        }

        let is_dynamic = self.requires_js(url);

        // Acquire rate limiter token and semaphore permit
        self.rate_limiter.lock().await.acquire().await;
        let _permit = self
            .semaphore
            .acquire()
            .await
            .with_context(|| "Semaphore closed")?;

        // Phase 2: Intent-Gated Peek with Enhanced Scoring
        // For non-whitelisted domains, peek at the first 10KB
        let is_technical = url.contains("github.com")
            || url.contains("arxiv.org")
            || url.contains("docs.")
            || url.contains("rust-lang.org");

        let (status, html) = if !is_technical {
            let peek_html = self.fetch_head_only(url).await.unwrap_or_default();

            // Enhanced intent scoring with URL boosting
            let _fast_result = FastExtractor::extract(&peek_html);
            let url_boosted_score = self.enhanced_intent_score(&peek_html, url);

            // Increased threshold from 0.2 to 0.35 for better noise filtering
            if url_boosted_score < 0.35 {
                tracing::debug!(
                    "Aborting fetch for low-intent peek (score={:.3}): {}",
                    url_boosted_score,
                    url
                );
                anyhow::bail!("Low intent score: {}", url_boosted_score);
            } else {
                self.fetch_with_retry(url).await?
            }
        } else {
            self.fetch_with_retry(url).await?
        };

        // Phase 3: Content Deduplication Check
        if self.is_duplicate_content(&html) {
            tracing::debug!("Skipping duplicate content: {}", url);
            anyhow::bail!("Duplicate content");
        }

        // Phase 4: Native Path Extraction (Rust-native)
        let fast_result = FastExtractor::extract(&html);

        // Phase 5: Trafilatura Fallback (only if low quality or explicit)
        let (title, content) = if fast_result.quality_score < 0.6 {
            if let Some(ref trafilatura) = self.trafilatura {
                let requests = vec![ExtractRequest {
                    url: url.to_string(),
                    html: html.clone(),
                }];
                match trafilatura.extract_batch(requests).await {
                    Ok(results) if results.len() == 1 && results[0].success => {
                        let r = &results[0];
                        (
                            r.title.clone().unwrap_or(fast_result.title),
                            r.content.clone().unwrap_or(fast_result.content),
                        )
                    }
                    _ => (fast_result.title, fast_result.content),
                }
            } else {
                (fast_result.title, fast_result.content)
            }
        } else {
            (fast_result.title, fast_result.content)
        };

        let fetch_time_ms = start.elapsed().as_millis() as u64;

        Ok(CrawlResult {
            url: url.to_string(),
            title,
            content,
            html: Some(html),
            status,
            fetch_time_ms,
            is_dynamic,
        })
    }

    /// Enhanced intent scoring with URL-based boosting
    fn enhanced_intent_score(&self, text: &str, url: &str) -> f32 {
        // Get base score from fast scorer
        let _base_score = self
            .trafilatura
            .as_ref()
            .map(|_| 0.5f32) // Placeholder - we'll use a dedicated scorer
            .unwrap_or(0.5f32);

        // Use the FastIntentScorer from inference module if available
        // For now, use simple keyword matching
        let text_lower = text.to_lowercase();
        let mut keyword_score = 0.1f32;

        let high_signal_keywords = [
            "tutorial",
            "guide",
            "how-to",
            "benchmark",
            "analysis",
            "framework",
            "library",
            "documentation",
            "api",
            "reference",
        ];

        for keyword in &high_signal_keywords {
            if text_lower.contains(keyword) {
                keyword_score += 0.1;
            }
        }

        // URL-based boosting
        let mut url_boost = 1.0f32;
        if url.contains("github.com")
            || url.contains("arxiv.org")
            || url.contains(".edu")
            || url.contains("docs.")
        {
            url_boost = 1.5; // Technical content boost
        } else if url.contains("/tutorial/") || url.contains("/guide/") {
            url_boost = 1.3;
        } else if url.contains("news.") || url.contains("blog.") {
            url_boost = 0.8; // News penalty
        }

        (keyword_score.min(1.0) * url_boost).min(1.0)
    }

    /// Fetch with exponential backoff retry
    async fn fetch_with_retry(&self, url: &str) -> Result<(u16, String)> {
        let mut last_err = None;

        for attempt in 0..=self.max_retries {
            if attempt > 0 {
                let backoff = Duration::from_millis(100 * 2u64.pow(attempt - 1));
                tokio::time::sleep(backoff).await;
            }

            match self.client.get(url).send().await {
                Ok(resp) => {
                    let status = resp.status().as_u16();
                    if status == 429 || status >= 500 {
                        last_err = Some(anyhow::anyhow!("HTTP {}", status));
                        continue;
                    }
                    let html = resp
                        .text()
                        .await
                        .with_context(|| format!("Failed to read response: {}", url))?;
                    return Ok((status, html));
                }
                Err(e) => {
                    last_err = Some(e.into());
                }
            }
        }

        Err(last_err.unwrap_or_else(|| anyhow::anyhow!("Max retries exceeded")))
    }

    /// Fetch multiple URLs concurrently with Trafilatura batch extraction
    pub async fn fetch_batch(&self, urls: Vec<&str>) -> Result<Vec<CrawlResult>> {
        // Phase 1: Fetch all HTML concurrently
        let fetch_tasks: Vec<_> = urls
            .iter()
            .map(|url| {
                let url = url.to_string();
                async move {
                    let result = self.fetch_raw(&url).await;
                    (url, result)
                }
            })
            .collect();

        let fetch_results = futures::future::join_all(fetch_tasks).await;

        // Separate successful fetches for batch Trafilatura processing
        let mut raw_results: Vec<(String, u16, String)> = Vec::new();
        let mut errors: Vec<(String, anyhow::Error)> = Vec::new();

        for (url, result) in fetch_results {
            match result {
                Ok((status, html)) => raw_results.push((url, status, html)),
                Err(e) => errors.push((url, e)),
            }
        }

        // Phase 2: Native Fast Extraction
        let mut results = Vec::new();
        let mut low_quality_indices = Vec::new();

        for (idx, (url, status, html)) in raw_results.iter().enumerate() {
            let is_dynamic = self.requires_js(url);
            let fast_result = FastExtractor::extract(html);

            results.push(CrawlResult {
                url: url.clone(),
                title: fast_result.title,
                content: fast_result.content,
                html: Some(html.clone()),
                status: *status,
                fetch_time_ms: 0,
                is_dynamic,
            });

            if fast_result.quality_score < 0.6 {
                low_quality_indices.push(idx);
            }
        }

        // Phase 3: Trafilatura Fallback (only for low-quality)
        if let Some(ref trafilatura) = self.trafilatura {
            if !low_quality_indices.is_empty() {
                let requests: Vec<ExtractRequest> = low_quality_indices
                    .iter()
                    .map(|&idx| {
                        let (url, _, html) = &raw_results[idx];
                        ExtractRequest {
                            url: url.clone(),
                            html: html.clone(),
                        }
                    })
                    .collect();

                if let Ok(extract_results) = trafilatura.extract_batch(requests).await {
                    for (&idx, extract) in low_quality_indices.iter().zip(extract_results.iter()) {
                        if extract.success {
                            if let Some(ref mut res) = results.get_mut(idx) {
                                if let Some(title) = &extract.title {
                                    res.title = title.clone();
                                }
                                if let Some(content) = &extract.content {
                                    res.content = content.clone();
                                }
                            }
                        }
                    }
                }
            }
        }

        // Log errors
        for (url, e) in &errors {
            tracing::warn!("Failed to fetch {}: {}", url, e);
        }

        Ok(results)
    }

    /// Raw fetch without robots.txt or rate limiting (used internally by fetch_batch)
    async fn fetch_raw(&self, url: &str) -> Result<(u16, String)> {
        let _start = Instant::now();

        if self.respect_robots {
            let allowed = self
                .robots_cache
                .lock()
                .await
                .is_allowed(url, &self.user_agent)
                .await?;
            if !allowed {
                anyhow::bail!("Blocked by robots.txt: {}", url);
            }
        }

        self.rate_limiter.lock().await.acquire().await;
        let _permit = self
            .semaphore
            .acquire()
            .await
            .with_context(|| "Semaphore closed")?;

        self.fetch_with_retry(url).await
    }

    /// Get reference to Trafilatura client
    pub fn trafilatura(&self) -> Option<&TrafilaturaClient> {
        self.trafilatura.as_ref()
    }
}

/// Extract outbound links from HTML
pub fn find_links(html: &str, _base_url: &str) -> Vec<String> {
    let mut links = Vec::new();
    // Simple regex for absolute http/https links
    let re = match regex::Regex::new(r#"href=["'](https?://[^"']+)["']"#) {
        Ok(re) => re,
        Err(_) => return links,
    };

    for cap in re.captures_iter(html) {
        if let Some(link) = cap.get(1) {
            let link_str = link.as_str();

            // Filter out obvious noise
            if link_str.contains("javascript:")
                || link_str.contains("mailto:")
                || link_str.contains("/wp-json/")
                || link_str.contains("/login")
                || link_str.ends_with(".png")
                || link_str.ends_with(".jpg")
                || link_str.ends_with(".css")
                || link_str.ends_with(".js")
            {
                continue;
            }

            links.push(link_str.to_string());
        }
    }

    links.sort();
    links.dedup();
    links
}

/// Extract title from HTML
pub fn extract_title(html: &str) -> Option<String> {
    let title_start = html.find("<title>")?;
    let title_end = html[title_start..].find("</title>")?;

    let title = html[title_start + 7..title_start + title_end].trim();
    // Decode HTML entities
    let title = title
        .replace("&amp;", "&")
        .replace("&lt;", "<")
        .replace("&gt;", ">")
        .replace("&quot;", "\"")
        .replace("&#39;", "'");
    Some(title)
}

/// Strip HTML tags from content
pub fn strip_html(html: &str) -> String {
    let mut result = String::with_capacity(html.len() / 2);
    let mut in_tag = false;
    let mut tag_buffer = String::new();
    let mut skip_stack = Vec::new();

    // Tags whose content we want to skip entirely
    let skip_tags = [
        "script", "style", "head", "nav", "footer", "header", "aside",
    ];

    for ch in html.chars() {
        if ch == '<' {
            in_tag = true;
            tag_buffer.clear();
            continue;
        }
        if ch == '>' && in_tag {
            in_tag = false;
            let tag_content = tag_buffer.to_lowercase();
            let is_closing = tag_content.starts_with('/');
            let tag_name = if is_closing {
                &tag_content[1..]
            } else {
                tag_content.split_whitespace().next().unwrap_or("")
            };

            if skip_tags.contains(&tag_name) {
                if is_closing {
                    skip_stack.pop();
                } else {
                    skip_stack.push(tag_name.to_string());
                }
            }
            // Add space for block-level elements to avoid merging words
            if [
                "p", "div", "br", "h1", "h2", "h3", "h4", "h5", "h6", "li", "tr",
            ]
            .contains(&tag_name)
            {
                result.push(' ');
            }
            continue;
        }
        if in_tag {
            tag_buffer.push(ch);
            continue;
        }
        if skip_stack.is_empty() {
            result.push(ch);
        }
    }

    // Clean up whitespace and entities
    let cleaned = result
        .replace("&nbsp;", " ")
        .replace("&amp;", "&")
        .replace("&lt;", "<")
        .replace("&gt;", ">")
        .replace("&quot;", "\"")
        .replace("&#39;", "'");

    cleaned.split_whitespace().collect::<Vec<_>>().join(" ")
}

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

    #[test]
    fn test_extract_title() {
        let html = "<html><head><title>Test Page</title></head><body></body></html>";
        assert_eq!(extract_title(html), Some("Test Page".to_string()));
    }

    #[test]
    fn test_extract_title_with_entities() {
        let html = "<title>Test &amp; Page</title>";
        assert_eq!(extract_title(html), Some("Test & Page".to_string()));
    }

    #[test]
    fn test_extract_title_none() {
        let html = "<html><body>No title</body></html>";
        assert_eq!(extract_title(html), None);
    }

    #[test]
    fn test_strip_html() {
        let html = "<p>Hello <b>World</b></p>";
        let text = strip_html(html);
        assert_eq!(text, "Hello World");
    }

    #[test]
    fn test_strip_html_removes_scripts() {
        let html = "<p>Visible</p><script>alert('hidden')</script><p>Also visible</p>";
        let text = strip_html(html);
        assert!(!text.contains("alert"));
        assert!(text.contains("Visible"));
        assert!(text.contains("Also visible"));
    }

    #[test]
    fn test_strip_html_removes_styles() {
        let html = "<p>Text</p><style>body { color: red; }</style><p>More</p>";
        let text = strip_html(html);
        assert!(!text.contains("color"));
        assert!(text.contains("Text"));
        assert!(text.contains("More"));
    }

    #[tokio::test]
    async fn test_rate_limiter() {
        let mut limiter = RateLimiter::new(100);
        let start = Instant::now();
        for _ in 0..5 {
            limiter.acquire().await;
        }
        // Should be fast since we have tokens
        assert!(start.elapsed() < Duration::from_millis(100));
    }

    #[test]
    fn test_js_whitelist_detection() {
        let crawler = Crawler::new(
            10,
            30,
            "test".to_string(),
            false,
            true,
            8,
            3,
            3600,
            vec!["producthunt.com".to_string()],
            None,
            16,
            60,
        )
        .unwrap();

        assert!(crawler.requires_js("https://producthunt.com/posts/test"));
        assert!(!crawler.requires_js("https://example.com/page"));
    }

    #[test]
    fn test_trafilatura_request_serialization() {
        let req = ExtractRequest {
            url: "https://example.com".to_string(),
            html: "<html><body>Test</body></html>".to_string(),
        };
        let json = serde_json::to_string(&req).unwrap();
        assert!(json.contains("example.com"));
        assert!(json.contains("Test"));
    }

    #[test]
    fn test_trafilatura_response_deserialization() {
        let json =
            r#"{"url":"https://example.com","title":"Test","content":"Hello","success":true}"#;
        let resp: ExtractResponse = serde_json::from_str(json).unwrap();
        assert!(resp.success);
        assert_eq!(resp.title, Some("Test".to_string()));
        assert_eq!(resp.content, Some("Hello".to_string()));
    }

    #[test]
    fn test_trafilatura_response_with_error() {
        let json = r#"{"url":"https://example.com","title":null,"content":null,"success":false,"error":"timeout"}"#;
        let resp: ExtractResponse = serde_json::from_str(json).unwrap();
        assert!(!resp.success);
        assert_eq!(resp.error, Some("timeout".to_string()));
    }

    #[tokio::test]
    async fn test_robots_cache_creation() {
        let client = Client::builder().user_agent("test").build().unwrap();
        let cache = RobotsCache::new(3600, client);
        assert!(cache.cache.is_empty());
    }
}