File size: 26,170 Bytes
0ca462b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
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
//! Trending monitor module for IntentForge v2
//!
//! Monitors RSS feeds and GitHub trending to discover high-signal content.

use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// RSS feed source configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FeedSource {
    pub name: String,
    pub url: String,
    pub category: String,
    #[serde(default = "default_priority")]
    pub priority: u32,
}

/// Domain to monitor
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DomainSource {
    pub name: String,
    pub base_url: String,
    pub category: String,
    #[serde(default = "default_priority")]
    pub priority: u32,
    pub sitemap: Option<String>,
}

/// Seed URL configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SeedSource {
    pub name: String,
    pub url: String,
    pub category: String,
    #[serde(default = "default_priority")]
    pub priority: u32,
}

fn default_priority() -> u32 {
    5
}

/// Parsed feed item
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FeedItem {
    pub id: String,
    pub title: String,
    pub link: String,
    pub description: Option<String>,
    pub published_at: Option<DateTime<Utc>>,
    pub source: String,
    pub category: String,
    pub priority: u32,
}

/// Trending item with scores
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrendingItem {
    pub id: String,
    pub title: String,
    pub url: String,
    pub category: String,
    pub source: String,
    pub trending_score: f32,
    pub velocity: f32,
    pub published_at: Option<DateTime<Utc>>,
}

/// Feed sources configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SourcesConfig {
    pub sources: Vec<FeedSource>,
    #[serde(default)]
    pub domains: Vec<DomainSource>,
    #[serde(default)]
    pub seed_urls: Vec<SeedSource>,
}

impl SourcesConfig {
    /// Load sources from YAML file
    pub fn from_file<P: AsRef<std::path::Path>>(path: P) -> Result<Self> {
        let file = std::fs::File::open(path.as_ref())
            .with_context(|| format!("Failed to open sources file: {:?}", path.as_ref()))?;

        let config: SourcesConfig =
            serde_yaml::from_reader(file).with_context(|| "Failed to parse sources YAML")?;

        Ok(config)
    }

    /// Group sources by category
    pub fn by_category(&self) -> HashMap<String, Vec<&FeedSource>> {
        let mut by_cat: HashMap<String, Vec<&FeedSource>> = HashMap::new();
        for source in &self.sources {
            by_cat
                .entry(source.category.clone())
                .or_default()
                .push(source);
        }
        by_cat
    }
}

/// Trending monitor
pub struct TrendingMonitor {
    sources: Vec<FeedSource>,
    client: reqwest::Client,
}

/// List of human-like user agents to rotate
const USER_AGENTS: &[&str] = &[
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:123.0) Gecko/20100101 Firefox/123.0",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.3 Safari/605.1.15",
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
];

impl TrendingMonitor {
    /// Create a new trending monitor
    pub fn new(sources: Vec<FeedSource>) -> Result<Self> {
        let mut headers = reqwest::header::HeaderMap::new();
        headers.insert(
            reqwest::header::ACCEPT,
            reqwest::header::HeaderValue::from_static(
                "application/rss+xml, application/atom+xml, application/xml, text/xml, */*",
            ),
        );
        headers.insert(
            reqwest::header::ACCEPT_ENCODING,
            reqwest::header::HeaderValue::from_static("gzip, deflate, br"),
        );
        headers.insert(
            reqwest::header::ACCEPT_LANGUAGE,
            reqwest::header::HeaderValue::from_static("en-US,en;q=0.9"),
        );
        headers.insert(
            reqwest::header::CACHE_CONTROL,
            reqwest::header::HeaderValue::from_static("max-age=0"),
        );

        // Use first user agent by default
        let user_agent = USER_AGENTS[0];

        let client = reqwest::Client::builder()
            .user_agent(user_agent)
            .default_headers(headers)
            .timeout(std::time::Duration::from_secs(30))
            .build()
            .with_context(|| "Failed to create HTTP client")?;

        Ok(Self { sources, client })
    }

    /// Get a random user agent
    fn random_user_agent() -> &'static str {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};
        let mut hasher = DefaultHasher::new();
        std::time::SystemTime::now().hash(&mut hasher);
        let idx = (hasher.finish() as usize) % USER_AGENTS.len();
        USER_AGENTS[idx]
    }

    /// Add random delay between requests (100-500ms)
    async fn random_delay() {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};
        let mut hasher = DefaultHasher::new();
        std::time::SystemTime::now().hash(&mut hasher);
        let delay_ms = 100 + (hasher.finish() % 400);
        tokio::time::sleep(std::time::Duration::from_millis(delay_ms)).await;
    }

    /// Fetch and parse a single RSS feed with retry logic and HTML fallback
    pub async fn fetch_feed(&self, source: &FeedSource) -> Result<Vec<FeedItem>> {
        let mut last_err = None;
        let max_retries = 3;

        for attempt in 1..=max_retries {
            match self.fetch_feed_internal(source).await {
                Ok(items) => {
                    if !items.is_empty() {
                        return Ok(items);
                    }
                    // Empty feed, try HTML scraping as fallback
                }
                Err(e) => {
                    tracing::warn!(
                        "Attempt {}/{} failed for {}: {}",
                        attempt,
                        max_retries,
                        source.name,
                        e
                    );
                    last_err = Some(e);
                    if attempt < max_retries {
                        tokio::time::sleep(std::time::Duration::from_secs(attempt * 2)).await;
                    }
                }
            }
        }

        // If RSS failed, try HTML scraping as fallback
        tracing::info!(
            "RSS failed for {}, trying HTML scraping fallback",
            source.name
        );
        match self.scrape_html_fallback(source).await {
            Ok(items) if !items.is_empty() => {
                tracing::info!(
                    "HTML scraping found {} items for {}",
                    items.len(),
                    source.name
                );
                return Ok(items);
            }
            _ => {}
        }

        Err(last_err.unwrap_or_else(|| {
            anyhow::anyhow!("Failed to fetch feed after {} attempts", max_retries)
        }))
    }

    /// HTML scraping fallback when RSS fails
    async fn scrape_html_fallback(&self, source: &FeedSource) -> Result<Vec<FeedItem>> {
        // Get the base URL from the feed URL
        let base_url = if let Ok(url) = url::Url::parse(&source.url) {
            format!("{}://{}", url.scheme(), url.host_str().unwrap_or(""))
        } else {
            return Ok(Vec::new());
        };

        // Try common article pages
        let paths = vec!["/", "/blog", "/news", "/articles"];
        let mut all_items = Vec::new();

        for path in paths {
            let url = format!("{}{}", base_url.trim_end_matches('/'), path);

            match self
                .client
                .get(&url)
                .header("User-Agent", Self::random_user_agent())
                .header("Accept", "text/html,application/xhtml+xml")
                .send()
                .await
            {
                Ok(resp) if resp.status().is_success() => {
                    if let Ok(html) = resp.text().await {
                        let items = self.extract_links_from_html(&html, &base_url, source);
                        all_items.extend(items);
                    }
                }
                _ => continue,
            }

            if !all_items.is_empty() {
                break;
            }
        }

        // Deduplicate by URL
        let mut seen_urls = std::collections::HashSet::new();
        all_items.retain(|item| seen_urls.insert(item.link.clone()));

        // Limit to 10 items
        all_items.truncate(10);

        Ok(all_items)
    }

    /// Extract links from HTML as feed items
    fn extract_links_from_html(
        &self,
        html: &str,
        base_url: &str,
        source: &FeedSource,
    ) -> Vec<FeedItem> {
        let mut items = Vec::new();

        // Simple regex to find links with titles
        let link_regex =
            regex::Regex::new(r#"<a[^>]+href="([^"]+)"[^>]*>([^<]{20,200})</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();

                // Skip navigation links, etc.
                if title.len() < 20 || title.len() > 200 {
                    continue;
                }
                if href.starts_with('#') || href.starts_with("javascript:") {
                    continue;
                }

                // Build full URL
                let full_url = if href.starts_with("http") {
                    href.to_string()
                } else if href.starts_with('/') {
                    format!("{}{}", base_url.trim_end_matches('/'), href)
                } else {
                    format!("{}/{}", base_url.trim_end_matches('/'), href)
                };

                // Skip if same domain as base (likely navigation)
                if let (Ok(base), Ok(link)) =
                    (url::Url::parse(base_url), url::Url::parse(&full_url))
                {
                    if base.host_str() == link.host_str() {
                        items.push(FeedItem {
                            id: format!("scraped-{}", items.len()),
                            title: title.to_string(),
                            link: full_url,
                            description: Some(format!("Scraped from {}", source.name)),
                            published_at: Some(chrono::Utc::now()),
                            source: source.name.clone(),
                            category: source.category.clone(),
                            priority: source.priority,
                        });
                    }
                }
            }
        }

        items
    }

    /// Internal fetch logic with human-like headers
    async fn fetch_feed_internal(&self, source: &FeedSource) -> Result<Vec<FeedItem>> {
        // Add random delay between requests
        Self::random_delay().await;

        // Build request with human-like headers
        let response = self
            .client
            .get(&source.url)
            .header("User-Agent", Self::random_user_agent())
            .header(
                "Accept",
                "application/rss+xml, application/atom+xml, application/xml, text/xml, */*",
            )
            .header("Accept-Language", "en-US,en;q=0.9")
            .header("Referer", "https://www.google.com/")
            .header("DNT", "1")
            .header("Connection", "keep-alive")
            .header("Upgrade-Insecure-Requests", "1")
            .send()
            .await
            .with_context(|| format!("Network error fetching feed: {}", source.url))?;

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

        // Handle 403 Forbidden - try with different approach
        if status == 403 {
            // Try fetching via HTTPS with different user agent
            let https_url = source.url.replace("http://", "https://");
            if https_url != source.url {
                tracing::info!("Retrying {} with HTTPS", source.name);
                return self.fetch_with_different_client(&https_url, source).await;
            }
            anyhow::bail!("HTTP 403 Forbidden (site blocks automated access)");
        }

        if !status.is_success() {
            anyhow::bail!("HTTP {} (Content-Type: {})", status, content_type);
        }

        let bytes = response
            .bytes()
            .await
            .with_context(|| format!("Failed to read feed body: {}", source.url))?;

        // Parse RSS/Atom feed
        match self.parse_feed(&bytes, source) {
            Ok(items) => Ok(items),
            Err(e) => {
                let body_preview = String::from_utf8_lossy(&bytes);
                let preview_len = body_preview.len().min(256);
                anyhow::bail!(
                    "Parsing error: {} - Body start: {}",
                    e,
                    &body_preview[..preview_len]
                );
            }
        }
    }

    /// Try fetching with a different HTTP client configuration
    async fn fetch_with_different_client(
        &self,
        url: &str,
        source: &FeedSource,
    ) -> Result<Vec<FeedItem>> {
        // Create a new client with different settings
        let mut headers = reqwest::header::HeaderMap::new();
        headers.insert(
            reqwest::header::ACCEPT,
            reqwest::header::HeaderValue::from_static("*/*"),
        );
        headers.insert(
            reqwest::header::ACCEPT_LANGUAGE,
            reqwest::header::HeaderValue::from_static("en-US,en;q=0.5"),
        );

        let client = reqwest::Client::builder()
            .user_agent("Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)")
            .default_headers(headers)
            .timeout(std::time::Duration::from_secs(30))
            .build()?;

        let response = client
            .get(url)
            .send()
            .await
            .with_context(|| format!("Network error fetching feed: {}", url))?;

        if !response.status().is_success() {
            anyhow::bail!("HTTP {} even with different client", response.status());
        }

        let bytes = response.bytes().await?;
        self.parse_feed(&bytes, source)
    }

    /// Parse RSS/Atom XML into feed items
    fn parse_feed(&self, xml_bytes: &[u8], source: &FeedSource) -> Result<Vec<FeedItem>> {
        let feed = feed_rs::parser::parse(xml_bytes)
            .with_context(|| format!("Failed to parse feed from {}", source.name))?;

        let mut items = Vec::new();

        for entry in feed.entries {
            let id = entry.id;
            let title = entry
                .title
                .map(|t| t.content)
                .unwrap_or_else(|| "Untitled".to_string());
            let link = entry
                .links
                .first()
                .map(|l| l.href.clone())
                .unwrap_or_default();
            let description = entry.summary.map(|s| s.content);
            let published_at = entry.published.or(entry.updated);

            items.push(FeedItem {
                id,
                title,
                link,
                description,
                published_at,
                source: source.name.clone(),
                category: source.category.clone(),
                priority: source.priority,
            });
        }

        Ok(items)
    }

    /// Fetch all feeds and return items
    pub async fn fetch_all(self: std::sync::Arc<Self>) -> Result<Vec<FeedItem>> {
        let mut all_items = Vec::new();
        let mut set = tokio::task::JoinSet::new();

        for source in self.sources.clone() {
            let self_clone = self.clone();
            set.spawn(async move {
                // Add a timeout to individual feed fetches to prevent stalling
                match tokio::time::timeout(
                    std::time::Duration::from_secs(30),
                    self_clone.fetch_feed(&source),
                )
                .await
                {
                    Ok(Ok(items)) => Ok((source.name, items)),
                    Ok(Err(e)) => Err(format!("{}: {}", source.name, e)),
                    Err(_) => Err(format!("{}: Timeout after 30s", source.name)),
                }
            });
        }

        while let Some(res) = set.join_next().await {
            match res {
                Ok(Ok((_name, items))) => all_items.extend(items),
                Ok(Err(e)) => tracing::warn!("Failed to fetch feed: {}", e),
                Err(e) => tracing::error!("Join error: {}", e),
            }
        }

        // Also fetch GitHub trending (single source, sequential is fine)
        match self.fetch_github_trending().await {
            Ok(items) => all_items.extend(items),
            Err(e) => tracing::warn!("Failed to fetch GitHub trending: {}", e),
        }

        // Also fetch Hacker News New Stories
        match self.fetch_hacker_news().await {
            Ok(items) => all_items.extend(items),
            Err(e) => tracing::warn!("Failed to fetch Hacker News: {}", e),
        }

        Ok(all_items)
    }

    /// Fetch Hacker News New Stories using the Firebase API
    pub async fn fetch_hacker_news(&self) -> Result<Vec<FeedItem>> {
        let url = "https://hacker-news.firebaseio.com/v0/newstories.json";
        let response = self
            .client
            .get(url)
            .send()
            .await
            .with_context(|| "Failed to fetch Hacker News new stories IDs")?;

        let ids: Vec<u64> = response
            .json()
            .await
            .with_context(|| "Failed to parse HN story IDs")?;

        let mut items = Vec::new();
        // Limit to top 30 new stories to avoid rate limiting and excessive work
        let top_ids = &ids[..30.min(ids.len())];

        let mut fetch_tasks = Vec::new();
        for &id in top_ids {
            let client = self.client.clone();
            fetch_tasks.push(tokio::spawn(async move {
                let story_url = format!("https://hacker-news.firebaseio.com/v0/item/{}.json", id);
                match client.get(&story_url).send().await {
                    Ok(resp) => resp.json::<serde_json::Value>().await.ok(),
                    Err(_) => None,
                }
            }));
        }

        let results = futures::future::join_all(fetch_tasks).await;
        for result in results {
            if let Ok(Some(story)) = result {
                let id = story["id"].as_u64().unwrap_or(0).to_string();
                let title = story["title"]
                    .as_str()
                    .unwrap_or("Untitled Hacker News Story")
                    .to_string();
                let link = match story["url"].as_str() {
                    Some(l) => l.to_string(),
                    None => continue, // Skip stories with no external link (Ask HN, etc.)
                };
                let published_at = story["time"]
                    .as_i64()
                    .map(|t| DateTime::from_timestamp(t, 0).unwrap_or_default());

                items.push(FeedItem {
                    id: format!("hn-{}", id),
                    title,
                    link,
                    description: Some(format!("New story on Hacker News (ID: {})", id)),
                    published_at,
                    source: "Hacker News".to_string(),
                    category: "tech".to_string(),
                    priority: 8,
                });
            }
        }

        Ok(items)
    }

    /// Get pre-computed embedding for a category (placeholder)
    pub fn get_category_embedding(&self, category: &str) -> Vec<f32> {
        // Pre-computed embeddings for categories using a 384-dim vector (MiniLM-L6-v2)
        // For now, returning a deterministic dummy vector based on category name
        let mut vector = vec![0.0; 384];
        for (i, byte) in category.as_bytes().iter().enumerate() {
            if i < 384 {
                vector[i] = (*byte as f32) / 255.0;
            }
        }
        vector
    }

    /// Fetch GitHub trending repositories
    pub async fn fetch_github_trending(&self) -> Result<Vec<FeedItem>> {
        let url = "https://github.com/trending";
        let response = self
            .client
            .get(url)
            .send()
            .await
            .with_context(|| "Failed to fetch GitHub trending")?;

        let html = response
            .text()
            .await
            .with_context(|| "Failed to read GitHub trending body")?;

        let document = scraper::Html::parse_document(&html);

        // Select repo rows from the trending page
        let row_selector = scraper::Selector::parse("article.Box-row")
            .map_err(|e| anyhow::anyhow!("Invalid CSS selector: {:?}", e))?;
        let repo_selector = scraper::Selector::parse("h2 a")
            .map_err(|e| anyhow::anyhow!("Invalid CSS selector: {:?}", e))?;
        let desc_selector = scraper::Selector::parse("p")
            .map_err(|e| anyhow::anyhow!("Invalid CSS selector: {:?}", e))?;
        let lang_selector = scraper::Selector::parse("[itemprop=programmingLanguage]")
            .map_err(|e| anyhow::anyhow!("Invalid CSS selector: {:?}", e))?;
        let stars_selector = scraper::Selector::parse("a[href*='/stargazers']")
            .map_err(|e| anyhow::anyhow!("Invalid CSS selector: {:?}", e))?;

        let mut items = Vec::new();

        for row in document.select(&row_selector) {
            // Extract repo path from link
            let repo_path = row
                .select(&repo_selector)
                .next()
                .and_then(|el| el.value().attr("href"))
                .map(|s| s.trim().trim_start_matches('/').to_string());

            let repo_name = match repo_path {
                Some(name) if !name.is_empty() => name,
                _ => continue,
            };

            // Extract description
            let description = row
                .select(&desc_selector)
                .next()
                .map(|el| el.text().collect::<String>().trim().to_string())
                .filter(|s| !s.is_empty());

            // Extract language
            let language = row
                .select(&lang_selector)
                .next()
                .map(|el| el.text().collect::<String>().trim().to_string());

            // Extract star count
            let stars = row
                .select(&stars_selector)
                .next()
                .map(|el| el.text().collect::<String>().trim().replace(",", ""))
                .and_then(|s| s.parse::<u64>().ok());

            let mut tags = Vec::new();
            if let Some(lang) = language {
                tags.push(lang);
            }

            let mut desc_text =
                description.unwrap_or_else(|| "Trending repository on GitHub".to_string());
            if let Some(stars) = stars {
                desc_text.push_str(&format!(" ({} stars)", stars));
            }

            items.push(FeedItem {
                id: format!("gh-trending-{}", repo_name.replace("/", "-")),
                title: format!("GitHub: {}", repo_name),
                link: format!("https://github.com/{}", repo_name),
                description: Some(desc_text),
                published_at: Some(Utc::now()),
                source: "GitHub Trending".to_string(),
                category: "devtools".to_string(),
                priority: 9,
            });

            if items.len() >= 25 {
                break;
            }
        }

        if items.is_empty() {
            tracing::warn!(
                "No trending repos found on GitHub page, HTML structure may have changed"
            );
        }

        Ok(items)
    }

    /// Calculate trending score for items
    pub fn calculate_trending(&self, items: Vec<FeedItem>) -> Vec<TrendingItem> {
        let now = Utc::now();

        items
            .into_iter()
            .map(|item| {
                // Calculate velocity based on recency and priority
                let age_hours = item
                    .published_at
                    .map(|t| now.signed_duration_since(t).num_seconds() as f32 / 3600.0)
                    .unwrap_or(24.0);

                // Decay function: newer items get higher velocity
                let velocity = (item.priority as f32) / (age_hours + 1.0).ln();

                // Trending score combines velocity with category weight
                let trending_score = velocity * get_category_weight(&item.category);

                TrendingItem {
                    id: item.id,
                    title: item.title,
                    url: item.link,
                    category: item.category,
                    source: item.source,
                    trending_score,
                    velocity,
                    published_at: item.published_at,
                }
            })
            .collect()
    }
}

/// Get category weight for trending calculation
fn get_category_weight(category: &str) -> f32 {
    match category {
        "ai" => 1.5,
        "tech" => 1.2,
        "startups" => 1.1,
        "devtools" => 1.0,
        "science" => 1.3,
        "products" => 1.2,
        _ => 1.0,
    }
}

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

    #[test]
    fn test_category_weight() {
        assert_eq!(get_category_weight("ai"), 1.5);
        assert_eq!(get_category_weight("tech"), 1.2);
        assert_eq!(get_category_weight("unknown"), 1.0);
    }
}