use tauri::{command, State};
use tracing::{info, error};
use std::collections::HashMap;

use crate::app_state::AppState;
use crate::business::services::error_handling_service::{
    ErrorHandlingService, ErrorStatistics, ErrorCategory, UserFriendlyError
};

/// 获取错误统计信息
/// 遵循 Tauri 开发规范的命令设计原则
#[command]
pub async fn get_error_statistics(
    state: State<'_, AppState>,
) -> Result<ErrorStatistics, String> {
    info!("获取错误统计信息");

    // 创建错误处理服务
    let service = ErrorHandlingService::new();

    // 获取统计信息
    match service.get_error_statistics() {
        Ok(stats) => {
            info!("错误统计信息获取成功，总错误数: {}", stats.total_errors);
            Ok(stats)
        }
        Err(e) => {
            error!("获取错误统计信息失败: {}", e);
            Err(format!("获取错误统计信息失败: {}", e))
        }
    }
}

/// 清除错误历史记录
#[command]
pub async fn clear_error_history(
    state: State<'_, AppState>,
) -> Result<(), String> {
    info!("清除错误历史记录");

    // 创建错误处理服务
    let service = ErrorHandlingService::new();

    // 清除历史记录
    match service.clear_error_history() {
        Ok(()) => {
            info!("错误历史记录清除成功");
            Ok(())
        }
        Err(e) => {
            error!("清除错误历史记录失败: {}", e);
            Err(format!("清除错误历史记录失败: {}", e))
        }
    }
}

/// 获取特定类别的错误
#[command]
pub async fn get_errors_by_category(
    state: State<'_, AppState>,
    category: String,
) -> Result<Vec<UserFriendlyError>, String> {
    info!("获取特定类别的错误: {}", category);

    // 解析错误类别
    let error_category = match category.as_str() {
        "Network" => ErrorCategory::Network,
        "Database" => ErrorCategory::Database,
        "FileSystem" => ErrorCategory::FileSystem,
        "Validation" => ErrorCategory::Validation,
        "Permission" => ErrorCategory::Permission,
        "Configuration" => ErrorCategory::Configuration,
        "External" => ErrorCategory::External,
        "Internal" => ErrorCategory::Internal,
        _ => return Err("无效的错误类别".to_string()),
    };

    // 创建错误处理服务
    let service = ErrorHandlingService::new();

    // 获取特定类别的错误
    match service.get_errors_by_category(error_category) {
        Ok(errors) => {
            info!("获取到 {} 个 {} 类别的错误", errors.len(), category);
            Ok(errors)
        }
        Err(e) => {
            error!("获取特定类别错误失败: {}", e);
            Err(format!("获取特定类别错误失败: {}", e))
        }
    }
}

/// 检查系统健康状态
#[command]
pub async fn check_system_health(
    state: State<'_, AppState>,
) -> Result<serde_json::Value, String> {
    info!("检查系统健康状态");

    // 创建错误处理服务
    let service = ErrorHandlingService::new();

    // 检查系统健康状态
    match service.check_system_health() {
        Ok(health_info) => {
            info!("系统健康状态检查完成: {}", health_info);
            Ok(health_info)
        }
        Err(e) => {
            error!("检查系统健康状态失败: {}", e);
            Err(format!("检查系统健康状态失败: {}", e))
        }
    }
}

/// 处理并记录错误
#[command]
pub async fn handle_and_record_error(
    state: State<'_, AppState>,
    error_message: String,
    context: Option<HashMap<String, String>>,
) -> Result<UserFriendlyError, String> {
    info!("处理并记录错误: {}", error_message);

    // 创建错误处理服务
    let service = ErrorHandlingService::new();

    // 创建一个简单的错误实现
    #[derive(Debug)]
    struct SimpleError(String);
    impl std::fmt::Display for SimpleError {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(f, "{}", self.0)
        }
    }
    impl std::error::Error for SimpleError {}

    let error = SimpleError(error_message);
    
    // 处理错误
    let user_friendly_error = service.handle_error(&error, context);
    
    info!("错误处理完成，错误ID: {}", user_friendly_error.id);
    Ok(user_friendly_error)
}

/// 获取错误处理建议
#[command]
pub async fn get_error_suggestions(
    state: State<'_, AppState>,
    error_message: String,
) -> Result<Vec<String>, String> {
    info!("获取错误处理建议: {}", error_message);

    // 创建错误处理服务
    let service = ErrorHandlingService::new();

    // 创建一个简单的错误实现
    #[derive(Debug)]
    struct SimpleError(String);
    impl std::fmt::Display for SimpleError {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(f, "{}", self.0)
        }
    }
    impl std::error::Error for SimpleError {}

    let error = SimpleError(error_message);
    
    // 处理错误并获取建议
    let user_friendly_error = service.handle_error(&error, None);
    
    info!("获取到 {} 条错误处理建议", user_friendly_error.suggestions.len());
    Ok(user_friendly_error.suggestions)
}

/// 检查错误是否可以重试
#[command]
pub async fn check_error_retry_capability(
    state: State<'_, AppState>,
    error_message: String,
) -> Result<serde_json::Value, String> {
    info!("检查错误重试能力: {}", error_message);

    // 创建错误处理服务
    let service = ErrorHandlingService::new();

    // 创建一个简单的错误实现
    #[derive(Debug)]
    struct SimpleError(String);
    impl std::fmt::Display for SimpleError {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(f, "{}", self.0)
        }
    }
    impl std::error::Error for SimpleError {}

    let error = SimpleError(error_message);
    
    // 处理错误并获取重试信息
    let user_friendly_error = service.handle_error(&error, None);
    
    let retry_info = serde_json::json!({
        "can_retry": user_friendly_error.can_retry,
        "retry_delay_seconds": user_friendly_error.retry_delay_seconds,
        "error_severity": user_friendly_error.severity,
        "error_category": user_friendly_error.category
    });
    
    info!("错误重试能力检查完成: {}", retry_info);
    Ok(retry_info)
}

/// 获取错误帮助信息
#[command]
pub async fn get_error_help_info(
    state: State<'_, AppState>,
    error_message: String,
) -> Result<serde_json::Value, String> {
    info!("获取错误帮助信息: {}", error_message);

    // 创建错误处理服务
    let service = ErrorHandlingService::new();

    // 创建一个简单的错误实现
    #[derive(Debug)]
    struct SimpleError(String);
    impl std::fmt::Display for SimpleError {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(f, "{}", self.0)
        }
    }
    impl std::error::Error for SimpleError {}

    let error = SimpleError(error_message);
    
    // 处理错误并获取帮助信息
    let user_friendly_error = service.handle_error(&error, None);
    
    let help_info = serde_json::json!({
        "title": user_friendly_error.title,
        "message": user_friendly_error.message,
        "suggestions": user_friendly_error.suggestions,
        "help_url": user_friendly_error.help_url,
        "severity": user_friendly_error.severity,
        "category": user_friendly_error.category
    });
    
    info!("错误帮助信息获取完成");
    Ok(help_info)
}

/// 导出错误报告
#[command]
pub async fn export_error_report(
    state: State<'_, AppState>,
    include_context: Option<bool>,
) -> Result<String, String> {
    info!("导出错误报告");

    // 创建错误处理服务
    let service = ErrorHandlingService::new();

    // 获取错误统计信息
    let stats = service.get_error_statistics()
        .map_err(|e| format!("获取错误统计失败: {}", e))?;

    // 获取系统健康状态
    let health = service.check_system_health()
        .map_err(|e| format!("获取系统健康状态失败: {}", e))?;

    // 构建错误报告
    let report = serde_json::json!({
        "report_timestamp": chrono::Utc::now(),
        "system_health": health,
        "error_statistics": stats,
        "include_context": include_context.unwrap_or(false)
    });

    // 转换为格式化的JSON字符串
    let report_json = serde_json::to_string_pretty(&report)
        .map_err(|e| format!("序列化错误报告失败: {}", e))?;

    info!("错误报告导出完成，大小: {} 字节", report_json.len());
    Ok(report_json)
}
