use crate::data::models::image_generation_record::{ImageGenerationRecord, ImageGenerationStatus};
use crate::data::repositories::image_generation_repository::ImageGenerationRepository;
use crate::infrastructure::database::Database;
use anyhow::Result;
use std::sync::Arc;
use tracing::{error, info};

/// 图片生成服务
pub struct ImageGenerationService {
    repository: ImageGenerationRepository,
}

impl ImageGenerationService {
    /// 创建新的图片生成服务
    pub fn new(database: Arc<Database>) -> Self {
        let repository = ImageGenerationRepository::new(database);
        
        // 初始化数据库表
        if let Err(e) = repository.init_tables() {
            error!("初始化图片生成记录表失败: {}", e);
        }
        
        Self { repository }
    }

    /// 创建新的图片生成记录
    pub fn create_record(&self, prompt: String, reference_image_path: Option<String>) -> Result<ImageGenerationRecord> {
        let record = ImageGenerationRecord::new(prompt, reference_image_path);
        
        info!("创建图片生成记录: {}", record.id);
        self.repository.save(&record)?;
        
        Ok(record)
    }

    /// 开始生成任务
    pub fn start_generation(&self, record_id: &str, task_id: String) -> Result<()> {
        info!("开始图片生成任务: {} -> {}", record_id, task_id);
        
        if let Some(mut record) = self.repository.find_by_id(record_id)? {
            record.start_generation(task_id);
            self.repository.save(&record)?;
        }
        
        Ok(())
    }

    /// 更新生成进度
    pub fn update_progress(&self, record_id: &str, progress: f32) -> Result<()> {
        self.repository.update_progress(record_id, progress)?;
        Ok(())
    }

    /// 根据任务ID更新进度
    pub fn update_progress_by_task_id(&self, task_id: &str, progress: f32) -> Result<()> {
        if let Some(record) = self.repository.find_by_task_id(task_id)? {
            self.update_progress(&record.id, progress)?;
        }
        Ok(())
    }

    /// 完成生成任务
    pub fn complete_generation(&self, record_id: &str, result_urls: Vec<String>) -> Result<()> {
        info!("完成图片生成任务: {} -> {} 张图片", record_id, result_urls.len());
        
        self.repository.update_result(record_id, result_urls)?;
        Ok(())
    }

    /// 根据任务ID完成生成
    pub fn complete_generation_by_task_id(&self, task_id: &str, result_urls: Vec<String>) -> Result<()> {
        if let Some(record) = self.repository.find_by_task_id(task_id)? {
            self.complete_generation(&record.id, result_urls)?;
        }
        Ok(())
    }

    /// 设置生成失败
    pub fn fail_generation(&self, record_id: &str, error_message: String) -> Result<()> {
        error!("图片生成任务失败: {} -> {}", record_id, error_message);
        
        self.repository.set_error(record_id, error_message)?;
        Ok(())
    }

    /// 根据任务ID设置失败
    pub fn fail_generation_by_task_id(&self, task_id: &str, error_message: String) -> Result<()> {
        if let Some(record) = self.repository.find_by_task_id(task_id)? {
            self.fail_generation(&record.id, error_message)?;
        }
        Ok(())
    }

    /// 取消生成任务
    pub fn cancel_generation(&self, record_id: &str) -> Result<()> {
        info!("取消图片生成任务: {}", record_id);
        
        self.repository.update_status(record_id, ImageGenerationStatus::Cancelled)?;
        Ok(())
    }

    /// 获取记录详情
    pub fn get_record(&self, record_id: &str) -> Result<Option<ImageGenerationRecord>> {
        self.repository.find_by_id(record_id)
    }

    /// 根据任务ID获取记录
    pub fn get_record_by_task_id(&self, task_id: &str) -> Result<Option<ImageGenerationRecord>> {
        self.repository.find_by_task_id(task_id)
    }

    /// 获取所有记录
    pub fn get_all_records(&self, limit: Option<i32>) -> Result<Vec<ImageGenerationRecord>> {
        self.repository.get_all(limit)
    }

    /// 获取指定状态的记录
    pub fn get_records_by_status(&self, status: ImageGenerationStatus, limit: Option<i32>) -> Result<Vec<ImageGenerationRecord>> {
        self.repository.get_by_status(status, limit)
    }

    /// 删除记录
    pub fn delete_record(&self, record_id: &str) -> Result<()> {
        info!("删除图片生成记录: {}", record_id);
        
        self.repository.delete(record_id)?;
        Ok(())
    }

    /// 获取正在处理的任务数量
    pub fn get_processing_count(&self) -> Result<i32> {
        self.repository.get_processing_count()
    }

    /// 清理旧记录
    pub fn cleanup_old_records(&self, keep_count: i32) -> Result<i32> {
        info!("清理旧的图片生成记录，保留最近 {} 条", keep_count);
        
        self.repository.cleanup_old_records(keep_count)
    }

    /// 重置卡住的任务
    pub fn reset_stuck_tasks(&self) -> Result<i32> {
        info!("重置卡住的图片生成任务");
        
        let stuck_records = self.repository.get_by_status(ImageGenerationStatus::Processing, None)?;
        let mut reset_count = 0;
        
        for record in stuck_records {
            // 检查任务是否卡住（超过30分钟仍在处理中）
            if let Some(started_at) = record.started_at {
                let duration = chrono::Utc::now() - started_at;
                if duration.num_minutes() > 30 {
                    self.repository.update_status(&record.id, ImageGenerationStatus::Failed)?;
                    self.repository.set_error(&record.id, "任务超时，已自动重置".to_string())?;
                    reset_count += 1;
                }
            }
        }
        
        if reset_count > 0 {
            info!("重置了 {} 个卡住的任务", reset_count);
        }
        
        Ok(reset_count)
    }

    /// 获取统计信息
    pub fn get_statistics(&self) -> Result<ImageGenerationStatistics> {
        let all_records = self.repository.get_all(None)?;
        
        let total_count = all_records.len() as i32;
        let completed_count = all_records.iter().filter(|r| r.status == ImageGenerationStatus::Completed).count() as i32;
        let failed_count = all_records.iter().filter(|r| r.status == ImageGenerationStatus::Failed).count() as i32;
        let processing_count = all_records.iter().filter(|r| r.status == ImageGenerationStatus::Processing).count() as i32;
        let pending_count = all_records.iter().filter(|r| r.status == ImageGenerationStatus::Pending).count() as i32;
        
        let success_rate = if total_count > 0 {
            (completed_count as f32 / total_count as f32) * 100.0
        } else {
            0.0
        };
        
        let average_duration = if completed_count > 0 {
            let total_duration: i64 = all_records.iter()
                .filter(|r| r.status == ImageGenerationStatus::Completed && r.duration_ms.is_some())
                .map(|r| r.duration_ms.unwrap_or(0))
                .sum();
            total_duration / completed_count as i64
        } else {
            0
        };
        
        Ok(ImageGenerationStatistics {
            total_count,
            completed_count,
            failed_count,
            processing_count,
            pending_count,
            success_rate,
            average_duration_ms: average_duration,
        })
    }
}

/// 图片生成统计信息
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ImageGenerationStatistics {
    pub total_count: i32,
    pub completed_count: i32,
    pub failed_count: i32,
    pub processing_count: i32,
    pub pending_count: i32,
    pub success_rate: f32,
    pub average_duration_ms: i64,
}
