//! 性能分析模块
//! 
//! 提供性能监控、性能分析、优化建议等功能

use std::time::{Duration, Instant};
use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use chrono::{DateTime, Utc};

/// 性能指标
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceMetrics {
    /// 文档加载时间 (ms)
    pub document_load_time_ms: f64,
    /// 渲染时间 (ms)
    pub render_time_ms: f64,
    /// 搜索响应时间 (ms)
    pub search_response_time_ms: f64,
    /// 内存使用 (MB)
    pub memory_usage_mb: f64,
    /// CPU 使用率 (%)
    pub cpu_usage_percent: f64,
    /// 帧率 (FPS)
    pub fps: f64,
    /// 测量时间
    pub measured_at: DateTime<Utc>,
}

impl Default for PerformanceMetrics {
    fn default() -> Self {
        Self {
            document_load_time_ms: 0.0,
            render_time_ms: 0.0,
            search_response_time_ms: 0.0,
            memory_usage_mb: 0.0,
            cpu_usage_percent: 0.0,
            fps: 60.0,
            measured_at: Utc::now(),
        }
    }
}

/// 性能分析器
pub struct PerformanceProfiler {
    /// 计时器
    timers: HashMap<String, Instant>,
    /// 性能记录
    metrics_history: Vec<PerformanceMetrics>,
    /// 当前指标
    current_metrics: PerformanceMetrics,
}

impl PerformanceProfiler {
    /// 创建性能分析器
    pub fn new() -> Self {
        Self {
            timers: HashMap::new(),
            metrics_history: Vec::new(),
            current_metrics: PerformanceMetrics::default(),
        }
    }
    
    /// 开始计时
    pub fn start_timer(&mut self, name: &str) {
        self.timers.insert(name.to_string(), Instant::now());
    }
    
    /// 结束计时并记录
    pub fn end_timer(&mut self, name: &str) -> Option<Duration> {
        if let Some(start) = self.timers.remove(name) {
            let duration = start.elapsed();
            
            // 更新当前指标
            match name {
                "document_load" => {
                    self.current_metrics.document_load_time_ms = duration.as_millis() as f64;
                }
                "render" => {
                    self.current_metrics.render_time_ms = duration.as_millis() as f64;
                }
                "search" => {
                    self.current_metrics.search_response_time_ms = duration.as_millis() as f64;
                }
                _ => {}
            }
            
            Some(duration)
        } else {
            None
        }
    }
    
    /// 记录内存使用
    pub fn record_memory_usage(&mut self, memory_mb: f64) {
        self.current_metrics.memory_usage_mb = memory_mb;
    }
    
    /// 记录帧率
    pub fn record_fps(&mut self, fps: f64) {
        self.current_metrics.fps = fps;
    }
    
    /// 保存当前指标
    pub fn save_metrics(&mut self) {
        self.current_metrics.measured_at = Utc::now();
        self.metrics_history.push(self.current_metrics.clone());
        
        // 保留最近 100 条记录
        if self.metrics_history.len() > 100 {
            self.metrics_history.remove(0);
        }
    }
    
    /// 获取平均文档加载时间
    pub fn avg_document_load_time(&self) -> f64 {
        if self.metrics_history.is_empty() {
            return 0.0;
        }
        let sum: f64 = self.metrics_history.iter()
            .map(|m| m.document_load_time_ms)
            .sum();
        sum / self.metrics_history.len() as f64
    }
    
    /// 获取平均渲染时间
    pub fn avg_render_time(&self) -> f64 {
        if self.metrics_history.is_empty() {
            return 0.0;
        }
        let sum: f64 = self.metrics_history.iter()
            .map(|m| m.render_time_ms)
            .sum();
        sum / self.metrics_history.len() as f64
    }
    
    /// 获取性能建议
    pub fn get_optimization_suggestions(&self) -> Vec<String> {
        let mut suggestions = Vec::new();
        
        if self.current_metrics.document_load_time_ms > 1000.0 {
            suggestions.push(
                "文档加载时间超过 1 秒，建议：\n  \
                 - 使用懒加载\n  \
                 - 预加载常用文档\n  \
                 - 优化文档解析算法".to_string()
            );
        }
        
        if self.current_metrics.render_time_ms > 100.0 {
            suggestions.push(
                "渲染时间超过 100ms，建议：\n  \
                 - 使用虚拟滚动\n  \
                 - 减少 DOM 操作\n  \
                 - 使用 WebAssembly 加速渲染".to_string()
            );
        }
        
        if self.current_metrics.memory_usage_mb > 500.0 {
            suggestions.push(
                "内存使用超过 500MB，建议：\n  \
                 - 及时释放不用的文档\n  \
                 - 使用内存池\n  \
                 - 优化数据结构".to_string()
            );
        }
        
        if self.current_metrics.fps < 30.0 {
            suggestions.push(
                "帧率低于 30FPS，建议：\n  \
                 - 减少动画复杂度\n  \
                 - 使用 requestAnimationFrame\n  \
                 - 优化重绘区域".to_string()
            );
        }
        
        suggestions
    }
    
    /// 导出性能报告
    pub fn export_report(&self) -> String {
        let mut report = String::new();
        
        report.push_str("## ReadFlow 性能报告\n\n");
        report.push_str(&format!("生成时间：{}\n\n", Utc::now().format("%Y-%m-%d %H:%M:%S")));
        
        report.push_str("### 当前指标\n\n");
        report.push_str(&format!("- 文档加载时间：{:.2}ms\n", self.current_metrics.document_load_time_ms));
        report.push_str(&format!("- 渲染时间：{:.2}ms\n", self.current_metrics.render_time_ms));
        report.push_str(&format!("- 搜索响应时间：{:.2}ms\n", self.current_metrics.search_response_time_ms));
        report.push_str(&format!("- 内存使用：{:.2}MB\n", self.current_metrics.memory_usage_mb));
        report.push_str(&format!("- 帧率：{:.1}FPS\n\n", self.current_metrics.fps));
        
        report.push_str("### 平均指标\n\n");
        report.push_str(&format!("- 平均文档加载时间：{:.2}ms\n", self.avg_document_load_time()));
        report.push_str(&format!("- 平均渲染时间：{:.2}ms\n\n", self.avg_render_time()));
        
        let suggestions = self.get_optimization_suggestions();
        if !suggestions.is_empty() {
            report.push_str("### 优化建议\n\n");
            for (i, suggestion) in suggestions.iter().enumerate() {
                report.push_str(&format!("{}. {}\n\n", i + 1, suggestion));
            }
        }
        
        report
    }
}

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

/// 缓存管理器
pub struct CacheManager {
    /// 缓存数据
    cache: HashMap<String, CacheEntry>,
    /// 最大缓存大小 (MB)
    max_size_mb: f64,
    /// 当前缓存大小 (MB)
    current_size_mb: f64,
}

#[derive(Debug, Clone)]
struct CacheEntry {
    data: Vec<u8>,
    accessed_at: Instant,
    size_bytes: usize,
}

impl CacheManager {
    /// 创建缓存管理器
    pub fn new(max_size_mb: f64) -> Self {
        Self {
            cache: HashMap::new(),
            max_size_mb,
            current_size_mb: 0.0,
        }
    }
    
    /// 获取缓存
    pub fn get(&mut self, key: &str) -> Option<&Vec<u8>> {
        if let Some(entry) = self.cache.get_mut(key) {
            entry.accessed_at = Instant::now();
            Some(&entry.data)
        } else {
            None
        }
    }
    
    /// 设置缓存
    pub fn set(&mut self, key: String, data: Vec<u8>) {
        let size_bytes = data.len();
        let size_mb = size_bytes as f64 / (1024.0 * 1024.0);
        
        // 如果超出限制，清理最不常用的条目
        while self.current_size_mb + size_mb > self.max_size_mb {
            self.evict_lru();
        }
        
        self.cache.insert(key, CacheEntry {
            data,
            accessed_at: Instant::now(),
            size_bytes,
        });
        
        self.current_size_mb += size_mb;
    }
    
    /// 清理最不常用的条目
    fn evict_lru(&mut self) {
        let mut oldest_key: Option<String> = None;
        let mut oldest_time = Instant::now();
        
        for (key, entry) in &self.cache {
            if entry.accessed_at < oldest_time {
                oldest_time = entry.accessed_at;
                oldest_key = Some(key.clone());
            }
        }
        
        if let Some(key) = oldest_key {
            if let Some(entry) = self.cache.remove(&key) {
                self.current_size_mb -= entry.size_bytes as f64 / (1024.0 * 1024.0);
            }
        }
    }
    
    /// 清除所有缓存
    pub fn clear(&mut self) {
        self.cache.clear();
        self.current_size_mb = 0.0;
    }
    
    /// 获取缓存命中率
    pub fn hit_rate(&self) -> f64 {
        // 简化实现，实际需要记录访问次数
        0.0
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_profiler_timer() {
        let mut profiler = PerformanceProfiler::new();
        
        profiler.start_timer("test");
        std::thread::sleep(Duration::from_millis(10));
        let duration = profiler.end_timer("test");
        
        assert!(duration.is_some());
        assert!(duration.unwrap().as_millis() >= 10);
    }
    
    #[test]
    fn test_cache_manager() {
        let mut cache = CacheManager::new(10.0);
        
        cache.set("key1".to_string(), vec![1, 2, 3]);
        assert!(cache.get("key1").is_some());
        assert!(cache.get("key2").is_none());
    }
}
