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

/// 视频生成任务
/// 遵循 Tauri 开发规范的数据模型设计原则
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VideoGenerationTask {
    pub id: String,
    pub model_id: String,
    pub prompt_config: VideoPromptConfig,
    pub selected_photos: Vec<String>, // 选中的照片ID列表
    pub status: VideoGenerationStatus,
    pub result: Option<VideoGenerationResult>,
    pub error_message: Option<String>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub completed_at: Option<DateTime<Utc>>,
}

/// 视频生成提示词配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VideoPromptConfig {
    pub product: String,    // 产品描述，如"超短牛仔裙（白色紧身蕾丝短袖）"
    pub scene: String,      // 场景描述，如"室内可爱简约的女性卧室"
    pub model_desc: String, // 模特描述，如"单马尾充满媚态，对自己的性感妩媚十分自信，眼神勾人"
    pub template: String,   // 模板类型，如"抚媚眼神"
    pub duplicate: u32,     // 生成数量，默认为1
}

/// 视频生成状态
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum VideoGenerationStatus {
    Pending,     // 等待中
    Processing,  // 处理中
    Completed,   // 已完成
    Failed,      // 失败
    Cancelled,   // 已取消
}

/// 视频生成结果
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VideoGenerationResult {
    pub video_urls: Vec<String>,        // 生成的视频URL列表
    pub video_paths: Vec<String>,       // 本地保存的视频路径列表
    pub generation_time: u64,           // 生成耗时（毫秒）
    pub api_response: Option<String>,   // API原始响应
}

/// 创建视频生成任务请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateVideoGenerationRequest {
    pub model_id: String,
    pub prompt_config: VideoPromptConfig,
    pub selected_photos: Vec<String>,
}

/// 视频生成任务查询参数
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VideoGenerationQueryParams {
    pub model_id: Option<String>,
    pub status: Option<VideoGenerationStatus>,
    pub limit: Option<u32>,
    pub offset: Option<u32>,
}

/// Dify API 配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DifyApiConfig {
    pub host: String,
    pub api_key: String,
}

impl Default for DifyApiConfig {
    fn default() -> Self {
        Self {
            host: "https://dify.bowongai.com".to_string(),
            api_key: "app-Lm10XUBJKnE1bnG6VPfiD1se".to_string(),
        }
    }
}

/// Dify API 请求体
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DifyApiRequest {
    pub inputs: DifyInputs,
    pub response_mode: String,
    pub user: String,
}

/// Dify API 输入参数
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DifyInputs {
    pub product: String,
    pub scene: String,
    pub model: String,
    pub image: String,
    pub duplicate: u32,
    pub template: String,
}

/// Dify API 响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DifyApiResponse {
    pub data: Option<DifyResponseData>,
    pub error: Option<String>,
}

/// Dify API 响应数据
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DifyResponseData {
    pub outputs: DifyOutputs,
}

/// Dify API 输出
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DifyOutputs {
    pub output: Vec<String>, // 生成的视频URL列表
}

impl VideoGenerationTask {
    /// 创建新的视频生成任务
    pub fn new(
        model_id: String,
        prompt_config: VideoPromptConfig,
        selected_photos: Vec<String>,
    ) -> Self {
        let now = Utc::now();
        Self {
            id: uuid::Uuid::new_v4().to_string(),
            model_id,
            prompt_config,
            selected_photos,
            status: VideoGenerationStatus::Pending,
            result: None,
            error_message: None,
            created_at: now,
            updated_at: now,
            completed_at: None,
        }
    }

    /// 更新任务状态
    pub fn update_status(&mut self, status: VideoGenerationStatus) {
        self.status = status;
        self.updated_at = Utc::now();
        
        if matches!(status, VideoGenerationStatus::Completed | VideoGenerationStatus::Failed) {
            self.completed_at = Some(Utc::now());
        }
    }

    /// 设置任务结果
    pub fn set_result(&mut self, result: VideoGenerationResult) {
        self.result = Some(result);
        self.update_status(VideoGenerationStatus::Completed);
    }

    /// 设置错误信息
    pub fn set_error(&mut self, error: String) {
        self.error_message = Some(error);
        self.update_status(VideoGenerationStatus::Failed);
    }

    /// 验证任务数据
    pub fn validate(&self) -> Result<(), String> {
        if self.model_id.is_empty() {
            return Err("模特ID不能为空".to_string());
        }

        if self.prompt_config.product.is_empty() {
            return Err("产品描述不能为空".to_string());
        }

        if self.prompt_config.scene.is_empty() {
            return Err("场景描述不能为空".to_string());
        }

        if self.prompt_config.model_desc.is_empty() {
            return Err("模特描述不能为空".to_string());
        }

        if self.prompt_config.template.is_empty() {
            return Err("模板类型不能为空".to_string());
        }

        if self.selected_photos.is_empty() {
            return Err("必须选择至少一张照片".to_string());
        }

        if self.prompt_config.duplicate == 0 {
            return Err("生成数量必须大于0".to_string());
        }

        Ok(())
    }
}

impl Default for VideoPromptConfig {
    fn default() -> Self {
        Self {
            product: String::new(),
            scene: String::new(),
            model_desc: String::new(),
            template: "抚媚眼神".to_string(),
            duplicate: 1,
        }
    }
}
