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

use crate::app_state::AppState;
use crate::data::models::comfyui::ComfyUIConfig;

/// ComfyUI V2 配置请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComfyUIV2ConfigRequest {
    pub base_url: String,
    pub timeout: Option<u64>,
    pub retry_attempts: Option<u32>,
    pub enable_cache: Option<bool>,
    pub max_concurrency: Option<u32>,
    pub websocket_url: Option<String>,
}

/// ComfyUI V2 配置响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComfyUIV2ConfigResponse {
    pub base_url: String,
    pub timeout: u64,
    pub retry_attempts: u32,
    pub enable_cache: bool,
    pub max_concurrency: u32,
    pub websocket_url: String,
    pub timeout_seconds: u64,
    pub retry_delay_ms: u64,
    pub enable_websocket: bool,
    pub custom_headers: Option<HashMap<String, String>>,
}

impl From<ComfyUIConfig> for ComfyUIV2ConfigResponse {
    fn from(config: ComfyUIConfig) -> Self {
        // 从base_url推导websocket_url
        let websocket_url = if config.base_url.starts_with("https://") {
            config.base_url.replace("https://", "wss://") + "/ws"
        } else {
            config.base_url.replace("http://", "ws://") + "/ws"
        };

        Self {
            base_url: config.base_url.clone(),
            timeout: config.timeout_seconds * 1000, // 转换为毫秒
            retry_attempts: config.retry_attempts,
            enable_cache: config.enable_cache,
            max_concurrency: config.max_concurrency,
            websocket_url,
            timeout_seconds: config.timeout_seconds,
            retry_delay_ms: config.retry_delay_ms,
            enable_websocket: config.enable_websocket,
            custom_headers: config.custom_headers,
        }
    }
}

impl From<ComfyUIV2ConfigRequest> for ComfyUIConfig {
    fn from(request: ComfyUIV2ConfigRequest) -> Self {
        Self {
            base_url: request.base_url,
            timeout_seconds: request.timeout.unwrap_or(30000) / 1000, // 转换为秒
            retry_attempts: request.retry_attempts.unwrap_or(3),
            retry_delay_ms: 1000, // 默认1秒
            enable_websocket: true, // 默认启用
            enable_cache: request.enable_cache.unwrap_or(true),
            max_concurrency: request.max_concurrency.unwrap_or(4),
            custom_headers: None,
        }
    }
}

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

    let service_manager = state.get_comfyui_manager().await
        .map_err(|e| format!("获取ComfyUI管理器失败: {}", e))?;
    
    match service_manager.get_config().await {
        Ok(config) => {
            debug!("获取配置成功: {:?}", config);
            Ok(ComfyUIV2ConfigResponse::from(config))
        },
        Err(e) => {
            error!("获取配置失败: {}", e);
            // 返回默认配置
            let default_config = ComfyUIConfig::default();
            Ok(ComfyUIV2ConfigResponse::from(default_config))
        }
    }
}

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

    let service_manager = state.get_comfyui_manager().await
        .map_err(|e| format!("获取ComfyUI管理器失败: {}", e))?;
    
    let config = ComfyUIConfig::from(config_request);
    
    match service_manager.update_config(config.clone()).await {
        Ok(_) => {
            info!("配置更新成功");
            Ok(ComfyUIV2ConfigResponse::from(config))
        },
        Err(e) => {
            error!("配置更新失败: {}", e);
            Err(format!("配置更新失败: {}", e))
        }
    }
}

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

    let service_manager = state.get_comfyui_manager().await
        .map_err(|e| format!("获取ComfyUI管理器失败: {}", e))?;
    
    let default_config = ComfyUIConfig::default();
    
    match service_manager.update_config(default_config.clone()).await {
        Ok(_) => {
            info!("配置重置成功");
            Ok(ComfyUIV2ConfigResponse::from(default_config))
        },
        Err(e) => {
            error!("配置重置失败: {}", e);
            Err(format!("配置重置失败: {}", e))
        }
    }
}

/// 验证ComfyUI配置
#[tauri::command]
pub async fn comfyui_v2_validate_config(
    config_request: ComfyUIV2ConfigRequest,
) -> Result<bool, String> {
    info!("Command: comfyui_v2_validate_config - {:?}", config_request);

    // 基本验证
    if config_request.base_url.is_empty() {
        return Err("API地址不能为空".to_string());
    }

    if !config_request.base_url.starts_with("http://") && !config_request.base_url.starts_with("https://") {
        return Err("API地址必须以http://或https://开头".to_string());
    }

    if let Some(timeout) = config_request.timeout {
        if timeout == 0 {
            return Err("超时时间必须大于0".to_string());
        }
        if timeout > 300000 { // 5分钟
            return Err("超时时间不能超过5分钟".to_string());
        }
    }

    if let Some(retry_attempts) = config_request.retry_attempts {
        if retry_attempts > 10 {
            return Err("重试次数不能超过10次".to_string());
        }
    }

    if let Some(max_concurrency) = config_request.max_concurrency {
        if max_concurrency == 0 {
            return Err("最大并发数必须大于0".to_string());
        }
        if max_concurrency > 20 {
            return Err("最大并发数不能超过20".to_string());
        }
    }

    Ok(true)
}

/// 测试ComfyUI连接
#[tauri::command]
pub async fn comfyui_v2_test_connection(
    config_request: ComfyUIV2ConfigRequest,
) -> Result<bool, String> {
    info!("Command: comfyui_v2_test_connection - {:?}", config_request);

    // 首先验证配置
    comfyui_v2_validate_config(config_request.clone()).await?;

    // 创建临时的ComfyUI客户端进行连接测试
    let config = ComfyUIConfig::from(config_request);
    
    // 使用ComfyUI SDK进行连接测试
    let client_config = comfyui_sdk::types::ComfyUIClientConfig {
        base_url: config.base_url.clone(),
        timeout: Some(std::time::Duration::from_secs(config.timeout_seconds)),
        retry_attempts: Some(config.retry_attempts),
        retry_delay: Some(std::time::Duration::from_millis(config.retry_delay_ms)),
        headers: config.custom_headers.clone(),
    };

    match comfyui_sdk::client::ComfyUIClient::new(client_config) {
        Ok(client) => {
            // 尝试获取系统信息来测试连接
            match client.get_system_stats().await {
                Ok(_) => {
                    info!("连接测试成功");
                    Ok(true)
                },
                Err(e) => {
                    error!("连接测试失败: {}", e);
                    Err(format!("连接测试失败: {}", e))
                }
            }
        },
        Err(e) => {
            error!("创建客户端失败: {}", e);
            Err(format!("创建客户端失败: {}", e))
        }
    }
}
