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

/// 模特动态实体模型
/// 遵循 Tauri 开发规范的数据模型设计原则
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelDynamic {
    pub id: String,
    pub model_id: String,
    pub title: Option<String>,
    pub description: String,
    pub prompt: String,
    pub source_image_path: String,
    pub ai_model: String, // 使用的AI模型，如"极梦"
    pub video_count: u32, // 生成视频个数
    pub generated_videos: Vec<GeneratedVideo>,
    pub status: DynamicStatus,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

/// 生成的视频
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GeneratedVideo {
    pub id: String,
    pub dynamic_id: String,
    pub video_path: String,
    pub thumbnail_path: Option<String>,
    pub file_size: u64,
    pub duration: u32, // 视频时长（秒）
    pub status: VideoGenerationStatus,
    pub generation_progress: Option<u32>, // 生成进度 0-100
    pub error_message: Option<String>,
    pub created_at: DateTime<Utc>,
}

/// 动态状态枚举
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum DynamicStatus {
    Draft,      // 草稿
    Publishing, // 发布中
    Published,  // 已发布
    Failed,     // 失败
}

/// 视频生成状态枚举
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum VideoGenerationStatus {
    Pending,    // 等待中
    Generating, // 生成中
    Completed,  // 已完成
    Failed,     // 失败
}

/// 创建动态请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateModelDynamicRequest {
    pub model_id: String,
    pub title: Option<String>,
    pub description: String,
    pub prompt: String,
    pub source_image_path: String,
    pub ai_model: String,
    pub video_count: u32,
}

/// 更新动态请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateModelDynamicRequest {
    pub title: Option<String>,
    pub description: Option<String>,
    pub prompt: Option<String>,
    pub status: Option<DynamicStatus>,
}

/// 模特动态统计
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelDynamicStats {
    pub total_dynamics: u32,
    pub published_dynamics: u32,
    pub total_videos: u32,
    pub completed_videos: u32,
    pub generating_videos: u32,
    pub failed_videos: u32,
}

/// AI模型选项
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AIModelOption {
    pub id: String,
    pub name: String,
    pub description: String,
    pub is_available: bool,
    pub max_video_count: u32,
}

impl ModelDynamic {
    /// 创建新的模特动态
    pub fn new(
        model_id: String,
        description: String,
        prompt: String,
        source_image_path: String,
        ai_model: String,
        video_count: u32,
    ) -> Self {
        let now = Utc::now();
        Self {
            id: Uuid::new_v4().to_string(),
            model_id,
            title: None,
            description,
            prompt,
            source_image_path,
            ai_model,
            video_count,
            generated_videos: Vec::new(),
            status: DynamicStatus::Draft,
            created_at: now,
            updated_at: now,
        }
    }

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

        if self.description.trim().is_empty() {
            return Err("动态描述不能为空".to_string());
        }

        if self.prompt.trim().is_empty() {
            return Err("提示词不能为空".to_string());
        }

        if self.source_image_path.trim().is_empty() {
            return Err("源图片路径不能为空".to_string());
        }

        if self.ai_model.trim().is_empty() {
            return Err("AI模型不能为空".to_string());
        }

        if self.video_count == 0 || self.video_count > 9 {
            return Err("视频个数必须在1-9之间".to_string());
        }

        Ok(())
    }

    /// 更新状态
    pub fn update_status(&mut self, status: DynamicStatus) {
        self.status = status;
        self.updated_at = Utc::now();
    }

    /// 添加生成的视频
    pub fn add_generated_video(&mut self, video: GeneratedVideo) {
        self.generated_videos.push(video);
        self.updated_at = Utc::now();
    }

    /// 获取已完成的视频数量
    pub fn completed_video_count(&self) -> usize {
        self.generated_videos
            .iter()
            .filter(|v| v.status == VideoGenerationStatus::Completed)
            .count()
    }

    /// 获取生成中的视频数量
    pub fn generating_video_count(&self) -> usize {
        self.generated_videos
            .iter()
            .filter(|v| v.status == VideoGenerationStatus::Generating)
            .count()
    }

    /// 获取失败的视频数量
    pub fn failed_video_count(&self) -> usize {
        self.generated_videos
            .iter()
            .filter(|v| v.status == VideoGenerationStatus::Failed)
            .count()
    }
}

impl GeneratedVideo {
    /// 创建新的生成视频
    pub fn new(dynamic_id: String, video_path: String) -> Self {
        Self {
            id: Uuid::new_v4().to_string(),
            dynamic_id,
            video_path,
            thumbnail_path: None,
            file_size: 0,
            duration: 0,
            status: VideoGenerationStatus::Pending,
            generation_progress: None,
            error_message: None,
            created_at: Utc::now(),
        }
    }

    /// 更新生成进度
    pub fn update_progress(&mut self, progress: u32) {
        self.generation_progress = Some(progress);
        if progress >= 100 {
            self.status = VideoGenerationStatus::Completed;
        } else {
            self.status = VideoGenerationStatus::Generating;
        }
    }

    /// 标记为失败
    pub fn mark_as_failed(&mut self, error_message: String) {
        self.status = VideoGenerationStatus::Failed;
        self.error_message = Some(error_message);
        self.generation_progress = None;
    }

    /// 标记为完成
    pub fn mark_as_completed(&mut self, file_size: u64, duration: u32, thumbnail_path: Option<String>) {
        self.status = VideoGenerationStatus::Completed;
        self.file_size = file_size;
        self.duration = duration;
        self.thumbnail_path = thumbnail_path;
        self.generation_progress = Some(100);
    }
}

impl Default for DynamicStatus {
    fn default() -> Self {
        DynamicStatus::Draft
    }
}

impl Default for VideoGenerationStatus {
    fn default() -> Self {
        VideoGenerationStatus::Pending
    }
}
