//! ComfyUI V2 队列管理命令
//! 基于队列管理器的 Tauri 命令

use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tauri::State;
use tracing::{info, warn, error, debug};

use crate::app_state::AppState;
use crate::business::services::queue_manager::{
    QueueManager, QueueTask, QueueConfig, QueueStatistics, QueueEvent,
    TaskPriority, TaskType, QueueTaskStatus,
};
use crate::data::models::comfyui::ParameterValues;

// ==================== 请求和响应类型 ====================

/// 添加任务请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AddTaskRequest {
    pub task_type: String, // "workflow" | "template" | "batch"
    pub workflow_id: Option<String>,
    pub template_id: Option<String>,
    pub priority: Option<String>, // "low" | "normal" | "high" | "urgent"
    pub parameters: Option<ParameterValues>,
    pub estimated_duration: Option<u64>,
    pub max_retries: Option<u32>,
    pub tags: Option<Vec<String>>,
    pub user_id: Option<String>,
}

/// 队列任务响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueueTaskResponse {
    pub id: String,
    pub execution_id: Option<String>,
    pub workflow_id: Option<String>,
    pub template_id: Option<String>,
    pub task_type: String,
    pub priority: String,
    pub parameters: Option<ParameterValues>,
    pub created_at: String,
    pub estimated_duration: Option<u64>,
    pub retry_count: u32,
    pub max_retries: u32,
    pub status: String,
    pub tags: Vec<String>,
    pub user_id: Option<String>,
}

/// 队列统计响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueueStatisticsResponse {
    pub total_tasks: u64,
    pub pending_tasks: u32,
    pub running_tasks: u32,
    pub completed_tasks: u64,
    pub failed_tasks: u64,
    pub average_wait_time: f64,
    pub average_execution_time: f64,
    pub throughput: f64,
    pub by_priority: HashMap<String, u32>,
    pub by_type: HashMap<String, u32>,
}

/// 队列配置请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueueConfigRequest {
    pub max_queue_size: Option<usize>,
    pub max_concurrent_executions: Option<u32>,
    pub task_timeout_seconds: Option<u64>,
    pub queue_check_interval_seconds: Option<u64>,
    pub enable_priority_scheduling: Option<bool>,
    pub enable_auto_retry: Option<bool>,
    pub default_max_retries: Option<u32>,
}

/// 批量操作请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchOperationRequest {
    pub task_ids: Vec<String>,
    pub operation: String, // "cancel" | "retry" | "priority_change"
    pub new_priority: Option<String>,
}

/// 队列事件响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueueEventResponse {
    pub event_type: String,
    pub data: serde_json::Value,
    pub timestamp: String,
}

// ==================== 队列管理命令 ====================

/// 启动队列管理器
#[tauri::command]
pub async fn comfyui_v2_start_queue_manager(
    config: Option<QueueConfigRequest>,
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("Command: comfyui_v2_start_queue_manager");

    // TODO: 从应用状态获取或创建队列管理器
    Ok("队列管理器已启动".to_string())
}

/// 停止队列管理器
#[tauri::command]
pub async fn comfyui_v2_stop_queue_manager(
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("Command: comfyui_v2_stop_queue_manager");

    // TODO: 停止队列管理器
    Ok("队列管理器已停止".to_string())
}

/// 添加任务到队列
#[tauri::command]
pub async fn comfyui_v2_add_task_to_queue(
    request: AddTaskRequest,
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("Command: comfyui_v2_add_task_to_queue");

    // 转换任务类型
    let task_type = match request.task_type.as_str() {
        "workflow" => TaskType::WorkflowExecution,
        "template" => TaskType::TemplateExecution,
        "batch" => TaskType::BatchExecution,
        _ => return Err("无效的任务类型".to_string()),
    };

    // 转换优先级
    let priority = match request.priority.as_deref() {
        Some("low") => TaskPriority::Low,
        Some("normal") => TaskPriority::Normal,
        Some("high") => TaskPriority::High,
        Some("urgent") => TaskPriority::Urgent,
        _ => TaskPriority::Normal,
    };

    // 创建队列任务
    let task = QueueTask {
        id: String::new(), // 将由队列管理器生成
        execution_id: None,
        workflow_id: request.workflow_id,
        template_id: request.template_id,
        task_type,
        priority,
        parameters: request.parameters,
        created_at: chrono::Utc::now(),
        estimated_duration: request.estimated_duration,
        retry_count: 0,
        max_retries: request.max_retries.unwrap_or(3),
        status: QueueTaskStatus::Pending,
        tags: request.tags.unwrap_or_default(),
        user_id: request.user_id,
    };

    // TODO: 添加到队列管理器
    let task_id = uuid::Uuid::new_v4().to_string();
    Ok(task_id)
}

/// 取消队列中的任务
#[tauri::command]
pub async fn comfyui_v2_cancel_queue_task(
    task_id: String,
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("Command: comfyui_v2_cancel_queue_task - {}", task_id);

    // TODO: 从队列管理器取消任务
    Ok("任务已取消".to_string())
}

/// 获取队列状态 (简化版本，用于前端)
#[tauri::command]
pub async fn comfyui_v2_get_queue_status(
    state: State<'_, AppState>,
) -> Result<serde_json::Value, String> {
    info!("Command: comfyui_v2_get_queue_status");

    let service_manager = state.get_comfyui_manager().await
        .map_err(|e| format!("获取ComfyUI管理器失败: {}", e))?;

    let comfyui_manager = service_manager.get_comfyui_manager().await
        .map_err(|e| format!("获取ComfyUI管理器失败: {}", e))?;

    match comfyui_manager.get_queue_status().await {
        Ok(status) => {
            // 返回前端期望的简单格式
            Ok(serde_json::json!({
                "running_count": status.queue_running.len(),
                "pending_count": status.queue_pending.len(),
                "history_count": 0 // TODO: 从历史记录获取
            }))
        },
        Err(e) => {
            error!("获取队列状态失败: {}", e);
            Err(format!("获取队列状态失败: {}", e))
        }
    }
}

/// 获取队列中的任务列表
#[tauri::command]
pub async fn comfyui_v2_list_queue_tasks(
    status_filter: Option<String>,
    priority_filter: Option<String>,
    limit: Option<u32>,
    state: State<'_, AppState>,
) -> Result<Vec<QueueTaskResponse>, String> {
    info!("Command: comfyui_v2_list_queue_tasks");

    // TODO: 从队列管理器获取任务列表
    Ok(Vec::new())
}

/// 获取单个队列任务详情
#[tauri::command]
pub async fn comfyui_v2_get_queue_task(
    task_id: String,
    state: State<'_, AppState>,
) -> Result<QueueTaskResponse, String> {
    info!("Command: comfyui_v2_get_queue_task - {}", task_id);

    // TODO: 从队列管理器获取任务详情
    Err("任务不存在".to_string())
}

/// 修改任务优先级
#[tauri::command]
pub async fn comfyui_v2_change_task_priority(
    task_id: String,
    new_priority: String,
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("Command: comfyui_v2_change_task_priority - {} -> {}", task_id, new_priority);

    // TODO: 修改任务优先级
    Ok("任务优先级已修改".to_string())
}

/// 重试失败的任务
#[tauri::command]
pub async fn comfyui_v2_retry_failed_task(
    task_id: String,
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("Command: comfyui_v2_retry_failed_task - {}", task_id);

    // TODO: 重试任务
    Ok("任务已重新加入队列".to_string())
}

/// 批量操作队列任务
#[tauri::command]
pub async fn comfyui_v2_batch_queue_operation(
    request: BatchOperationRequest,
    state: State<'_, AppState>,
) -> Result<Vec<String>, String> {
    info!("Command: comfyui_v2_batch_queue_operation - {} 个任务", request.task_ids.len());

    // TODO: 执行批量操作
    let results = request.task_ids.iter()
        .map(|id| format!("操作成功: {}", id))
        .collect();

    Ok(results)
}

/// 清理已完成的任务
#[tauri::command]
pub async fn comfyui_v2_cleanup_completed_tasks(
    older_than_hours: Option<u32>,
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("Command: comfyui_v2_cleanup_completed_tasks");

    // TODO: 清理已完成的任务
    Ok("已完成任务清理完成".to_string())
}

/// 获取队列性能指标
#[tauri::command]
pub async fn comfyui_v2_get_queue_metrics(
    time_range_hours: Option<u32>,
    state: State<'_, AppState>,
) -> Result<serde_json::Value, String> {
    info!("Command: comfyui_v2_get_queue_metrics");

    // TODO: 获取性能指标
    Ok(serde_json::json!({
        "throughput": 0.0,
        "average_wait_time": 0.0,
        "average_execution_time": 0.0,
        "success_rate": 0.0,
        "queue_utilization": 0.0
    }))
}

/// 暂停队列处理
#[tauri::command]
pub async fn comfyui_v2_pause_queue(
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("Command: comfyui_v2_pause_queue");

    // TODO: 暂停队列
    Ok("队列已暂停".to_string())
}

/// 恢复队列处理
#[tauri::command]
pub async fn comfyui_v2_resume_queue(
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("Command: comfyui_v2_resume_queue");

    // TODO: 恢复队列
    Ok("队列已恢复".to_string())
}

/// 订阅队列事件
#[tauri::command]
pub async fn comfyui_v2_subscribe_queue_events(
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("Command: comfyui_v2_subscribe_queue_events");

    // TODO: 订阅队列事件
    Ok("已订阅队列事件".to_string())
}

// ==================== 辅助函数 ====================

/// 转换队列任务为响应
fn convert_queue_task(task: &QueueTask) -> QueueTaskResponse {
    QueueTaskResponse {
        id: task.id.clone(),
        execution_id: task.execution_id.clone(),
        workflow_id: task.workflow_id.clone(),
        template_id: task.template_id.clone(),
        task_type: match task.task_type {
            TaskType::WorkflowExecution => "workflow".to_string(),
            TaskType::TemplateExecution => "template".to_string(),
            TaskType::BatchExecution => "batch".to_string(),
        },
        priority: task.priority.to_string(),
        parameters: task.parameters.clone(),
        created_at: task.created_at.to_rfc3339(),
        estimated_duration: task.estimated_duration,
        retry_count: task.retry_count,
        max_retries: task.max_retries,
        status: match task.status {
            QueueTaskStatus::Pending => "pending".to_string(),
            QueueTaskStatus::Scheduled => "scheduled".to_string(),
            QueueTaskStatus::Running => "running".to_string(),
            QueueTaskStatus::Completed => "completed".to_string(),
            QueueTaskStatus::Failed => "failed".to_string(),
            QueueTaskStatus::Cancelled => "cancelled".to_string(),
            QueueTaskStatus::Paused => "paused".to_string(),
        },
        tags: task.tags.clone(),
        user_id: task.user_id.clone(),
    }
}

/// 转换队列统计为响应
fn convert_queue_statistics(stats: &QueueStatistics) -> QueueStatisticsResponse {
    QueueStatisticsResponse {
        total_tasks: stats.total_tasks,
        pending_tasks: stats.pending_tasks,
        running_tasks: stats.running_tasks,
        completed_tasks: stats.completed_tasks,
        failed_tasks: stats.failed_tasks,
        average_wait_time: stats.average_wait_time,
        average_execution_time: stats.average_execution_time,
        throughput: stats.throughput,
        by_priority: stats.by_priority.clone(),
        by_type: stats.by_type.clone(),
    }
}

/// 转换队列事件为响应
fn convert_queue_event(event: &QueueEvent) -> QueueEventResponse {
    let (event_type, data) = match event {
        QueueEvent::TaskAdded { task_id, priority, timestamp } => (
            "task_added".to_string(),
            serde_json::json!({
                "task_id": task_id,
                "priority": priority.to_string(),
                "timestamp": timestamp
            })
        ),
        QueueEvent::TaskStarted { task_id, execution_id, timestamp } => (
            "task_started".to_string(),
            serde_json::json!({
                "task_id": task_id,
                "execution_id": execution_id,
                "timestamp": timestamp
            })
        ),
        QueueEvent::TaskCompleted { task_id, execution_id, execution_time, timestamp } => (
            "task_completed".to_string(),
            serde_json::json!({
                "task_id": task_id,
                "execution_id": execution_id,
                "execution_time": execution_time,
                "timestamp": timestamp
            })
        ),
        QueueEvent::TaskFailed { task_id, execution_id, error, timestamp } => (
            "task_failed".to_string(),
            serde_json::json!({
                "task_id": task_id,
                "execution_id": execution_id,
                "error": error,
                "timestamp": timestamp
            })
        ),
        QueueEvent::TaskCancelled { task_id, timestamp } => (
            "task_cancelled".to_string(),
            serde_json::json!({
                "task_id": task_id,
                "timestamp": timestamp
            })
        ),
        QueueEvent::QueueStatusUpdated { pending_count, running_count, timestamp } => (
            "queue_status_updated".to_string(),
            serde_json::json!({
                "pending_count": pending_count,
                "running_count": running_count,
                "timestamp": timestamp
            })
        ),
    };

    QueueEventResponse {
        event_type,
        data,
        timestamp: chrono::Utc::now().to_rfc3339(),
    }
}
