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

/// 执行环境类型枚举
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum EnvironmentType {
    /// 本地ComfyUI
    LocalComfyui,
}

impl std::fmt::Display for EnvironmentType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            EnvironmentType::LocalComfyui => write!(f, "local_comfyui"),
        }
    }
}

impl From<String> for EnvironmentType {
    fn from(s: String) -> Self {
        match s.as_str() {
            "local_comfyui" => EnvironmentType::LocalComfyui,
            _ => EnvironmentType::LocalComfyui, // 默认使用本地ComfyUI
        }
    }
}

/// 健康状态枚举
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum HealthStatus {
    /// 健康
    Healthy,
    /// 不健康
    Unhealthy,
    /// 未知状态
    Unknown,
    /// 维护中
    Maintenance,
}

impl std::fmt::Display for HealthStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            HealthStatus::Healthy => write!(f, "healthy"),
            HealthStatus::Unhealthy => write!(f, "unhealthy"),
            HealthStatus::Unknown => write!(f, "unknown"),
            HealthStatus::Maintenance => write!(f, "maintenance"),
        }
    }
}

impl From<String> for HealthStatus {
    fn from(s: String) -> Self {
        match s.as_str() {
            "healthy" => HealthStatus::Healthy,
            "unhealthy" => HealthStatus::Unhealthy,
            "maintenance" => HealthStatus::Maintenance,
            _ => HealthStatus::Unknown,
        }
    }
}

/// 工作流执行环境数据模型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowExecutionEnvironment {
    pub id: Option<i64>,

    // 基本信息
    pub name: String,
    pub environment_type: EnvironmentType,
    pub description: Option<String>,
    
    // 连接配置
    pub base_url: String,
    pub api_key: Option<String>,
    pub connection_config_json: Option<serde_json::Value>,
    
    // 能力配置
    pub supported_workflow_types: Vec<String>,
    pub max_concurrent_jobs: i32,
    pub priority: i32,
    
    // 状态信息
    pub is_active: bool,
    pub is_available: bool,
    pub last_health_check: Option<DateTime<Utc>>,
    pub health_status: HealthStatus,
    
    // 性能统计
    pub average_response_time_ms: Option<i32>,
    pub success_rate: f64,
    pub total_executions: i32,
    pub failed_executions: i32,
    
    // 资源限制
    pub max_memory_mb: Option<i32>,
    pub max_execution_time_seconds: Option<i32>,
    
    // 元数据
    pub metadata_json: Option<serde_json::Value>,
    pub tags: Option<Vec<String>>,
    
    // 时间戳
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

/// 创建执行环境请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateExecutionEnvironmentRequest {
    pub name: String,
    pub environment_type: EnvironmentType,
    pub description: Option<String>,
    pub base_url: String,
    pub api_key: Option<String>,
    pub connection_config_json: Option<serde_json::Value>,
    pub supported_workflow_types: Vec<String>,
    pub max_concurrent_jobs: Option<i32>,
    pub priority: Option<i32>,
    pub max_memory_mb: Option<i32>,
    pub max_execution_time_seconds: Option<i32>,
    pub metadata_json: Option<serde_json::Value>,
    pub tags: Option<Vec<String>>,
}

/// 更新执行环境请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateExecutionEnvironmentRequest {
    pub name: Option<String>,
    pub description: Option<String>,
    pub base_url: Option<String>,
    pub api_key: Option<String>,
    pub connection_config_json: Option<serde_json::Value>,
    pub supported_workflow_types: Option<Vec<String>>,
    pub max_concurrent_jobs: Option<i32>,
    pub priority: Option<i32>,
    pub is_active: Option<bool>,
    pub is_available: Option<bool>,
    pub max_memory_mb: Option<i32>,
    pub max_execution_time_seconds: Option<i32>,
    pub metadata_json: Option<serde_json::Value>,
    pub tags: Option<Vec<String>>,
}

/// 执行环境查询过滤器
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ExecutionEnvironmentFilter {
    pub environment_type: Option<EnvironmentType>,
    pub is_active: Option<bool>,
    pub is_available: Option<bool>,
    pub health_status: Option<HealthStatus>,
    pub supported_workflow_type: Option<String>,
}

/// 连接配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectionConfig {
    pub timeout_seconds: Option<u32>,
    pub retry_attempts: Option<u32>,
    pub retry_delay_ms: Option<u32>,
    pub max_retries: Option<u32>,
    pub connection_pool_size: Option<u32>,
    pub keep_alive: Option<bool>,
    pub verify_ssl: Option<bool>,
    pub custom_headers: Option<HashMap<String, String>>,
}

/// 健康检查结果
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthCheckResult {
    pub status: HealthStatus,
    pub response_time_ms: i32,
    pub error_message: Option<String>,
    pub details: Option<serde_json::Value>,
    pub checked_at: DateTime<Utc>,
}

impl WorkflowExecutionEnvironment {
    /// 创建新的执行环境
    pub fn new(request: CreateExecutionEnvironmentRequest) -> Self {
        let now = Utc::now();
        Self {
            id: None,
            name: request.name,
            environment_type: request.environment_type,
            description: request.description,
            base_url: request.base_url,
            api_key: request.api_key,
            connection_config_json: request.connection_config_json,
            supported_workflow_types: request.supported_workflow_types,
            max_concurrent_jobs: request.max_concurrent_jobs.unwrap_or(1),
            priority: request.priority.unwrap_or(0),
            is_active: true,
            is_available: true,
            last_health_check: None,
            health_status: HealthStatus::Unknown,
            average_response_time_ms: None,
            success_rate: 1.0,
            total_executions: 0,
            failed_executions: 0,
            max_memory_mb: request.max_memory_mb,
            max_execution_time_seconds: request.max_execution_time_seconds,
            metadata_json: request.metadata_json,
            tags: request.tags,
            created_at: now,
            updated_at: now,
        }
    }

    /// 检查是否支持指定的工作流类型
    pub fn supports_workflow_type(&self, workflow_type: &str) -> bool {
        self.supported_workflow_types.contains(&workflow_type.to_string())
    }

    /// 更新健康状态
    pub fn update_health_status(&mut self, result: HealthCheckResult) {
        self.health_status = result.status;
        self.last_health_check = Some(result.checked_at);
        self.updated_at = Utc::now();
        
        // 更新平均响应时间
        if let Some(current_avg) = self.average_response_time_ms {
            self.average_response_time_ms = Some((current_avg + result.response_time_ms) / 2);
        } else {
            self.average_response_time_ms = Some(result.response_time_ms);
        }
    }

    /// 记录执行结果
    pub fn record_execution(&mut self, success: bool) {
        self.total_executions += 1;
        if !success {
            self.failed_executions += 1;
        }
        
        // 更新成功率
        self.success_rate = (self.total_executions - self.failed_executions) as f64 / self.total_executions as f64;
        self.updated_at = Utc::now();
    }

    /// 检查是否可用于执行
    pub fn is_ready_for_execution(&self) -> bool {
        self.is_active && self.is_available && self.health_status == HealthStatus::Healthy
    }

    /// 获取连接配置
    pub fn get_connection_config(&self) -> Result<Option<ConnectionConfig>, serde_json::Error> {
        match &self.connection_config_json {
            Some(config) => Ok(Some(serde_json::from_value(config.clone())?)),
            None => Ok(None),
        }
    }

    /// 计算负载分数（用于负载均衡）
    pub fn calculate_load_score(&self) -> f64 {
        if !self.is_ready_for_execution() {
            return 0.0;
        }
        
        // 基于优先级、成功率和响应时间计算分数
        let priority_score = self.priority as f64;
        let success_score = self.success_rate * 100.0;
        let response_score = match self.average_response_time_ms {
            Some(time) => 1000.0 / (time as f64 + 1.0), // 响应时间越短分数越高
            None => 50.0, // 默认分数
        };
        
        priority_score + success_score + response_score
    }
}
