use crate::data::models::image_generation_record::{ImageGenerationRecord, ImageGenerationStatus};
use crate::infrastructure::database::Database;
use anyhow::{Result, anyhow};
use std::sync::Arc;

/// 图片生成记录仓库
pub struct ImageGenerationRepository {
    database: Arc<Database>,
}

impl ImageGenerationRepository {
    /// 创建新的图片生成记录仓库
    pub fn new(database: Arc<Database>) -> Self {
        Self { database }
    }

    /// 初始化数据库表
    pub fn init_tables(&self) -> Result<()> {
if !self.database.has_pool() {
            return Err(anyhow!("连接池未启用，无法安全执行数据库操作"));
        }

        let conn = self
            .database
            .acquire_from_pool()
            .map_err(|e| anyhow!("获取连接池连接失败: {}", e))?;
        
        crate::data::models::image_generation_record::create_table(&conn)
            .map_err(|e| anyhow::anyhow!("创建图片生成记录表失败: {}", e))?;
        
        Ok(())
    }

    /// 保存图片生成记录
    pub fn save(&self, record: &ImageGenerationRecord) -> Result<()> {
        if !self.database.has_pool() {
            return Err(anyhow!("连接池未启用，无法安全执行数据库操作"));
        }

        let conn = self
            .database
            .acquire_from_pool()
            .map_err(|e| anyhow!("获取连接池连接失败: {}", e))?;
        
        record.save(&conn)
            .map_err(|e| anyhow::anyhow!("保存图片生成记录失败: {}", e))?;
        
        Ok(())
    }

    /// 根据ID查找记录
    pub fn find_by_id(&self, id: &str) -> Result<Option<ImageGenerationRecord>> {
        if !self.database.has_pool() {
            return Err(anyhow!("连接池未启用，无法安全执行数据库操作"));
        }

        let conn = self
            .database
            .acquire_from_pool()
            .map_err(|e| anyhow!("获取连接池连接失败: {}", e))?;
        
        ImageGenerationRecord::find_by_id(&conn, id)
            .map_err(|e| anyhow::anyhow!("查找图片生成记录失败: {}", e))
    }

    /// 根据任务ID查找记录
    pub fn find_by_task_id(&self, task_id: &str) -> Result<Option<ImageGenerationRecord>> {
        if !self.database.has_pool() {
            return Err(anyhow!("连接池未启用，无法安全执行数据库操作"));
        }

        let conn = self
            .database
            .acquire_from_pool()
            .map_err(|e| anyhow!("获取连接池连接失败: {}", e))?;
        
        ImageGenerationRecord::find_by_task_id(&conn, task_id)
            .map_err(|e| anyhow::anyhow!("根据任务ID查找图片生成记录失败: {}", e))
    }

    /// 获取所有记录（按创建时间倒序）
    pub fn get_all(&self, limit: Option<i32>) -> Result<Vec<ImageGenerationRecord>> {
        if !self.database.has_pool() {
            return Err(anyhow!("连接池未启用，无法安全执行数据库操作"));
        }

        let conn = self
            .database
            .acquire_from_pool()
            .map_err(|e| anyhow!("获取连接池连接失败: {}", e))?;
        
        ImageGenerationRecord::get_all(&conn, limit)
            .map_err(|e| anyhow::anyhow!("获取图片生成记录列表失败: {}", e))
    }

    /// 获取指定状态的记录
    pub fn get_by_status(&self, status: ImageGenerationStatus, limit: Option<i32>) -> Result<Vec<ImageGenerationRecord>> {
        if !self.database.has_pool() {
            return Err(anyhow!("连接池未启用，无法安全执行数据库操作"));
        }

        let conn = self
            .database
            .acquire_from_pool()
            .map_err(|e| anyhow!("获取连接池连接失败: {}", e))?;
        
        let sql = if let Some(limit) = limit {
            format!(
                "SELECT * FROM image_generation_records WHERE status = ?1 ORDER BY created_at DESC LIMIT {}",
                limit
            )
        } else {
            "SELECT * FROM image_generation_records WHERE status = ?1 ORDER BY created_at DESC".to_string()
        };

        let mut stmt = conn.prepare(&sql)
            .map_err(|e| anyhow::anyhow!("准备查询语句失败: {}", e))?;
        
        let rows = stmt.query_map([status.as_str()], ImageGenerationRecord::from_row)
            .map_err(|e| anyhow::anyhow!("执行查询失败: {}", e))?;

        let mut records = Vec::new();
        for row in rows {
            records.push(row.map_err(|e| anyhow::anyhow!("解析记录失败: {}", e))?);
        }

        Ok(records)
    }

    /// 删除记录
    pub fn delete(&self, id: &str) -> Result<()> {
        if !self.database.has_pool() {
            return Err(anyhow!("连接池未启用，无法安全执行数据库操作"));
        }

        let conn = self
            .database
            .acquire_from_pool()
            .map_err(|e| anyhow!("获取连接池连接失败: {}", e))?;
        
        if let Some(record) = ImageGenerationRecord::find_by_id(&conn, id)
            .map_err(|e| anyhow::anyhow!("查找要删除的记录失败: {}", e))? {
            record.delete(&conn)
                .map_err(|e| anyhow::anyhow!("删除图片生成记录失败: {}", e))?;
        }
        
        Ok(())
    }

    /// 更新记录状态
    pub fn update_status(&self, id: &str, status: ImageGenerationStatus) -> Result<()> {
        if let Some(mut record) = self.find_by_id(id)? {
            match status {
                ImageGenerationStatus::Processing => {
                    if record.status == ImageGenerationStatus::Pending {
                        record.status = status;
                        if record.started_at.is_none() {
                            record.started_at = Some(chrono::Utc::now());
                        }
                    }
                }
                ImageGenerationStatus::Completed => {
                    record.status = status;
                    record.progress = 1.0;
                    if record.completed_at.is_none() {
                        record.completed_at = Some(chrono::Utc::now());
                        if let Some(started_at) = record.started_at {
                            record.duration_ms = Some((chrono::Utc::now() - started_at).num_milliseconds());
                        }
                    }
                }
                ImageGenerationStatus::Failed | ImageGenerationStatus::Cancelled => {
                    record.status = status;
                    if record.completed_at.is_none() {
                        record.completed_at = Some(chrono::Utc::now());
                        if let Some(started_at) = record.started_at {
                            record.duration_ms = Some((chrono::Utc::now() - started_at).num_milliseconds());
                        }
                    }
                }
                _ => {
                    record.status = status;
                }
            }
            
            self.save(&record)?;
        }
        
        Ok(())
    }

    /// 更新记录进度
    pub fn update_progress(&self, id: &str, progress: f32) -> Result<()> {
        if let Some(mut record) = self.find_by_id(id)? {
            record.update_progress(progress);
            self.save(&record)?;
        }
        
        Ok(())
    }

    /// 更新记录结果
    pub fn update_result(&self, id: &str, result_urls: Vec<String>) -> Result<()> {
        if let Some(mut record) = self.find_by_id(id)? {
            record.complete_generation(result_urls);
            self.save(&record)?;
        }
        
        Ok(())
    }

    /// 设置记录错误信息
    pub fn set_error(&self, id: &str, error_message: String) -> Result<()> {
        if let Some(mut record) = self.find_by_id(id)? {
            record.fail_generation(error_message);
            self.save(&record)?;
        }
        
        Ok(())
    }

    /// 获取正在处理的记录数量
    pub fn get_processing_count(&self) -> Result<i32> {
        if !self.database.has_pool() {
            return Err(anyhow!("连接池未启用，无法安全执行数据库操作"));
        }

        let conn = self
            .database
            .acquire_from_pool()
            .map_err(|e| anyhow!("获取连接池连接失败: {}", e))?;
        
        let count: i32 = conn.query_row(
            "SELECT COUNT(*) FROM image_generation_records WHERE status IN ('pending', 'processing')",
            [],
            |row| row.get(0)
        ).map_err(|e| anyhow::anyhow!("查询处理中记录数量失败: {}", e))?;
        
        Ok(count)
    }

    /// 清理旧记录（保留最近的N条记录）
    pub fn cleanup_old_records(&self, keep_count: i32) -> Result<i32> {
        if !self.database.has_pool() {
            return Err(anyhow!("连接池未启用，无法安全执行数据库操作"));
        }

        let conn = self
            .database
            .acquire_from_pool()
            .map_err(|e| anyhow!("获取连接池连接失败: {}", e))?;
        
        let deleted_count = conn.execute(
            r#"
            DELETE FROM image_generation_records 
            WHERE id NOT IN (
                SELECT id FROM image_generation_records 
                ORDER BY created_at DESC 
                LIMIT ?1
            )
            "#,
            [keep_count]
        ).map_err(|e| anyhow::anyhow!("清理旧记录失败: {}", e))?;
        
        Ok(deleted_count as i32)
    }
}
