//! ComfyUI V2 实时通信命令
//! 基于增强版实时监控服务的 Tauri 命令

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

use crate::app_state::AppState;
use crate::business::services::{
    realtime_monitor_v2::{RealtimeMonitorV2, RealtimeMonitorConfig, ConnectionStatus, EventStatistics},
    realtime_monitor::MonitorStats,
    tauri_event_emitter::TauriEventEmitter,
};

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

/// 实时监控配置请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RealtimeMonitorConfigRequest {
    pub reconnect_interval_seconds: Option<u64>,
    pub max_reconnect_interval_seconds: Option<u64>,
    pub heartbeat_interval_seconds: Option<u64>,
    pub event_buffer_size: Option<usize>,
    pub auto_reconnect: Option<bool>,
}

/// 连接状态响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectionStatusResponse {
    pub connected: bool,
    pub last_connected_at: Option<String>,
    pub last_disconnected_at: Option<String>,
    pub reconnect_attempts: u32,
    pub total_connections: u32,
    pub error_message: Option<String>,
}

/// 事件统计响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EventStatisticsResponse {
    pub total_events: u64,
    pub events_by_type: std::collections::HashMap<String, u64>,
    pub last_event_time: Option<String>,
    pub events_per_minute: f64,
    pub start_time: String,
}

/// 监控统计响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MonitorStatsResponse {
    pub is_running: bool,
    pub connection_status: ConnectionStatusResponse,
    pub event_statistics: EventStatisticsResponse,
    pub tracked_executions: usize,
    pub event_subscribers: usize,
    pub custom_subscribers: usize,
}

/// 事件订阅响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EventSubscriptionResponse {
    pub subscribed: bool,
    pub subscription_id: String,
    pub event_types: Vec<String>,
}

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

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

    let service_manager = get_service_manager(&state).await?;
    
    // 创建监控配置
    let monitor_config = config.map(|req| RealtimeMonitorConfig {
        reconnect_interval: std::time::Duration::from_secs(req.reconnect_interval_seconds.unwrap_or(5)),
        max_reconnect_interval: std::time::Duration::from_secs(req.max_reconnect_interval_seconds.unwrap_or(60)),
        heartbeat_interval: std::time::Duration::from_secs(req.heartbeat_interval_seconds.unwrap_or(30)),
        event_buffer_size: req.event_buffer_size.unwrap_or(1000),
        auto_reconnect: req.auto_reconnect.unwrap_or(true),
    });

    // 创建增强版实时监控
    let comfyui_manager = service_manager.get_comfyui_manager().await
        .map_err(|e| format!("获取 ComfyUI 管理器失败: {}", e))?;
    let repository = service_manager.get_repository();

    let realtime_monitor = RealtimeMonitorV2::new(
        comfyui_manager,
        repository,
        monitor_config,
    );

    // 启动监控
    realtime_monitor.start().await
        .map_err(|e| format!("启动实时监控失败: {}", e))?;

    // TODO: 将监控实例保存到应用状态中

    Ok("增强版实时监控已启动".to_string())
}

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

    // TODO: 从应用状态获取监控实例并停止
    Ok("增强版实时监控已停止".to_string())
}

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

    // TODO: 从应用状态获取监控实例
    Ok(ConnectionStatusResponse {
        connected: false,
        last_connected_at: None,
        last_disconnected_at: None,
        reconnect_attempts: 0,
        total_connections: 0,
        error_message: Some("监控未启动".to_string()),
    })
}

/// 获取事件统计
#[tauri::command]
pub async fn comfyui_v2_get_realtime_event_statistics(
    state: State<'_, AppState>,
) -> Result<EventStatisticsResponse, String> {
    info!("Command: comfyui_v2_get_realtime_event_statistics");

    // TODO: 从应用状态获取监控实例
    Ok(EventStatisticsResponse {
        total_events: 0,
        events_by_type: std::collections::HashMap::new(),
        last_event_time: None,
        events_per_minute: 0.0,
        start_time: chrono::Utc::now().to_rfc3339(),
    })
}

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

    // TODO: 从应用状态获取监控实例
    Ok(MonitorStatsResponse {
        is_running: false,
        connection_status: ConnectionStatusResponse {
            connected: false,
            last_connected_at: None,
            last_disconnected_at: None,
            reconnect_attempts: 0,
            total_connections: 0,
            error_message: Some("监控未启动".to_string()),
        },
        event_statistics: EventStatisticsResponse {
            total_events: 0,
            events_by_type: std::collections::HashMap::new(),
            last_event_time: None,
            events_per_minute: 0.0,
            start_time: chrono::Utc::now().to_rfc3339(),
        },
        tracked_executions: 0,
        event_subscribers: 0,
        custom_subscribers: 0,
    })
}

/// 注册执行映射
#[tauri::command]
pub async fn comfyui_v2_register_execution_mapping(
    prompt_id: String,
    execution_id: String,
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("Command: comfyui_v2_register_execution_mapping - {} -> {}", prompt_id, execution_id);

    // TODO: 从应用状态获取监控实例并注册映射
    Ok("执行映射已注册".to_string())
}

/// 清理执行映射
#[tauri::command]
pub async fn comfyui_v2_cleanup_execution_mappings(
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("Command: comfyui_v2_cleanup_execution_mappings");

    // TODO: 清理过期的执行映射
    Ok("执行映射已清理".to_string())
}

// ==================== 事件订阅管理命令 ====================

/// 订阅实时事件（通过 Tauri 事件系统）
#[tauri::command]
pub async fn comfyui_v2_subscribe_realtime_events_enhanced(
    event_types: Option<Vec<String>>,
    state: State<'_, AppState>,
) -> Result<EventSubscriptionResponse, String> {
    info!("Command: comfyui_v2_subscribe_realtime_events_enhanced");

    let subscription_id = uuid::Uuid::new_v4().to_string();
    let event_types = event_types.unwrap_or_else(|| vec![
        "connection_changed".to_string(),
        "execution_started".to_string(),
        "execution_progress".to_string(),
        "node_executing".to_string(),
        "execution_completed".to_string(),
        "execution_failed".to_string(),
        "queue_updated".to_string(),
        "system_status_updated".to_string(),
    ]);

    // TODO: 实现事件订阅逻辑

    Ok(EventSubscriptionResponse {
        subscribed: true,
        subscription_id,
        event_types,
    })
}

/// 取消订阅实时事件
#[tauri::command]
pub async fn comfyui_v2_unsubscribe_realtime_events(
    subscription_id: String,
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("Command: comfyui_v2_unsubscribe_realtime_events - {}", subscription_id);

    // TODO: 实现取消订阅逻辑
    Ok("事件订阅已取消".to_string())
}

/// 获取活跃的事件订阅
#[tauri::command]
pub async fn comfyui_v2_get_active_event_subscriptions(
    state: State<'_, AppState>,
) -> Result<Vec<EventSubscriptionResponse>, String> {
    info!("Command: comfyui_v2_get_active_event_subscriptions");

    // TODO: 获取活跃订阅列表
    Ok(Vec::new())
}

// ==================== 高级功能命令 ====================

/// 重连 WebSocket
#[tauri::command]
pub async fn comfyui_v2_reconnect_websocket(
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("Command: comfyui_v2_reconnect_websocket");

    // TODO: 强制重连 WebSocket
    Ok("WebSocket 重连已触发".to_string())
}

/// 发送自定义 WebSocket 消息
#[tauri::command]
pub async fn comfyui_v2_send_websocket_message(
    message: serde_json::Value,
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("Command: comfyui_v2_send_websocket_message");

    // TODO: 发送自定义消息
    Ok("消息已发送".to_string())
}

/// 获取 WebSocket 连接质量
#[tauri::command]
pub async fn comfyui_v2_get_websocket_quality(
    state: State<'_, AppState>,
) -> Result<serde_json::Value, String> {
    info!("Command: comfyui_v2_get_websocket_quality");

    // TODO: 获取连接质量指标
    Ok(serde_json::json!({
        "latency_ms": 0,
        "packet_loss": 0.0,
        "connection_stability": "unknown",
        "last_ping_time": null
    }))
}

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

/// 获取服务管理器
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_connection_status(status: &ConnectionStatus) -> ConnectionStatusResponse {
    ConnectionStatusResponse {
        connected: status.connected,
        last_connected_at: status.last_connected_at.map(|t| t.to_rfc3339()),
        last_disconnected_at: status.last_disconnected_at.map(|t| t.to_rfc3339()),
        reconnect_attempts: status.reconnect_attempts,
        total_connections: status.total_connections,
        error_message: status.error_message.clone(),
    }
}

/// 转换事件统计
fn convert_event_statistics(stats: &EventStatistics) -> EventStatisticsResponse {
    EventStatisticsResponse {
        total_events: stats.total_events,
        events_by_type: stats.events_by_type.clone(),
        last_event_time: stats.last_event_time.map(|t| t.to_rfc3339()),
        events_per_minute: stats.events_per_minute,
        start_time: stats.start_time.to_rfc3339(),
    }
}

/// 转换监控统计
fn convert_monitor_stats(stats: &MonitorStats) -> MonitorStatsResponse {
    MonitorStatsResponse {
        is_running: stats.is_running,
        connection_status: ConnectionStatusResponse {
            connected: stats.websocket_connected,
            last_connected_at: None,
            last_disconnected_at: None,
            reconnect_attempts: 0,
            total_connections: 0,
            error_message: None,
        },
        event_statistics: EventStatisticsResponse {
            total_events: 0,
            events_by_type: std::collections::HashMap::new(),
            last_event_time: None,
            events_per_minute: 0.0,
            start_time: chrono::Utc::now().to_rfc3339(),
        },
        tracked_executions: stats.tracked_executions,
        event_subscribers: stats.event_subscribers,
        custom_subscribers: 0, // MonitorStats 中没有这个字段，设为默认值
    }
}
