use chrono::{DateTime, Utc};
use rusqlite::{params, Connection, Result as SqliteResult, Row};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

/// 图片生成记录状态
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ImageGenerationStatus {
    Pending,    // 等待中
    Processing, // 处理中
    Completed,  // 已完成
    Failed,     // 失败
    Cancelled,  // 已取消
}

impl ImageGenerationStatus {
    pub fn as_str(&self) -> &'static str {
        match self {
            ImageGenerationStatus::Pending => "pending",
            ImageGenerationStatus::Processing => "processing",
            ImageGenerationStatus::Completed => "completed",
            ImageGenerationStatus::Failed => "failed",
            ImageGenerationStatus::Cancelled => "cancelled",
        }
    }

    pub fn from_str(s: &str) -> Self {
        match s {
            "pending" => ImageGenerationStatus::Pending,
            "processing" => ImageGenerationStatus::Processing,
            "completed" => ImageGenerationStatus::Completed,
            "failed" => ImageGenerationStatus::Failed,
            "cancelled" => ImageGenerationStatus::Cancelled,
            _ => ImageGenerationStatus::Pending,
        }
    }
}

/// 图片生成记录
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageGenerationRecord {
    pub id: String,
    pub task_id: Option<String>,
    pub prompt: String,
    pub reference_image_path: Option<String>,
    pub reference_image_url: Option<String>,
    pub status: ImageGenerationStatus,
    pub progress: f32,
    pub result_urls: Vec<String>,
    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<i64>,
}

impl ImageGenerationRecord {
    /// 创建新的图片生成记录
    pub fn new(prompt: String, reference_image_path: Option<String>) -> Self {
        Self {
            id: Uuid::new_v4().to_string(),
            task_id: None,
            prompt,
            reference_image_path,
            reference_image_url: None,
            status: ImageGenerationStatus::Pending,
            progress: 0.0,
            result_urls: Vec::new(),
            error_message: None,
            created_at: Utc::now(),
            started_at: None,
            completed_at: None,
            duration_ms: None,
        }
    }

    /// 开始生成
    pub fn start_generation(&mut self, task_id: String) {
        self.task_id = Some(task_id);
        self.status = ImageGenerationStatus::Processing;
        self.started_at = Some(Utc::now());
    }

    /// 更新进度
    pub fn update_progress(&mut self, progress: f32) {
        self.progress = progress;
        if progress > 0.0 && self.status == ImageGenerationStatus::Pending {
            self.status = ImageGenerationStatus::Processing;
        }
    }

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

    /// 失败处理
    pub fn fail_generation(&mut self, error_message: String) {
        self.status = ImageGenerationStatus::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());
        }
    }

    /// 取消生成
    pub fn cancel_generation(&mut self) {
        self.status = ImageGenerationStatus::Cancelled;
        self.completed_at = Some(Utc::now());
        
        if let Some(started_at) = self.started_at {
            self.duration_ms = Some((Utc::now() - started_at).num_milliseconds());
        }
    }

    /// 从数据库行创建记录
    pub fn from_row(row: &Row) -> SqliteResult<Self> {
        let result_urls_json: String = row.get("result_urls")?;
        let result_urls: Vec<String> = serde_json::from_str(&result_urls_json).unwrap_or_default();

        let created_at_str: String = row.get("created_at")?;
        let created_at = DateTime::parse_from_rfc3339(&created_at_str)
            .map_err(|_| rusqlite::Error::InvalidColumnType(0, "created_at".to_string(), rusqlite::types::Type::Text))?
            .with_timezone(&Utc);

        let started_at_str: Option<String> = row.get("started_at")?;
        let started_at = started_at_str
            .and_then(|s| DateTime::parse_from_rfc3339(&s).ok())
            .map(|dt| dt.with_timezone(&Utc));

        let completed_at_str: Option<String> = row.get("completed_at")?;
        let completed_at = completed_at_str
            .and_then(|s| DateTime::parse_from_rfc3339(&s).ok())
            .map(|dt| dt.with_timezone(&Utc));

        Ok(Self {
            id: row.get("id")?,
            task_id: row.get("task_id")?,
            prompt: row.get("prompt")?,
            reference_image_path: row.get("reference_image_path")?,
            reference_image_url: row.get("reference_image_url")?,
            status: ImageGenerationStatus::from_str(&row.get::<_, String>("status")?),
            progress: row.get("progress")?,
            result_urls,
            error_message: row.get("error_message")?,
            created_at,
            started_at,
            completed_at,
            duration_ms: row.get("duration_ms")?,
        })
    }

    /// 保存到数据库
    pub fn save(&self, conn: &Connection) -> SqliteResult<()> {
        let result_urls_json = serde_json::to_string(&self.result_urls).unwrap_or_default();

        conn.execute(
            r#"
            INSERT OR REPLACE INTO image_generation_records (
                id, task_id, prompt, reference_image_path, reference_image_url,
                status, progress, result_urls, error_message,
                created_at, started_at, completed_at, duration_ms
            ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)
            "#,
            params![
                self.id,
                self.task_id,
                self.prompt,
                self.reference_image_path,
                self.reference_image_url,
                self.status.as_str(),
                self.progress,
                result_urls_json,
                self.error_message,
                self.created_at.to_rfc3339(),
                self.started_at.map(|dt| dt.to_rfc3339()),
                self.completed_at.map(|dt| dt.to_rfc3339()),
                self.duration_ms,
            ],
        )?;

        Ok(())
    }

    /// 根据ID查找记录
    pub fn find_by_id(conn: &Connection, id: &str) -> SqliteResult<Option<Self>> {
        let mut stmt = conn.prepare(
            "SELECT * FROM image_generation_records WHERE id = ?1"
        )?;

        let mut rows = stmt.query_map(params![id], Self::from_row)?;

        match rows.next() {
            Some(row) => Ok(Some(row?)),
            None => Ok(None),
        }
    }

    /// 根据任务ID查找记录
    pub fn find_by_task_id(conn: &Connection, task_id: &str) -> SqliteResult<Option<Self>> {
        let mut stmt = conn.prepare(
            "SELECT * FROM image_generation_records WHERE task_id = ?1"
        )?;

        let mut rows = stmt.query_map(params![task_id], Self::from_row)?;

        match rows.next() {
            Some(row) => Ok(Some(row?)),
            None => Ok(None),
        }
    }

    /// 获取所有记录（按创建时间倒序）
    pub fn get_all(conn: &Connection, limit: Option<i32>) -> SqliteResult<Vec<Self>> {
        let sql = if let Some(limit) = limit {
            format!("SELECT * FROM image_generation_records ORDER BY created_at DESC LIMIT {}", limit)
        } else {
            "SELECT * FROM image_generation_records ORDER BY created_at DESC".to_string()
        };

        let mut stmt = conn.prepare(&sql)?;
        let rows = stmt.query_map([], Self::from_row)?;

        let mut records = Vec::new();
        for row in rows {
            records.push(row?);
        }

        Ok(records)
    }

    /// 删除记录
    pub fn delete(&self, conn: &Connection) -> SqliteResult<()> {
        conn.execute(
            "DELETE FROM image_generation_records WHERE id = ?1",
            params![self.id],
        )?;
        Ok(())
    }
}

/// 创建图片生成记录表
pub fn create_table(conn: &Connection) -> SqliteResult<()> {
    conn.execute(
        r#"
        CREATE TABLE IF NOT EXISTS image_generation_records (
            id TEXT PRIMARY KEY,
            task_id TEXT,
            prompt TEXT NOT NULL,
            reference_image_path TEXT,
            reference_image_url TEXT,
            status TEXT NOT NULL DEFAULT 'pending',
            progress REAL NOT NULL DEFAULT 0.0,
            result_urls TEXT NOT NULL DEFAULT '[]',
            error_message TEXT,
            created_at TEXT NOT NULL,
            started_at TEXT,
            completed_at TEXT,
            duration_ms INTEGER
        )
        "#,
        [],
    )?;

    // 创建索引
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_image_generation_records_task_id ON image_generation_records(task_id)",
        [],
    )?;

    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_image_generation_records_created_at ON image_generation_records(created_at)",
        [],
    )?;

    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_image_generation_records_status ON image_generation_records(status)",
        [],
    )?;

    Ok(())
}
