use colored::*;
use thiserror::Error;

pub type Result<T> = std::result::Result<T, OpsCLIError>;

#[derive(Error, Debug)]
pub enum OpsCLIError {
    #[error("SSH connection error: {0}")]
    SSHConnection(String),

    #[error("Command execution error: {0}")]
    CommandExecution(String),

    #[error("Configuration error: {0}")]
    Configuration(String),

    #[error("AWS error: {0}")]
    AWS(String),

    #[error("Validation error: {0}")]
    Validation(String),

    #[error("IO error: {0}")]
    IO(#[from] std::io::Error),

    #[error("HTTP error: {0}")]
    HTTP(#[from] reqwest::Error),

    #[error("General error: {0}")]
    General(#[from] anyhow::Error),
}

pub fn handle_error(error: &OpsCLIError) {
    eprintln!("{} {}", "✗ 错误:".red().bold(), error);

    // 如果设置了 DEBUG 环境变量，显示详细信息
    if std::env::var("DEBUG").is_ok() {
        if let Some(source) = std::error::Error::source(error) {
            eprintln!("\n{}", "详细信息:".yellow());
            eprintln!("{:?}", source);
        }
    }

    // 提供帮助提示
    match error {
        OpsCLIError::SSHConnection(_) => {
            eprintln!("\n{}", "提示:".cyan());
            eprintln!("  • 检查 SSH 密钥是否存在: ls -la ~/.ssh/optima-ec2-key");
            eprintln!("  • 检查网络连接");
            eprintln!("  • 验证 EC2 主机地址");
        }
        OpsCLIError::Configuration(_) => {
            eprintln!("\n{}", "提示:".cyan());
            eprintln!("  • 检查配置文件: ~/.config/optima-ops-cli/config.json");
            eprintln!("  • 验证环境变量设置");
        }
        _ => {}
    }
}
