use crate::data::models::video_classification::*;
use crate::infrastructure::database::Database;
use anyhow::Result;
use rusqlite::params;
use std::sync::Arc;

use chrono::Utc;

/// AI视频分类数据仓库
/// 遵循 Tauri 开发规范的数据访问层设计模式
pub struct VideoClassificationRepository {
    database: Arc<Database>,
}

impl VideoClassificationRepository {
    /// 创建新的视频分类仓库实例
    pub fn new(database: Arc<Database>) -> Self {
        Self { database }
    }

    /// 创建分类记录
    pub async fn create_classification_record(&self, record: VideoClassificationRecord) -> Result<VideoClassificationRecord> {
        let conn = self.database.get_connection();
        let conn = conn.lock().unwrap();

        conn.execute(
            "INSERT INTO video_classification_records (
                id, segment_id, material_id, project_id, category, confidence, reasoning,
                features, product_match, quality_score, gemini_file_uri, raw_response,
                status, error_message, created_at, updated_at
            ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16)",
            params![
                record.id,
                record.segment_id,
                record.material_id,
                record.project_id,
                record.category,
                record.confidence,
                record.reasoning,
                serde_json::to_string(&record.features)?,
                record.product_match,
                record.quality_score,
                record.gemini_file_uri,
                record.raw_response,
                serde_json::to_string(&record.status)?,
                record.error_message,
                record.created_at.to_rfc3339(),
                record.updated_at.to_rfc3339()
            ],
        )?;

        Ok(record)
    }

    /// 根据片段ID获取分类记录
    pub async fn get_by_segment_id(&self, segment_id: &str) -> Result<Option<VideoClassificationRecord>> {
        let conn = self.database.get_connection();
        let conn = conn.lock().unwrap();

        let mut stmt = conn.prepare(
            "SELECT id, segment_id, material_id, project_id, category, confidence, reasoning,
                    features, product_match, quality_score, gemini_file_uri, raw_response,
                    status, error_message, created_at, updated_at
             FROM video_classification_records WHERE segment_id = ?1"
        )?;

        let mut rows = stmt.query_map([segment_id], |row| {
            let features_json: String = row.get(7)?;
            let features: Vec<String> = serde_json::from_str(&features_json).unwrap_or_default();
            
            let status_json: String = row.get(12)?;
            let status: ClassificationStatus = serde_json::from_str(&status_json).unwrap_or_default();

            Ok(VideoClassificationRecord {
                id: row.get(0)?,
                segment_id: row.get(1)?,
                material_id: row.get(2)?,
                project_id: row.get(3)?,
                category: row.get(4)?,
                confidence: row.get(5)?,
                reasoning: row.get(6)?,
                features,
                product_match: row.get(8)?,
                quality_score: row.get(9)?,
                gemini_file_uri: row.get(10)?,
                raw_response: row.get(11)?,
                status,
                error_message: row.get(13)?,
                created_at: chrono::DateTime::parse_from_rfc3339(&row.get::<_, String>(14)?).map_err(|_e| rusqlite::Error::InvalidColumnType(14, "created_at".to_string(), rusqlite::types::Type::Text))?.with_timezone(&Utc),
                updated_at: chrono::DateTime::parse_from_rfc3339(&row.get::<_, String>(15)?).map_err(|_e| rusqlite::Error::InvalidColumnType(15, "updated_at".to_string(), rusqlite::types::Type::Text))?.with_timezone(&Utc),
            })
        })?;

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

    /// 根据素材ID获取所有分类记录
    pub async fn get_by_material_id(&self, material_id: &str) -> Result<Vec<VideoClassificationRecord>> {
        let conn = self.database.get_connection();
        let conn = conn.lock().unwrap();

        let mut stmt = conn.prepare(
            "SELECT id, segment_id, material_id, project_id, category, confidence, reasoning,
                    features, product_match, quality_score, gemini_file_uri, raw_response,
                    status, error_message, created_at, updated_at
             FROM video_classification_records WHERE material_id = ?1 ORDER BY created_at DESC"
        )?;

        let rows = stmt.query_map([material_id], |row| {
            let features_json: String = row.get(7)?;
            let features: Vec<String> = serde_json::from_str(&features_json).unwrap_or_default();
            
            let status_json: String = row.get(12)?;
            let status: ClassificationStatus = serde_json::from_str(&status_json).unwrap_or_default();

            Ok(VideoClassificationRecord {
                id: row.get(0)?,
                segment_id: row.get(1)?,
                material_id: row.get(2)?,
                project_id: row.get(3)?,
                category: row.get(4)?,
                confidence: row.get(5)?,
                reasoning: row.get(6)?,
                features,
                product_match: row.get(8)?,
                quality_score: row.get(9)?,
                gemini_file_uri: row.get(10)?,
                raw_response: row.get(11)?,
                status,
                error_message: row.get(13)?,
                created_at: chrono::DateTime::parse_from_rfc3339(&row.get::<_, String>(14)?).map_err(|_e| rusqlite::Error::InvalidColumnType(14, "created_at".to_string(), rusqlite::types::Type::Text))?.with_timezone(&Utc),
                updated_at: chrono::DateTime::parse_from_rfc3339(&row.get::<_, String>(15)?).map_err(|_e| rusqlite::Error::InvalidColumnType(15, "updated_at".to_string(), rusqlite::types::Type::Text))?.with_timezone(&Utc),
            })
        })?;

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

        Ok(records)
    }

    /// 根据项目ID获取分类记录（支持分页和过滤）
    pub async fn get_by_project_id_with_pagination(
        &self,
        project_id: &str,
        page: u32,
        page_size: u32,
        status_filter: Option<&ClassificationStatus>,
        search_keyword: Option<&str>
    ) -> Result<(Vec<VideoClassificationRecord>, u64)> {
        let conn = self.database.get_connection();
        let conn = conn.lock().unwrap();

        // 直接查询项目的所有分类记录
        let mut stmt = conn.prepare(
            "SELECT id, segment_id, material_id, project_id, category, confidence, reasoning,
                    features, product_match, quality_score, gemini_file_uri, raw_response,
                    status, error_message, created_at, updated_at
             FROM video_classification_records WHERE project_id = ?1 ORDER BY created_at DESC"
        )?;

        let rows = stmt.query_map([project_id], |row| {
            let features_json: String = row.get(7)?;
            let features: Vec<String> = serde_json::from_str(&features_json).unwrap_or_default();

            let status_json: String = row.get(12)?;
            let status: ClassificationStatus = serde_json::from_str(&status_json).unwrap_or_default();

            Ok(VideoClassificationRecord {
                id: row.get(0)?,
                segment_id: row.get(1)?,
                material_id: row.get(2)?,
                project_id: row.get(3)?,
                category: row.get(4)?,
                confidence: row.get(5)?,
                reasoning: row.get(6)?,
                features,
                product_match: row.get(8)?,
                quality_score: row.get(9)?,
                gemini_file_uri: row.get(10)?,
                raw_response: row.get(11)?,
                status,
                error_message: row.get(13)?,
                created_at: chrono::DateTime::parse_from_rfc3339(&row.get::<_, String>(14)?).map_err(|_e| rusqlite::Error::InvalidColumnType(14, "created_at".to_string(), rusqlite::types::Type::Text))?.with_timezone(&Utc),
                updated_at: chrono::DateTime::parse_from_rfc3339(&row.get::<_, String>(15)?).map_err(|_e| rusqlite::Error::InvalidColumnType(15, "updated_at".to_string(), rusqlite::types::Type::Text))?.with_timezone(&Utc),
            })
        })?;

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

        // 在内存中应用过滤
        let filtered_records: Vec<VideoClassificationRecord> = project_records.into_iter()
            .filter(|record| {
                // 状态过滤
                if let Some(filter_status) = status_filter {
                    if &record.status != filter_status {
                        return false;
                    }
                }

                // 关键词搜索
                if let Some(keyword) = search_keyword {
                    let keyword_lower = keyword.to_lowercase();
                    let matches = record.category.to_lowercase().contains(&keyword_lower) ||
                                 record.reasoning.to_lowercase().contains(&keyword_lower) ||
                                 record.error_message.as_ref().map_or(false, |msg| msg.to_lowercase().contains(&keyword_lower));
                    if !matches {
                        return false;
                    }
                }

                true
            })
            .collect();

        let total_count = filtered_records.len() as u64;

        // 应用分页
        let offset = ((page - 1) * page_size) as usize;
        let end = std::cmp::min(offset + page_size as usize, filtered_records.len());
        let page_records = if offset < filtered_records.len() {
            filtered_records[offset..end].to_vec()
        } else {
            Vec::new()
        };

        Ok((page_records, total_count))
    }

    /// 创建分类任务
    pub async fn create_classification_task(&self, task: VideoClassificationTask) -> Result<VideoClassificationTask> {
        let conn = self.database.get_connection();
        let conn = conn.lock().unwrap();

        conn.execute(
            "INSERT INTO video_classification_tasks (
                id, segment_id, material_id, project_id, video_file_path, status, priority,
                retry_count, max_retries, gemini_file_uri, prompt_text, error_message,
                started_at, completed_at, created_at, updated_at
            ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16)",
            params![
                task.id,
                task.segment_id,
                task.material_id,
                task.project_id,
                task.video_file_path,
                serde_json::to_string(&task.status)?,
                task.priority,
                task.retry_count,
                task.max_retries,
                task.gemini_file_uri,
                task.prompt_text,
                task.error_message,
                task.started_at.map(|dt| dt.to_rfc3339()),
                task.completed_at.map(|dt| dt.to_rfc3339()),
                task.created_at.to_rfc3339(),
                task.updated_at.to_rfc3339()
            ],
        )?;

        Ok(task)
    }

    /// 更新分类任务
    pub async fn update_classification_task(&self, task: &VideoClassificationTask) -> Result<()> {
        let conn = self.database.get_connection();
        let conn = conn.lock().unwrap();

        conn.execute(
            "UPDATE video_classification_tasks SET
                status = ?1, retry_count = ?2, gemini_file_uri = ?3, prompt_text = ?4,
                error_message = ?5, started_at = ?6, completed_at = ?7, updated_at = ?8
             WHERE id = ?9",
            params![
                serde_json::to_string(&task.status)?,
                task.retry_count,
                task.gemini_file_uri,
                task.prompt_text,
                task.error_message,
                task.started_at.map(|dt| dt.to_rfc3339()),
                task.completed_at.map(|dt| dt.to_rfc3339()),
                task.updated_at.to_rfc3339(),
                task.id
            ],
        )?;

        Ok(())
    }

    /// 获取待处理的任务（按优先级排序）
    pub async fn get_pending_tasks(&self, limit: Option<i32>) -> Result<Vec<VideoClassificationTask>> {
        let conn = self.database.get_connection();
        let conn = conn.lock().unwrap();

        // 调试：检查TaskStatus::Pending的序列化结果
        let _pending_status_json = serde_json::to_string(&TaskStatus::Pending)?;

        // 使用正确的JSON序列化格式查询
        let pending_status_json = serde_json::to_string(&TaskStatus::Pending)?;

        let sql = if let Some(limit) = limit {
            format!(
                "SELECT id, segment_id, material_id, project_id, video_file_path, status, priority,
                        retry_count, max_retries, gemini_file_uri, prompt_text, error_message,
                        started_at, completed_at, created_at, updated_at
                 FROM video_classification_tasks
                 WHERE status = ?
                 ORDER BY priority DESC, created_at ASC
                 LIMIT {}", limit
            )
        } else {
            "SELECT id, segment_id, material_id, project_id, video_file_path, status, priority,
                    retry_count, max_retries, gemini_file_uri, prompt_text, error_message,
                    started_at, completed_at, created_at, updated_at
             FROM video_classification_tasks
             WHERE status = ?
             ORDER BY priority DESC, created_at ASC".to_string()
        };

        let mut stmt = conn.prepare(&sql)?;
        let rows = stmt.query_map([&pending_status_json], |row| {
            let status_json: String = row.get(5)?;
            let status: TaskStatus = serde_json::from_str(&status_json).unwrap_or_default();

            Ok(VideoClassificationTask {
                id: row.get(0)?,
                segment_id: row.get(1)?,
                material_id: row.get(2)?,
                project_id: row.get(3)?,
                video_file_path: row.get(4)?,
                status,
                priority: row.get(6)?,
                retry_count: row.get(7)?,
                max_retries: row.get(8)?,
                gemini_file_uri: row.get(9)?,
                prompt_text: row.get(10)?,
                error_message: row.get(11)?,
                started_at: row.get::<_, Option<String>>(12)?.and_then(|s| chrono::DateTime::parse_from_rfc3339(&s).ok()).map(|dt| dt.with_timezone(&Utc)),
                completed_at: row.get::<_, Option<String>>(13)?.and_then(|s| chrono::DateTime::parse_from_rfc3339(&s).ok()).map(|dt| dt.with_timezone(&Utc)),
                created_at: {
                    let created_at_str: String = row.get(14)?;
                    chrono::DateTime::parse_from_rfc3339(&created_at_str)
                        .map_err(|e| {
                            println!("❌ 解析created_at失败: '{}', 错误: {}", created_at_str, e);
                            rusqlite::Error::InvalidColumnType(14, "created_at".to_string(), rusqlite::types::Type::Text)
                        })?
                        .with_timezone(&Utc)
                },
                updated_at: {
                    let updated_at_str: String = row.get(15)?;
                    chrono::DateTime::parse_from_rfc3339(&updated_at_str)
                        .map_err(|e| {
                            println!("❌ 解析updated_at失败: '{}', 错误: {}", updated_at_str, e);
                            rusqlite::Error::InvalidColumnType(15, "updated_at".to_string(), rusqlite::types::Type::Text)
                        })?
                        .with_timezone(&Utc)
                },
            })
        })?;

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

        Ok(tasks)
    }

    /// 根据项目ID获取分类任务（支持分页和过滤）
    pub async fn get_tasks_by_project_id_with_pagination(
        &self,
        project_id: &str,
        page: u32,
        page_size: u32,
        status_filter: Option<&TaskStatus>,
        search_keyword: Option<&str>
    ) -> Result<(Vec<VideoClassificationTask>, u64)> {
        let conn = self.database.get_connection();
        let conn = conn.lock().unwrap();

        // 简化查询，获取项目的所有任务
        let mut stmt = conn.prepare(
            "SELECT id, segment_id, material_id, project_id, video_file_path, status, priority,
             retry_count, max_retries, gemini_file_uri, prompt_text, error_message,
             started_at, completed_at, created_at, updated_at
             FROM video_classification_tasks
             WHERE project_id = ?1
             ORDER BY created_at DESC"
        )?;

        let rows = stmt.query_map([project_id], |row| {
            let status_json: String = row.get(5)?;
            let status: TaskStatus = serde_json::from_str(&status_json).unwrap_or_default();

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

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

            Ok(VideoClassificationTask {
                id: row.get(0)?,
                segment_id: row.get(1)?,
                material_id: row.get(2)?,
                project_id: row.get(3)?,
                video_file_path: row.get(4)?,
                status,
                priority: row.get(6)?,
                retry_count: row.get(7)?,
                max_retries: row.get(8)?,
                gemini_file_uri: row.get(9)?,
                prompt_text: row.get(10)?,
                error_message: row.get(11)?,
                started_at,
                completed_at,
                created_at: chrono::DateTime::parse_from_rfc3339(&row.get::<_, String>(14)?).map_err(|_e| rusqlite::Error::InvalidColumnType(14, "created_at".to_string(), rusqlite::types::Type::Text))?.with_timezone(&Utc),
                updated_at: chrono::DateTime::parse_from_rfc3339(&row.get::<_, String>(15)?).map_err(|_e| rusqlite::Error::InvalidColumnType(15, "updated_at".to_string(), rusqlite::types::Type::Text))?.with_timezone(&Utc),
            })
        })?;

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

        // 在内存中应用过滤
        let filtered_tasks: Vec<VideoClassificationTask> = all_tasks.into_iter()
            .filter(|task| {
                // 状态过滤
                if let Some(filter_status) = status_filter {
                    if &task.status != filter_status {
                        return false;
                    }
                }

                // 关键词搜索
                if let Some(keyword) = search_keyword {
                    let keyword_lower = keyword.to_lowercase();
                    let matches = task.video_file_path.to_lowercase().contains(&keyword_lower) ||
                                 task.error_message.as_ref().map_or(false, |msg| msg.to_lowercase().contains(&keyword_lower));
                    if !matches {
                        return false;
                    }
                }

                true
            })
            .collect();

        let total_count = filtered_tasks.len() as u64;

        // 应用分页
        let offset = ((page - 1) * page_size) as usize;
        let end = std::cmp::min(offset + page_size as usize, filtered_tasks.len());
        let page_tasks = if offset < filtered_tasks.len() {
            filtered_tasks[offset..end].to_vec()
        } else {
            Vec::new()
        };

        Ok((page_tasks, total_count))
    }

    /// 获取分类统计信息
    pub async fn get_classification_stats(&self, project_id: Option<&str>) -> Result<ClassificationStats> {
        let conn = self.database.get_connection();
        let conn = conn.lock().unwrap();

        let (task_where_clause, record_where_clause) = if let Some(project_id) = project_id {
            (format!(" WHERE project_id = '{}'", project_id), format!(" WHERE project_id = '{}'", project_id))
        } else {
            ("".to_string(), "".to_string())
        };

        // 获取正确的状态JSON字符串
        let pending_json = serde_json::to_string(&TaskStatus::Pending)?;
        let uploading_json = serde_json::to_string(&TaskStatus::Uploading)?;
        let analyzing_json = serde_json::to_string(&TaskStatus::Analyzing)?;
        let completed_json = serde_json::to_string(&TaskStatus::Completed)?;
        let failed_json = serde_json::to_string(&TaskStatus::Failed)?;

        // 调试：查看数据库中实际的任务状态分布
        let debug_query = if let Some(project_id) = project_id {
            format!("SELECT status, COUNT(*) FROM video_classification_tasks WHERE project_id = '{}' GROUP BY status", project_id)
        } else {
            "SELECT status, COUNT(*) FROM video_classification_tasks GROUP BY status".to_string()
        };

        let mut debug_stmt = conn.prepare(&debug_query)?;
        let _debug_rows = debug_stmt.query_map([], |row| {
            Ok((row.get::<_, String>(0)?, row.get::<_, i32>(1)?))
        })?;

        // 获取任务统计
        let mut stmt = conn.prepare(&format!(
            "SELECT
                COUNT(*) as total,
                SUM(CASE WHEN status = ? THEN 1 ELSE 0 END) as pending,
                SUM(CASE WHEN status = ? OR status = ? THEN 1 ELSE 0 END) as processing,
                SUM(CASE WHEN status = ? THEN 1 ELSE 0 END) as completed,
                SUM(CASE WHEN status = ? THEN 1 ELSE 0 END) as failed
             FROM video_classification_tasks{}", task_where_clause
        ))?;

        let task_stats = stmt.query_row([&pending_json, &uploading_json, &analyzing_json, &completed_json, &failed_json], |row| {
            let total: i32 = row.get::<_, Option<i32>>(0)?.unwrap_or(0);
            let pending: i32 = row.get::<_, Option<i32>>(1)?.unwrap_or(0);
            let processing: i32 = row.get::<_, Option<i32>>(2)?.unwrap_or(0);
            let completed: i32 = row.get::<_, Option<i32>>(3)?.unwrap_or(0);
            let failed: i32 = row.get::<_, Option<i32>>(4)?.unwrap_or(0);
            Ok((total, pending, processing, completed, failed))
        })?;

        // 获取分类记录统计
        let mut stmt = conn.prepare(&format!(
            "SELECT 
                COUNT(*) as total,
                AVG(confidence) as avg_confidence,
                AVG(quality_score) as avg_quality
             FROM video_classification_records{}", record_where_clause
        ))?;

        let record_stats = stmt.query_row([], |row| {
            Ok((
                row.get::<_, Option<i32>>(0)?.unwrap_or(0),
                row.get::<_, Option<f64>>(1)?.unwrap_or(0.0),
                row.get::<_, Option<f64>>(2)?.unwrap_or(0.0),
            ))
        })?;

        // 获取分类记录状态统计
        let mut stmt = conn.prepare(&format!(
            "SELECT
                SUM(CASE WHEN status = ? THEN 1 ELSE 0 END) as classified,
                SUM(CASE WHEN status = ? THEN 1 ELSE 0 END) as failed,
                SUM(CASE WHEN status = ? THEN 1 ELSE 0 END) as needs_review
             FROM video_classification_records{}", record_where_clause
        ))?;

        let classified_json = serde_json::to_string(&ClassificationStatus::Classified).unwrap();
        let failed_json = serde_json::to_string(&ClassificationStatus::Failed).unwrap();
        let needs_review_json = serde_json::to_string(&ClassificationStatus::NeedsReview).unwrap();

        let record_status_stats = stmt.query_row([&classified_json, &failed_json, &needs_review_json], |row| {
            Ok((
                row.get::<_, Option<i32>>(0)?.unwrap_or(0),
                row.get::<_, Option<i32>>(1)?.unwrap_or(0),
                row.get::<_, Option<i32>>(2)?.unwrap_or(0),
            ))
        })?;

        Ok(ClassificationStats {
            total_tasks: task_stats.0,
            pending_tasks: task_stats.1,
            processing_tasks: task_stats.2,
            completed_tasks: task_stats.3,
            failed_tasks: task_stats.4,
            total_classifications: record_stats.0,
            successful_classifications: record_status_stats.0,
            failed_classifications: record_status_stats.1,
            needs_review_classifications: record_status_stats.2,
            average_confidence: record_stats.1,
            average_quality_score: record_stats.2,
        })
    }

    /// 检查片段是否已分类
    pub async fn is_segment_classified(&self, segment_id: &str) -> Result<bool> {
        let conn = self.database.get_connection();
        let conn = conn.lock().unwrap();

        let mut stmt = conn.prepare(
            "SELECT COUNT(*) FROM video_classification_records WHERE segment_id = ?1"
        )?;

        let count: i32 = stmt.query_row([segment_id], |row| row.get(0))?;
        Ok(count > 0)
    }

    /// 删除分类任务
    pub async fn delete_task(&self, task_id: &str) -> Result<()> {
        let conn = self.database.get_connection();
        let conn = conn.lock().unwrap();

        conn.execute("DELETE FROM video_classification_tasks WHERE id = ?1", [task_id])?;
        Ok(())
    }

    /// 恢复卡住的任务状态
    /// 将所有处理中的任务（Uploading, Analyzing）重置为Pending状态
    pub async fn recover_stuck_tasks(&self) -> Result<usize> {
        let conn = self.database.get_connection();
        let conn = conn.lock().unwrap();

        let uploading_json = serde_json::to_string(&TaskStatus::Uploading)?;
        let analyzing_json = serde_json::to_string(&TaskStatus::Analyzing)?;
        let pending_json = serde_json::to_string(&TaskStatus::Pending)?;

        println!("🔄 开始恢复卡住的任务状态...");

        // 查询卡住的任务
        let mut stmt = conn.prepare(
            "SELECT id, status FROM video_classification_tasks WHERE status = ? OR status = ?"
        )?;

        let stuck_tasks: Vec<(String, String)> = stmt.query_map([&uploading_json, &analyzing_json], |row| {
            Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
        })?.collect::<Result<Vec<_>, _>>()?;

        if stuck_tasks.is_empty() {
            println!("✅ 没有发现卡住的任务");
            return Ok(0);
        }

        println!("🔍 发现 {} 个卡住的任务:", stuck_tasks.len());
        for (id, status) in &stuck_tasks {
            println!("   任务ID: {}, 状态: {}", &id[..8], status);
        }

        // 重置任务状态
        let now_rfc3339 = chrono::Utc::now().to_rfc3339();
        let updated = conn.execute(
            "UPDATE video_classification_tasks
             SET status = ?, started_at = NULL, updated_at = ?
             WHERE status = ? OR status = ?",
            [&pending_json, &now_rfc3339, &uploading_json, &analyzing_json]
        )?;

        println!("✅ 已恢复 {} 个任务状态为Pending", updated);
        Ok(updated)
    }

    /// 修复数据库中的日期格式问题
    /// 将SQLite格式的日期转换为RFC3339格式
    pub async fn fix_date_formats(&self) -> Result<usize> {
        let conn = self.database.get_connection();
        let conn = conn.lock().unwrap();

        println!("🔧 开始修复数据库中的日期格式...");

        // 查询所有可能有问题的任务
        let mut stmt = conn.prepare(
            "SELECT id, created_at, updated_at FROM video_classification_tasks"
        )?;

        let rows: Vec<(String, String, String)> = stmt.query_map([], |row| {
            Ok((
                row.get::<_, String>(0)?,
                row.get::<_, String>(1)?,
                row.get::<_, String>(2)?,
            ))
        })?.collect::<Result<Vec<_>, _>>()?;

        let mut fixed_count = 0;

        for (id, created_at, updated_at) in rows {
            let mut needs_update = false;
            let mut new_created_at = created_at.clone();
            let mut new_updated_at = updated_at.clone();

            // 检查并修复created_at
            if chrono::DateTime::parse_from_rfc3339(&created_at).is_err() {
                // 尝试解析SQLite格式的日期
                if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(&created_at, "%Y-%m-%d %H:%M:%S") {
                    new_created_at = dt.and_utc().to_rfc3339();
                    needs_update = true;
                    println!("🔧 修复created_at: {} -> {}", created_at, new_created_at);
                }
            }

            // 检查并修复updated_at
            if chrono::DateTime::parse_from_rfc3339(&updated_at).is_err() {
                // 尝试解析SQLite格式的日期
                if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(&updated_at, "%Y-%m-%d %H:%M:%S") {
                    new_updated_at = dt.and_utc().to_rfc3339();
                    needs_update = true;
                    println!("🔧 修复updated_at: {} -> {}", updated_at, new_updated_at);
                }
            }

            // 更新记录
            if needs_update {
                conn.execute(
                    "UPDATE video_classification_tasks SET created_at = ?, updated_at = ? WHERE id = ?",
                    [&new_created_at, &new_updated_at, &id]
                )?;
                fixed_count += 1;
            }
        }

        println!("✅ 已修复 {} 个任务的日期格式", fixed_count);
        Ok(fixed_count)
    }

    /// 根据ID获取分类任务
    pub async fn get_task_by_id(&self, task_id: &str) -> Result<Option<VideoClassificationTask>> {
        let conn = self.database.get_connection();
        let conn = conn.lock().unwrap();

        let mut stmt = conn.prepare(
            "SELECT id, segment_id, material_id, project_id, video_file_path, status, priority,
                    retry_count, max_retries, gemini_file_uri, prompt_text, error_message,
                    started_at, completed_at, created_at, updated_at
             FROM video_classification_tasks WHERE id = ?1"
        )?;

        let mut rows = stmt.query_map([task_id], |row| {
            let status_json: String = row.get(5)?;
            let status: TaskStatus = serde_json::from_str(&status_json).unwrap_or_default();

            Ok(VideoClassificationTask {
                id: row.get(0)?,
                segment_id: row.get(1)?,
                material_id: row.get(2)?,
                project_id: row.get(3)?,
                video_file_path: row.get(4)?,
                status,
                priority: row.get(6)?,
                retry_count: row.get(7)?,
                max_retries: row.get(8)?,
                gemini_file_uri: row.get(9)?,
                prompt_text: row.get(10)?,
                error_message: row.get(11)?,
                started_at: row.get::<_, Option<String>>(12)?.and_then(|s| chrono::DateTime::parse_from_rfc3339(&s).ok()).map(|dt| dt.with_timezone(&Utc)),
                completed_at: row.get::<_, Option<String>>(13)?.and_then(|s| chrono::DateTime::parse_from_rfc3339(&s).ok()).map(|dt| dt.with_timezone(&Utc)),
                created_at: chrono::DateTime::parse_from_rfc3339(&row.get::<_, String>(14)?).map_err(|_e| rusqlite::Error::InvalidColumnType(14, "created_at".to_string(), rusqlite::types::Type::Text))?.with_timezone(&Utc),
                updated_at: chrono::DateTime::parse_from_rfc3339(&row.get::<_, String>(15)?).map_err(|_e| rusqlite::Error::InvalidColumnType(15, "updated_at".to_string(), rusqlite::types::Type::Text))?.with_timezone(&Utc),
            })
        })?;

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

    /// 根据ID获取分类任务
    pub async fn get_classification_task_by_id(&self, task_id: &str) -> Result<Option<VideoClassificationTask>> {
        self.get_task_by_id(task_id).await
    }
}
