use anyhow::{Result, anyhow};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use tracing::{error, warn, info};
use chrono::{DateTime, Utc};

/// 错误严重程度
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum ErrorSeverity {
    Low,      // 轻微错误，不影响主要功能
    Medium,   // 中等错误，影响部分功能
    High,     // 严重错误，影响主要功能
    Critical, // 致命错误，系统无法正常运行
}

/// 错误类别
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum ErrorCategory {
    Network,        // 网络相关错误
    Database,       // 数据库相关错误
    FileSystem,     // 文件系统相关错误
    Validation,     // 数据验证错误
    Permission,     // 权限相关错误
    Configuration,  // 配置相关错误
    External,       // 外部服务错误
    Internal,       // 内部逻辑错误
}

/// 用户友好的错误信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserFriendlyError {
    pub id: String,
    pub title: String,
    pub message: String,
    pub severity: ErrorSeverity,
    pub category: ErrorCategory,
    pub suggestions: Vec<String>,
    pub can_retry: bool,
    pub retry_delay_seconds: Option<u32>,
    pub help_url: Option<String>,
    pub timestamp: DateTime<Utc>,
    pub context: HashMap<String, String>,
}

/// 错误统计信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorStatistics {
    pub total_errors: u64,
    pub errors_by_category: HashMap<ErrorCategory, u64>,
    pub errors_by_severity: HashMap<ErrorSeverity, u64>,
    pub recent_errors: Vec<UserFriendlyError>,
    pub error_rate_per_hour: f64,
    pub most_common_errors: Vec<(String, u64)>,
}

/// 错误处理服务
/// 遵循 Tauri 开发规范的业务逻辑设计原则
pub struct ErrorHandlingService {
    error_history: Arc<Mutex<Vec<UserFriendlyError>>>,
    error_templates: HashMap<String, UserFriendlyError>,
    max_history_size: usize,
}

impl ErrorHandlingService {
    /// 创建新的错误处理服务实例
    pub fn new() -> Self {
        let mut service = Self {
            error_history: Arc::new(Mutex::new(Vec::new())),
            error_templates: HashMap::new(),
            max_history_size: 1000,
        };
        
        service.initialize_error_templates();
        service
    }

    /// 初始化错误模板
    fn initialize_error_templates(&mut self) {
        // 网络错误模板
        self.error_templates.insert("network_timeout".to_string(), UserFriendlyError {
            id: "network_timeout".to_string(),
            title: "网络连接超时".to_string(),
            message: "网络连接超时，请检查网络连接后重试".to_string(),
            severity: ErrorSeverity::Medium,
            category: ErrorCategory::Network,
            suggestions: vec![
                "检查网络连接是否正常".to_string(),
                "尝试刷新页面或重新启动应用".to_string(),
                "如果问题持续存在，请联系技术支持".to_string(),
            ],
            can_retry: true,
            retry_delay_seconds: Some(5),
            help_url: Some("https://help.example.com/network-issues".to_string()),
            timestamp: Utc::now(),
            context: HashMap::new(),
        });

        // 文件系统错误模板
        self.error_templates.insert("file_not_found".to_string(), UserFriendlyError {
            id: "file_not_found".to_string(),
            title: "文件未找到".to_string(),
            message: "指定的文件不存在或已被移动".to_string(),
            severity: ErrorSeverity::Medium,
            category: ErrorCategory::FileSystem,
            suggestions: vec![
                "确认文件路径是否正确".to_string(),
                "检查文件是否被移动或删除".to_string(),
                "尝试重新选择文件".to_string(),
            ],
            can_retry: false,
            retry_delay_seconds: None,
            help_url: Some("https://help.example.com/file-issues".to_string()),
            timestamp: Utc::now(),
            context: HashMap::new(),
        });

        // 数据库错误模板
        self.error_templates.insert("database_connection".to_string(), UserFriendlyError {
            id: "database_connection".to_string(),
            title: "数据库连接失败".to_string(),
            message: "无法连接到数据库，请稍后重试".to_string(),
            severity: ErrorSeverity::High,
            category: ErrorCategory::Database,
            suggestions: vec![
                "检查数据库服务是否正常运行".to_string(),
                "确认数据库连接配置是否正确".to_string(),
                "尝试重启应用程序".to_string(),
            ],
            can_retry: true,
            retry_delay_seconds: Some(10),
            help_url: Some("https://help.example.com/database-issues".to_string()),
            timestamp: Utc::now(),
            context: HashMap::new(),
        });

        // 权限错误模板
        self.error_templates.insert("permission_denied".to_string(), UserFriendlyError {
            id: "permission_denied".to_string(),
            title: "权限不足".to_string(),
            message: "没有足够的权限执行此操作".to_string(),
            severity: ErrorSeverity::Medium,
            category: ErrorCategory::Permission,
            suggestions: vec![
                "以管理员身份运行应用程序".to_string(),
                "检查文件或目录的访问权限".to_string(),
                "联系系统管理员获取必要权限".to_string(),
            ],
            can_retry: false,
            retry_delay_seconds: None,
            help_url: Some("https://help.example.com/permission-issues".to_string()),
            timestamp: Utc::now(),
            context: HashMap::new(),
        });
    }

    /// 处理错误并生成用户友好的错误信息
    pub fn handle_error(&self, error: &dyn std::error::Error, context: Option<HashMap<String, String>>) -> UserFriendlyError {
        let error_message = error.to_string();
        let error_id = self.classify_error(&error_message);
        
        let user_error = if let Some(template) = self.error_templates.get(&error_id) {
            let mut error = template.clone();
            error.timestamp = Utc::now();
            if let Some(ctx) = context {
                error.context = ctx;
            }
            error
        } else {
            // 创建通用错误
            UserFriendlyError {
                id: "generic_error".to_string(),
                title: "操作失败".to_string(),
                message: format!("操作执行失败: {}", error_message),
                severity: ErrorSeverity::Medium,
                category: ErrorCategory::Internal,
                suggestions: vec![
                    "请稍后重试".to_string(),
                    "如果问题持续存在，请联系技术支持".to_string(),
                ],
                can_retry: true,
                retry_delay_seconds: Some(3),
                help_url: None,
                timestamp: Utc::now(),
                context: context.unwrap_or_default(),
            }
        };

        // 记录错误
        self.record_error(&user_error);
        
        // 记录到日志
        match user_error.severity {
            ErrorSeverity::Critical => error!("Critical error: {} - {}", user_error.title, user_error.message),
            ErrorSeverity::High => error!("High severity error: {} - {}", user_error.title, user_error.message),
            ErrorSeverity::Medium => warn!("Medium severity error: {} - {}", user_error.title, user_error.message),
            ErrorSeverity::Low => info!("Low severity error: {} - {}", user_error.title, user_error.message),
        }

        user_error
    }

    /// 分类错误类型
    fn classify_error(&self, error_message: &str) -> String {
        let message_lower = error_message.to_lowercase();
        
        if message_lower.contains("timeout") || message_lower.contains("connection refused") {
            "network_timeout".to_string()
        } else if message_lower.contains("file not found") || message_lower.contains("no such file") {
            "file_not_found".to_string()
        } else if message_lower.contains("database") || message_lower.contains("sql") {
            "database_connection".to_string()
        } else if message_lower.contains("permission") || message_lower.contains("access denied") {
            "permission_denied".to_string()
        } else {
            "generic_error".to_string()
        }
    }

    /// 记录错误到历史记录
    fn record_error(&self, error: &UserFriendlyError) {
        if let Ok(mut history) = self.error_history.lock() {
            history.push(error.clone());
            
            // 限制历史记录大小
            if history.len() > self.max_history_size {
                history.remove(0);
            }
        }
    }

    /// 获取错误统计信息
    pub fn get_error_statistics(&self) -> Result<ErrorStatistics> {
        let history = self.error_history.lock()
            .map_err(|e| anyhow!("获取错误历史失败: {}", e))?;

        let total_errors = history.len() as u64;
        
        // 按类别统计
        let mut errors_by_category = HashMap::new();
        let mut errors_by_severity = HashMap::new();
        let mut error_counts = HashMap::new();

        for error in history.iter() {
            *errors_by_category.entry(error.category.clone()).or_insert(0) += 1;
            *errors_by_severity.entry(error.severity.clone()).or_insert(0) += 1;
            *error_counts.entry(error.id.clone()).or_insert(0) += 1;
        }

        // 获取最近的错误（最多10个）
        let recent_errors = history.iter()
            .rev()
            .take(10)
            .cloned()
            .collect();

        // 计算错误率（简化计算，假设1小时内的错误）
        let now = Utc::now();
        let one_hour_ago = now - chrono::Duration::hours(1);
        let recent_error_count = history.iter()
            .filter(|e| e.timestamp > one_hour_ago)
            .count() as f64;
        let error_rate_per_hour = recent_error_count;

        // 最常见的错误
        let mut most_common_errors: Vec<(String, u64)> = error_counts.into_iter().collect();
        most_common_errors.sort_by(|a, b| b.1.cmp(&a.1));
        most_common_errors.truncate(5);

        Ok(ErrorStatistics {
            total_errors,
            errors_by_category,
            errors_by_severity,
            recent_errors,
            error_rate_per_hour,
            most_common_errors,
        })
    }

    /// 清除错误历史记录
    pub fn clear_error_history(&self) -> Result<()> {
        let mut history = self.error_history.lock()
            .map_err(|e| anyhow!("获取错误历史失败: {}", e))?;
        
        history.clear();
        info!("错误历史记录已清除");
        Ok(())
    }

    /// 获取特定类别的错误
    pub fn get_errors_by_category(&self, category: ErrorCategory) -> Result<Vec<UserFriendlyError>> {
        let history = self.error_history.lock()
            .map_err(|e| anyhow!("获取错误历史失败: {}", e))?;

        let filtered_errors = history.iter()
            .filter(|e| e.category == category)
            .cloned()
            .collect();

        Ok(filtered_errors)
    }

    /// 检查系统健康状态
    pub fn check_system_health(&self) -> Result<serde_json::Value> {
        let stats = self.get_error_statistics()?;
        
        let health_status = if stats.error_rate_per_hour > 50.0 {
            "unhealthy"
        } else if stats.error_rate_per_hour > 20.0 {
            "degraded"
        } else {
            "healthy"
        };

        let critical_errors = stats.errors_by_severity.get(&ErrorSeverity::Critical).unwrap_or(&0);
        let high_errors = stats.errors_by_severity.get(&ErrorSeverity::High).unwrap_or(&0);

        Ok(serde_json::json!({
            "status": health_status,
            "error_rate_per_hour": stats.error_rate_per_hour,
            "critical_errors": critical_errors,
            "high_severity_errors": high_errors,
            "total_errors": stats.total_errors,
            "timestamp": Utc::now()
        }))
    }
}

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