use crate::data::models::video_classification::*;
use crate::business::services::video_classification_service::VideoClassificationService;
use anyhow::{Result, anyhow};
use std::sync::Arc;
use tokio::sync::{Mutex, RwLock};
use tokio::time::{sleep, Duration};
use std::collections::{HashMap, HashSet};


/// 队列状态
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum QueueStatus {
    Stopped,
    Running,
    Paused,
}

/// 队列统计信息
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct QueueStats {
    pub status: QueueStatus,
    pub total_tasks: usize,
    pub pending_tasks: usize,
    pub processing_tasks: usize,
    pub completed_tasks: usize,
    pub failed_tasks: usize,
    pub current_task_id: Option<String>,
    pub processing_rate: f64, // 任务/分钟
}

/// 任务进度信息
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TaskProgress {
    pub task_id: String,
    pub status: TaskStatus,
    pub progress_percentage: f64,
    pub current_step: String,
    pub error_message: Option<String>,
    pub started_at: Option<chrono::DateTime<chrono::Utc>>,
    pub estimated_completion: Option<chrono::DateTime<chrono::Utc>>,
}

/// AI视频分类任务队列
/// 遵循 Tauri 开发规范的业务层设计模式
pub struct VideoClassificationQueue {
    pub service: Arc<VideoClassificationService>,
    status: Arc<RwLock<QueueStatus>>,
    current_tasks: Arc<RwLock<HashSet<String>>>,
    task_progress: Arc<RwLock<HashMap<String, TaskProgress>>>,
    stats: Arc<RwLock<QueueStats>>,
    max_concurrent_tasks: usize,
    processing_delay: Duration,
    worker_handles: Arc<Mutex<Vec<tokio::task::JoinHandle<()>>>>,
}

impl VideoClassificationQueue {
    /// 创建新的任务队列
    pub fn new(service: Arc<VideoClassificationService>) -> Self {
        // 根据系统资源动态调整并发数，但最大不超过10
        let max_concurrent_tasks = Self::calculate_optimal_concurrency();

        Self {
            service,
            status: Arc::new(RwLock::new(QueueStatus::Stopped)),
            current_tasks: Arc::new(RwLock::new(HashSet::new())),
            task_progress: Arc::new(RwLock::new(HashMap::new())),
            stats: Arc::new(RwLock::new(QueueStats {
                status: QueueStatus::Stopped,
                total_tasks: 0,
                pending_tasks: 0,
                processing_tasks: 0,
                completed_tasks: 0,
                failed_tasks: 0,
                current_task_id: None,
                processing_rate: 0.0,
            })),
            max_concurrent_tasks,
            processing_delay: Duration::from_millis(500), // 减少任务间延迟
            worker_handles: Arc::new(Mutex::new(Vec::new())),
        }
    }

    /// 计算最优并发数
    fn calculate_optimal_concurrency() -> usize {
        // 获取CPU核心数
        let cpu_cores = std::thread::available_parallelism()
            .map(|n| n.get())
            .unwrap_or(4); // 默认4核

        // 考虑到AI分类任务主要是I/O密集型（网络请求），可以设置更高的并发数
        // 但限制在10以内以避免过度消耗资源
        let optimal = std::cmp::min(cpu_cores * 2, 80);

        println!("🔧 检测到 {} 个CPU核心，设置AI视频分类并发数为: {}", cpu_cores, optimal);
        optimal
    }

    /// 启动队列处理
    pub async fn start(&self) -> Result<()> {
        let mut status = self.status.write().await;
        if *status == QueueStatus::Running {
            return Err(anyhow!("队列已经在运行中"));
        }
        
        *status = QueueStatus::Running;
        drop(status);

        // 修复数据库中的日期格式问题
        match self.service.fix_date_formats().await {
            Ok(fixed_count) => {
                if fixed_count > 0 {
                    println!("🔧 队列启动时修复了 {} 个任务的日期格式", fixed_count);
                }
            }
            Err(e) => {
                println!("⚠️ 修复日期格式时出错: {}", e);
            }
        }

        // 恢复卡住的任务状态
        match self.service.recover_stuck_tasks().await {
            Ok(recovered_count) => {
                if recovered_count > 0 {
                    println!("🔄 队列启动时恢复了 {} 个卡住的任务", recovered_count);
                }
            }
            Err(e) => {
                println!("⚠️ 恢复卡住任务时出错: {}", e);
            }
        }

        // 更新统计信息
        self.update_stats().await?;

        // 启动多个并发处理worker
        self.start_workers().await?;

        println!("AI视频分类队列已启动");
        Ok(())
    }

    /// 停止队列处理
    pub async fn stop(&self) -> Result<()> {
        let mut status = self.status.write().await;
        *status = QueueStatus::Stopped;
        drop(status);

        // 等待所有worker完成
        self.stop_workers().await;

        // 更新统计信息
        self.update_stats().await?;

        println!("AI视频分类队列已停止");
        Ok(())
    }

    /// 暂停队列处理
    pub async fn pause(&self) -> Result<()> {
        let mut status = self.status.write().await;
        if *status != QueueStatus::Running {
            return Err(anyhow!("队列未在运行中"));
        }
        
        *status = QueueStatus::Paused;
        
        // 更新统计信息
        self.update_stats().await?;
        
        println!("AI视频分类队列已暂停");
        Ok(())
    }

    /// 恢复队列处理
    pub async fn resume(&self) -> Result<()> {
        let mut status = self.status.write().await;
        if *status != QueueStatus::Paused {
            return Err(anyhow!("队列未处于暂停状态"));
        }
        
        *status = QueueStatus::Running;
        
        // 更新统计信息
        self.update_stats().await?;
        
        println!("AI视频分类队列已恢复");
        Ok(())
    }

    /// 添加批量分类任务到队列
    pub async fn add_batch_tasks(&self, request: BatchClassificationRequest) -> Result<Vec<String>> {
        let tasks = self.service.create_batch_classification_tasks(request).await?;
        let task_ids: Vec<String> = tasks.iter().map(|t| t.id.clone()).collect();
        
        // 初始化任务进度
        let mut progress_map = self.task_progress.write().await;
        for task in &tasks {
            progress_map.insert(task.id.clone(), TaskProgress {
                task_id: task.id.clone(),
                status: TaskStatus::Pending,
                progress_percentage: 0.0,
                current_step: "等待处理".to_string(),
                error_message: None,
                started_at: None,
                estimated_completion: None,
            });
        }
        
        // 更新统计信息
        self.update_stats().await?;
        
        println!("已添加 {} 个分类任务到队列", tasks.len());
        Ok(task_ids)
    }

    /// 获取队列统计信息
    pub async fn get_stats(&self) -> QueueStats {
        self.stats.read().await.clone()
    }

    /// 获取项目的队列统计信息
    pub async fn get_project_stats(&self, project_id: &str) -> Result<QueueStats> {
        let status = self.status.read().await.clone();
        let current_tasks = self.current_tasks.read().await;
        let current_task = if current_tasks.is_empty() {
            None
        } else {
            current_tasks.iter().next().cloned()
        };

        // 获取项目特定的分类统计
        let classification_stats = self.service.get_classification_stats(Some(project_id)).await?;

        Ok(QueueStats {
            status,
            total_tasks: classification_stats.total_tasks as usize,
            pending_tasks: classification_stats.pending_tasks as usize,
            processing_tasks: classification_stats.processing_tasks as usize,
            completed_tasks: classification_stats.completed_tasks as usize,
            failed_tasks: classification_stats.failed_tasks as usize,
            current_task_id: current_task,
            processing_rate: self.stats.read().await.processing_rate, // 保持全局处理速率
        })
    }

    /// 获取任务进度
    pub async fn get_task_progress(&self, task_id: &str) -> Option<TaskProgress> {
        self.task_progress.read().await.get(task_id).cloned()
    }

    /// 获取所有任务进度
    pub async fn get_all_task_progress(&self) -> HashMap<String, TaskProgress> {
        self.task_progress.read().await.clone()
    }

    /// 获取项目的任务进度
    pub async fn get_project_task_progress(&self, _project_id: &str) -> HashMap<String, TaskProgress> {
        // 暂时返回所有任务进度，后续可以通过数据库查询来过滤项目相关任务
        // TODO: 实现真正的项目过滤逻辑
        self.task_progress.read().await.clone()
    }

    /// 启动多个worker进行并发处理
    async fn start_workers(&self) -> Result<()> {
        let mut handles = self.worker_handles.lock().await;

        // 启动处理worker
        for worker_id in 0..self.max_concurrent_tasks {
            let queue_clone = self.clone_for_processing();
            let handle = tokio::spawn(async move {
                queue_clone.worker_loop(worker_id).await;
            });
            handles.push(handle);
        }

        // 启动统计更新worker
        let stats_queue_clone = self.clone_for_processing();
        let stats_handle = tokio::spawn(async move {
            stats_queue_clone.stats_update_loop().await;
        });
        handles.push(stats_handle);

        println!("🚀 启动了 {} 个并发处理worker + 1个统计更新worker", self.max_concurrent_tasks);
        Ok(())
    }

    /// 停止所有worker
    async fn stop_workers(&self) {
        let mut handles = self.worker_handles.lock().await;

        // 等待所有worker完成
        for handle in handles.drain(..) {
            if !handle.is_finished() {
                let _ = handle.await;
            }
        }

        println!("🛑 所有worker已停止");
    }

    /// Worker处理循环 - 每个worker独立运行
    async fn worker_loop(&self, worker_id: usize) {
        println!("🔧 Worker {} 启动", worker_id);
        let mut completed_count = 0;
        let mut error_count = 0;
        let max_consecutive_errors = 5; // 最大连续错误次数

        loop {
            let status = self.status.read().await.clone();

            match status {
                QueueStatus::Stopped => {
                    println!("🛑 Worker {} 收到停止信号", worker_id);
                    break;
                }
                QueueStatus::Paused => {
                    sleep(Duration::from_secs(1)).await;
                    continue;
                }
                QueueStatus::Running => {
                    // 检查错误计数，如果连续错误过多则暂停该worker
                    if error_count >= max_consecutive_errors {
                        println!("⚠️ Worker {} 连续错误过多，暂停30秒", worker_id);
                        sleep(Duration::from_secs(30)).await;
                        error_count = 0; // 重置错误计数
                        continue;
                    }

                    // 尝试获取并处理下一个任务
                    match self.try_process_next_task(worker_id).await {
                        Ok(Some(_)) => {
                            completed_count += 1;
                            error_count = 0; // 成功处理任务，重置错误计数
                            println!("✅ Worker {} 完成任务 #{}", worker_id, completed_count);

                            // 任务间短暂延迟
                            sleep(self.processing_delay).await;
                        }
                        Ok(None) => {
                            // 没有可用任务，等待一段时间
                            sleep(Duration::from_secs(2)).await;
                        }
                        Err(e) => {
                            error_count += 1;
                            println!("❌ Worker {} 处理任务时发生错误 ({}/{}): {}",
                                worker_id, error_count, max_consecutive_errors, e);

                            // 根据错误次数调整等待时间
                            let wait_time = std::cmp::min(error_count * 2, 30);
                            sleep(Duration::from_secs(wait_time as u64)).await;
                        }
                    }
                }
            }
        }

        println!("🔧 Worker {} 已退出，共完成 {} 个任务，发生 {} 次错误",
            worker_id, completed_count, error_count);
    }

    /// 统计信息更新循环
    async fn stats_update_loop(&self) {
        println!("📊 统计更新worker启动");

        loop {
            let status = self.status.read().await.clone();

            if status == QueueStatus::Stopped {
                break;
            }

            // 定期更新统计信息
            if let Err(e) = self.update_stats().await {
                println!("⚠️ 更新统计信息失败: {}", e);
            }

            // 每5秒更新一次统计信息
            sleep(Duration::from_secs(5)).await;
        }

        println!("📊 统计更新worker已退出");
    }

    /// 检查是否应该自动停止队列
    /// 当等待中=0且处理中=0时，说明没有任务需要处理
    async fn check_should_auto_stop(&self) -> Result<bool> {
        // 获取当前统计信息
        let stats = self.stats.read().await;

        // 检查是否有待处理或正在处理的任务
        let has_pending = stats.pending_tasks > 0;
        let has_processing = stats.processing_tasks > 0;
        let has_current_tasks = !self.current_tasks.read().await.is_empty();

        // 如果没有待处理、没有正在处理、也没有当前任务，则可以停止
        let should_stop = !has_pending && !has_processing && !has_current_tasks;

        if should_stop {
            println!("📊 队列状态检查:");
            println!("   等待中任务: {}", stats.pending_tasks);
            println!("   处理中任务: {}", stats.processing_tasks);
            println!("   当前任务: {}", if has_current_tasks { "有" } else { "无" });
            println!("   结论: 没有任务需要处理，准备自动停止");
        }

        Ok(should_stop)
    }

    /// 尝试获取并处理下一个任务（支持并发）
    async fn try_process_next_task(&self, worker_id: usize) -> Result<Option<String>> {
        // 检查当前正在处理的任务数量
        let current_tasks_count = self.current_tasks.read().await.len();
        if current_tasks_count >= self.max_concurrent_tasks {
            return Ok(None); // 已达到最大并发数
        }

        // 获取待处理任务
        let pending_tasks = self.service.get_pending_tasks(Some(1)).await?;

        if let Some(task) = pending_tasks.first() {
            let task_id = task.id.clone();

            // 尝试将任务添加到当前处理列表（原子操作）
            {
                let mut current_tasks = self.current_tasks.write().await;
                if current_tasks.contains(&task_id) {
                    // 任务已被其他worker获取
                    return Ok(None);
                }
                current_tasks.insert(task_id.clone());
            }

            println!("📋 Worker {} 获取任务: {}", worker_id, task_id);
            println!("📁 任务视频文件: {}", task.video_file_path);

            // 更新任务进度
            self.update_task_progress(&task_id, TaskStatus::Uploading, 10.0, "开始处理").await;

            let task_start_time = std::time::Instant::now();

            // 处理任务
            println!("🚀 Worker {} 开始处理分类任务: {}", worker_id, task_id);
            let result = match tokio::time::timeout(
                Duration::from_secs(300), // 5分钟超时
                self.service.process_classification_task(&task_id)
            ).await {
                Ok(Ok(_)) => {
                    let task_duration = task_start_time.elapsed();
                    self.update_task_progress(&task_id, TaskStatus::Completed, 100.0, "处理完成").await;
                    println!("✅ Worker {} 任务处理成功: {} (耗时: {:?})", worker_id, task_id, task_duration);
                    Ok(Some(task_id.clone()))
                }
                Ok(Err(e)) => {
                    let task_duration = task_start_time.elapsed();
                    self.update_task_progress_with_error(&task_id, TaskStatus::Failed, e.to_string()).await;
                    println!("❌ Worker {} 任务处理失败: {} - {} (耗时: {:?})", worker_id, task_id, e, task_duration);
                    Err(e)
                }
                Err(_) => {
                    let task_duration = task_start_time.elapsed();
                    let timeout_error = anyhow!("任务处理超时 (5分钟)");
                    self.update_task_progress_with_error(&task_id, TaskStatus::Failed, timeout_error.to_string()).await;
                    println!("⏰ Worker {} 任务处理超时: {} (耗时: {:?})", worker_id, task_id, task_duration);
                    Err(timeout_error)
                }
            };

            // 从当前任务列表中移除
            {
                let mut current_tasks = self.current_tasks.write().await;
                current_tasks.remove(&task_id);
                println!("🔄 Worker {} 完成任务: {}", worker_id, task_id);
            }

            result
        } else {
            Ok(None) // 没有待处理任务
        }
    }

    /// 更新任务进度
    async fn update_task_progress(&self, task_id: &str, status: TaskStatus, progress: f64, step: &str) {
        let mut progress_map = self.task_progress.write().await;
        if let Some(task_progress) = progress_map.get_mut(task_id) {
            task_progress.status = status;
            task_progress.progress_percentage = progress;
            task_progress.current_step = step.to_string();
            
            if task_progress.started_at.is_none() && progress > 0.0 {
                task_progress.started_at = Some(chrono::Utc::now());
            }
        }
    }

    /// 更新任务进度（带错误信息）
    async fn update_task_progress_with_error(&self, task_id: &str, status: TaskStatus, error: String) {
        let mut progress_map = self.task_progress.write().await;
        if let Some(task_progress) = progress_map.get_mut(task_id) {
            task_progress.status = status;
            task_progress.error_message = Some(error);
            task_progress.current_step = "处理失败".to_string();
        }
    }

    /// 更新统计信息
    async fn update_stats(&self) -> Result<()> {
        let status = self.status.read().await.clone();
        let current_tasks = self.current_tasks.read().await;
        let current_task_id = if current_tasks.is_empty() {
            None
        } else {
            current_tasks.iter().next().cloned()
        };

        // 获取分类统计
        let classification_stats = self.service.get_classification_stats(None).await?;

        let mut stats = self.stats.write().await;
        stats.status = status;
        stats.total_tasks = classification_stats.total_tasks as usize;
        stats.pending_tasks = classification_stats.pending_tasks as usize;
        stats.processing_tasks = classification_stats.processing_tasks as usize;
        stats.completed_tasks = classification_stats.completed_tasks as usize;
        stats.failed_tasks = classification_stats.failed_tasks as usize;
        stats.current_task_id = current_task_id;

        Ok(())
    }

    /// 克隆用于处理的实例
    fn clone_for_processing(&self) -> Self {
        Self {
            service: Arc::clone(&self.service),
            status: Arc::clone(&self.status),
            current_tasks: Arc::clone(&self.current_tasks),
            task_progress: Arc::clone(&self.task_progress),
            stats: Arc::clone(&self.stats),
            max_concurrent_tasks: self.max_concurrent_tasks,
            processing_delay: self.processing_delay,
            worker_handles: Arc::new(Mutex::new(Vec::new())),
        }
    }
}
