use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use anyhow::Result;
use tracing::{info, debug};

use crate::data::models::watermark::{BatchWatermarkTask, BatchTaskStatus, BatchProgress};

/// 任务状态管理器
/// 用于跟踪批量水印处理任务的状态
pub struct TaskManager {
    tasks: Arc<Mutex<HashMap<String, BatchWatermarkTask>>>,
}

impl TaskManager {
    /// 创建新的任务管理器
    pub fn new() -> Self {
        Self {
            tasks: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    /// 添加任务
    pub fn add_task(&self, task: BatchWatermarkTask) -> Result<()> {
        let mut tasks = self.tasks.lock().unwrap();
        debug!(task_id = %task.task_id, "添加任务到管理器");
        tasks.insert(task.task_id.clone(), task);
        Ok(())
    }

    /// 获取任务状态
    pub fn get_task(&self, task_id: &str) -> Option<BatchWatermarkTask> {
        let tasks = self.tasks.lock().unwrap();
        tasks.get(task_id).cloned()
    }

    /// 更新任务状态
    pub fn update_task_status(&self, task_id: &str, status: BatchTaskStatus) -> Result<()> {
        let mut tasks = self.tasks.lock().unwrap();
        if let Some(task) = tasks.get_mut(task_id) {
            task.status = status.clone();
            task.updated_at = chrono::Utc::now();
            
            // 如果任务开始运行，设置开始时间
            if status == BatchTaskStatus::Running && task.started_at.is_none() {
                task.started_at = Some(chrono::Utc::now());
            }
            
            // 如果任务完成，设置完成时间
            if matches!(status, BatchTaskStatus::Completed | BatchTaskStatus::Failed | BatchTaskStatus::Cancelled) {
                task.completed_at = Some(chrono::Utc::now());
            }
            
            debug!(task_id = %task_id, status = ?status, "更新任务状态");
            Ok(())
        } else {
            Err(anyhow::anyhow!("任务不存在: {}", task_id))
        }
    }

    /// 更新任务进度
    pub fn update_task_progress(&self, task_id: &str, progress: BatchProgress) -> Result<()> {
        let mut tasks = self.tasks.lock().unwrap();
        if let Some(task) = tasks.get_mut(task_id) {
            task.progress = progress;
            task.updated_at = chrono::Utc::now();
            debug!(
                task_id = %task_id, 
                processed = task.progress.processed_items,
                total = task.progress.total_items,
                percentage = task.progress.progress_percentage,
                "更新任务进度"
            );
            Ok(())
        } else {
            Err(anyhow::anyhow!("任务不存在: {}", task_id))
        }
    }

    /// 移除任务
    pub fn remove_task(&self, task_id: &str) -> Option<BatchWatermarkTask> {
        let mut tasks = self.tasks.lock().unwrap();
        let removed = tasks.remove(task_id);
        if removed.is_some() {
            debug!(task_id = %task_id, "从管理器中移除任务");
        }
        removed
    }

    /// 获取所有任务
    pub fn get_all_tasks(&self) -> Vec<BatchWatermarkTask> {
        let tasks = self.tasks.lock().unwrap();
        tasks.values().cloned().collect()
    }

    /// 获取运行中的任务数量
    pub fn get_running_task_count(&self) -> usize {
        let tasks = self.tasks.lock().unwrap();
        tasks.values().filter(|task| task.status == BatchTaskStatus::Running).count()
    }

    /// 清理已完成的任务（超过指定时间）
    pub fn cleanup_completed_tasks(&self, max_age_hours: u64) -> usize {
        let mut tasks = self.tasks.lock().unwrap();
        let cutoff_time = chrono::Utc::now() - chrono::Duration::hours(max_age_hours as i64);
        
        let initial_count = tasks.len();
        tasks.retain(|_, task| {
            // 保留未完成的任务或最近完成的任务
            !matches!(task.status, BatchTaskStatus::Completed | BatchTaskStatus::Failed | BatchTaskStatus::Cancelled)
                || task.completed_at.map_or(true, |completed| completed > cutoff_time)
        });
        
        let removed_count = initial_count - tasks.len();
        if removed_count > 0 {
            info!(removed_count = removed_count, "清理已完成的任务");
        }
        removed_count
    }

    /// 取消任务
    pub fn cancel_task(&self, task_id: &str) -> Result<()> {
        self.update_task_status(task_id, BatchTaskStatus::Cancelled)
    }

    /// 暂停任务
    pub fn pause_task(&self, task_id: &str) -> Result<()> {
        self.update_task_status(task_id, BatchTaskStatus::Paused)
    }

    /// 恢复任务
    pub fn resume_task(&self, task_id: &str) -> Result<()> {
        self.update_task_status(task_id, BatchTaskStatus::Running)
    }
}

impl Default for TaskManager {
    fn default() -> Self {
        Self::new()
    }
}

// 全局任务管理器实例
lazy_static::lazy_static! {
    pub static ref TASK_MANAGER: TaskManager = TaskManager::new();
}
