// src/monitoring/mod.rs
//! Monitoring system for tracking scraper performance and health
//!
//! This module provides:
//! - Real-time metrics collection
//! - Web-based dashboard
//! - Session logging
//! - Minimal performance overhead

pub mod metrics;
pub mod events;
pub mod service;
pub mod webserver;
pub mod logger;

pub use events::{MonitoringEvent,RenewalReason, InstanceStatusChange};
pub use metrics::{ConfigSnapshot, ProxyInfo, ProxyStatus};
pub use service::{MonitoringService, MonitoringHandle};
pub use webserver::WebServer;

use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::{mpsc, RwLock};

/// Initialize the complete monitoring system
pub async fn init_monitoring(
    config_snapshot: ConfigSnapshot,
    log_dir: PathBuf,
    dashboard_port: u16,
) -> anyhow::Result<(MonitoringHandle, tokio::task::JoinHandle<()>)> {
    // Create channel for events
    let (tx, rx) = mpsc::unbounded_channel();

    // Create monitoring service
    let service = MonitoringService::new(config_snapshot, rx, log_dir);
    let service_arc = Arc::new(RwLock::new(service));

    // Start monitoring service task
    let service_clone = Arc::clone(&service_arc);
    let monitoring_task = tokio::spawn(async move {
        println!("🚀 MONITORING TASK STARTED!");
        // Take ownership of the service
        let mut service = {
            let mut guard = service_clone.write().await;
            std::mem::replace(
                &mut *guard,
                MonitoringService::new(
                    ConfigSnapshot {
                        max_parallel_instances: 0,
                        max_tasks_per_instance: 0,
                        enable_vpn_rotation: false,
                        max_requests_per_session: 0,
                        min_request_interval_ms: 0,
                        max_retry_attempts: 0,
                    },
                    mpsc::unbounded_channel().1,
                    PathBuf::new(),
                ),
            )
        };
        
        println!("✅ ABOUT TO RUN SERVICE!");
        service.run().await;
    });

    // Start web server
    let webserver = WebServer::new(Arc::clone(&service_arc), dashboard_port);
    tokio::spawn(async move {
        if let Err(e) = webserver.run().await {
            eprintln!("Web server error: {}", e);
        }
    });

    // Create handle for emitting events
    let handle = MonitoringHandle::new(tx);

    Ok((handle, monitoring_task))
}