File size: 24,586 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
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
#![allow(dead_code)]
//! Domain Manager Module for IntentForge v2
//!
//! Manages domains with automatic source discovery, validation, and performance tracking.
//! Provides reliable, always-updated sources for each domain.

use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;

use crate::redis_store::RedisStore;

const DOMAIN_STATS_KEY: &str = "domain_manager:stats";
const SOURCE_HEALTH_KEY: &str = "domain_manager:source_health";
const DOMAIN_SOURCES_KEY: &str = "domain_manager:domain_sources";

/// Source type enumeration
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum SourceType {
    RssFeed,
    AtomFeed,
    Sitemap,
    Api,
    Html,
    Json,
}

/// Source health status
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum HealthStatus {
    Healthy,
    Degraded,
    Unhealthy,
    Unknown,
}

/// Source performance metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SourceMetrics {
    pub total_requests: u64,
    pub successful_requests: u64,
    pub failed_requests: u64,
    pub avg_response_time_ms: f64,
    pub last_success_at: Option<i64>,
    pub last_failure_at: Option<i64>,
    pub consecutive_failures: u32,
    pub items_fetched: u64,
    pub quality_score: f32,
}

impl Default for SourceMetrics {
    fn default() -> Self {
        Self {
            total_requests: 0,
            successful_requests: 0,
            failed_requests: 0,
            avg_response_time_ms: 0.0,
            last_success_at: None,
            last_failure_at: None,
            consecutive_failures: 0,
            items_fetched: 0,
            quality_score: 0.5,
        }
    }
}

impl SourceMetrics {
    /// Calculate success rate
    pub fn success_rate(&self) -> f32 {
        if self.total_requests == 0 {
            return 0.0;
        }
        self.successful_requests as f32 / self.total_requests as f32
    }

    /// Calculate health status based on metrics
    pub fn health_status(&self) -> HealthStatus {
        if self.total_requests == 0 {
            return HealthStatus::Unknown;
        }

        let success_rate = self.success_rate();
        if success_rate >= 0.9 && self.consecutive_failures < 3 {
            HealthStatus::Healthy
        } else if success_rate >= 0.5 && self.consecutive_failures < 5 {
            HealthStatus::Degraded
        } else {
            HealthStatus::Unhealthy
        }
    }

    /// Update metrics after a request
    pub fn record_success(&mut self, response_time_ms: f64, items_count: usize) {
        self.total_requests += 1;
        self.successful_requests += 1;
        self.consecutive_failures = 0;
        self.last_success_at = Some(chrono::Utc::now().timestamp());
        self.items_fetched += items_count as u64;

        // Update rolling average response time
        let n = self.successful_requests as f64;
        self.avg_response_time_ms = (self.avg_response_time_ms * (n - 1.0) + response_time_ms) / n;
    }

    pub fn record_failure(&mut self) {
        self.total_requests += 1;
        self.failed_requests += 1;
        self.consecutive_failures += 1;
        self.last_failure_at = Some(chrono::Utc::now().timestamp());
    }
}

/// Source configuration with metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ManagedSource {
    pub id: String,
    pub domain: String,
    pub name: String,
    pub url: String,
    pub source_type: SourceType,
    pub category: String,
    pub priority: u32,
    pub enabled: bool,
    pub discovered_at: i64,
    pub last_checked_at: Option<i64>,
    pub check_interval_secs: u64,
    pub metrics: SourceMetrics,
}

impl ManagedSource {
    pub fn new(
        domain: String,
        name: String,
        url: String,
        source_type: SourceType,
        category: String,
        priority: u32,
    ) -> Self {
        Self {
            id: format!("{}-{}", domain, uuid::Uuid::new_v4()),
            domain,
            name,
            url,
            source_type,
            category,
            priority,
            enabled: true,
            discovered_at: chrono::Utc::now().timestamp(),
            last_checked_at: None,
            check_interval_secs: 3600, // 1 hour default
            metrics: SourceMetrics::default(),
        }
    }

    /// Calculate effective priority based on metrics
    pub fn effective_priority(&self) -> f32 {
        let base_priority = self.priority as f32;
        let health_multiplier = match self.metrics.health_status() {
            HealthStatus::Healthy => 1.0,
            HealthStatus::Degraded => 0.7,
            HealthStatus::Unhealthy => 0.3,
            HealthStatus::Unknown => 0.5,
        };
        let quality_multiplier = self.metrics.quality_score;
        base_priority * health_multiplier * quality_multiplier
    }
}

/// Domain configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Domain {
    pub name: String,
    pub base_url: String,
    pub category: String,
    pub priority: u32,
    pub enabled: bool,
    pub sources: Vec<String>, // Source IDs
    pub discovered_sources: Vec<String>,
    pub last_discovery_at: Option<i64>,
    pub discovery_interval_secs: u64,
}

impl Domain {
    pub fn new(name: String, base_url: String, category: String, priority: u32) -> Self {
        Self {
            name,
            base_url,
            category,
            priority,
            enabled: true,
            sources: Vec::new(),
            discovered_sources: Vec::new(),
            last_discovery_at: None,
            discovery_interval_secs: 86400, // 24 hours default
        }
    }
}

/// Domain Manager - manages domains and their sources
pub struct DomainManager {
    redis: Arc<RedisStore>,
    domains: Arc<RwLock<HashMap<String, Domain>>>,
    sources: Arc<RwLock<HashMap<String, ManagedSource>>>,
    client: reqwest::Client,
}

impl DomainManager {
    /// Create a new domain manager
    pub fn new(redis: Arc<RedisStore>) -> Self {
        let client = reqwest::Client::builder()
            .user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 IntentForge/0.1")
            .timeout(std::time::Duration::from_secs(30))
            .build()
            .unwrap_or_default();

        Self {
            redis,
            domains: Arc::new(RwLock::new(HashMap::new())),
            sources: Arc::new(RwLock::new(HashMap::new())),
            client,
        }
    }

    /// Initialize from sources.yaml
    pub async fn init_from_config(&self, config: &crate::trending::SourcesConfig) -> Result<()> {
        {
            let mut domains = self.domains.write().await;
            let mut sources = self.sources.write().await;

            // Add domains from config
            for domain_source in &config.domains {
                let domain = Domain::new(
                    domain_source.name.clone(),
                    domain_source.base_url.clone(),
                    domain_source.category.clone(),
                    domain_source.priority,
                );
                domains.insert(domain.name.clone(), domain);
            }

            // Add RSS feeds as sources
            for feed in &config.sources {
                let source = ManagedSource::new(
                    feed.name.clone(), // Use name as domain for feeds
                    feed.name.clone(),
                    feed.url.clone(),
                    SourceType::RssFeed,
                    feed.category.clone(),
                    feed.priority,
                );
                sources.insert(source.id.clone(), source);
            }
        }

        // Load persisted state from Redis
        self.load_state().await?;

        let domains_len = self.domains.read().await.len();
        let sources_len = self.sources.read().await.len();

        tracing::info!(
            "Domain manager initialized with {} domains and {} sources",
            domains_len,
            sources_len
        );

        Ok(())
    }

    /// Load state from Redis
    async fn load_state(&self) -> Result<()> {
        let mut conn = self.redis.get_connection().await?;

        // Load domain sources mapping
        let domain_sources_json: Option<String> = redis::cmd("GET")
            .arg(DOMAIN_SOURCES_KEY)
            .query_async(&mut conn)
            .await?;

        if let Some(json) = domain_sources_json {
            if let Ok(domain_sources) = serde_json::from_str::<HashMap<String, Vec<String>>>(&json)
            {
                let mut domains = self.domains.write().await;
                for (domain_name, source_ids) in domain_sources {
                    if let Some(domain) = domains.get_mut(&domain_name) {
                        domain.discovered_sources = source_ids;
                    }
                }
            }
        }

        // Load source health data
        let source_health_json: Option<String> = redis::cmd("GET")
            .arg(SOURCE_HEALTH_KEY)
            .query_async(&mut conn)
            .await?;

        if let Some(json) = source_health_json {
            if let Ok(source_health) = serde_json::from_str::<HashMap<String, SourceMetrics>>(&json)
            {
                let mut sources = self.sources.write().await;
                for (source_id, metrics) in source_health {
                    if let Some(source) = sources.get_mut(&source_id) {
                        source.metrics = metrics;
                    }
                }
            }
        }

        Ok(())
    }

    /// Save state to Redis
    pub async fn save_state(&self) -> Result<()> {
        let mut conn = self.redis.get_connection().await?;

        // Save domain sources mapping
        let domains = self.domains.read().await;
        let domain_sources: HashMap<String, Vec<String>> = domains
            .iter()
            .map(|(name, domain)| {
                (
                    name.clone(),
                    domain
                        .sources
                        .iter()
                        .chain(domain.discovered_sources.iter())
                        .cloned()
                        .collect(),
                )
            })
            .collect();

        let domain_sources_json = serde_json::to_string(&domain_sources)?;
        redis::cmd("SET")
            .arg(DOMAIN_SOURCES_KEY)
            .arg(&domain_sources_json)
            .arg("EX")
            .arg(86400)
            .query_async::<()>(&mut conn)
            .await?;

        // Save source health data
        let sources = self.sources.read().await;
        let source_health: HashMap<String, SourceMetrics> = sources
            .iter()
            .map(|(id, source)| (id.clone(), source.metrics.clone()))
            .collect();

        let source_health_json = serde_json::to_string(&source_health)?;
        redis::cmd("SET")
            .arg(SOURCE_HEALTH_KEY)
            .arg(&source_health_json)
            .arg("EX")
            .arg(86400)
            .query_async::<()>(&mut conn)
            .await?;

        Ok(())
    }

    /// Discover sources for a domain
    pub async fn discover_sources(&self, domain_name: &str) -> Result<Vec<ManagedSource>> {
        let domain = {
            let domains = self.domains.read().await;
            domains.get(domain_name).cloned()
        };

        let domain = match domain {
            Some(d) => d,
            None => return Ok(Vec::new()),
        };

        let mut discovered = Vec::new();

        // Try common RSS/Atom feed locations
        let feed_paths = vec![
            "/feed",
            "/feed/",
            "/rss",
            "/rss/",
            "/atom.xml",
            "/feed.xml",
            "/rss.xml",
            "/blog/feed",
            "/blog/rss",
            "/blog/feed.xml",
            "/blog/rss.xml",
            "/index.xml",
        ];

        for path in feed_paths {
            let url = format!("{}{}", domain.base_url.trim_end_matches('/'), path);
            if let Ok(Some(source)) = self.check_feed_url(&url, &domain).await {
                discovered.push(source);
            }
        }

        // Check for sitemap
        let sitemap_url = format!("{}/sitemap.xml", domain.base_url.trim_end_matches('/'));
        if let Ok(Some(source)) = self.check_sitemap_url(&sitemap_url, &domain).await {
            discovered.push(source);
        }

        // Check robots.txt for sitemap
        let robots_url = format!("{}/robots.txt", domain.base_url.trim_end_matches('/'));
        if let Ok(sitemaps) = self.extract_sitemaps_from_robots(&robots_url).await {
            for sitemap_url in sitemaps {
                if let Ok(Some(source)) = self.check_sitemap_url(&sitemap_url, &domain).await {
                    discovered.push(source);
                }
            }
        }

        // Update domain with discovered sources
        {
            let mut domains = self.domains.write().await;
            if let Some(domain) = domains.get_mut(domain_name) {
                domain.last_discovery_at = Some(chrono::Utc::now().timestamp());
                domain.discovered_sources = discovered.iter().map(|s| s.id.clone()).collect();
            }
        }

        // Add sources to manager
        {
            let mut sources = self.sources.write().await;
            for source in &discovered {
                sources.insert(source.id.clone(), source.clone());
            }
        }

        tracing::info!(
            "Discovered {} sources for domain '{}'",
            discovered.len(),
            domain_name
        );

        Ok(discovered)
    }

    /// Check if a URL is a valid feed
    async fn check_feed_url(&self, url: &str, domain: &Domain) -> Result<Option<ManagedSource>> {
        let start = std::time::Instant::now();

        match self.client.get(url).send().await {
            Ok(resp) if resp.status().is_success() => {
                let content_type = resp
                    .headers()
                    .get("content-type")
                    .and_then(|v| v.to_str().ok())
                    .unwrap_or("")
                    .to_lowercase();

                let body = resp.text().await?;

                // Check if it's a feed
                let is_feed = content_type.contains("xml")
                    || content_type.contains("rss")
                    || content_type.contains("atom")
                    || body.contains("<rss")
                    || body.contains("<feed")
                    || body.contains("<channel>");

                if is_feed {
                    let source_type = if body.contains("<feed") {
                        SourceType::AtomFeed
                    } else {
                        SourceType::RssFeed
                    };

                    let name = format!("{} Feed", domain.name);
                    let mut source = ManagedSource::new(
                        domain.name.clone(),
                        name,
                        url.to_string(),
                        source_type,
                        domain.category.clone(),
                        domain.priority,
                    );

                    let elapsed = start.elapsed().as_millis() as f64;
                    source.metrics.record_success(elapsed, 0);
                    source.last_checked_at = Some(chrono::Utc::now().timestamp());

                    return Ok(Some(source));
                }
            }
            _ => {}
        }

        Ok(None)
    }

    /// Check if a sitemap URL is valid
    async fn check_sitemap_url(&self, url: &str, domain: &Domain) -> Result<Option<ManagedSource>> {
        let start = std::time::Instant::now();

        match self.client.get(url).send().await {
            Ok(resp) if resp.status().is_success() => {
                let body = resp.text().await?;

                if body.contains("<sitemapindex") || body.contains("<urlset") {
                    let name = format!("{} Sitemap", domain.name);
                    let mut source = ManagedSource::new(
                        domain.name.clone(),
                        name,
                        url.to_string(),
                        SourceType::Sitemap,
                        domain.category.clone(),
                        domain.priority,
                    );

                    let elapsed = start.elapsed().as_millis() as f64;
                    source.metrics.record_success(elapsed, 0);
                    source.last_checked_at = Some(chrono::Utc::now().timestamp());

                    return Ok(Some(source));
                }
            }
            _ => {}
        }

        Ok(None)
    }

    /// Extract sitemap URLs from robots.txt
    async fn extract_sitemaps_from_robots(&self, robots_url: &str) -> Result<Vec<String>> {
        let mut sitemaps = Vec::new();

        if let Ok(resp) = self.client.get(robots_url).send().await {
            if resp.status().is_success() {
                let body = resp.text().await?;
                for line in body.lines() {
                    let line = line.trim();
                    if line.to_lowercase().starts_with("sitemap:") {
                        let sitemap_url = line["sitemap:".len()..].trim().to_string();
                        if !sitemap_url.is_empty() {
                            sitemaps.push(sitemap_url);
                        }
                    }
                }
            }
        }

        Ok(sitemaps)
    }

    /// Get best sources for a category
    pub async fn get_best_sources(&self, category: &str, limit: usize) -> Vec<ManagedSource> {
        let sources = self.sources.read().await;
        let mut category_sources: Vec<&ManagedSource> = sources
            .values()
            .filter(|s| s.category == category && s.enabled)
            .collect();

        // Sort by effective priority
        category_sources.sort_by(|a, b| {
            b.effective_priority()
                .partial_cmp(&a.effective_priority())
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        category_sources.into_iter().take(limit).cloned().collect()
    }

    /// Get sources for a domain
    pub async fn get_domain_sources(&self, domain_name: &str) -> Vec<ManagedSource> {
        let domains = self.domains.read().await;
        let sources = self.sources.read().await;

        if let Some(domain) = domains.get(domain_name) {
            domain
                .sources
                .iter()
                .chain(domain.discovered_sources.iter())
                .filter_map(|id| sources.get(id).cloned())
                .collect()
        } else {
            Vec::new()
        }
    }

    /// Update source metrics
    pub async fn update_source_metrics(
        &self,
        source_id: &str,
        success: bool,
        response_time_ms: f64,
        items_count: usize,
    ) -> Result<()> {
        let mut sources = self.sources.write().await;
        if let Some(source) = sources.get_mut(source_id) {
            if success {
                source.metrics.record_success(response_time_ms, items_count);
            } else {
                source.metrics.record_failure();
            }
            source.last_checked_at = Some(chrono::Utc::now().timestamp());
        }

        // Persist to Redis periodically
        static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
        let count = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        if count.is_multiple_of(100) {
            self.save_state().await?;
        }

        Ok(())
    }

    /// Run discovery for all domains
    pub async fn run_discovery(&self) -> Result<usize> {
        let domain_names: Vec<String> = {
            let domains = self.domains.read().await;
            domains.keys().cloned().collect()
        };

        let mut total_discovered = 0;

        for domain_name in domain_names {
            // Check if discovery is needed
            let needs_discovery = {
                let domains = self.domains.read().await;
                if let Some(domain) = domains.get(&domain_name) {
                    if !domain.enabled {
                        continue;
                    }
                    match domain.last_discovery_at {
                        Some(last) => {
                            let elapsed = chrono::Utc::now().timestamp() - last;
                            elapsed as u64 >= domain.discovery_interval_secs
                        }
                        None => true,
                    }
                } else {
                    false
                }
            };

            if needs_discovery {
                match self.discover_sources(&domain_name).await {
                    Ok(sources) => {
                        total_discovered += sources.len();
                    }
                    Err(e) => {
                        tracing::warn!(
                            "Failed to discover sources for domain '{}': {}",
                            domain_name,
                            e
                        );
                    }
                }
            }
        }

        if total_discovered > 0 {
            self.save_state().await?;
        }

        Ok(total_discovered)
    }

    /// Get domain statistics
    pub async fn get_stats(&self) -> DomainManagerStats {
        let domains = self.domains.read().await;
        let sources = self.sources.read().await;

        let total_domains = domains.len();
        let enabled_domains = domains.values().filter(|d| d.enabled).count();
        let total_sources = sources.len();
        let healthy_sources = sources
            .values()
            .filter(|s| s.metrics.health_status() == HealthStatus::Healthy)
            .count();

        let sources_by_category: HashMap<String, usize> =
            sources.values().fold(HashMap::new(), |mut acc, s| {
                *acc.entry(s.category.clone()).or_insert(0) += 1;
                acc
            });

        DomainManagerStats {
            total_domains,
            enabled_domains,
            total_sources,
            healthy_sources,
            sources_by_category,
        }
    }
}

/// Domain manager statistics
#[derive(Debug, Serialize)]
pub struct DomainManagerStats {
    pub total_domains: usize,
    pub enabled_domains: usize,
    pub total_sources: usize,
    pub healthy_sources: usize,
    pub sources_by_category: HashMap<String, usize>,
}

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

    #[test]
    fn test_source_metrics_default() {
        let metrics = SourceMetrics::default();
        assert_eq!(metrics.total_requests, 0);
        assert_eq!(metrics.success_rate(), 0.0);
        assert_eq!(metrics.health_status(), HealthStatus::Unknown);
    }

    #[test]
    fn test_source_metrics_success_rate() {
        let mut metrics = SourceMetrics::default();
        metrics.total_requests = 100;
        metrics.successful_requests = 95;
        assert_eq!(metrics.success_rate(), 0.95);
    }

    #[test]
    fn test_source_metrics_health_status() {
        let mut metrics = SourceMetrics::default();

        // Healthy
        metrics.total_requests = 100;
        metrics.successful_requests = 95;
        metrics.consecutive_failures = 1;
        assert_eq!(metrics.health_status(), HealthStatus::Healthy);

        // Degraded
        metrics.successful_requests = 70;
        metrics.consecutive_failures = 3;
        assert_eq!(metrics.health_status(), HealthStatus::Degraded);

        // Unhealthy
        metrics.successful_requests = 30;
        metrics.consecutive_failures = 10;
        assert_eq!(metrics.health_status(), HealthStatus::Unhealthy);
    }

    #[test]
    fn test_managed_source_effective_priority() {
        let mut source = ManagedSource::new(
            "example.com".to_string(),
            "Example".to_string(),
            "https://example.com/feed".to_string(),
            SourceType::RssFeed,
            "tech".to_string(),
            10,
        );

        // Unknown health
        assert!(source.effective_priority() > 0.0);

        // Healthy with good quality
        source.metrics.total_requests = 100;
        source.metrics.successful_requests = 95;
        source.metrics.quality_score = 0.9;
        let priority = source.effective_priority();
        assert!(priority > 5.0);
    }
}