//! ComfyUI V2 执行管理命令
//! 基于新的执行引擎的 Tauri 命令

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

use crate::app_state::AppState;
use crate::business::services::execution_engine::{
    ExecutionEngine, ExecutionResult, ExecutionConfig, ExecutionStats
};
use crate::business::services::realtime_monitor::{RealtimeMonitor, RealtimeEvent, MonitorStats};
use crate::data::models::comfyui::{ExecutionStatus, ParameterValues};

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

/// 工作流执行请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecuteWorkflowRequest {
    pub workflow_id: String,
    pub parameters: Option<ParameterValues>,
    pub timeout_seconds: Option<u64>,
    pub priority: Option<i32>,
    pub wait_for_completion: Option<bool>,
}

/// 模板执行请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecuteTemplateRequest {
    pub template_id: String,
    pub parameters: ParameterValues,
    pub timeout_seconds: Option<u64>,
    pub priority: Option<i32>,
    pub wait_for_completion: Option<bool>,
}

/// 执行响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionResponse {
    pub execution_id: String,
    pub prompt_id: String,
    pub status: String,
    pub output_urls: Vec<String>,
    pub node_outputs: Option<HashMap<String, serde_json::Value>>,
    pub execution_time: Option<u64>,
    pub error_message: Option<String>,
    pub created_at: Option<String>,
    pub completed_at: Option<String>,
}

/// 执行历史查询请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionHistoryRequest {
    pub limit: Option<u32>,
    pub status_filter: Option<String>,
    pub workflow_id: Option<String>,
    pub template_id: Option<String>,
}

/// 实时事件响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RealtimeEventResponse {
    pub event_type: String,
    pub prompt_id: String,
    pub execution_id: Option<String>,
    pub data: serde_json::Value,
    pub timestamp: String,
}

// ==================== 执行控制命令 ====================

/// 执行工作流
#[tauri::command]
pub async fn comfyui_v2_execute_workflow(
    request: ExecuteWorkflowRequest,
    state: State<'_, AppState>,
) -> Result<ExecutionResponse, String> {
    info!("Command: comfyui_v2_execute_workflow - {}", request.workflow_id);

    let service_manager = get_service_manager(&state).await?;
    let execution_engine = service_manager.get_execution_engine().await
        .map_err(|e| format!("获取执行引擎失败: {}", e))?;
    let repository = service_manager.get_repository();

    // 获取工作流
    let workflow = match repository.get_workflow(&request.workflow_id) {
        Ok(Some(workflow)) => workflow,
        Ok(None) => return Err("工作流不存在".to_string()),
        Err(e) => return Err(format!("获取工作流失败: {}", e)),
    };

    // 创建执行配置
    let config = ExecutionConfig {
        timeout: Duration::from_secs(request.timeout_seconds.unwrap_or(300)),
        priority: request.priority,
        wait_for_completion: request.wait_for_completion.unwrap_or(true),
        progress_interval: Duration::from_secs(1),
    };

    // 执行工作流
    let result = execution_engine.execute_workflow(&workflow, request.parameters, config).await
        .map_err(|e| format!("执行工作流失败: {}", e))?;

    Ok(convert_execution_result(&result))
}

/// 执行模板
#[tauri::command]
pub async fn comfyui_v2_execute_template(
    request: ExecuteTemplateRequest,
    state: State<'_, AppState>,
) -> Result<ExecutionResponse, String> {
    info!("Command: comfyui_v2_execute_template - {}", request.template_id);

    let service_manager = get_service_manager(&state).await?;
    let execution_engine = service_manager.get_execution_engine().await
        .map_err(|e| format!("获取执行引擎失败: {}", e))?;

    // 创建执行配置
    let config = ExecutionConfig {
        timeout: Duration::from_secs(request.timeout_seconds.unwrap_or(300)),
        priority: request.priority,
        wait_for_completion: request.wait_for_completion.unwrap_or(true),
        progress_interval: Duration::from_secs(1),
    };

    // 执行模板
    let result = execution_engine.execute_template(&request.template_id, request.parameters, config).await
        .map_err(|e| format!("执行模板失败: {}", e))?;

    Ok(convert_execution_result(&result))
}

/// 取消执行
#[tauri::command]
pub async fn comfyui_v2_cancel_execution(
    execution_id: String,
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("Command: comfyui_v2_cancel_execution - {}", execution_id);

    // TODO: 取消执行
    Ok("执行已取消".to_string())
}

/// 获取执行状态
#[tauri::command]
pub async fn comfyui_v2_get_execution_status(
    execution_id: String,
    state: State<'_, AppState>,
) -> Result<ExecutionResponse, String> {
    info!("Command: comfyui_v2_get_execution_status - {}", execution_id);

    // TODO: 获取执行状态
    Err("执行记录不存在".to_string())
}

/// 获取执行历史
#[tauri::command]
pub async fn comfyui_v2_get_execution_history(
    request: ExecutionHistoryRequest,
    state: State<'_, AppState>,
) -> Result<Vec<ExecutionResponse>, String> {
    info!("Command: comfyui_v2_get_execution_history");

    // TODO: 获取执行历史
    Ok(Vec::new())
}

/// 清理已完成的执行记录
#[tauri::command]
pub async fn comfyui_v2_cleanup_completed_executions(
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("Command: comfyui_v2_cleanup_completed_executions");

    // TODO: 清理执行记录
    Ok("清理完成".to_string())
}

/// 获取执行统计信息
#[tauri::command]
pub async fn comfyui_v2_get_execution_stats(
    state: State<'_, AppState>,
) -> Result<ExecutionStats, String> {
    info!("Command: comfyui_v2_get_execution_stats");

    // TODO: 获取执行统计
    Ok(ExecutionStats {
        running_count: 0,
        running_executions: Vec::new(),
    })
}

// ==================== 实时监控命令 ====================

/// 启动实时监控
#[tauri::command]
pub async fn comfyui_v2_start_realtime_monitor(
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("Command: comfyui_v2_start_realtime_monitor");

    // TODO: 启动实时监控
    Ok("实时监控已启动".to_string())
}

/// 停止实时监控
#[tauri::command]
pub async fn comfyui_v2_stop_realtime_monitor(
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("Command: comfyui_v2_stop_realtime_monitor");

    // TODO: 停止实时监控
    Ok("实时监控已停止".to_string())
}

/// 获取监控统计信息
#[tauri::command]
pub async fn comfyui_v2_get_monitor_stats(
    state: State<'_, AppState>,
) -> Result<MonitorStats, String> {
    info!("Command: comfyui_v2_get_monitor_stats");

    // TODO: 获取监控统计
    Ok(MonitorStats {
        is_running: false,
        websocket_connected: false,
        tracked_executions: 0,
        event_subscribers: 0,
    })
}

/// 订阅实时事件（WebSocket 风格的命令）
#[tauri::command]
pub async fn comfyui_v2_subscribe_realtime_events(
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("Command: comfyui_v2_subscribe_realtime_events");

    // TODO: 订阅实时事件
    // 注意：这个命令可能需要特殊处理，因为它涉及长连接
    Ok("已订阅实时事件".to_string())
}

// ==================== 批量操作命令 ====================

/// 批量执行工作流
#[tauri::command]
pub async fn comfyui_v2_batch_execute_workflows(
    requests: Vec<ExecuteWorkflowRequest>,
    state: State<'_, AppState>,
) -> Result<Vec<ExecutionResponse>, String> {
    info!("Command: comfyui_v2_batch_execute_workflows - {} 个工作流", requests.len());

    // TODO: 批量执行工作流
    Ok(Vec::new())
}

/// 批量执行模板
#[tauri::command]
pub async fn comfyui_v2_batch_execute_templates(
    requests: Vec<ExecuteTemplateRequest>,
    state: State<'_, AppState>,
) -> Result<Vec<ExecutionResponse>, String> {
    info!("Command: comfyui_v2_batch_execute_templates - {} 个模板", requests.len());

    // TODO: 批量执行模板
    Ok(Vec::new())
}

/// 批量取消执行
#[tauri::command]
pub async fn comfyui_v2_batch_cancel_executions(
    execution_ids: Vec<String>,
    state: State<'_, AppState>,
) -> Result<Vec<String>, String> {
    info!("Command: comfyui_v2_batch_cancel_executions - {} 个执行", execution_ids.len());

    // TODO: 批量取消执行
    Ok(execution_ids.into_iter().map(|id| format!("已取消: {}", id)).collect())
}

/// 批量获取执行状态
#[tauri::command]
pub async fn comfyui_v2_batch_get_execution_status(
    execution_ids: Vec<String>,
    state: State<'_, AppState>,
) -> Result<Vec<ExecutionResponse>, String> {
    info!("Command: comfyui_v2_batch_get_execution_status - {} 个执行", execution_ids.len());

    // TODO: 批量获取执行状态
    Ok(Vec::new())
}

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

/// 获取服务管理器
async fn get_service_manager(state: &State<'_, AppState>) -> Result<std::sync::Arc<crate::business::services::service_manager::ServiceManager>, String> {
    state.get_comfyui_manager().await
        .map_err(|e| format!("获取ComfyUI服务管理器失败: {}", e))
}

/// 获取配置管理器
async fn get_config_manager(state: &State<'_, AppState>) -> Result<std::sync::Arc<crate::business::services::config_manager::ConfigManager>, String> {
    state.get_config_manager().await
        .map_err(|e| format!("获取配置管理器失败: {}", e))
}

/// 转换执行结果为响应
fn convert_execution_result(result: &ExecutionResult) -> ExecutionResponse {
    ExecutionResponse {
        execution_id: result.execution_id.clone(),
        prompt_id: result.prompt_id.clone(),
        status: result.status.to_string(),
        output_urls: result.output_urls.clone(),
        node_outputs: result.node_outputs.clone(),
        execution_time: result.execution_time,
        error_message: result.error_message.clone(),
        created_at: None, // TODO: 从数据库获取
        completed_at: None, // TODO: 从数据库获取
    }
}

/// 转换实时事件为响应
fn convert_realtime_event(event: &RealtimeEvent) -> RealtimeEventResponse {
    let (event_type, prompt_id, execution_id, data) = match event {
        RealtimeEvent::ExecutionStarted { prompt_id, execution_id } => (
            "execution_started".to_string(),
            prompt_id.clone(),
            execution_id.clone(),
            serde_json::json!({}),
        ),
        RealtimeEvent::ExecutionProgress { prompt_id, execution_id, progress, current_node, total_nodes } => (
            "execution_progress".to_string(),
            prompt_id.clone(),
            execution_id.clone(),
            serde_json::json!({
                "progress": progress,
                "current_node": current_node,
                "total_nodes": total_nodes
            }),
        ),
        RealtimeEvent::ExecutionCompleted { prompt_id, execution_id, outputs, output_urls } => (
            "execution_completed".to_string(),
            prompt_id.clone(),
            execution_id.clone(),
            serde_json::json!({
                "outputs": outputs,
                "output_urls": output_urls
            }),
        ),
        RealtimeEvent::ExecutionFailed { prompt_id, execution_id, error } => (
            "execution_failed".to_string(),
            prompt_id.clone(),
            execution_id.clone(),
            serde_json::json!({
                "error": error
            }),
        ),
        RealtimeEvent::QueueUpdated { running_count, pending_count } => (
            "queue_updated".to_string(),
            "".to_string(),
            None,
            serde_json::json!({
                "running_count": running_count,
                "pending_count": pending_count
            }),
        ),
        RealtimeEvent::ConnectionChanged { connected, message } => (
            "connection_changed".to_string(),
            "".to_string(),
            None,
            serde_json::json!({
                "connected": connected,
                "message": message
            }),
        ),
    };

    RealtimeEventResponse {
        event_type,
        prompt_id,
        execution_id,
        data,
        timestamp: chrono::Utc::now().to_rfc3339(),
    }
}
