#![allow(unused_imports)]

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

use crate::app_state::AppState;
use crate::config::{ComfyUISettings, ComfyUISDKConfig};
use crate::business::services::comfyui_integration_service::{
    ComfyUIIntegrationService, IntegrationConfig, UnifiedWorkflowResult, QueueStatusInfo
};
use crate::data::models::outfit_photo_generation::WorkflowNodeReplacement;

/// ComfyUI SDK 状态信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SDKStatusInfo {
    pub sdk_available: bool,
    pub current_service_type: String,
    pub sdk_config: ComfyUISDKConfig,
    pub health_status: bool,
    pub queue_status: Option<QueueStatusInfo>,
}

/// 工作流执行请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowExecutionRequest {
    pub workflow: serde_json::Value,
    pub replacements: Vec<WorkflowNodeReplacement>,
    pub use_sdk: Option<bool>,
    pub timeout_seconds: Option<u64>,
}

/// 获取 ComfyUI SDK 状态
#[tauri::command]
pub async fn get_comfyui_sdk_status(
    state: State<'_, AppState>,
) -> Result<SDKStatusInfo, String> {
    // TODO: 实现配置获取
    let config = crate::config::AppConfig::load();
    let comfyui_settings = &config.comfyui_settings;
    
    // 创建集成服务来检查状态
    let integration_config = IntegrationConfig {
        prefer_sdk: comfyui_settings.sdk_config.prefer_sdk,
        fallback_to_legacy: comfyui_settings.sdk_config.fallback_to_legacy,
        timeout: comfyui_settings.get_sdk_timeout(),
        retry_attempts: comfyui_settings.sdk_config.sdk_retry_attempts,
    };

    match ComfyUIIntegrationService::new(comfyui_settings.clone(), integration_config).await {
        Ok(service) => {
            let health_status = service.check_health().await.unwrap_or(false);
            let queue_status = service.get_queue_status().await.ok();
            
            Ok(SDKStatusInfo {
                sdk_available: true,
                current_service_type: service.get_current_service_type().to_string(),
                sdk_config: comfyui_settings.sdk_config.clone(),
                health_status,
                queue_status,
            })
        }
        Err(e) => {
            warn!("创建 ComfyUI 集成服务失败: {}", e);
            Ok(SDKStatusInfo {
                sdk_available: false,
                current_service_type: "None".to_string(),
                sdk_config: comfyui_settings.sdk_config.clone(),
                health_status: false,
                queue_status: None,
            })
        }
    }
}

/// 更新 ComfyUI SDK 配置
#[tauri::command]
pub async fn update_comfyui_sdk_config(
    state: State<'_, AppState>,
    sdk_config: ComfyUISDKConfig,
) -> Result<(), String> {
    // TODO: 实现配置保存
    info!("SDK 配置更新请求: {:?}", sdk_config);
    
    info!("ComfyUI SDK 配置已更新");
    Ok(())
}

/// 切换 ComfyUI 服务类型
#[tauri::command]
pub async fn switch_comfyui_service_type(
    state: State<'_, AppState>,
    use_sdk: bool,
) -> Result<String, String> {
    // TODO: 实现配置获取
    let config = crate::config::AppConfig::load();
    let mut comfyui_settings = config.comfyui_settings.clone();
    
    // 更新配置
    comfyui_settings.sdk_config.prefer_sdk = use_sdk;
    
    let integration_config = IntegrationConfig {
        prefer_sdk: use_sdk,
        fallback_to_legacy: true,
        timeout: comfyui_settings.get_sdk_timeout(),
        retry_attempts: comfyui_settings.sdk_config.sdk_retry_attempts,
    };

    match ComfyUIIntegrationService::new(comfyui_settings.clone(), integration_config).await {
        Ok(service) => {
            let service_type = service.get_current_service_type();
            info!("已切换到 ComfyUI 服务类型: {}", service_type);
            Ok(service_type.to_string())
        }
        Err(e) => {
            error!("切换 ComfyUI 服务类型失败: {}", e);
            Err(format!("切换服务类型失败: {}", e))
        }
    }
}

/// 执行工作流（使用集成服务）
#[tauri::command]
pub async fn execute_workflow_with_sdk(
    state: State<'_, AppState>,
    request: WorkflowExecutionRequest,
) -> Result<UnifiedWorkflowResult, String> {
    // TODO: 实现配置获取
    let config = crate::config::AppConfig::load();
    let comfyui_settings = &config.comfyui_settings;
    
    if !comfyui_settings.enabled {
        return Err("ComfyUI 功能未启用".to_string());
    }

    let integration_config = IntegrationConfig {
        prefer_sdk: request.use_sdk.unwrap_or(comfyui_settings.sdk_config.prefer_sdk),
        fallback_to_legacy: comfyui_settings.sdk_config.fallback_to_legacy,
        timeout: std::time::Duration::from_secs(
            request.timeout_seconds.unwrap_or(comfyui_settings.sdk_config.sdk_timeout_seconds)
        ),
        retry_attempts: comfyui_settings.sdk_config.sdk_retry_attempts,
    };

    let service = ComfyUIIntegrationService::new(comfyui_settings.clone(), integration_config.clone()).await
        .map_err(|e| format!("创建集成服务失败: {}", e))?;

    service.execute_workflow(request.workflow, request.replacements, integration_config).await
        .map_err(|e| format!("执行工作流失败: {}", e))
}

/// 获取 ComfyUI 队列状态
#[tauri::command]
pub async fn get_comfyui_queue_status(
    state: State<'_, AppState>,
) -> Result<QueueStatusInfo, String> {
    // TODO: 实现配置获取
    let config = crate::config::AppConfig::load();
    let comfyui_settings = &config.comfyui_settings;
    
    let integration_config = IntegrationConfig::default();
    
    let service = ComfyUIIntegrationService::new(comfyui_settings.clone(), integration_config).await
        .map_err(|e| format!("创建集成服务失败: {}", e))?;

    service.get_queue_status().await
        .map_err(|e| format!("获取队列状态失败: {}", e))
}

/// 取消工作流执行
#[tauri::command]
pub async fn cancel_comfyui_workflow(
    state: State<'_, AppState>,
    prompt_id: String,
) -> Result<(), String> {
    // TODO: 实现配置获取
    let config = crate::config::AppConfig::load();
    let comfyui_settings = &config.comfyui_settings;
    
    let integration_config = IntegrationConfig::default();
    
    let service = ComfyUIIntegrationService::new(comfyui_settings.clone(), integration_config).await
        .map_err(|e| format!("创建集成服务失败: {}", e))?;

    service.cancel_workflow(&prompt_id).await
        .map_err(|e| format!("取消工作流失败: {}", e))
}

/// 测试 ComfyUI SDK 连接
#[tauri::command]
pub async fn test_comfyui_sdk_connection(
    state: State<'_, AppState>,
    settings: ComfyUISettings,
) -> Result<bool, String> {
    let integration_config = IntegrationConfig {
        prefer_sdk: settings.sdk_config.prefer_sdk,
        fallback_to_legacy: true,
        timeout: settings.get_sdk_timeout(),
        retry_attempts: 1, // 测试时只尝试一次
    };

    match ComfyUIIntegrationService::new(settings, integration_config).await {
        Ok(service) => {
            service.check_health().await
                .map_err(|e| format!("连接测试失败: {}", e))
        }
        Err(e) => {
            warn!("创建测试服务失败: {}", e);
            Ok(false)
        }
    }
}

/// 获取 ComfyUI 服务信息
#[tauri::command]
pub async fn get_comfyui_service_info(
    state: State<'_, AppState>,
) -> Result<ServiceInfo, String> {
    // TODO: 实现配置获取
    let config = crate::config::AppConfig::load();
    let comfyui_settings = &config.comfyui_settings;
    
    Ok(ServiceInfo {
        base_url: comfyui_settings.base_url(),
        enabled: comfyui_settings.enabled,
        sdk_enabled: comfyui_settings.is_sdk_enabled(),
        timeout_seconds: comfyui_settings.timeout_seconds,
        sdk_config: comfyui_settings.sdk_config.clone(),
    })
}

/// 服务信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServiceInfo {
    pub base_url: String,
    pub enabled: bool,
    pub sdk_enabled: bool,
    pub timeout_seconds: u64,
    pub sdk_config: ComfyUISDKConfig,
}

/// 重置 ComfyUI SDK 配置为默认值
#[tauri::command]
pub async fn reset_comfyui_sdk_config(
    state: State<'_, AppState>,
) -> Result<ComfyUISDKConfig, String> {
    // TODO: 实现配置重置功能
    info!("ComfyUI SDK 配置重置请求");
    Ok(ComfyUISDKConfig::default())
}
