//! ComfyUI V2 命令层
//! 基于新的 SDK 架构重写的 Tauri 命令

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

use crate::app_state::AppState;
use crate::business::services::{
    comfyui_v2_service::{ComfyUIV2Service, ComfyUIV2Config, ConnectionStatus, SystemInfo, QueueStatus},
    template_engine::{TemplateEngine, CacheStats},
    execution_engine::{ExecutionEngine, ExecutionResult, ExecutionConfig, ExecutionStats},
    realtime_monitor_v2::{RealtimeMonitorV2, RealtimeEventV2, MonitorStats},
    config_manager::{ConfigManager, ConfigStats, ConfigHealthStatus},
    error_handler::{ComfyUIError, ErrorHandleResult, ErrorStats},
};
use crate::data::models::comfyui::{
    WorkflowModel, TemplateModel, ExecutionModel, ExecutionStatus, ComfyUIConfig,
    ParameterValues, ValidationResult,
};
use comfyui_sdk::types::{ComfyUIWorkflow, ComfyUINode};
use crate::business::services::comfyui_manager::ComfyUIManager;

// ==================== 请求类型定义 ====================

/// 创建工作流请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateWorkflowRequest {
    pub name: String,
    pub description: Option<String>,
    pub workflow_json: serde_json::Value,
    pub tags: Option<Vec<String>>,
}

/// 更新工作流请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateWorkflowRequest {
    pub id: String,
    pub name: Option<String>,
    pub description: Option<String>,
    pub workflow_json: Option<serde_json::Value>,
    pub tags: Option<Vec<String>>,
}

/// 创建模板请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateTemplateRequest {
    pub name: String,
    pub description: Option<String>,
    pub template_json: serde_json::Value,
    pub parameters: Option<serde_json::Value>,
    pub tags: Option<Vec<String>>,
}

/// 执行模板请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecuteTemplateRequest {
    pub template_id: String,
    pub parameters: serde_json::Value,
    pub priority: Option<u32>,
}

// ==================== 响应类型定义 ====================

/// 连接状态响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectionStatusResponse {
    pub connected: bool,
    pub status: String,
    pub base_url: String,
    pub last_health_check: Option<String>,
    pub timeout_seconds: u64,
    pub retry_attempts: u32,
}

/// 系统信息响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemInfoResponse {
    pub os: String,
    pub python_version: String,
    pub embedded_python: bool,
    pub devices: Vec<DeviceInfoResponse>,
}

/// 设备信息响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeviceInfoResponse {
    pub name: String,
    pub device_type: String,
    pub vram_total: u64,
    pub vram_free: u64,
    pub torch_vram_total: u64,
    pub torch_vram_free: u64,
}

/// 队列状态响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueueStatusResponse {
    pub running_count: u32,
    pub pending_count: u32,
    pub running_tasks: Vec<QueueTaskResponse>,
    pub pending_tasks: Vec<QueueTaskResponse>,
}

/// 队列任务响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueueTaskResponse {
    pub prompt_id: String,
    pub number: u32,
    pub status: String,
}

/// 健康检查响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthCheckResponse {
    pub healthy: bool,
    pub connection_status: String,
    pub websocket_connected: bool,
    pub last_check_time: Option<String>,
    pub error_message: Option<String>,
}

// ==================== 基础连接管理命令 ====================

/// 连接到 ComfyUI 服务
#[tauri::command]
pub async fn comfyui_v2_connect(
    state: State<'_, AppState>,
) -> Result<ConnectionStatusResponse, String> {
    info!("Command: comfyui_v2_connect");

    // 获取配置管理器
    let config_manager = get_config_manager(&state).await?;
    let config = config_manager.get_comfyui_config().await;

    // 创建 ComfyUI 管理器
    let manager = ComfyUIManager::new(config)
        .map_err(|e| format!("创建管理器失败: {}", e))?;

    // 尝试连接
    match manager.connect().await {
        Ok(_) => {
            let stats = manager.get_connection_stats().await;
            info!("ComfyUI 连接成功");
            
            Ok(ConnectionStatusResponse {
                connected: true,
                status: stats.status.to_string(),
                base_url: stats.base_url,
                last_health_check: stats.last_health_check.map(|t| format!("{:?}", t)),
                timeout_seconds: stats.timeout_seconds,
                retry_attempts: stats.retry_attempts,
            })
        }
        Err(e) => {
            error!("ComfyUI 连接失败: {}", e);
            Err(format!("连接失败: {}", e))
        }
    }
}

/// 断开 ComfyUI 连接
#[tauri::command]
pub async fn comfyui_v2_disconnect(
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("Command: comfyui_v2_disconnect");

    // TODO: 从应用状态获取管理器实例
    // 这里需要在应用状态中维护管理器实例
    
    Ok("连接已断开".to_string())
}

/// 检查连接状态
#[tauri::command]
pub async fn comfyui_v2_get_connection_status(
    state: State<'_, AppState>,
) -> Result<ConnectionStatusResponse, String> {
    info!("Command: comfyui_v2_get_connection_status");

    // TODO: 从应用状态获取管理器实例
    // 临时返回默认状态
    Ok(ConnectionStatusResponse {
        connected: false,
        status: "未连接".to_string(),
        base_url: "http://localhost:8188".to_string(),
        last_health_check: None,
        timeout_seconds: 300,
        retry_attempts: 3,
    })
}

/// 健康检查
#[tauri::command]
pub async fn comfyui_v2_health_check(
    state: State<'_, AppState>,
) -> Result<HealthCheckResponse, String> {
    info!("Command: comfyui_v2_health_check");

    // TODO: 实现健康检查逻辑
    Ok(HealthCheckResponse {
        healthy: false,
        connection_status: "未连接".to_string(),
        websocket_connected: false,
        last_check_time: None,
        error_message: Some("服务未初始化".to_string()),
    })
}

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

    // TODO: 从管理器获取系统信息
    Err("功能暂未实现".to_string())
}

/// 获取队列基本状态
#[tauri::command]
pub async fn comfyui_v2_get_queue_basic_status(
    state: State<'_, AppState>,
) -> Result<QueueStatusResponse, String> {
    info!("Command: comfyui_v2_get_queue_basic_status");

    // TODO: 从管理器获取队列状态
    Ok(QueueStatusResponse {
        running_count: 0,
        pending_count: 0,
        running_tasks: Vec::new(),
        pending_tasks: Vec::new(),
    })
}

// ==================== 配置管理命令 ====================

/// 获取 ComfyUI 配置
#[tauri::command]
pub async fn comfyui_v2_get_config(
    state: State<'_, AppState>,
) -> Result<ComfyUIConfig, String> {
    info!("Command: comfyui_v2_get_config");

    let config_manager = get_config_manager(&state).await?;
    let config = config_manager.get_comfyui_config().await;
    
    Ok(config)
}

/// 更新 ComfyUI 配置
#[tauri::command]
pub async fn comfyui_v2_update_config(
    config: ComfyUIConfig,
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("Command: comfyui_v2_update_config");

    let config_manager = get_config_manager(&state).await?;
    
    match config_manager.update_comfyui_config(config).await {
        Ok(_) => {
            info!("ComfyUI 配置更新成功");
            Ok("配置更新成功".to_string())
        }
        Err(e) => {
            error!("配置更新失败: {}", e);
            Err(format!("配置更新失败: {}", e))
        }
    }
}

/// 验证配置
#[tauri::command]
pub async fn comfyui_v2_validate_config(
    config: ComfyUIConfig,
    state: State<'_, AppState>,
) -> Result<ValidationResult, String> {
    info!("Command: comfyui_v2_validate_config");

    let validation = config.validate();
    Ok(validation)
}

/// 重置配置为默认值
#[tauri::command]
pub async fn comfyui_v2_reset_config(
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("Command: comfyui_v2_reset_config");

    let config_manager = get_config_manager(&state).await?;
    
    match config_manager.reset_comfyui_config().await {
        Ok(_) => {
            info!("ComfyUI 配置重置成功");
            Ok("配置重置成功".to_string())
        }
        Err(e) => {
            error!("配置重置失败: {}", e);
            Err(format!("配置重置失败: {}", e))
        }
    }
}

// ==================== 统计和监控命令 ====================

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

    let config_manager = get_config_manager(&state).await?;
    let stats = config_manager.get_config_stats().await;
    
    Ok(stats)
}

/// 获取配置健康状态
#[tauri::command]
pub async fn comfyui_v2_get_config_health(
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("Command: comfyui_v2_get_config_health");

    let config_manager = get_config_manager(&state).await?;
    
    match config_manager.health_check().await {
        Ok(status) => Ok(status.to_string()),
        Err(e) => Err(format!("健康检查失败: {}", e)),
    }
}

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

/// 获取配置管理器
async fn get_config_manager(state: &State<'_, AppState>) -> Result<ConfigManager, String> {
    // 创建默认配置（临时实现）
    let app_config = crate::config::AppConfig::default();
    Ok(ConfigManager::new(app_config, None))
}

/// 获取服务管理器（临时实现）
async fn get_service_manager(state: &State<'_, AppState>) -> Result<crate::business::services::service_manager::ServiceManager, String> {
    let config_manager = get_config_manager(state).await?;
    let db_path = "mixvideo.db".to_string(); // 临时硬编码
    let service_manager = crate::business::services::service_manager::ServiceManager::new(config_manager, db_path);

    // 初始化服务管理器
    service_manager.initialize().await
        .map_err(|e| format!("服务管理器初始化失败: {}", e))?;

    Ok(service_manager)
}

/// 转换系统信息
fn convert_system_info(info: comfyui_sdk::types::SystemStats) -> SystemInfoResponse {
    SystemInfoResponse {
        os: info.system.os,
        python_version: info.system.python_version,
        embedded_python: info.system.embedded_python,
        devices: info.devices.into_iter().map(|device| DeviceInfoResponse {
            name: device.name,
            device_type: device.device_type,
            vram_total: device.vram_total,
            vram_free: device.vram_free,
            torch_vram_total: device.torch_vram_total,
            torch_vram_free: device.torch_vram_free,
        }).collect(),
    }
}

/// 转换队列状态
fn convert_queue_status(status: comfyui_sdk::types::QueueStatus) -> QueueStatusResponse {
    QueueStatusResponse {
        running_count: status.queue_running.len() as u32,
        pending_count: status.queue_pending.len() as u32,
        running_tasks: status.queue_running.into_iter().map(|item| QueueTaskResponse {
            prompt_id: item.prompt_id,
            number: item.number,
            status: "running".to_string(),
        }).collect(),
        pending_tasks: status.queue_pending.into_iter().map(|item| QueueTaskResponse {
            prompt_id: item.prompt_id,
            number: item.number,
            status: "pending".to_string(),
        }).collect(),
    }
}

// ==================== 工作流管理命令 ====================

/// 工作流响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowResponse {
    pub id: String,
    pub name: String,
    pub description: Option<String>,
    pub workflow_data: HashMap<String, serde_json::Value>,
    pub version: String,
    pub created_at: String,
    pub updated_at: String,
    pub enabled: bool,
    pub tags: Vec<String>,
    pub category: Option<String>,
}

/// 创建工作流
#[tauri::command]
pub async fn comfyui_v2_create_workflow(
    request: CreateWorkflowRequest,
    state: State<'_, AppState>,
) -> Result<WorkflowResponse, String> {
    info!("Command: comfyui_v2_create_workflow - {}", request.name);

    let service_manager = get_service_manager(&state).await?;
    let repository = service_manager.get_repository();

    // 转换工作流数据
    let workflow_data: ComfyUIWorkflow = request.workflow_data.into_iter()
        .map(|(k, v)| {
            let node = serde_json::from_value(v)
                .map_err(|e| format!("解析工作流节点失败: {}", e))?;
            Ok((k, node))
        })
        .collect::<Result<HashMap<String, ComfyUINode>, String>>()?;

    // 创建工作流模型
    let mut workflow = WorkflowModel::new(request.name, workflow_data);

    // 设置可选字段
    workflow.description = request.description;
    workflow.category = request.category;
    workflow.tags = request.tags;

    // 保存到数据库
    repository.create_workflow(&workflow)
        .map_err(|e| format!("创建工作流失败: {}", e))?;

    Ok(convert_workflow_model(&workflow))
}

/// 获取工作流列表
#[tauri::command]
pub async fn comfyui_v2_list_workflows(
    enabled_only: Option<bool>,
    state: State<'_, AppState>,
) -> Result<Vec<WorkflowResponse>, String> {
    info!("Command: comfyui_v2_list_workflows");

    let service_manager = get_service_manager(&state).await?;
    let repository = service_manager.get_repository();

    let workflows = repository.list_workflows(enabled_only.unwrap_or(true))
        .map_err(|e| format!("获取工作流列表失败: {}", e))?;

    let responses = workflows.iter().map(convert_workflow_model).collect();
    Ok(responses)
}

/// 获取单个工作流
#[tauri::command]
pub async fn comfyui_v2_get_workflow(
    workflow_id: String,
    state: State<'_, AppState>,
) -> Result<WorkflowResponse, String> {
    info!("Command: comfyui_v2_get_workflow - {}", workflow_id);

    let service_manager = get_service_manager(&state).await?;
    let repository = service_manager.get_repository();

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

/// 更新工作流
#[tauri::command]
pub async fn comfyui_v2_update_workflow(
    request: UpdateWorkflowRequest,
    state: State<'_, AppState>,
) -> Result<WorkflowResponse, String> {
    info!("Command: comfyui_v2_update_workflow - {}", request.id);

    // TODO: 更新工作流
    Err("功能暂未实现".to_string())
}

/// 删除工作流
#[tauri::command]
pub async fn comfyui_v2_delete_workflow(
    workflow_id: String,
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("Command: comfyui_v2_delete_workflow - {}", workflow_id);

    let service_manager = get_service_manager(&state).await?;
    let repository = service_manager.get_repository();

    repository.delete_workflow(&workflow_id)
        .map_err(|e| format!("删除工作流失败: {}", e))?;

    Ok("工作流删除成功".to_string())
}

/// 按分类获取工作流
#[tauri::command]
pub async fn comfyui_v2_get_workflows_by_category(
    category: String,
    state: State<'_, AppState>,
) -> Result<Vec<WorkflowResponse>, String> {
    info!("Command: comfyui_v2_get_workflows_by_category - {}", category);

    // TODO: 按分类获取工作流
    Ok(Vec::new())
}

/// 搜索工作流
#[tauri::command]
pub async fn comfyui_v2_search_workflows(
    query: String,
    state: State<'_, AppState>,
) -> Result<Vec<WorkflowResponse>, String> {
    info!("Command: comfyui_v2_search_workflows - {}", query);

    // TODO: 搜索工作流
    Ok(Vec::new())
}

/// 转换工作流模型为响应
fn convert_workflow_model(workflow: &WorkflowModel) -> WorkflowResponse {
    WorkflowResponse {
        id: workflow.id.clone(),
        name: workflow.name.clone(),
        description: workflow.description.clone(),
        workflow_data: workflow.workflow_data.iter()
            .map(|(k, v)| (k.clone(), serde_json::to_value(v).unwrap_or(serde_json::Value::Null)))
            .collect(),
        version: workflow.version.clone(),
        created_at: workflow.created_at.to_rfc3339(),
        updated_at: workflow.updated_at.to_rfc3339(),
        enabled: workflow.enabled,
        tags: workflow.tags.clone(),
        category: workflow.category.clone(),
    }
}
