//! 增强版性能监控服务
//! 提供系统性能监控、指标收集和性能分析

use anyhow::{Result, anyhow};
use std::collections::{HashMap, VecDeque};
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use tokio::sync::{RwLock, Mutex};
use tracing::{info, warn, error, debug};
use serde::{Serialize, Deserialize};

/// 系统性能指标
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemMetrics {
    /// 时间戳
    pub timestamp: u64,
    /// CPU 使用率 (%)
    pub cpu_usage: f64,
    /// 内存使用量 (MB)
    pub memory_usage: u64,
    /// 内存使用率 (%)
    pub memory_usage_percent: f64,
    /// 磁盘使用量 (MB)
    pub disk_usage: u64,
    /// 磁盘 I/O 读取速率 (MB/s)
    pub disk_read_rate: f64,
    /// 磁盘 I/O 写入速率 (MB/s)
    pub disk_write_rate: f64,
    /// 网络接收速率 (MB/s)
    pub network_rx_rate: f64,
    /// 网络发送速率 (MB/s)
    pub network_tx_rate: f64,
}

/// 应用性能指标
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApplicationMetrics {
    /// 时间戳
    pub timestamp: u64,
    /// 活跃连接数
    pub active_connections: u32,
    /// 队列长度
    pub queue_length: u32,
    /// 缓存命中率 (%)
    pub cache_hit_rate: f64,
    /// 平均响应时间 (ms)
    pub average_response_time: f64,
    /// 错误率 (%)
    pub error_rate: f64,
    /// 吞吐量 (请求/秒)
    pub throughput: f64,
    /// 并发执行数
    pub concurrent_executions: u32,
}

/// 综合性能指标
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceMetrics {
    /// 系统指标
    pub system: SystemMetrics,
    /// 应用指标
    pub application: ApplicationMetrics,
}

/// 性能警报
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceAlert {
    /// 警报 ID
    pub id: String,
    /// 警报类型
    pub alert_type: AlertType,
    /// 严重程度
    pub severity: AlertSeverity,
    /// 消息
    pub message: String,
    /// 当前值
    pub current_value: f64,
    /// 阈值
    pub threshold: f64,
    /// 触发时间
    pub triggered_at: u64,
    /// 是否已解决
    pub resolved: bool,
    /// 解决时间
    pub resolved_at: Option<u64>,
}

/// 警报类型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AlertType {
    HighCpuUsage,
    HighMemoryUsage,
    LowDiskSpace,
    SlowResponse,
    HighErrorRate,
    LowCacheHitRate,
    QueueBacklog,
    TooManyConnections,
}

/// 警报严重程度
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum AlertSeverity {
    Info,
    Warning,
    Error,
    Critical,
}

/// 性能阈值配置
#[derive(Debug, Clone)]
pub struct PerformanceThresholds {
    pub cpu_usage_warning: f64,
    pub cpu_usage_critical: f64,
    pub memory_usage_warning: f64,
    pub memory_usage_critical: f64,
    pub response_time_warning: f64,
    pub response_time_critical: f64,
    pub error_rate_warning: f64,
    pub error_rate_critical: f64,
    pub cache_hit_rate_warning: f64,
    pub queue_length_warning: u32,
    pub queue_length_critical: u32,
}

impl Default for PerformanceThresholds {
    fn default() -> Self {
        Self {
            cpu_usage_warning: 70.0,
            cpu_usage_critical: 90.0,
            memory_usage_warning: 80.0,
            memory_usage_critical: 95.0,
            response_time_warning: 1000.0,
            response_time_critical: 5000.0,
            error_rate_warning: 5.0,
            error_rate_critical: 10.0,
            cache_hit_rate_warning: 50.0,
            queue_length_warning: 100,
            queue_length_critical: 500,
        }
    }
}

/// 性能监控配置
#[derive(Debug, Clone)]
pub struct PerformanceMonitorConfig {
    pub monitor_interval: Duration,
    pub history_retention: Duration,
    pub max_history_records: usize,
    pub enable_alerts: bool,
    pub thresholds: PerformanceThresholds,
}

impl Default for PerformanceMonitorConfig {
    fn default() -> Self {
        Self {
            monitor_interval: Duration::from_secs(30),
            history_retention: Duration::from_secs(24 * 3600),
            max_history_records: 2880,
            enable_alerts: true,
            thresholds: PerformanceThresholds::default(),
        }
    }
}

/// 指标提供者特征
pub trait MetricsProvider: Send + Sync {
    /// 获取应用指标
    fn get_application_metrics(&self) -> Result<ApplicationMetrics>;
}

/// 增强版性能监控服务
pub struct PerformanceMonitorV2 {
    config: PerformanceMonitorConfig,
    metrics_history: Arc<RwLock<VecDeque<PerformanceMetrics>>>,
    active_alerts: Arc<RwLock<HashMap<String, PerformanceAlert>>>,
    alert_history: Arc<RwLock<VecDeque<PerformanceAlert>>>,
    monitor_handle: Arc<RwLock<Option<tokio::task::JoinHandle<()>>>>,
    is_running: Arc<RwLock<bool>>,
    metrics_providers: Arc<RwLock<Vec<Arc<dyn MetricsProvider>>>>,
}

impl PerformanceMonitorV2 {
    /// 创建新的性能监控服务
    pub fn new(config: PerformanceMonitorConfig) -> Self {
        Self {
            config,
            metrics_history: Arc::new(RwLock::new(VecDeque::new())),
            active_alerts: Arc::new(RwLock::new(HashMap::new())),
            alert_history: Arc::new(RwLock::new(VecDeque::new())),
            monitor_handle: Arc::new(RwLock::new(None)),
            is_running: Arc::new(RwLock::new(false)),
            metrics_providers: Arc::new(RwLock::new(Vec::new())),
        }
    }

    /// 启动性能监控
    pub async fn start(&self) -> Result<()> {
        info!("启动增强版性能监控服务");

        {
            let running = self.is_running.read().await;
            if *running {
                return Ok(());
            }
        }

        let monitor_task = self.spawn_monitor_task().await?;
        
        {
            let mut handle = self.monitor_handle.write().await;
            *handle = Some(monitor_task);
        }

        {
            let mut running = self.is_running.write().await;
            *running = true;
        }

        info!("增强版性能监控服务已启动");
        Ok(())
    }

    /// 停止性能监控
    pub async fn stop(&self) -> Result<()> {
        info!("停止增强版性能监控服务");

        let handle = {
            let mut handle_guard = self.monitor_handle.write().await;
            handle_guard.take()
        };

        if let Some(handle) = handle {
            handle.abort();
        }

        {
            let mut running = self.is_running.write().await;
            *running = false;
        }

        info!("增强版性能监控服务已停止");
        Ok(())
    }

    /// 添加指标提供者
    pub async fn add_metrics_provider(&self, provider: Arc<dyn MetricsProvider>) {
        let mut providers = self.metrics_providers.write().await;
        providers.push(provider);
    }

    /// 获取当前性能指标
    pub async fn get_current_metrics(&self) -> Result<PerformanceMetrics> {
        self.collect_metrics().await
    }

    /// 获取性能指标历史
    pub async fn get_metrics_history(&self, duration: Option<Duration>) -> Vec<PerformanceMetrics> {
        let history = self.metrics_history.read().await;
        
        if let Some(duration) = duration {
            let cutoff_time = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs() - duration.as_secs();
            
            history.iter()
                .filter(|metrics| metrics.system.timestamp >= cutoff_time)
                .cloned()
                .collect()
        } else {
            history.iter().cloned().collect()
        }
    }

    /// 获取活跃警报
    pub async fn get_active_alerts(&self) -> Vec<PerformanceAlert> {
        let alerts = self.active_alerts.read().await;
        alerts.values().cloned().collect()
    }

    /// 获取警报历史
    pub async fn get_alert_history(&self, limit: Option<usize>) -> Vec<PerformanceAlert> {
        let history = self.alert_history.read().await;
        
        if let Some(limit) = limit {
            history.iter().rev().take(limit).cloned().collect()
        } else {
            history.iter().cloned().collect()
        }
    }

    /// 收集性能指标
    async fn collect_metrics(&self) -> Result<PerformanceMetrics> {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        // 收集系统指标
        let system = SystemMetrics {
            timestamp,
            cpu_usage: self.get_cpu_usage().await.unwrap_or(0.0),
            memory_usage: self.get_memory_usage().await.unwrap_or(0),
            memory_usage_percent: self.get_memory_usage_percent().await.unwrap_or(0.0),
            disk_usage: self.get_disk_usage().await.unwrap_or(0),
            disk_read_rate: self.get_disk_read_rate().await.unwrap_or(0.0),
            disk_write_rate: self.get_disk_write_rate().await.unwrap_or(0.0),
            network_rx_rate: self.get_network_rx_rate().await.unwrap_or(0.0),
            network_tx_rate: self.get_network_tx_rate().await.unwrap_or(0.0),
        };

        // 收集应用指标
        let mut application = ApplicationMetrics {
            timestamp,
            active_connections: 0,
            queue_length: 0,
            cache_hit_rate: 0.0,
            average_response_time: 0.0,
            error_rate: 0.0,
            throughput: 0.0,
            concurrent_executions: 0,
        };

        // 从指标提供者收集应用指标
        {
            let providers = self.metrics_providers.read().await;
            for provider in providers.iter() {
                if let Ok(metrics) = provider.get_application_metrics() {
                    // 合并指标（这里使用简单的覆盖策略）
                    application.active_connections = metrics.active_connections;
                    application.queue_length = metrics.queue_length;
                    application.cache_hit_rate = metrics.cache_hit_rate;
                    application.average_response_time = metrics.average_response_time;
                    application.error_rate = metrics.error_rate;
                    application.throughput = metrics.throughput;
                    application.concurrent_executions = metrics.concurrent_executions;
                }
            }
        }

        Ok(PerformanceMetrics {
            system,
            application,
        })
    }

    /// 生成监控任务
    async fn spawn_monitor_task(&self) -> Result<tokio::task::JoinHandle<()>> {
        let metrics_history = Arc::clone(&self.metrics_history);
        let active_alerts = Arc::clone(&self.active_alerts);
        let alert_history = Arc::clone(&self.alert_history);
        let metrics_providers = Arc::clone(&self.metrics_providers);
        let config = self.config.clone();
        let is_running = Arc::clone(&self.is_running);

        let handle = tokio::spawn(async move {
            info!("增强版性能监控任务已启动");

            while *is_running.read().await {
                // 收集指标
                match Self::collect_metrics_internal(&metrics_providers).await {
                    Ok(metrics) => {
                        // 存储指标
                        {
                            let mut history = metrics_history.write().await;
                            history.push_back(metrics.clone());
                            
                            // 清理过期数据
                            let cutoff_time = metrics.system.timestamp - config.history_retention.as_secs();
                            while let Some(front) = history.front() {
                                if front.system.timestamp < cutoff_time {
                                    history.pop_front();
                                } else {
                                    break;
                                }
                            }
                            
                            // 限制最大记录数
                            while history.len() > config.max_history_records {
                                history.pop_front();
                            }
                        }

                        // 检查警报
                        if config.enable_alerts {
                            Self::check_alerts(&metrics, &config.thresholds, &active_alerts, &alert_history).await;
                        }
                    }
                    Err(e) => {
                        error!("收集性能指标失败: {}", e);
                    }
                }

                tokio::time::sleep(config.monitor_interval).await;
            }

            info!("增强版性能监控任务已停止");
        });

        Ok(handle)
    }

    /// 内部指标收集方法
    async fn collect_metrics_internal(
        metrics_providers: &Arc<RwLock<Vec<Arc<dyn MetricsProvider>>>>
    ) -> Result<PerformanceMetrics> {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        // 模拟系统指标
        let system = SystemMetrics {
            timestamp,
            cpu_usage: 45.0,
            memory_usage: 1024,
            memory_usage_percent: 60.0,
            disk_usage: 50 * 1024,
            disk_read_rate: 10.0,
            disk_write_rate: 5.0,
            network_rx_rate: 2.0,
            network_tx_rate: 1.5,
        };

        // 收集应用指标
        let mut application = ApplicationMetrics {
            timestamp,
            active_connections: 0,
            queue_length: 0,
            cache_hit_rate: 0.0,
            average_response_time: 0.0,
            error_rate: 0.0,
            throughput: 0.0,
            concurrent_executions: 0,
        };

        {
            let providers = metrics_providers.read().await;
            for provider in providers.iter() {
                if let Ok(metrics) = provider.get_application_metrics() {
                    application = metrics;
                    break; // 使用第一个成功的提供者
                }
            }
        }

        Ok(PerformanceMetrics {
            system,
            application,
        })
    }

    /// 检查警报
    async fn check_alerts(
        metrics: &PerformanceMetrics,
        thresholds: &PerformanceThresholds,
        active_alerts: &Arc<RwLock<HashMap<String, PerformanceAlert>>>,
        alert_history: &Arc<RwLock<VecDeque<PerformanceAlert>>>,
    ) {
        let mut new_alerts = Vec::new();

        // 检查各种指标
        if metrics.system.cpu_usage >= thresholds.cpu_usage_critical {
            new_alerts.push(Self::create_alert(
                AlertType::HighCpuUsage,
                AlertSeverity::Critical,
                format!("CPU 使用率过高: {:.1}%", metrics.system.cpu_usage),
                metrics.system.cpu_usage,
                thresholds.cpu_usage_critical,
            ));
        }

        if metrics.system.memory_usage_percent >= thresholds.memory_usage_critical {
            new_alerts.push(Self::create_alert(
                AlertType::HighMemoryUsage,
                AlertSeverity::Critical,
                format!("内存使用率过高: {:.1}%", metrics.system.memory_usage_percent),
                metrics.system.memory_usage_percent,
                thresholds.memory_usage_critical,
            ));
        }

        if metrics.application.average_response_time >= thresholds.response_time_critical {
            new_alerts.push(Self::create_alert(
                AlertType::SlowResponse,
                AlertSeverity::Critical,
                format!("响应时间过长: {:.1}ms", metrics.application.average_response_time),
                metrics.application.average_response_time,
                thresholds.response_time_critical,
            ));
        }

        // 更新活跃警报
        {
            let mut alerts = active_alerts.write().await;
            for alert in new_alerts {
                alerts.insert(alert.id.clone(), alert.clone());
                
                {
                    let mut history = alert_history.write().await;
                    history.push_back(alert);
                    if history.len() > 1000 {
                        history.pop_front();
                    }
                }
            }
        }
    }

    /// 创建警报
    fn create_alert(
        alert_type: AlertType,
        severity: AlertSeverity,
        message: String,
        current_value: f64,
        threshold: f64,
    ) -> PerformanceAlert {
        PerformanceAlert {
            id: uuid::Uuid::new_v4().to_string(),
            alert_type,
            severity,
            message,
            current_value,
            threshold,
            triggered_at: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs(),
            resolved: false,
            resolved_at: None,
        }
    }

    /// 检查是否正在运行
    pub async fn is_running(&self) -> bool {
        *self.is_running.read().await
    }

    // 系统指标收集方法（模拟实现）
    async fn get_cpu_usage(&self) -> Result<f64> { Ok(45.0) }
    async fn get_memory_usage(&self) -> Result<u64> { Ok(1024) }
    async fn get_memory_usage_percent(&self) -> Result<f64> { Ok(60.0) }
    async fn get_disk_usage(&self) -> Result<u64> { Ok(50 * 1024) }
    async fn get_disk_read_rate(&self) -> Result<f64> { Ok(10.0) }
    async fn get_disk_write_rate(&self) -> Result<f64> { Ok(5.0) }
    async fn get_network_rx_rate(&self) -> Result<f64> { Ok(2.0) }
    async fn get_network_tx_rate(&self) -> Result<f64> { Ok(1.5) }
}
