/// 性能监控系统
/// 遵循 Tauri 开发规范的性能优化原则
use std::time::{Duration, Instant};
use std::collections::HashMap;
use serde::{Serialize, Deserialize};

/// 性能指标结构
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceMetric {
    pub name: String,
    pub current_value: f64,
    pub average_value: f64,
    pub max_value: f64,
    pub min_value: f64,
    pub sample_count: u64,
    pub last_updated: std::time::SystemTime,
}

/// 性能监控器
/// 遵循 Tauri 开发规范的性能标准：
/// - 应用启动时间≤3秒
/// - 内存占用≤100MB（空闲状态）
/// - CPU使用率≤5%（空闲状态）
/// - 响应时间≤100ms（UI交互）
pub struct PerformanceMonitor {
    metrics: HashMap<String, PerformanceMetric>,
    startup_time: Instant,
}

impl PerformanceMonitor {
    /// 创建新的性能监控器
    pub fn new() -> Self {
        Self {
            metrics: HashMap::new(),
            startup_time: Instant::now(),
        }
    }

    /// 记录性能指标
    /// 遵循性能监控的最佳实践
    pub fn record_metric(&mut self, name: &str, value: f64) {
        let metric = self.metrics.entry(name.to_string()).or_insert_with(|| {
            PerformanceMetric {
                name: name.to_string(),
                current_value: value,
                average_value: value,
                max_value: value,
                min_value: value,
                sample_count: 0,
                last_updated: std::time::SystemTime::now(),
            }
        });

        metric.current_value = value;
        metric.max_value = metric.max_value.max(value);
        metric.min_value = metric.min_value.min(value);
        metric.sample_count += 1;
        metric.average_value = (metric.average_value * (metric.sample_count - 1) as f64 + value)
            / metric.sample_count as f64;
        metric.last_updated = std::time::SystemTime::now();
    }

    /// 获取性能指标
    pub fn get_metric(&self, name: &str) -> Option<&PerformanceMetric> {
        self.metrics.get(name)
    }

    /// 获取启动时间
    pub fn get_startup_time(&self) -> Duration {
        self.startup_time.elapsed()
    }

    /// 获取所有性能指标
    pub fn get_all_metrics(&self) -> &HashMap<String, PerformanceMetric> {
        &self.metrics
    }

    /// 检查性能是否符合 Tauri 开发规范标准
    pub fn check_performance_standards(&self) -> PerformanceReport {
        let mut report = PerformanceReport {
            startup_time_ok: true,
            memory_usage_ok: true,
            cpu_usage_ok: true,
            response_time_ok: true,
            issues: Vec::new(),
        };

        // 检查启动时间（≤3秒）
        if self.get_startup_time() > Duration::from_secs(3) {
            report.startup_time_ok = false;
            report.issues.push("启动时间超过3秒标准".to_string());
        }

        // 检查内存使用（≤100MB）
        if let Some(memory_metric) = self.get_metric("memory_usage_mb") {
            if memory_metric.current_value > 100.0 {
                report.memory_usage_ok = false;
                report.issues.push("内存使用超过100MB标准".to_string());
            }
        }

        // 检查CPU使用率（≤5%）
        if let Some(cpu_metric) = self.get_metric("cpu_usage_percent") {
            if cpu_metric.current_value > 5.0 {
                report.cpu_usage_ok = false;
                report.issues.push("CPU使用率超过5%标准".to_string());
            }
        }

        // 检查响应时间（≤100ms）
        if let Some(response_metric) = self.get_metric("response_time_ms") {
            if response_metric.current_value > 100.0 {
                report.response_time_ok = false;
                report.issues.push("响应时间超过100ms标准".to_string());
            }
        }

        report
    }
}

/// 性能报告
#[derive(Debug, Serialize, Deserialize)]
pub struct PerformanceReport {
    pub startup_time_ok: bool,
    pub memory_usage_ok: bool,
    pub cpu_usage_ok: bool,
    pub response_time_ok: bool,
    pub issues: Vec<String>,
}

impl Default for PerformanceMonitor {
    fn default() -> Self {
        Self::new()
    }
}

/// 性能监控宏
/// 用于简化性能监控的使用
#[macro_export]
macro_rules! measure_performance {
    ($monitor:expr, $name:expr, $code:block) => {
        {
            let start = std::time::Instant::now();
            let result = $code;
            let duration = start.elapsed();
            $monitor.record_metric($name, duration.as_millis() as f64);
            result
        }
    };
}

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

    #[test]
    fn test_performance_monitor() {
        let mut monitor = PerformanceMonitor::new();
        
        // 测试记录指标
        monitor.record_metric("test_metric", 50.0);
        monitor.record_metric("test_metric", 75.0);
        
        let metric = monitor.get_metric("test_metric").unwrap();
        assert_eq!(metric.sample_count, 2);
        assert_eq!(metric.current_value, 75.0);
        assert_eq!(metric.max_value, 75.0);
        assert_eq!(metric.min_value, 50.0);
        assert_eq!(metric.average_value, 62.5);
    }

    #[test]
    fn test_performance_standards() {
        let mut monitor = PerformanceMonitor::new();
        
        // 模拟符合标准的性能指标
        monitor.record_metric("memory_usage_mb", 80.0);
        monitor.record_metric("cpu_usage_percent", 3.0);
        monitor.record_metric("response_time_ms", 50.0);
        
        let report = monitor.check_performance_standards();
        assert!(report.memory_usage_ok);
        assert!(report.cpu_usage_ok);
        assert!(report.response_time_ok);
        assert!(report.issues.is_empty());
    }
}
