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

/// 工作流模板类型枚举
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum WorkflowType {
    /// 穿搭生成
    OutfitGeneration,
    /// 背景替换
    BackgroundReplacement,
    /// 人像美化
    PortraitEnhancement,
    /// 图片放大
    ImageUpscaling,
    /// 风格转换
    StyleTransfer,
    /// 自定义类型
    Custom(String),
}

impl std::fmt::Display for WorkflowType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            WorkflowType::OutfitGeneration => write!(f, "outfit_generation"),
            WorkflowType::BackgroundReplacement => write!(f, "background_replacement"),
            WorkflowType::PortraitEnhancement => write!(f, "portrait_enhancement"),
            WorkflowType::ImageUpscaling => write!(f, "image_upscaling"),
            WorkflowType::StyleTransfer => write!(f, "style_transfer"),
            WorkflowType::Custom(name) => write!(f, "{}", name),
        }
    }
}

impl From<String> for WorkflowType {
    fn from(s: String) -> Self {
        match s.as_str() {
            "outfit_generation" => WorkflowType::OutfitGeneration,
            "background_replacement" => WorkflowType::BackgroundReplacement,
            "portrait_enhancement" => WorkflowType::PortraitEnhancement,
            "image_upscaling" => WorkflowType::ImageUpscaling,
            "style_transfer" => WorkflowType::StyleTransfer,
            _ => WorkflowType::Custom(s),
        }
    }
}

/// 工作流模板数据模型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowTemplate {
    pub id: Option<i64>,
    
    // 基本信息
    pub name: String,
    pub base_name: String,
    pub version: String,
    #[serde(rename = "type")]
    pub workflow_type: WorkflowType,
    pub description: Option<String>,
    
    // 配置信息
    pub comfyui_workflow_json: serde_json::Value,
    pub ui_config_json: serde_json::Value,
    pub execution_config_json: Option<serde_json::Value>,
    
    // 输入输出定义
    pub input_schema_json: Option<serde_json::Value>,
    pub output_schema_json: Option<serde_json::Value>,
    
    // 状态管理
    pub is_active: bool,
    pub is_published: bool,
    
    // 元数据
    pub tags: Option<Vec<String>>,
    pub category: Option<String>,
    pub author: Option<String>,
    
    // 时间戳
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

/// 工作流模板创建请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateWorkflowTemplateRequest {
    pub name: String,
    pub base_name: String,
    pub version: String,
    #[serde(rename = "type")]
    pub workflow_type: WorkflowType,
    pub description: Option<String>,
    pub comfyui_workflow_json: serde_json::Value,
    pub ui_config_json: serde_json::Value,
    pub execution_config_json: Option<serde_json::Value>,
    pub input_schema_json: Option<serde_json::Value>,
    pub output_schema_json: Option<serde_json::Value>,
    pub tags: Option<Vec<String>>,
    pub category: Option<String>,
    pub author: Option<String>,
}

/// 工作流模板更新请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateWorkflowTemplateRequest {
    pub name: Option<String>,
    pub description: Option<String>,
    pub comfyui_workflow_json: Option<serde_json::Value>,
    pub ui_config_json: Option<serde_json::Value>,
    pub execution_config_json: Option<serde_json::Value>,
    pub input_schema_json: Option<serde_json::Value>,
    pub output_schema_json: Option<serde_json::Value>,
    pub is_active: Option<bool>,
    pub is_published: Option<bool>,
    pub tags: Option<Vec<String>>,
    pub category: Option<String>,
    pub author: Option<String>,
}

/// 工作流模板查询过滤器
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct WorkflowTemplateFilter {
    pub workflow_type: Option<WorkflowType>,
    pub is_active: Option<bool>,
    pub is_published: Option<bool>,
    pub category: Option<String>,
    pub author: Option<String>,
    pub base_name: Option<String>,
    pub search_term: Option<String>,
}

/// UI配置字段类型
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UIFieldType {
    Text,
    Textarea,
    Number,
    Select,
    Checkbox,
    ImageUpload,
    FileUpload,
    Slider,
    ColorPicker,
}

/// UI配置字段定义
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UIField {
    pub name: String,
    #[serde(rename = "type")]
    pub field_type: UIFieldType,
    pub label: String,
    pub required: bool,
    pub placeholder: Option<String>,
    pub default_value: Option<serde_json::Value>,
    pub options: Option<Vec<String>>,
    pub validation: Option<serde_json::Value>,
    pub accept: Option<String>, // for file uploads
    pub min: Option<f64>,       // for numbers/sliders
    pub max: Option<f64>,       // for numbers/sliders
    pub step: Option<f64>,      // for numbers/sliders
}

/// UI配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UIConfig {
    pub form_fields: Vec<UIField>,
    pub layout: Option<serde_json::Value>,
    pub theme: Option<String>,
    pub custom_css: Option<String>,
}

/// 执行配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionConfig {
    pub timeout_seconds: Option<u32>,
    pub retry_attempts: Option<u32>,
    pub max_concurrent: Option<u32>,
    pub priority: Option<i32>,
    pub resource_limits: Option<ResourceLimits>,
}

/// 资源限制配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceLimits {
    pub max_memory_mb: Option<u32>,
    pub max_cpu_cores: Option<u32>,
    pub max_gpu_memory_mb: Option<u32>,
}

impl WorkflowTemplate {
    /// 创建新的工作流模板
    pub fn new(request: CreateWorkflowTemplateRequest) -> Self {
        let now = Utc::now();
        Self {
            id: None,
            name: request.name,
            base_name: request.base_name,
            version: request.version,
            workflow_type: request.workflow_type,
            description: request.description,
            comfyui_workflow_json: request.comfyui_workflow_json,
            ui_config_json: request.ui_config_json,
            execution_config_json: request.execution_config_json,
            input_schema_json: request.input_schema_json,
            output_schema_json: request.output_schema_json,
            is_active: true,
            is_published: false,
            tags: request.tags,
            category: request.category,
            author: request.author,
            created_at: now,
            updated_at: now,
        }
    }

    /// 获取UI配置
    pub fn get_ui_config(&self) -> Result<UIConfig, serde_json::Error> {
        serde_json::from_value(self.ui_config_json.clone())
    }

    /// 获取执行配置
    pub fn get_execution_config(&self) -> Result<Option<ExecutionConfig>, serde_json::Error> {
        match &self.execution_config_json {
            Some(config) => Ok(Some(serde_json::from_value(config.clone())?)),
            None => Ok(None),
        }
    }

    /// 验证输入数据是否符合schema
    pub fn validate_input(&self, input: &serde_json::Value) -> Result<(), String> {
        // 这里可以实现JSON Schema验证
        // 暂时简单检查必需字段
        if let Some(schema) = &self.input_schema_json {
            // TODO: 实现完整的JSON Schema验证
            // 可以使用 jsonschema crate
        }
        Ok(())
    }

    /// 生成完整的工作流名称（包含版本）
    pub fn full_name(&self) -> String {
        format!("{} v{}", self.name, self.version)
    }
}
