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

/// 穿搭图片生成状态
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum OutfitImageStatus {
    Pending,
    Processing,
    Completed,
    Failed,
}

impl std::fmt::Display for OutfitImageStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            OutfitImageStatus::Pending => write!(f, "pending"),
            OutfitImageStatus::Processing => write!(f, "processing"),
            OutfitImageStatus::Completed => write!(f, "completed"),
            OutfitImageStatus::Failed => write!(f, "failed"),
        }
    }
}

impl From<String> for OutfitImageStatus {
    fn from(s: String) -> Self {
        match s.as_str() {
            "pending" => OutfitImageStatus::Pending,
            "processing" => OutfitImageStatus::Processing,
            "completed" => OutfitImageStatus::Completed,
            "failed" => OutfitImageStatus::Failed,
            _ => OutfitImageStatus::Pending,
        }
    }
}

/// 穿搭图片生成记录
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OutfitImageRecord {
    pub id: String,
    pub model_id: String,
    pub model_image_id: String, // 使用的模特形象图片ID
    pub generation_prompt: Option<String>, // 生成提示词
    pub status: OutfitImageStatus,
    pub progress: f32,
    pub result_urls: Vec<String>, // 生成的穿搭图片URLs
    pub error_message: Option<String>,
    pub created_at: DateTime<Utc>,
    pub started_at: Option<DateTime<Utc>>,
    pub completed_at: Option<DateTime<Utc>>,
    pub duration_ms: Option<u64>,
    pub comfyui_prompt_id: Option<String>, // ComfyUI 任务ID，用于精确匹配任务状态更新

    // 关联数据
    pub product_images: Vec<ProductImage>,
    pub outfit_images: Vec<OutfitImage>,
}

impl OutfitImageRecord {
    /// 创建新的穿搭图片生成记录
    pub fn new(model_id: String, model_image_id: String, generation_prompt: Option<String>) -> Self {
        Self {
            id: Uuid::new_v4().to_string(),
            model_id,
            model_image_id,
            generation_prompt,
            status: OutfitImageStatus::Pending,
            progress: 0.0,
            result_urls: Vec::new(),
            error_message: None,
            created_at: Utc::now(),
            started_at: None,
            completed_at: None,
            duration_ms: None,
            comfyui_prompt_id: None,
            product_images: Vec::new(),
            outfit_images: Vec::new(),
        }
    }

    /// 开始处理
    pub fn start_processing(&mut self) {
        self.status = OutfitImageStatus::Processing;
        self.started_at = Some(Utc::now());
        self.progress = 0.0;
    }

    /// 更新进度
    pub fn update_progress(&mut self, progress: f32) {
        self.progress = progress.clamp(0.0, 1.0);
    }

    /// 完成处理
    pub fn complete(&mut self, result_urls: Vec<String>) {
        self.status = OutfitImageStatus::Completed;
        self.result_urls = result_urls;
        self.completed_at = Some(Utc::now());
        self.progress = 1.0;
        
        if let Some(started_at) = self.started_at {
            self.duration_ms = Some((Utc::now() - started_at).num_milliseconds() as u64);
        }
    }

    /// 处理失败
    pub fn fail(&mut self, error_message: String) {
        self.status = OutfitImageStatus::Failed;
        self.error_message = Some(error_message);
        self.completed_at = Some(Utc::now());

        if let Some(started_at) = self.started_at {
            self.duration_ms = Some((Utc::now() - started_at).num_milliseconds() as u64);
        }
    }

    /// 重置记录状态以便重试
    pub fn reset_for_retry(&mut self) {
        self.status = OutfitImageStatus::Pending;
        self.progress = 0.0;
        self.error_message = None;
        self.started_at = None;
        self.completed_at = None;
        self.duration_ms = None;
        self.comfyui_prompt_id = None; // 重置 ComfyUI 任务ID
        // 保留 result_urls，如果之前有部分成功的结果
        // self.result_urls.clear(); // 可选：是否清除之前的结果
    }

    /// 设置 ComfyUI 任务ID
    pub fn set_comfyui_prompt_id(&mut self, prompt_id: String) {
        self.comfyui_prompt_id = Some(prompt_id);
    }
}

/// 商品图片
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProductImage {
    pub id: String,
    pub outfit_record_id: String,
    pub file_path: String,
    pub file_name: String,
    pub file_size: u64,
    pub upload_url: Option<String>, // 上传到云端的URL
    pub description: Option<String>,
    pub created_at: DateTime<Utc>,
}

impl ProductImage {
    /// 创建新的商品图片
    pub fn new(
        outfit_record_id: String,
        file_path: String,
        file_name: String,
        file_size: u64,
    ) -> Self {
        Self {
            id: Uuid::new_v4().to_string(),
            outfit_record_id,
            file_path,
            file_name,
            file_size,
            upload_url: None,
            description: None,
            created_at: Utc::now(),
        }
    }
}

/// 穿搭图片（生成的结果图片）
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OutfitImage {
    pub id: String,
    pub outfit_record_id: String,
    pub image_url: String,
    pub local_path: Option<String>, // 本地缓存路径
    pub image_index: u32, // 在生成结果中的索引
    pub description: Option<String>,
    pub tags: Vec<String>,
    pub is_favorite: bool,
    pub created_at: DateTime<Utc>,
}

impl OutfitImage {
    /// 创建新的穿搭图片
    pub fn new(
        outfit_record_id: String,
        image_url: String,
        image_index: u32,
    ) -> Self {
        Self {
            id: Uuid::new_v4().to_string(),
            outfit_record_id,
            image_url,
            local_path: None,
            image_index,
            description: None,
            tags: Vec::new(),
            is_favorite: false,
            created_at: Utc::now(),
        }
    }
}

/// 穿搭图片生成请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OutfitImageGenerationRequest {
    pub record_id: Option<String>, // 指定要操作的记录ID（用于批量任务精确匹配）
    pub model_id: String,
    pub model_image_id: String, // 选择的模特形象图片ID
    pub product_image_paths: Vec<String>, // 商品图片路径列表
    pub generation_prompt: Option<String>, // 可选的生成提示词
    pub style_preferences: Option<Vec<String>>, // 风格偏好
    pub product_index: Option<usize>, // 商品编号（用于调试文件命名）
}

/// 穿搭图片生成响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OutfitImageGenerationResponse {
    pub record_id: String,
    pub generated_images: Vec<String>, // 生成的图片URLs
    pub generation_time_ms: u64,
    pub success: bool,
    pub error_message: Option<String>,
}

/// 穿搭图片统计信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OutfitImageStats {
    pub total_records: u32,
    pub total_images: u32,
    pub favorite_images: u32,
    pub pending_records: u32,
    pub processing_records: u32,
    pub completed_records: u32,
    pub failed_records: u32,
}

/// 穿搭图片记录分页响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OutfitImageRecordsResponse {
    pub records: Vec<OutfitImageRecord>,
    pub total_count: u32,
    pub page: u32,
    pub page_size: u32,
    pub has_more: bool,
}
