use std::collections::HashMap;
use std::time::{Duration, Instant};
use serde::{Deserialize, Serialize};
use std::sync::{Arc, Mutex};

/// 性能指标数据
#[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 total_time: Duration,
}

/// 性能快照
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceSnapshot {
    pub timestamp: u64,
    pub operation: String,
    pub duration: Duration,
    pub memory_usage: u64,
    pub success: bool,
}

/// 性能报告
#[derive(Debug, Serialize, Deserialize)]
pub struct PerformanceReport {
    pub total_operations: u64,
    pub average_response_time: Duration,
    pub slowest_operations: Vec<PerformanceSnapshot>,
    pub memory_usage_trend: Vec<u64>,
    pub error_rate: f64,
}

/// 性能监控器
pub struct PerformanceMonitor {
    metrics: Arc<Mutex<HashMap<String, PerformanceMetric>>>,
    snapshots: Arc<Mutex<Vec<PerformanceSnapshot>>>,
    max_snapshots: usize,
}

impl PerformanceMonitor {
    pub fn new() -> Self {
        Self {
            metrics: Arc::new(Mutex::new(HashMap::new())),
            snapshots: Arc::new(Mutex::new(Vec::new())),
            max_snapshots: 1000, // 保留最近1000条记录
        }
    }

    /// 开始监控操作
    pub fn start_operation(&self, operation: &str) -> OperationTimer {
        OperationTimer::new(operation.to_string(), Arc::clone(&self.metrics), Arc::clone(&self.snapshots))
    }

    /// 记录性能指标
    pub fn record_metric(&self, name: &str, value: f64) {
        let mut metrics = self.metrics.lock().unwrap();
        let metric = 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,
                total_time: Duration::from_secs(0),
            }
        });

        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;
    }

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

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

    /// 生成性能报告
    pub fn generate_report(&self) -> PerformanceReport {
        let snapshots = self.snapshots.lock().unwrap();
        let total_operations = snapshots.len() as u64;
        
        let average_response_time = if total_operations > 0 {
            let total_duration: Duration = snapshots.iter().map(|s| s.duration).sum();
            total_duration / total_operations as u32
        } else {
            Duration::from_secs(0)
        };

        let mut sorted_snapshots = snapshots.clone();
        sorted_snapshots.sort_by(|a, b| b.duration.cmp(&a.duration));
        let slowest_operations = sorted_snapshots.into_iter().take(10).collect();

        let memory_usage_trend: Vec<u64> = snapshots.iter().map(|s| s.memory_usage).collect();
        
        let error_count = snapshots.iter().filter(|s| !s.success).count();
        let error_rate = if total_operations > 0 {
            error_count as f64 / total_operations as f64
        } else {
            0.0
        };

        PerformanceReport {
            total_operations,
            average_response_time,
            slowest_operations,
            memory_usage_trend,
            error_rate,
        }
    }

    /// 清理旧的快照数据
    pub fn cleanup_old_snapshots(&self) {
        let mut snapshots = self.snapshots.lock().unwrap();
        if snapshots.len() > self.max_snapshots {
            let excess = snapshots.len() - self.max_snapshots;
            snapshots.drain(0..excess);
        }
    }
}

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

/// 操作计时器
pub struct OperationTimer {
    operation: String,
    start_time: Instant,
    metrics: Arc<Mutex<HashMap<String, PerformanceMetric>>>,
    snapshots: Arc<Mutex<Vec<PerformanceSnapshot>>>,
}

impl OperationTimer {
    fn new(
        operation: String,
        metrics: Arc<Mutex<HashMap<String, PerformanceMetric>>>,
        snapshots: Arc<Mutex<Vec<PerformanceSnapshot>>>,
    ) -> Self {
        Self {
            operation,
            start_time: Instant::now(),
            metrics,
            snapshots,
        }
    }

    /// 完成操作并记录结果
    pub fn finish(self, success: bool) {
        let duration = self.start_time.elapsed();
        let memory_usage = self.get_memory_usage();

        // 记录到指标
        {
            let mut metrics = self.metrics.lock().unwrap();
            let metric = metrics.entry(self.operation.clone()).or_insert_with(|| {
                PerformanceMetric {
                    name: self.operation.clone(),
                    current_value: duration.as_millis() as f64,
                    average_value: duration.as_millis() as f64,
                    max_value: duration.as_millis() as f64,
                    min_value: duration.as_millis() as f64,
                    sample_count: 0,
                    total_time: Duration::from_secs(0),
                }
            });

            let duration_ms = duration.as_millis() as f64;
            metric.current_value = duration_ms;
            metric.max_value = metric.max_value.max(duration_ms);
            metric.min_value = metric.min_value.min(duration_ms);
            metric.sample_count += 1;
            metric.total_time += duration;
            metric.average_value = metric.total_time.as_millis() as f64 / metric.sample_count as f64;
        }

        // 记录快照
        {
            let mut snapshots = self.snapshots.lock().unwrap();
            snapshots.push(PerformanceSnapshot {
                timestamp: std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap()
                    .as_secs(),
                operation: self.operation,
                duration,
                memory_usage,
                success,
            });
        }
    }

    fn get_memory_usage(&self) -> u64 {
        // 简化实现，实际应用中可以使用系统API获取真实内存使用
        // 这里返回一个模拟值
        0
    }
}

// 全局性能监控器实例
lazy_static::lazy_static! {
    pub static ref PERFORMANCE_MONITOR: PerformanceMonitor = PerformanceMonitor::new();
}

/// 性能监控宏
#[macro_export]
macro_rules! monitor_performance {
    ($operation:expr, $code:block) => {{
        let timer = crate::infrastructure::monitoring::PERFORMANCE_MONITOR.start_operation($operation);
        let result = $code;
        let success = result.is_ok();
        timer.finish(success);
        result
    }};
}
