use crate::app_state::AppState;
use crate::data::models::comfyui::*;
use anyhow::Result;
use tauri::State;
use tracing::{error, info};

/// 获取所有工作流
/// 
/// 前端调用示例：
/// ```typescript
/// const workflows = await invoke('comfyui_get_all_workflows');
/// ```
#[tauri::command]
pub async fn comfyui_get_all_workflows(
    state: State<'_, AppState>,
) -> Result<Vec<Workflow>, String> {
    info!("Command: comfyui_get_all_workflows");
    
    let app_state = state.inner();
    let comfyui_service = app_state.get_comfyui_service()
        .ok_or_else(|| "ComfyUI service not initialized".to_string())?;

    match comfyui_service.get_all_workflows().await {
        Ok(workflows) => {
            info!("Successfully retrieved {} workflows", workflows.len());
            Ok(workflows)
        }
        Err(e) => {
            error!("Failed to get workflows: {}", e);
            Err(format!("Failed to get workflows: {}", e))
        }
    }
}

/// 发布工作流
/// 
/// 前端调用示例：
/// ```typescript
/// const request = {
///     name: "my_workflow",
///     workflow_data: { /* workflow config */ },
///     description: "My test workflow",
///     version: "1.0"
/// };
/// const response = await invoke('comfyui_publish_workflow', { request });
/// ```
#[tauri::command]
pub async fn comfyui_publish_workflow(
    request: PublishWorkflowRequest,
    state: State<'_, AppState>,
) -> Result<PublishWorkflowResponse, String> {
    info!("Command: comfyui_publish_workflow - {}", request.name);
    
    let app_state = state.inner();
    let comfyui_service = app_state.get_comfyui_service()
        .ok_or_else(|| "ComfyUI service not initialized".to_string())?;

    match comfyui_service.publish_workflow(request).await {
        Ok(response) => {
            info!("Successfully published workflow");
            Ok(response)
        }
        Err(e) => {
            error!("Failed to publish workflow: {}", e);
            Err(format!("Failed to publish workflow: {}", e))
        }
    }
}

/// 删除工作流
/// 
/// 前端调用示例：
/// ```typescript
/// const response = await invoke('comfyui_delete_workflow', { 
///     workflowName: "my_workflow [20250101120000]" 
/// });
/// ```
#[tauri::command]
pub async fn comfyui_delete_workflow(
    workflow_name: String,
    state: State<'_, AppState>,
) -> Result<DeleteWorkflowResponse, String> {
    info!("Command: comfyui_delete_workflow - {}", workflow_name);
    
    let app_state = state.inner();
    let comfyui_service = app_state.get_comfyui_service()
        .ok_or_else(|| "ComfyUI service not initialized".to_string())?;

    match comfyui_service.delete_workflow(&workflow_name).await {
        Ok(response) => {
            info!("Successfully deleted workflow: {}", workflow_name);
            Ok(response)
        }
        Err(e) => {
            error!("Failed to delete workflow {}: {}", workflow_name, e);
            Err(format!("Failed to delete workflow: {}", e))
        }
    }
}

/// 执行工作流
///
/// 前端调用示例：
/// ```typescript
/// const request = {
///     base_name: "my_workflow",
///     version: "1.0", // 可选
///     request_data: { /* execution parameters */ }
/// };
/// const response = await invoke('comfyui_execute_workflow', { request });
/// ```
#[tauri::command]
pub async fn comfyui_execute_workflow(
    request: ExecuteWorkflowRequest,
    state: State<'_, AppState>,
) -> Result<ExecuteWorkflowResponse, String> {
    info!("Command: comfyui_execute_workflow - {}", request.base_name);
    info!("Request data: {:?}", request);

    let app_state = state.inner();
    let comfyui_service = app_state.get_comfyui_service()
        .ok_or_else(|| "ComfyUI service not initialized".to_string())?;

    info!("Using infrastructure ComfyUI service for /api/run/ endpoint");
    match comfyui_service.execute_workflow(request).await {
        Ok(response) => {
            info!("Successfully executed workflow via /api/run/ endpoint");
            Ok(response)
        }
        Err(e) => {
            error!("Failed to execute workflow via /api/run/ endpoint: {}", e);
            Err(format!("Failed to execute workflow: {}", e))
        }
    }
}

/// 获取工作流规范
/// 
/// 前端调用示例：
/// ```typescript
/// const request = {
///     base_name: "my_workflow",
///     version: "1.0" // 可选
/// };
/// const response = await invoke('comfyui_get_workflow_spec', { request });
/// ```
#[tauri::command]
pub async fn comfyui_get_workflow_spec(
    request: GetWorkflowSpecRequest,
    state: State<'_, AppState>,
) -> Result<GetWorkflowSpecResponse, String> {
    info!("Command: comfyui_get_workflow_spec - {}", request.base_name);
    
    let app_state = state.inner();
    let comfyui_service = app_state.get_comfyui_service()
        .ok_or_else(|| "ComfyUI service not initialized".to_string())?;

    match comfyui_service.get_workflow_spec(request).await {
        Ok(response) => {
            info!("Successfully retrieved workflow spec");
            Ok(response)
        }
        Err(e) => {
            error!("Failed to get workflow spec: {}", e);
            Err(format!("Failed to get workflow spec: {}", e))
        }
    }
}

/// 获取服务器状态
/// 
/// 前端调用示例：
/// ```typescript
/// const servers = await invoke('comfyui_get_servers_status');
/// ```
#[tauri::command]
pub async fn comfyui_get_servers_status(
    state: State<'_, AppState>,
) -> Result<Vec<ServerStatus>, String> {
    info!("Command: comfyui_get_servers_status");
    
    let app_state = state.inner();
    let comfyui_service = app_state.get_comfyui_service()
        .ok_or_else(|| "ComfyUI service not initialized".to_string())?;

    match comfyui_service.get_servers_status().await {
        Ok(servers) => {
            info!("Successfully retrieved status for {} servers", servers.len());
            Ok(servers)
        }
        Err(e) => {
            error!("Failed to get servers status: {}", e);
            Err(format!("Failed to get servers status: {}", e))
        }
    }
}

/// 获取服务器文件列表
/// 
/// 前端调用示例：
/// ```typescript
/// const files = await invoke('comfyui_list_server_files', { serverIndex: 0 });
/// ```
#[tauri::command]
pub async fn comfyui_list_server_files(
    server_index: i32,
    state: State<'_, AppState>,
) -> Result<ServerFiles, String> {
    info!("Command: comfyui_list_server_files - server {}", server_index);
    
    let app_state = state.inner();
    let comfyui_service = app_state.get_comfyui_service()
        .ok_or_else(|| "ComfyUI service not initialized".to_string())?;

    match comfyui_service.list_server_files(server_index).await {
        Ok(files) => {
            info!("Successfully retrieved files for server {}", server_index);
            Ok(files)
        }
        Err(e) => {
            error!("Failed to get server files for server {}: {}", server_index, e);
            Err(format!("Failed to get server files: {}", e))
        }
    }
}

/// 获取 API 根信息
/// 
/// 前端调用示例：
/// ```typescript
/// const apiInfo = await invoke('comfyui_get_api_root');
/// ```
#[tauri::command]
pub async fn comfyui_get_api_root(
    state: State<'_, AppState>,
) -> Result<ApiRootResponse, String> {
    info!("Command: comfyui_get_api_root");
    
    let app_state = state.inner();
    let comfyui_service = app_state.get_comfyui_service()
        .ok_or_else(|| "ComfyUI service not initialized".to_string())?;

    match comfyui_service.get_api_root().await {
        Ok(response) => {
            info!("Successfully retrieved API root information");
            Ok(response)
        }
        Err(e) => {
            error!("Failed to get API root: {}", e);
            Err(format!("Failed to get API root: {}", e))
        }
    }
}

/// 测试 ComfyUI 服务连接
///
/// 前端调用示例：
/// ```typescript
/// const isConnected = await invoke('comfyui_test_connection');
/// ```
#[tauri::command]
pub async fn comfyui_test_connection(
    state: State<'_, AppState>,
) -> Result<bool, String> {
    info!("Command: comfyui_test_connection");

    let app_state = state.inner();
    let comfyui_service = app_state.get_comfyui_service()
        .ok_or_else(|| "ComfyUI service not initialized".to_string())?;

    match comfyui_service.test_connection().await {
        Ok(is_connected) => {
            info!("Connection test result: {}", is_connected);
            Ok(is_connected)
        }
        Err(e) => {
            error!("Failed to test connection: {}", e);
            Err(format!("Failed to test connection: {}", e))
        }
    }
}

/// 直接获取 ComfyUI 原生 API 数据
///
/// 前端调用示例：
/// ```typescript
/// const data = await invoke('comfyui_get_native_data', { endpoint: 'history' });
/// ```
#[tauri::command]
pub async fn comfyui_get_native_data(
    endpoint: String,
    state: State<'_, AppState>,
) -> Result<serde_json::Value, String> {
    info!("Command: comfyui_get_native_data, endpoint: {}", endpoint);

    let app_state = state.inner();
    let comfyui_service = app_state.get_comfyui_service()
        .ok_or_else(|| "ComfyUI service not initialized".to_string())?;

    // 构建 URL
    let base_url = &comfyui_service.get_config().base_url;
    let url = if endpoint.starts_with('/') {
        format!("{}{}", base_url.trim_end_matches('/'), endpoint)
    } else {
        format!("{}/{}", base_url.trim_end_matches('/'), endpoint)
    };

    info!("Fetching data from: {}", url);

    // 创建 HTTP 客户端
    let client = reqwest::Client::new();

    match client.get(&url).send().await {
        Ok(response) => {
            if response.status().is_success() {
                match response.json::<serde_json::Value>().await {
                    Ok(data) => {
                        info!("Successfully fetched data from {}", endpoint);
                        Ok(data)
                    }
                    Err(e) => {
                        error!("Failed to parse JSON response: {}", e);
                        Err(format!("Failed to parse JSON response: {}", e))
                    }
                }
            } else {
                error!("HTTP error {}: {}", response.status(), url);
                Err(format!("HTTP error {}", response.status()))
            }
        }
        Err(e) => {
            error!("Failed to fetch data from {}: {}", url, e);
            Err(format!("Failed to fetch data: {}", e))
        }
    }
}

/// 直接从指定的 ComfyUI 节点获取数据（用于本地节点管理）
///
/// 前端调用示例：
/// ```typescript
/// const data = await invoke('comfyui_node_get_data', {
///   nodeUrl: 'http://192.168.0.193:8188',
///   endpoint: 'history'
/// });
/// ```
#[tauri::command]
pub async fn comfyui_node_get_data(
    nodeUrl: String,
    endpoint: String,
) -> Result<serde_json::Value, String> {
    info!("Command: comfyui_node_get_data, node: {}, endpoint: {}", nodeUrl, endpoint);

    // 构建 URL
    let url = if endpoint.starts_with('/') {
        format!("{}{}", nodeUrl.trim_end_matches('/'), endpoint)
    } else {
        format!("{}/{}", nodeUrl.trim_end_matches('/'), endpoint)
    };

    info!("Fetching data from node: {}", url);

    // 创建 HTTP 客户端
    let client = reqwest::Client::new();

    match client.get(&url).send().await {
        Ok(response) => {
            if response.status().is_success() {
                match response.json::<serde_json::Value>().await {
                    Ok(data) => {
                        info!("Successfully fetched data from node {} endpoint {}", nodeUrl, endpoint);
                        Ok(data)
                    }
                    Err(e) => {
                        error!("Failed to parse JSON response from node: {}", e);
                        Err(format!("Failed to parse JSON response: {}", e))
                    }
                }
            } else {
                error!("HTTP error {} from node: {}", response.status(), url);
                Err(format!("HTTP error {}", response.status()))
            }
        }
        Err(e) => {
            error!("Failed to fetch data from node {}: {}", url, e);
            Err(format!("Failed to fetch data: {}", e))
        }
    }
}

/// 获取 ComfyUI 服务配置
/// 
/// 前端调用示例：
/// ```typescript
/// const config = await invoke('comfyui_get_config');
/// ```
#[tauri::command]
pub async fn comfyui_get_config(
    state: State<'_, AppState>,
) -> Result<ComfyUIConfig, String> {
    info!("Command: comfyui_get_config");
    
    let app_state = state.inner();
    let comfyui_service = app_state.get_comfyui_service()
        .ok_or_else(|| "ComfyUI service not initialized".to_string())?;

    let legacy_config = comfyui_service.get_config().clone();
    // 转换为新的配置格式
    let config = ComfyUIConfig {
        base_url: legacy_config.base_url,
        timeout_seconds: legacy_config.timeout.unwrap_or(300),
        retry_attempts: legacy_config.retry_attempts.unwrap_or(3),
        retry_delay_ms: 1000,
        enable_websocket: true,
        enable_cache: legacy_config.enable_cache.unwrap_or(true),
        max_concurrency: legacy_config.max_concurrency.unwrap_or(4),
        custom_headers: None,
    };
    info!("Successfully retrieved ComfyUI configuration");
    Ok(config)
}

/// 更新 ComfyUI 服务配置
/// 
/// 前端调用示例：
/// ```typescript
/// const newConfig = {
///     base_url: "https://new-api-url.com",
///     timeout: 60,
///     retry_attempts: 5,
///     enable_cache: true,
///     max_concurrency: 10
/// };
/// const success = await invoke('comfyui_update_config', { config: newConfig });
/// ```
#[tauri::command]
pub async fn comfyui_update_config(
    config: ComfyUIConfig,
    state: State<'_, AppState>,
) -> Result<bool, String> {
    info!("Command: comfyui_update_config");
    
    let app_state = state.inner();
    
    match app_state.update_comfyui_config(config).await {
        Ok(_) => {
            info!("Successfully updated ComfyUI configuration");
            Ok(true)
        }
        Err(e) => {
            error!("Failed to update ComfyUI configuration: {}", e);
            Err(format!("Failed to update configuration: {}", e))
        }
    }
}
