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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
#![allow(dead_code)]
//! Anti-Detection HTTP Client for IntentForge v2
//!
//! Provides human-like HTTP requests with:
//! - User agent rotation
//! - Proxy rotation (free proxy lists)
//! - Request queuing with rate limiting
//! - Cookie handling
//! - Retry with exponential backoff
//! - HTML scraping fallback when RSS fails

use anyhow::{Context, Result};
use rand::Rng;
use std::collections::VecDeque;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::{Mutex, RwLock};

/// List of realistic user agents (Chrome, Firefox, Safari on different OS)
const USER_AGENTS: &[&str] = &[
    // Chrome on Windows
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",
    // Chrome on Mac
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36",
    // Firefox on Windows
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:133.0) Gecko/20100101 Firefox/133.0",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:132.0) Gecko/20100101 Firefox/132.0",
    // Firefox on Mac
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:133.0) Gecko/20100101 Firefox/133.0",
    // Safari on Mac
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.2 Safari/605.1.15",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.6 Safari/605.1.15",
    // Chrome on Linux
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
    // Edge on Windows
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0",
];

/// Common referer headers to appear more human-like
const REFERERS: &[&str] = &[
    "https://www.google.com/",
    "https://www.bing.com/",
    "https://duckduckgo.com/",
    "https://www.google.co.uk/",
    "https://www.google.de/",
    "",
];

/// Accept-Language headers for different regions
const ACCEPT_LANGUAGES: &[&str] = &[
    "en-US,en;q=0.9",
    "en-US,en;q=0.9,es;q=0.8",
    "en-GB,en;q=0.9",
    "en-US,en;q=0.9,de;q=0.8",
    "en;q=0.9",
];

/// Proxy configuration
#[derive(Debug, Clone)]
pub struct Proxy {
    pub url: String,
    pub proxy_type: ProxyType,
    pub latency_ms: u64,
    pub last_used: Option<Instant>,
    pub fail_count: u32,
}

#[derive(Debug, Clone, PartialEq)]
pub enum ProxyType {
    Http,
    Https,
    Socks5,
}

/// Token bucket rate limiter
pub struct RateLimiter {
    tokens: f64,
    max_tokens: f64,
    refill_rate: f64, // tokens per second
    last_refill: Instant,
}

impl RateLimiter {
    pub fn new(max_tokens: f64, refill_rate: f64) -> Self {
        Self {
            tokens: max_tokens,
            max_tokens,
            refill_rate,
            last_refill: Instant::now(),
        }
    }

    pub async fn acquire(&mut self) {
        loop {
            self.refill();
            if self.tokens >= 1.0 {
                self.tokens -= 1.0;
                return;
            }
            // Wait for a token to become available
            let wait_time = Duration::from_secs_f64((1.0 - self.tokens) / self.refill_rate);
            tokio::time::sleep(wait_time).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;
    }
}

/// Anti-detection HTTP client
pub struct AntiDetectionClient {
    client: reqwest::Client,
    proxies: Arc<RwLock<Vec<Proxy>>>,
    rate_limiters: Arc<RwLock<std::collections::HashMap<String, RateLimiter>>>,
    request_queue: Arc<Mutex<VecDeque<QueuedRequest>>>,
    cookie_jar: Arc<RwLock<std::collections::HashMap<String, String>>>,
}

struct QueuedRequest {
    url: String,
    domain: String,
    created_at: Instant,
}

impl AntiDetectionClient {
    /// Create a new anti-detection client
    pub async fn new() -> Result<Self> {
        let mut headers = reqwest::header::HeaderMap::new();
        headers.insert(
            reqwest::header::ACCEPT,
            reqwest::header::HeaderValue::from_static(
                "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
            ),
        );
        headers.insert(
            reqwest::header::ACCEPT_ENCODING,
            reqwest::header::HeaderValue::from_static("gzip, deflate, br"),
        );

        let client = reqwest::Client::builder()
            .user_agent(USER_AGENTS[0])
            .default_headers(headers)
            .timeout(Duration::from_secs(30))
            .pool_max_idle_per_host(2)
            .pool_idle_timeout(Duration::from_secs(30))
            .tcp_keepalive(Duration::from_secs(60))
            .build()
            .context("Failed to create HTTP client")?;

        let proxies = Arc::new(RwLock::new(Vec::new()));
        let rate_limiters = Arc::new(RwLock::new(std::collections::HashMap::new()));
        let request_queue = Arc::new(Mutex::new(VecDeque::new()));
        let cookie_jar = Arc::new(RwLock::new(std::collections::HashMap::new()));

        let instance = Self {
            client,
            proxies,
            rate_limiters,
            request_queue,
            cookie_jar,
        };

        // Load initial proxies
        instance.load_proxies().await?;

        Ok(instance)
    }

    /// Load proxies from free proxy lists
    async fn load_proxies(&self) -> Result<()> {
        let proxy_sources = vec![
            "https://api.proxyscrape.com/v2/?request=displayproxies&protocol=http&timeout=10000&country=all&ssl=all&anonymity=all",
            "https://raw.githubusercontent.com/TheSpeedX/PROXY-List/master/http.txt",
            "https://raw.githubusercontent.com/clarketm/proxy-list/master/proxy-list-raw.txt",
        ];

        let mut proxies = self.proxies.write().await;
        proxies.clear();

        for source in proxy_sources {
            match self.client.get(source).send().await {
                Ok(resp) => {
                    if let Ok(text) = resp.text().await {
                        for line in text.lines() {
                            let line = line.trim();
                            if !line.is_empty() && line.contains(':') {
                                let url = if line.starts_with("http") {
                                    line.to_string()
                                } else {
                                    format!("http://{}", line)
                                };
                                proxies.push(Proxy {
                                    url,
                                    proxy_type: ProxyType::Http,
                                    latency_ms: 0,
                                    last_used: None,
                                    fail_count: 0,
                                });
                            }
                        }
                    }
                }
                Err(e) => {
                    tracing::warn!("Failed to load proxies from {}: {}", source, e);
                }
            }
        }

        tracing::info!("Loaded {} proxies", proxies.len());
        Ok(())
    }

    /// Get a random user agent
    fn random_user_agent() -> &'static str {
        let mut rng = rand::thread_rng();
        USER_AGENTS[rng.gen_range(0..USER_AGENTS.len())]
    }

    /// Get a random referer
    fn random_referer() -> &'static str {
        let mut rng = rand::thread_rng();
        REFERERS[rng.gen_range(0..REFERERS.len())]
    }

    /// Get a random accept language
    fn random_accept_language() -> &'static str {
        let mut rng = rand::thread_rng();
        ACCEPT_LANGUAGES[rng.gen_range(0..ACCEPT_LANGUAGES.len())]
    }

    /// Get rate limiter for a domain
    async fn get_rate_limiter(&self, domain: &str) -> RateLimiter {
        let mut limiters = self.rate_limiters.write().await;
        limiters
            .entry(domain.to_string())
            .or_insert_with(|| {
                // Default: 2 requests per second per domain
                RateLimiter::new(5.0, 2.0)
            })
            .clone()
    }

    /// Add random delay between requests (200-800ms)
    async fn random_delay() {
        let mut rng = rand::thread_rng();
        let delay_ms = rng.gen_range(200..800);
        tokio::time::sleep(Duration::from_millis(delay_ms)).await;
    }

    /// Extract domain from URL
    fn extract_domain(url: &str) -> String {
        url::Url::parse(url)
            .ok()
            .and_then(|u| u.host_str().map(|h| h.to_string()))
            .unwrap_or_default()
    }

    /// Make a GET request with anti-detection measures
    pub async fn get(&self, url: &str) -> Result<reqwest::Response> {
        let domain = Self::extract_domain(url);

        // Rate limit per domain
        {
            let mut limiters = self.rate_limiters.write().await;
            let limiter = limiters
                .entry(domain.clone())
                .or_insert_with(|| RateLimiter::new(5.0, 2.0));
            limiter.acquire().await;
        }

        // Random delay
        Self::random_delay().await;

        // Build request with human-like headers
        let user_agent = Self::random_user_agent();
        let referer = Self::random_referer();
        let accept_language = Self::random_accept_language();

        let mut request = self
            .client
            .get(url)
            .header("User-Agent", user_agent)
            .header("Accept-Language", accept_language)
            .header("DNT", "1")
            .header("Connection", "keep-alive")
            .header("Upgrade-Insecure-Requests", "1")
            .header("Sec-Fetch-Dest", "document")
            .header("Sec-Fetch-Mode", "navigate")
            .header("Sec-Fetch-Site", "none")
            .header("Sec-Fetch-User", "?1")
            .header("Cache-Control", "max-age=0");

        if !referer.is_empty() {
            request = request.header("Referer", referer);
        }

        // Add cookies if we have any for this domain
        {
            let cookies = self.cookie_jar.read().await;
            if let Some(cookie) = cookies.get(&domain) {
                request = request.header("Cookie", cookie);
            }
        }

        // Send request with retry
        let response = self.send_with_retry(request, url, 3).await?;

        // Store cookies from response
        if let Some(set_cookie) = response.headers().get("set-cookie") {
            if let Ok(cookie_str) = set_cookie.to_str() {
                let mut cookies = self.cookie_jar.write().await;
                cookies.insert(domain, cookie_str.to_string());
            }
        }

        Ok(response)
    }

    /// Send request with retry and exponential backoff
    async fn send_with_retry(
        &self,
        request: reqwest::RequestBuilder,
        url: &str,
        max_retries: u32,
    ) -> Result<reqwest::Response> {
        let mut last_error = None;

        for attempt in 0..max_retries {
            let req = request.try_clone().context("Failed to clone request")?;

            match req.send().await {
                Ok(response) => {
                    let status = response.status();

                    // Handle rate limiting (429)
                    if status == 429 {
                        let retry_after = response
                            .headers()
                            .get("retry-after")
                            .and_then(|v| v.to_str().ok())
                            .and_then(|v| v.parse::<u64>().ok())
                            .unwrap_or(60);

                        tracing::warn!(
                            "Rate limited on {} (attempt {}/{}), waiting {}s",
                            url,
                            attempt + 1,
                            max_retries,
                            retry_after
                        );

                        tokio::time::sleep(Duration::from_secs(retry_after)).await;
                        continue;
                    }

                    // Handle 403 Forbidden - try with different user agent
                    if status == 403 && attempt < max_retries - 1 {
                        tracing::warn!(
                            "403 Forbidden on {} (attempt {}/{}), retrying with different headers",
                            url,
                            attempt + 1,
                            max_retries
                        );

                        // Wait before retry with exponential backoff
                        let wait_time = Duration::from_secs(2u64.pow(attempt));
                        tokio::time::sleep(wait_time).await;
                        continue;
                    }

                    return Ok(response);
                }
                Err(e) => {
                    last_error = Some(e);

                    if attempt < max_retries - 1 {
                        let wait_time = Duration::from_secs(2u64.pow(attempt));
                        tracing::warn!(
                            "Request failed on {} (attempt {}/{}): retrying in {:?}",
                            url,
                            attempt + 1,
                            max_retries,
                            wait_time
                        );
                        tokio::time::sleep(wait_time).await;
                    }
                }
            }
        }

        Err(last_error
            .map(|e| anyhow::anyhow!("{}", e))
            .unwrap_or_else(|| anyhow::anyhow!("Request failed after {} attempts", max_retries)))
    }

    /// Try fetching with proxy
    pub async fn get_with_proxy(&self, url: &str) -> Result<reqwest::Response> {
        let proxies = self.proxies.read().await;

        if proxies.is_empty() {
            return self.get(url).await;
        }

        // Try up to 3 different proxies
        let mut rng = rand::thread_rng();
        for _ in 0..3 {
            let proxy_idx = rng.gen_range(0..proxies.len());
            let proxy = &proxies[proxy_idx];

            let proxy_client = reqwest::Client::builder()
                .user_agent(Self::random_user_agent())
                .timeout(Duration::from_secs(15))
                .proxy(reqwest::Proxy::all(&proxy.url)?)
                .build();

            if let Ok(client) = proxy_client {
                match client.get(url).send().await {
                    Ok(resp) if resp.status().is_success() => {
                        return Ok(resp);
                    }
                    _ => continue,
                }
            }
        }

        // Fall back to direct request
        self.get(url).await
    }

    /// Scrape content from HTML page (fallback when RSS fails)
    pub async fn scrape_html(&self, url: &str) -> Result<Vec<ScrapedItem>> {
        let response = self.get(url).await?;
        let html = response.text().await?;

        let mut items = Vec::new();

        // Simple link extraction (for article-like pages)
        let link_regex = regex::Regex::new(r#"<a[^>]+href="([^"]+)"[^>]*>([^<]+)</a>"#).unwrap();

        for cap in link_regex.captures_iter(&html) {
            if let (Some(href), Some(title)) = (cap.get(1), cap.get(2)) {
                let href = href.as_str();
                let title = title.as_str().trim();

                // Filter for article-like links
                if title.len() > 20
                    && title.len() < 200
                    && !href.starts_with('#')
                    && !href.starts_with("javascript:")
                    && (href.starts_with("http") || href.starts_with('/'))
                {
                    let full_url = if href.starts_with('/') {
                        let base = url::Url::parse(url)?;
                        base.join(href)?.to_string()
                    } else {
                        href.to_string()
                    };

                    items.push(ScrapedItem {
                        title: title.to_string(),
                        url: full_url,
                        description: None,
                    });
                }
            }
        }

        // Limit to reasonable number
        items.truncate(20);

        Ok(items)
    }
}

/// Scraped item from HTML
#[derive(Debug, Clone)]
pub struct ScrapedItem {
    pub title: String,
    pub url: String,
    pub description: Option<String>,
}

impl Clone for RateLimiter {
    fn clone(&self) -> Self {
        Self {
            tokens: self.tokens,
            max_tokens: self.max_tokens,
            refill_rate: self.refill_rate,
            last_refill: Instant::now(),
        }
    }
}

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

    #[tokio::test]
    async fn test_rate_limiter() {
        let mut limiter = RateLimiter::new(5.0, 10.0);

        // Should be able to acquire 5 tokens immediately
        for _ in 0..5 {
            limiter.acquire().await;
        }

        // 6th token should require waiting
        let start = Instant::now();
        limiter.acquire().await;
        let elapsed = start.elapsed();

        // Should have waited approximately 0.1 seconds (1/10 tokens per second)
        assert!(elapsed >= Duration::from_millis(50));
    }

    #[test]
    fn test_extract_domain() {
        assert_eq!(
            AntiDetectionClient::extract_domain("https://example.com/path"),
            "example.com"
        );
        assert_eq!(
            AntiDetectionClient::extract_domain("http://sub.example.com:8080/path"),
            "sub.example.com"
        );
    }

    #[test]
    fn test_user_agent_rotation() {
        let mut agents = std::collections::HashSet::new();
        for _ in 0..20 {
            agents.insert(AntiDetectionClient::random_user_agent());
        }
        // Should have at least 3 different user agents
        assert!(agents.len() >= 3);
    }
}