use anyhow::{Result, anyhow};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::time::{Duration, Instant};
use reqwest::Client;
use tokio_tungstenite::{connect_async, tungstenite::Message};
use futures_util::StreamExt;
use tracing::{info, warn, error, debug};
use tokio::time::{sleep, timeout};

use crate::config::ComfyUISettings;
use crate::data::models::outfit_photo_generation::{
    WorkflowProgress, WorkflowNodeReplacement
};
use crate::business::services::cloud_upload_service::{CloudUploadService, UploadResult};

/// ComfyUI 执行错误类型
#[derive(Debug, thiserror::Error)]
pub enum ComfyUIError {
    #[error("网络连接错误: {0}")]
    NetworkError(String),
    #[error("工作流执行错误: {0}")]
    WorkflowError(String),
    #[error("WebSocket 连接错误: {0}")]
    WebSocketError(String),
    #[error("超时错误: {0}")]
    TimeoutError(String),
    #[error("节点错误: {node_id} - {message}")]
    NodeError { node_id: String, message: String },
    #[error("服务不可用")]
    ServiceUnavailable,
    #[error("无效的工作流格式: {0}")]
    InvalidWorkflow(String),
}

/// 重试配置
#[derive(Debug, Clone)]
pub struct RetryConfig {
    pub max_attempts: u32,
    pub initial_delay: Duration,
    pub max_delay: Duration,
    pub backoff_multiplier: f64,
}

impl Default for RetryConfig {
    fn default() -> Self {
        Self {
            max_attempts: 3,
            initial_delay: Duration::from_secs(1),
            max_delay: Duration::from_secs(30),
            backoff_multiplier: 2.0,
        }
    }
}

/// 工作流执行配置
#[derive(Debug, Clone)]
pub struct WorkflowExecutionConfig {
    pub retry_config: RetryConfig,
    pub execution_timeout: Duration,
    pub websocket_timeout: Duration,
    pub result_polling_interval: Duration,
}

impl Default for WorkflowExecutionConfig {
    fn default() -> Self {
        Self {
            retry_config: RetryConfig::default(),
            execution_timeout: Duration::from_secs(300), // 5 minutes
            websocket_timeout: Duration::from_secs(600), // 10 minutes
            result_polling_interval: Duration::from_secs(2),
        }
    }
}

/// ComfyUI 服务
/// 遵循 Tauri 开发规范的业务逻辑设计原则
pub struct ComfyUIService {
    client: Client,
    settings: ComfyUISettings,
    client_id: String,
    execution_config: WorkflowExecutionConfig,
}

/// ComfyUI 提示请求
#[derive(Debug, Serialize)]
struct PromptRequest {
    prompt: Value,
    client_id: String,
}

/// ComfyUI 提示响应
#[derive(Debug, Deserialize)]
struct PromptResponse {
    prompt_id: String,
    number: u32,
    node_errors: Option<Value>,
}

/// ComfyUI 历史记录响应
#[derive(Debug, Deserialize)]
struct HistoryResponse {
    #[serde(flatten)]
    history: HashMap<String, HistoryEntry>,
}

/// 历史记录条目
#[derive(Debug, Deserialize)]
struct HistoryEntry {
    prompt: Vec<Value>,
    outputs: HashMap<String, OutputNode>,
    status: Option<Value>,
}

/// 输出节点
#[derive(Debug, Deserialize)]
struct OutputNode {
    images: Option<Vec<ImageOutput>>,
}

/// 图片输出
#[derive(Debug, Deserialize)]
struct ImageOutput {
    filename: String,
    subfolder: String,
    #[serde(rename = "type")]
    image_type: String,
}

/// WebSocket 消息
#[derive(Debug, Deserialize)]
struct WebSocketMessage {
    #[serde(rename = "type")]
    message_type: String,
    data: Option<Value>,
}

impl ComfyUIService {
    /// 创建新的 ComfyUI 服务实例
    pub fn new(settings: ComfyUISettings) -> Self {
        Self::with_execution_config(settings, WorkflowExecutionConfig::default())
    }

    /// 创建带有自定义执行配置的 ComfyUI 服务实例
    pub fn with_execution_config(settings: ComfyUISettings, execution_config: WorkflowExecutionConfig) -> Self {
        let client = Client::builder()
            .timeout(Duration::from_secs(settings.timeout_seconds))
            .build()
            .expect("Failed to create HTTP client");

        Self {
            client,
            settings,
            client_id: uuid::Uuid::new_v4().to_string(),
            execution_config,
        }
    }

    /// 获取服务器基础 URL
    fn get_base_url(&self) -> String {
        let protocol = if self.settings.is_local { "http" } else { "https" };
        format!("{}://{}:{}", protocol, self.settings.server_address, self.settings.server_port)
    }

    /// 获取 WebSocket URL
    fn get_websocket_url(&self) -> String {
        let protocol = if self.settings.is_local { "ws" } else { "wss" };
        format!("{}://{}:{}/ws?clientId={}", 
            protocol, self.settings.server_address, self.settings.server_port, self.client_id)
    }

    /// 检查 ComfyUI 服务器连接
    pub async fn check_connection(&self) -> Result<bool> {
        let url = format!("{}/system_stats", self.get_base_url());

        match self.client.get(&url).send().await {
            Ok(response) => {
                if response.status().is_success() {
                    info!("ComfyUI 服务器连接成功");
                    Ok(true)
                } else {
                    warn!("ComfyUI 服务器响应错误: {}", response.status());
                    Ok(false)
                }
            }
            Err(e) => {
                error!("ComfyUI 服务器连接失败: {}", e);
                Ok(false)
            }
        }
    }

    /// 带重试机制的异步操作执行器
    async fn execute_with_retry<F, Fut, T>(&self, operation: F) -> Result<T, ComfyUIError>
    where
        F: Fn() -> Fut,
        Fut: std::future::Future<Output = Result<T, ComfyUIError>>,
    {
        let mut delay = self.execution_config.retry_config.initial_delay;
        let mut last_error = None;

        for attempt in 1..=self.execution_config.retry_config.max_attempts {
            match operation().await {
                Ok(result) => return Ok(result),
                Err(error) => {
                    last_error = Some(error);

                    if attempt < self.execution_config.retry_config.max_attempts {
                        warn!("操作失败，第 {} 次重试，延迟 {:?}", attempt, delay);
                        sleep(delay).await;

                        // 指数退避
                        delay = std::cmp::min(
                            Duration::from_millis(
                                (delay.as_millis() as f64 * self.execution_config.retry_config.backoff_multiplier) as u64
                            ),
                            self.execution_config.retry_config.max_delay,
                        );
                    }
                }
            }
        }

        Err(last_error.unwrap_or(ComfyUIError::ServiceUnavailable))
    }

    /// 加载工作流 JSON 文件
    pub async fn load_workflow(&self, workflow_path: &str) -> Result<Value> {
        let content = tokio::fs::read_to_string(workflow_path).await
            .map_err(|e| anyhow!("读取工作流文件失败: {} - {}", workflow_path, e))?;
        
        let workflow: Value = serde_json::from_str(&content)
            .map_err(|e| anyhow!("解析工作流 JSON 失败: {}", e))?;
        
        debug!("成功加载工作流文件: {}", workflow_path);
        Ok(workflow)
    }

    /// 替换工作流中的节点值
    pub fn replace_workflow_nodes(
        &self,
        mut workflow: Value,
        replacements: Vec<WorkflowNodeReplacement>,
    ) -> Result<Value> {
        if let Value::Object(ref mut workflow_obj) = workflow {
            for replacement in replacements {
                if let Some(node) = workflow_obj.get_mut(&replacement.node_id) {
                    if let Value::Object(ref mut node_obj) = node {
                        if let Some(inputs) = node_obj.get_mut("inputs") {
                            if let Value::Object(ref mut inputs_obj) = inputs {
                                let field_name = replacement.input_field.clone();
                                inputs_obj.insert(replacement.input_field, replacement.value);
                                debug!("替换节点 {} 的输入字段 {}", replacement.node_id, field_name);
                            }
                        }
                    }
                } else {
                    warn!("未找到节点 ID: {}", replacement.node_id);
                }
            }
        }
        
        Ok(workflow)
    }

    /// 自动替换 BOWONG-INPUT- 开头的节点
    pub fn auto_replace_input_nodes(
        &self,
        workflow: Value,
        model_image_url: &str,
        product_image_url: &str,
        prompt: &str,
        negative_prompt: Option<&str>,
    ) -> Result<Value> {
        let mut replacements = Vec::new();

        info!("🔄 开始替换工作流节点:");
        info!("   模特图片URL: {}", model_image_url);
        info!("   商品图片URL: {}", product_image_url);
        info!("   提示词: {}", prompt);
        if let Some(neg) = negative_prompt {
            info!("   负面提示词: {}", neg);
        }

        // 查找所有需要替换的节点（支持两种方式：节点ID或meta.title）
        if let Value::Object(ref workflow_obj) = workflow {
            for (node_id, node_value) in workflow_obj {
                let mut should_replace = false;
                let mut replacement_type = "";

                // 方式1: 检查节点ID是否以BOWONG-INPUT-开头
                if node_id.starts_with("BOWONG-INPUT-") {
                    should_replace = true;
                    if node_id.contains("MODEL") || node_id.contains("AVATAR") {
                        replacement_type = "model";
                    } else if node_id.contains("PRODUCT") || node_id.contains("CLOTH") {
                        replacement_type = "product";
                    } else if node_id.contains("PROMPT") || node_id.contains("TEXT") {
                        replacement_type = "prompt";
                    } else if node_id.contains("NEGATIVE") {
                        replacement_type = "negative";
                    } else if node_id.contains("SEED") || node_id.contains("RANDOM") {
                        replacement_type = "seed";
                    }
                }
                // 方式2: 检查节点的_meta.title字段
                else if let Value::Object(node_obj) = node_value {
                    if let Some(Value::Object(meta)) = node_obj.get("_meta") {
                        if let Some(Value::String(title)) = meta.get("title") {
                            if title.contains("BOWONG-INPUT-") {
                                should_replace = true;
                                if title.contains("模特") && !title.contains("描述") {
                                    replacement_type = "model";
                                } else if title.contains("穿搭") || title.contains("商品") || title.contains("PRODUCT") || title.contains("CLOTH") {
                                    replacement_type = "product";
                                } else if title.contains("提示") || title.contains("PROMPT") || title.contains("TEXT") || title.contains("描述") {
                                    replacement_type = "prompt";
                                } else if title.contains("负面") || title.contains("NEGATIVE") {
                                    replacement_type = "negative";
                                }
                            }
                        }
                    }
                }

                // 根据替换类型添加替换规则
                if should_replace {
                    match replacement_type {
                        "model" => {
                            // 确保使用CDN格式的URL
                            let cdn_url = self.convert_to_cdn_url(model_image_url);

                            // 替换image_url字段
                            replacements.push(WorkflowNodeReplacement {
                                node_id: node_id.clone(),
                                input_field: "image_url".to_string(),
                                value: Value::String(cdn_url),
                            });

                        }
                        "product" => {
                            // 确保使用CDN格式的URL
                            let cdn_url = self.convert_to_cdn_url(product_image_url);

                            // 替换image_url字段
                            replacements.push(WorkflowNodeReplacement {
                                node_id: node_id.clone(),
                                input_field: "image_url".to_string(),
                                value: Value::String(cdn_url),
                            });

                        }
                        "prompt" => {
                            // 只有当 prompt 不为空时才进行替换，保持工作流原始设置
                            if !prompt.trim().is_empty() {
                                // 根据节点类型决定使用哪个字段
                                let field_name = if let Value::Object(node_obj) = node_value {
                                    if let Some(Value::String(class_type)) = node_obj.get("class_type") {
                                        if class_type == "String" {
                                            "value"
                                        } else {
                                            "text"
                                        }
                                    } else {
                                        "text"
                                    }
                                } else {
                                    "text"
                                };

                                replacements.push(WorkflowNodeReplacement {
                                    node_id: node_id.clone(),
                                    input_field: field_name.to_string(),
                                    value: Value::String(prompt.to_string()),
                                });

                                info!("🔄 替换 prompt 节点 {}: {}", node_id, prompt);
                            } else {
                                info!("⏭️  跳过 prompt 节点 {} 替换，保持工作流原始设置", node_id);
                            }
                        }
                        "negative" => {
                            let neg_prompt = negative_prompt.unwrap_or("");

                            // 根据节点类型决定使用哪个字段
                            let field_name = if let Value::Object(node_obj) = node_value {
                                if let Some(Value::String(class_type)) = node_obj.get("class_type") {
                                    if class_type == "String" {
                                        "value"
                                    } else {
                                        "text"
                                    }
                                } else {
                                    "text"
                                }
                            } else {
                                "text"
                            };

                            replacements.push(WorkflowNodeReplacement {
                                node_id: node_id.clone(),
                                input_field: field_name.to_string(),
                                value: Value::String(neg_prompt.to_string()),
                            });
                        }
                        "seed" => {
                            // 生成随机种子值 (0 到 2^32-1)
                            use rand::Rng;
                            let mut rng = rand::thread_rng();
                            let random_seed: u32 = rng.gen();

                            info!("🎲 生成随机种子: {}", random_seed);

                            replacements.push(WorkflowNodeReplacement {
                                node_id: node_id.clone(),
                                input_field: "seed".to_string(),
                                value: Value::Number(serde_json::Number::from(random_seed)),
                            });
                        }
                        _ => {}
                    }
                }
            }
        }

        // 额外处理：为所有KSampler节点随机化seed
        if let Value::Object(ref workflow_obj) = workflow {
            for (node_id, node_value) in workflow_obj {
                if let Value::Object(node_obj) = node_value {
                    if let Some(Value::String(class_type)) = node_obj.get("class_type") {
                        if class_type == "KSampler" || class_type == "KSamplerAdvanced" {
                            // 检查是否已经有seed替换规则
                            let already_has_seed_replacement = replacements.iter()
                                .any(|r| r.node_id == *node_id && r.input_field == "seed");

                            if !already_has_seed_replacement {
                                // 生成随机种子值
                                use rand::Rng;
                                let mut rng = rand::thread_rng();
                                let random_seed: u32 = rng.gen();

                                info!("🎲 为KSampler节点 {} 生成随机种子: {}", node_id, random_seed);

                                replacements.push(WorkflowNodeReplacement {
                                    node_id: node_id.clone(),
                                    input_field: "seed".to_string(),
                                    value: Value::Number(serde_json::Number::from(random_seed)),
                                });
                            }
                        }
                    }
                }
            }
        }

        info!("🔍 找到 {} 个需要替换的节点", replacements.len());
        for replacement in &replacements {
            info!("   节点 {}: {} = {}", replacement.node_id, replacement.input_field, replacement.value);
        }

        self.replace_workflow_nodes(workflow, replacements)
    }

    /// 提交工作流到 ComfyUI（带重试机制）
    pub async fn submit_workflow(&self, workflow: Value) -> Result<String> {
        let workflow_clone = workflow.clone();

        let result = self.execute_with_retry(|| async {
            self.submit_workflow_internal(workflow_clone.clone()).await
        }).await;

        match result {
            Ok(prompt_id) => Ok(prompt_id),
            Err(e) => Err(anyhow!("工作流提交失败: {}", e)),
        }
    }

    /// 内部工作流提交实现
    async fn submit_workflow_internal(&self, workflow: Value) -> Result<String, ComfyUIError> {
        let url = format!("{}/prompt", self.get_base_url());

        let request = PromptRequest {
            prompt: workflow,
            client_id: self.client_id.clone(),
        };

        let response = self.client
            .post(&url)
            .header("Content-Type", "application/json")
            .json(&request)
            .send()
            .await
            .map_err(|e| ComfyUIError::NetworkError(e.to_string()))?;

        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();

            return Err(match status.as_u16() {
                503 => ComfyUIError::ServiceUnavailable,
                400 => ComfyUIError::InvalidWorkflow(text),
                _ => ComfyUIError::NetworkError(format!("{} - {}", status, text)),
            });
        }

        let prompt_response: PromptResponse = response.json().await
            .map_err(|e| ComfyUIError::NetworkError(format!("解析响应失败: {}", e)))?;

        if let Some(errors) = prompt_response.node_errors {
            // 检查是否真的有错误（不是空对象）
            if let Value::Object(error_map) = &errors {
                if !error_map.is_empty() {
                    return Err(ComfyUIError::WorkflowError(format!("节点错误: {}", errors)));
                }
            } else if errors != Value::Object(serde_json::Map::new()) {
                return Err(ComfyUIError::WorkflowError(format!("节点错误: {}", errors)));
            }
            // 如果是空对象 {} 则不认为是错误
            info!("收到空的节点错误对象，继续执行");
        }

        info!("工作流提交成功，提示 ID: {}", prompt_response.prompt_id);
        Ok(prompt_response.prompt_id)
    }

    /// 获取工作流执行历史
    pub async fn get_history(&self, prompt_id: &str) -> Result<Vec<String>> {
        let url = format!("{}/history/{}", self.get_base_url(), prompt_id);
        
        let response = self.client.get(&url).send().await?;
        
        if !response.status().is_success() {
            return Err(anyhow!("获取历史记录失败: {}", response.status()));
        }

        let history: HistoryResponse = response.json().await?;
        let mut image_filenames = Vec::new();

        if let Some(entry) = history.history.get(prompt_id) {
            info!("获取到历史记录，输出节点数量: {}", entry.outputs.len());
            for (node_id, output_node) in &entry.outputs {
                info!("处理输出节点: {}", node_id);
                if let Some(images) = &output_node.images {
                    info!("节点 {} 包含 {} 张图片", node_id, images.len());
                    for image in images {
                        info!("图片信息: filename={}, subfolder={}, type={}",
                              image.filename,
                              image.subfolder,
                              image.image_type);
                        if image.image_type == "output" {
                            // 构建完整的文件路径信息
                            let full_path = if image.subfolder.is_empty() {
                                image.filename.clone()
                            } else {
                                format!("{}:{}", image.subfolder, image.filename)
                            };
                            image_filenames.push(full_path);
                        }
                    }
                }
            }
        }

        Ok(image_filenames)
    }

    /// 下载生成的图片
    pub async fn download_image(
        &self,
        filename: &str,
        subfolder: &str,
        image_type: &str,
    ) -> Result<Vec<u8>> {
        let url = format!(
            "{}/view?filename={}&subfolder={}&type={}",
            self.get_base_url(),
            filename,
            subfolder,
            image_type
        );

        let response = self.client.get(&url).send().await?;

        if !response.status().is_success() {
            return Err(anyhow!("下载图片失败: {}", response.status()));
        }

        let image_data = response.bytes().await?;
        Ok(image_data.to_vec())
    }

    /// 通过 WebSocket 跟踪工作流执行进度（带超时机制）
    pub async fn track_workflow_progress<F>(
        &self,
        prompt_id: &str,
        mut progress_callback: F,
    ) -> Result<()>
    where
        F: FnMut(WorkflowProgress) + Send + 'static,
    {
        let result = timeout(
            self.execution_config.websocket_timeout,
            self.track_workflow_progress_internal(prompt_id, &mut progress_callback)
        ).await;

        match result {
            Ok(Ok(())) => Ok(()),
            Ok(Err(e)) => Err(e),
            Err(_) => Err(anyhow!("工作流执行超时")),
        }
    }

    /// 通过 WebSocket 跟踪工作流执行进度（带 prompt_id 的回调）
    pub async fn track_workflow_progress_with_prompt_id<F>(
        &self,
        prompt_id: &str,
        mut progress_callback: F,
    ) -> Result<()>
    where
        F: FnMut(String, WorkflowProgress) + Send + 'static,
    {
        let prompt_id_clone = prompt_id.to_string();
        let mut wrapped_callback = move |progress: WorkflowProgress| {
            progress_callback(prompt_id_clone.clone(), progress);
        };

        let result = timeout(
            self.execution_config.websocket_timeout,
            self.track_workflow_progress_internal(prompt_id, &mut wrapped_callback)
        ).await;

        match result {
            Ok(Ok(())) => Ok(()),
            Ok(Err(e)) => Err(e),
            Err(_) => Err(anyhow!("工作流执行超时")),
        }
    }

    /// 内部进度跟踪实现
    async fn track_workflow_progress_internal<F>(
        &self,
        prompt_id: &str,
        progress_callback: &mut F,
    ) -> Result<()>
    where
        F: FnMut(WorkflowProgress) + Send + 'static,
    {
        let ws_url = self.get_websocket_url();

        let (ws_stream, _) = connect_async(&ws_url).await
            .map_err(|e| anyhow!("WebSocket 连接失败: {}", e))?;

        let (_ws_sender, mut ws_receiver) = ws_stream.split();

        info!("WebSocket 连接成功，开始跟踪进度，提示 ID: {}", prompt_id);

        let start_time = Instant::now();

        // 进度跟踪状态
        let mut executed_nodes = std::collections::HashSet::new();
        let mut estimated_total_nodes = 10; // 默认估计值，会动态调整

        while let Some(message) = ws_receiver.next().await {
            match message {
                Ok(Message::Text(text)) => {
                    if let Ok(ws_message) = serde_json::from_str::<WebSocketMessage>(&text) {
                        match ws_message.message_type.as_str() {
                            "progress" => {
                                if let Some(data) = ws_message.data {
                                    if let (Some(current), Some(max)) = (
                                        data.get("value").and_then(|v| v.as_u64()),
                                        data.get("max").and_then(|v| v.as_u64()),
                                    ) {
                                        let progress = WorkflowProgress {
                                            current_step: current as u32,
                                            total_steps: max as u32,
                                            current_node_id: None,
                                            progress_percentage: (current as f32 / max as f32) * 100.0,
                                            status_message: format!("处理中: {}/{}", current, max),
                                        };
                                        progress_callback(progress);
                                    }
                                }
                            }
                            "executing" => {
                                if let Some(data) = ws_message.data {
                                    if let Some(node_value) = data.get("node") {
                                        if node_value.is_null() {
                                            // 执行完成 - node为null表示完成
                                            let progress = WorkflowProgress {
                                                current_step: executed_nodes.len() as u32,
                                                total_steps: executed_nodes.len() as u32,
                                                current_node_id: None,
                                                progress_percentage: 100.0,
                                                status_message: "执行完成".to_string(),
                                            };
                                            progress_callback(progress);
                                            info!("工作流执行完成，提示 ID: {}, 总共执行了 {} 个节点", prompt_id, executed_nodes.len());
                                            break;
                                        } else if let Some(node_id) = node_value.as_str() {
                                            // 记录新执行的节点
                                            executed_nodes.insert(node_id.to_string());

                                            // 动态调整总节点数估计
                                            if executed_nodes.len() > estimated_total_nodes {
                                                estimated_total_nodes = executed_nodes.len() + 5; // 预留一些余量
                                            }

                                            // 计算当前进度百分比
                                            let progress_percentage = (executed_nodes.len() as f32 / estimated_total_nodes as f32 * 90.0).min(90.0); // 最多90%，留10%给完成

                                            let progress = WorkflowProgress {
                                                current_step: executed_nodes.len() as u32,
                                                total_steps: estimated_total_nodes as u32,
                                                current_node_id: Some(node_id.to_string()),
                                                progress_percentage,
                                                status_message: format!("执行节点: {} ({}/{})", node_id, executed_nodes.len(), estimated_total_nodes),
                                            };
                                            progress_callback(progress);
                                        }
                                    }
                                }
                            }
                            "execution_error" => {
                                let error_details = ws_message.data
                                    .as_ref()
                                    .and_then(|d| d.get("exception_message"))
                                    .and_then(|m| m.as_str())
                                    .unwrap_or("未知错误");

                                error!("工作流执行错误: {}", error_details);
                                return Err(anyhow!("工作流执行错误: {}", error_details));
                            }
                            "execution_interrupted" => {
                                warn!("工作流执行被中断");
                                return Err(anyhow!("工作流执行被中断"));
                            }
                            _ => {
                                debug!("收到 WebSocket 消息: {}", ws_message.message_type);
                            }
                        }
                    }
                }
                Ok(Message::Close(_)) => {
                    info!("WebSocket 连接关闭");
                    break;
                }
                Err(e) => {
                    error!("WebSocket 错误: {}", e);
                    return Err(anyhow!("WebSocket 错误: {}", e));
                }
                _ => {}
            }

            // 检查是否超过执行超时时间
            if start_time.elapsed() > self.execution_config.execution_timeout {
                warn!("工作流执行超时");
                return Err(anyhow!("工作流执行超时"));
            }
        }

        Ok(())
    }

    /// 检查工作流是否完成
    pub async fn is_workflow_completed(&self, prompt_id: &str) -> Result<bool> {
        let result = self.execute_with_retry(|| async {
            self.check_workflow_status_internal(prompt_id).await
        }).await;

        match result {
            Ok(completed) => Ok(completed),
            Err(e) => Err(anyhow!("检查工作流状态失败: {}", e)),
        }
    }

    /// 内部工作流状态检查实现
    async fn check_workflow_status_internal(&self, prompt_id: &str) -> Result<bool, ComfyUIError> {
        let url = format!("{}/history/{}", self.get_base_url(), prompt_id);

        let response = self.client
            .get(&url)
            .send()
            .await
            .map_err(|e| ComfyUIError::NetworkError(e.to_string()))?;

        if !response.status().is_success() {
            return Err(ComfyUIError::NetworkError(format!("HTTP {}", response.status())));
        }

        let history: HistoryResponse = response.json().await
            .map_err(|e| ComfyUIError::NetworkError(format!("解析响应失败: {}", e)))?;

        Ok(history.history.contains_key(prompt_id))
    }

    /// 执行完整的工作流生成流程（增强版）
    pub async fn execute_workflow<F>(
        &self,
        workflow_path: &str,
        model_image_url: &str,
        product_image_url: &str,
        prompt: &str,
        negative_prompt: Option<&str>,
        progress_callback: F,
    ) -> Result<Vec<String>>
    where
        F: FnMut(WorkflowProgress) + Send + 'static,
    {
        info!("开始执行工作流: {}", workflow_path);
        let start_time = Instant::now();

        // 1. 验证服务器连接
        if !self.check_connection().await? {
            return Err(anyhow!("ComfyUI 服务器不可用"));
        }

        // 2. 加载工作流
        let workflow = self.load_workflow(workflow_path).await
            .map_err(|e| anyhow!("加载工作流失败: {}", e))?;

        // 3. 替换节点值
        let updated_workflow = self.auto_replace_input_nodes(
            workflow,
            model_image_url,
            product_image_url,
            prompt,
            negative_prompt,
        ).map_err(|e| anyhow!("替换工作流节点失败: {}", e))?;

        // 保存替换后的工作流到调试文件
        if let Err(e) = self.save_debug_workflow(&updated_workflow, workflow_path, None).await {
            warn!("保存调试工作流文件失败: {}", e);
        }

        // 4. 提交工作流
        let prompt_id = self.submit_workflow(updated_workflow).await
            .map_err(|e| anyhow!("提交工作流失败: {}", e))?;

        info!("工作流提交成功，提示 ID: {}", prompt_id);

        // 5. 跟踪进度
        self.track_workflow_progress(&prompt_id, progress_callback).await
            .map_err(|e| anyhow!("跟踪工作流进度失败: {}", e))?;

        // 6. 验证工作流完成状态
        let mut attempts = 0;
        let max_attempts = 10;

        while attempts < max_attempts {
            if self.is_workflow_completed(&prompt_id).await? {
                break;
            }

            attempts += 1;
            sleep(self.execution_config.result_polling_interval).await;
        }

        if attempts >= max_attempts {
            return Err(anyhow!("工作流完成状态验证超时"));
        }

        // 7. 获取结果
        let image_filenames = self.get_history(&prompt_id).await
            .map_err(|e| anyhow!("获取工作流结果失败: {}", e))?;

        if image_filenames.is_empty() {
            return Err(anyhow!("工作流执行完成但未生成任何图片"));
        }

        let execution_time = start_time.elapsed();
        info!("工作流执行完成，耗时: {:?}，生成图片数量: {}", execution_time, image_filenames.len());

        Ok(image_filenames)
    }

    /// 执行完整的工作流生成流程（带商品编号）
    pub async fn execute_workflow_indexed<F>(
        &self,
        workflow_path: &str,
        model_image_url: &str,
        product_image_url: &str,
        prompt: &str,
        negative_prompt: Option<&str>,
        progress_callback: F,
        product_index: Option<usize>,
    ) -> Result<Vec<String>>
    where
        F: FnMut(WorkflowProgress) + Send + 'static,
    {
        info!("开始执行工作流: {} (商品编号: {:?})", workflow_path, product_index.map(|i| i + 1));
        let start_time = Instant::now();

        // 1. 验证服务器连接
        if !self.check_connection().await? {
            return Err(anyhow!("ComfyUI 服务器不可用"));
        }

        // 2. 加载工作流
        let workflow = self.load_workflow(workflow_path).await
            .map_err(|e| anyhow!("加载工作流失败: {}", e))?;

        // 3. 替换节点值
        let updated_workflow = self.auto_replace_input_nodes(
            workflow,
            model_image_url,
            product_image_url,
            prompt,
            negative_prompt,
        ).map_err(|e| anyhow!("替换工作流节点失败: {}", e))?;

        // 保存替换后的工作流到调试文件（带商品编号）
        if let Err(e) = self.save_debug_workflow(&updated_workflow, workflow_path, product_index).await {
            warn!("保存调试工作流文件失败: {}", e);
        }

        // 4. 提交工作流
        let prompt_id = self.submit_workflow(updated_workflow).await
            .map_err(|e| anyhow!("提交工作流失败: {}", e))?;

        info!("工作流提交成功，提示 ID: {}", prompt_id);

        // 5. 跟踪进度
        self.track_workflow_progress(&prompt_id, progress_callback).await
            .map_err(|e| anyhow!("跟踪工作流进度失败: {}", e))?;

        // 6. 验证工作流完成状态
        let mut attempts = 0;
        let max_attempts = 10;

        while attempts < max_attempts {
            if self.is_workflow_completed(&prompt_id).await? {
                break;
            }

            attempts += 1;
            sleep(self.execution_config.result_polling_interval).await;
        }

        if attempts >= max_attempts {
            return Err(anyhow!("工作流完成状态验证超时"));
        }

        // 7. 获取结果
        let image_filenames = self.get_history(&prompt_id).await
            .map_err(|e| anyhow!("获取工作流结果失败: {}", e))?;

        if image_filenames.is_empty() {
            return Err(anyhow!("工作流执行完成但未生成任何图片"));
        }

        let execution_time = start_time.elapsed();
        info!("工作流执行完成，耗时: {:?}，生成图片数量: {}", execution_time, image_filenames.len());

        Ok(image_filenames)
    }

    /// 批量执行工作流（支持队列管理）
    pub async fn execute_workflow_batch(
        &self,
        workflows: Vec<(String, String, String, String, Option<String>)>, // (workflow_path, model_url, product_url, prompt, negative_prompt)
    ) -> Result<Vec<Result<Vec<String>>>>
    {
        let mut results = Vec::new();
        let total_workflows = workflows.len();

        for (index, (workflow_path, model_url, product_url, prompt, negative_prompt)) in workflows.into_iter().enumerate() {
            info!("执行批量工作流 {}/{}", index + 1, total_workflows);

            // 创建一个简单的进度回调，使用 move 捕获 index
            let result = self.execute_workflow(
                &workflow_path,
                &model_url,
                &product_url,
                &prompt,
                negative_prompt.as_deref(),
                move |progress: WorkflowProgress| {
                    debug!("工作流 {} 进度: {}%", index, progress.progress_percentage);
                },
            ).await;

            results.push(result);

            // 批量执行间隔，避免服务器过载
            if index < total_workflows - 1 {
                sleep(Duration::from_secs(1)).await;
            }
        }

        Ok(results)
    }

    /// 下载并上传生成的图片到云端
    pub async fn download_and_upload_images(
        &self,
        cloud_service: &CloudUploadService,
        image_filenames: &[String],
        remote_key_prefix: Option<&str>,
    ) -> Result<Vec<UploadResult>> {
        let mut upload_results = Vec::new();

        for file_path in image_filenames {
            info!("处理生成的图片: {}", file_path);

            // 解析文件路径，提取subfolder和filename
            let (subfolder, filename) = if file_path.contains(':') {
                let parts: Vec<&str> = file_path.splitn(2, ':').collect();
                (parts[0], parts[1])
            } else {
                ("", file_path.as_str())
            };

            info!("解析文件路径: subfolder='{}', filename='{}'", subfolder, filename);

            // 首先尝试使用从history API获取的确切路径
            let mut download_attempts = vec![
                (subfolder, "output"),    // 使用history API提供的subfolder
            ];

            // 如果history API没有提供subfolder，尝试常见路径
            if subfolder.is_empty() {
                download_attempts.extend(vec![
                    ("", "temp"),            // 临时文件路径
                    ("ComfyUI", "output"),   // ComfyUI子文件夹
                    ("outputs", "output"),   // outputs子文件夹
                ]);
            }

            let mut image_data = None;
            let mut last_error = String::new();

            for (sub_folder, image_type) in download_attempts {
                let download_url = format!(
                    "{}/view?filename={}&subfolder={}&type={}",
                    self.get_base_url(),
                    filename,
                    sub_folder,
                    image_type
                );
                info!("尝试下载图片: {} 从路径: {}", filename, download_url);

                match self.download_image(filename, sub_folder, image_type).await {
                    Ok(data) => {
                        info!("成功下载图片: {} 从路径: subfolder={}, type={}", filename, sub_folder, image_type);
                        image_data = Some(data);
                        break;
                    }
                    Err(e) => {
                        warn!("下载失败: {} 从路径: subfolder={}, type={} - {}", filename, sub_folder, image_type, e);
                        last_error = e.to_string();
                    }
                }
            }

            let image_data = match image_data {
                Some(data) => data,
                None => {
                    error!("所有下载路径都失败: {} - 最后错误: {}", filename, last_error);
                    upload_results.push(UploadResult {
                        success: false,
                        remote_url: None,
                        urn: None,
                        error_message: Some(format!("下载失败: {}", last_error)),
                        file_size: 0,
                    });
                    continue;
                }
            };

            // 保存到临时文件
            let temp_path = match self.save_temp_image(filename, &image_data).await {
                Ok(path) => path,
                Err(e) => {
                    error!("保存临时文件失败: {} - {}", filename, e);
                    upload_results.push(UploadResult {
                        success: false,
                        remote_url: None,
                        urn: None,
                        error_message: Some(format!("保存临时文件失败: {}", e)),
                        file_size: image_data.len() as u64,
                    });
                    continue;
                }
            };

            // 生成远程key
            let remote_key = if let Some(prefix) = remote_key_prefix {
                Some(format!("{}/{}", prefix, filename))
            } else {
                None
            };

            // 上传到云端
            let upload_result = cloud_service
                .upload_file(&temp_path, remote_key, None)
                .await;

            match upload_result {
                Ok(result) => {
                    if result.success {
                        info!("图片上传成功: {} -> {}", filename, result.remote_url.as_deref().unwrap_or("N/A"));
                    } else {
                        warn!("图片上传失败: {} - {}", filename, result.error_message.as_deref().unwrap_or("未知错误"));
                    }
                    upload_results.push(result);
                }
                Err(e) => {
                    error!("上传图片时发生错误: {} - {}", filename, e);
                    upload_results.push(UploadResult {
                        success: false,
                        remote_url: None,
                        urn: None,
                        error_message: Some(format!("上传错误: {}", e)),
                        file_size: image_data.len() as u64,
                    });
                }
            }

            // 清理临时文件
            if let Err(e) = tokio::fs::remove_file(&temp_path).await {
                warn!("清理临时文件失败: {} - {}", temp_path, e);
            }
        }

        Ok(upload_results)
    }

    /// 保存临时图片文件
    async fn save_temp_image(&self, filename: &str, image_data: &[u8]) -> Result<String> {
        let temp_dir = std::env::temp_dir();
        let temp_path = temp_dir.join(format!("comfyui_{}", filename));

        tokio::fs::write(&temp_path, image_data).await
            .map_err(|e| anyhow!("写入临时文件失败: {}", e))?;

        Ok(temp_path.to_string_lossy().to_string())
    }

    /// 执行工作流并自动上传结果到云端
    pub async fn execute_workflow_with_upload<F>(
        &self,
        cloud_service: &CloudUploadService,
        workflow_path: &str,
        model_image_url: &str,
        product_image_url: &str,
        prompt: &str,
        negative_prompt: Option<&str>,
        remote_key_prefix: Option<&str>,
        progress_callback: F,
    ) -> Result<Vec<UploadResult>>
    where
        F: FnMut(WorkflowProgress) + Send + 'static,
    {
        self.execute_workflow_with_upload_indexed(
            cloud_service,
            workflow_path,
            model_image_url,
            product_image_url,
            prompt,
            negative_prompt,
            remote_key_prefix,
            progress_callback,
            None, // 不指定商品编号
        ).await
    }

    /// 执行工作流并自动上传结果到云端（带商品编号）
    pub async fn execute_workflow_with_upload_indexed<F>(
        &self,
        cloud_service: &CloudUploadService,
        workflow_path: &str,
        model_image_url: &str,
        product_image_url: &str,
        prompt: &str,
        negative_prompt: Option<&str>,
        remote_key_prefix: Option<&str>,
        progress_callback: F,
        product_index: Option<usize>,
    ) -> Result<Vec<UploadResult>>
    where
        F: FnMut(WorkflowProgress) + Send + 'static,
    {
        info!("开始执行工作流并上传结果: {} (商品编号: {:?})", workflow_path, product_index.map(|i| i + 1));

        // 执行工作流
        let image_filenames = self.execute_workflow_indexed(
            workflow_path,
            model_image_url,
            product_image_url,
            prompt,
            negative_prompt,
            progress_callback,
            product_index,
        ).await?;

        if image_filenames.is_empty() {
            return Err(anyhow!("工作流执行完成但未生成任何图片"));
        }

        info!("工作流执行完成，开始上传 {} 张图片", image_filenames.len());

        // 下载并上传图片
        let upload_results = self.download_and_upload_images(
            cloud_service,
            &image_filenames,
            remote_key_prefix,
        ).await?;

        let successful_uploads = upload_results.iter().filter(|r| r.success).count();
        info!("图片上传完成: {}/{} 成功", successful_uploads, upload_results.len());

        Ok(upload_results)
    }

    /// 执行工作流并自动上传结果到云端（带商品编号），返回 prompt_id 和上传结果
    pub async fn execute_workflow_with_upload_indexed_with_prompt_id<F>(
        &self,
        cloud_service: &CloudUploadService,
        workflow_path: &str,
        model_image_url: &str,
        product_image_url: &str,
        prompt: &str,
        negative_prompt: Option<&str>,
        remote_key_prefix: Option<&str>,
        progress_callback: F,
        product_index: Option<usize>,
    ) -> Result<(String, Vec<UploadResult>)>
    where
        F: FnMut(WorkflowProgress) + Send + 'static,
    {
        info!("开始执行工作流并上传结果: {} (商品编号: {:?})", workflow_path, product_index.map(|i| i + 1));
        let start_time = Instant::now();

        // 1. 验证服务器连接
        if !self.check_connection().await? {
            return Err(anyhow!("ComfyUI 服务器不可用"));
        }

        // 2. 加载工作流
        let workflow = self.load_workflow(workflow_path).await
            .map_err(|e| anyhow!("加载工作流失败: {}", e))?;

        // 3. 替换节点值
        let updated_workflow = self.auto_replace_input_nodes(
            workflow,
            model_image_url,
            product_image_url,
            prompt,
            negative_prompt,
        ).map_err(|e| anyhow!("替换工作流节点失败: {}", e))?;

        // 4. 提交工作流并获取 prompt_id
        let prompt_id = self.submit_workflow(updated_workflow).await
            .map_err(|e| anyhow!("提交工作流失败: {}", e))?;

        info!("工作流提交成功，提示 ID: {}", prompt_id);

        // 5. 跟踪进度
        self.track_workflow_progress(&prompt_id, progress_callback).await
            .map_err(|e| anyhow!("跟踪工作流进度失败: {}", e))?;

        // 6. 验证工作流完成状态
        let mut attempts = 0;
        let max_attempts = 10;

        while attempts < max_attempts {
            if self.is_workflow_completed(&prompt_id).await? {
                break;
            }

            attempts += 1;
            if attempts >= max_attempts {
                return Err(anyhow!("工作流执行超时，已等待 {} 次检查", max_attempts));
            }

            tokio::time::sleep(Duration::from_secs(1)).await;
        }

        // 7. 获取结果
        let image_filenames = self.get_history(&prompt_id).await
            .map_err(|e| anyhow!("获取工作流结果失败: {}", e))?;

        if image_filenames.is_empty() {
            return Err(anyhow!("工作流执行完成但未生成任何图片"));
        }

        info!("工作流执行完成，开始上传 {} 张图片", image_filenames.len());

        // 8. 下载并上传图片
        let upload_results = self.download_and_upload_images(
            cloud_service,
            &image_filenames,
            remote_key_prefix,
        ).await?;

        let successful_uploads = upload_results.iter().filter(|r| r.success).count();
        info!("图片上传完成: {}/{} 成功", successful_uploads, upload_results.len());

        Ok((prompt_id, upload_results))
    }

    /// 执行工作流并自动上传结果到云端（带 prompt_id 的进度回调），返回 prompt_id 和上传结果
    pub async fn execute_workflow_with_upload_indexed_with_prompt_id_callback<F>(
        &self,
        cloud_service: &CloudUploadService,
        workflow_path: &str,
        model_image_url: &str,
        product_image_url: &str,
        prompt: &str,
        negative_prompt: Option<&str>,
        remote_key_prefix: Option<&str>,
        progress_callback: F,
        product_index: Option<usize>,
    ) -> Result<(String, Vec<UploadResult>)>
    where
        F: FnMut(String, WorkflowProgress) + Send + 'static,
    {
        info!("开始执行工作流并上传结果: {} (商品编号: {:?})", workflow_path, product_index.map(|i| i + 1));

        // 1. 验证服务器连接
        if !self.check_connection().await? {
            return Err(anyhow!("ComfyUI 服务器不可用"));
        }

        // 2. 加载工作流
        let workflow = self.load_workflow(workflow_path).await
            .map_err(|e| anyhow!("加载工作流失败: {}", e))?;

        // 3. 替换节点值
        let updated_workflow = self.auto_replace_input_nodes(
            workflow,
            model_image_url,
            product_image_url,
            prompt,
            negative_prompt,
        ).map_err(|e| anyhow!("替换工作流节点失败: {}", e))?;

        // 4. 提交工作流并获取 prompt_id
        let prompt_id = self.submit_workflow(updated_workflow).await
            .map_err(|e| anyhow!("提交工作流失败: {}", e))?;

        info!("工作流提交成功，提示 ID: {}", prompt_id);

        // 5. 跟踪进度（使用带 prompt_id 的回调）
        self.track_workflow_progress_with_prompt_id(&prompt_id, progress_callback).await
            .map_err(|e| anyhow!("跟踪工作流进度失败: {}", e))?;

        // 6. 验证工作流完成状态
        let mut attempts = 0;
        let max_attempts = 10;

        while attempts < max_attempts {
            if self.is_workflow_completed(&prompt_id).await? {
                break;
            }

            attempts += 1;
            if attempts >= max_attempts {
                return Err(anyhow!("工作流执行超时，已等待 {} 次检查", max_attempts));
            }

            tokio::time::sleep(Duration::from_secs(1)).await;
        }

        // 7. 获取结果
        let image_filenames = self.get_history(&prompt_id).await
            .map_err(|e| anyhow!("获取工作流结果失败: {}", e))?;

        if image_filenames.is_empty() {
            return Err(anyhow!("工作流执行完成但未生成任何图片"));
        }

        info!("工作流执行完成，开始上传 {} 张图片", image_filenames.len());

        // 8. 下载并上传图片
        let upload_results = self.download_and_upload_images(
            cloud_service,
            &image_filenames,
            remote_key_prefix,
        ).await?;

        let successful_uploads = upload_results.iter().filter(|r| r.success).count();
        info!("图片上传完成: {}/{} 成功", successful_uploads, upload_results.len());

        Ok((prompt_id, upload_results))
    }

    /// 保存调试用的工作流文件
    async fn save_debug_workflow(&self, workflow: &Value, original_path: &str, product_index: Option<usize>) -> Result<()> {
        use std::path::Path;
        use tokio::fs;

        // 获取原始文件的目录和文件名
        let original_path = Path::new(original_path);
        let parent_dir = original_path.parent().unwrap_or(Path::new("."));
        let file_stem = original_path.file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("workflow");

        // 生成调试文件名，根据商品编号区分
        let debug_filename = if let Some(index) = product_index {
            format!("{}_debug_replaced_{}.json", file_stem, index + 1)
        } else {
            format!("{}_debug_replaced.json", file_stem)
        };
        let debug_path = parent_dir.join(debug_filename);

        // 格式化JSON并保存
        let formatted_json = serde_json::to_string_pretty(workflow)
            .map_err(|e| anyhow!("序列化工作流失败: {}", e))?;

        fs::write(&debug_path, formatted_json).await
            .map_err(|e| anyhow!("写入调试文件失败: {}", e))?;

        info!("🔍 调试工作流已保存到: {}", debug_path.display());
        Ok(())
    }

    /// 将各种格式的URL转换为CDN格式
    fn convert_to_cdn_url(&self, url: &str) -> String {
        // 如果已经是CDN URL，直接返回
        if url.contains("cdn.roasmax.cn") {
            return url.to_string();
        }

        // 如果是bowongai-dev.modal.run格式，转换为cdn.roasmax.cn
        if url.contains("bowongai-dev.modal.run") {
            return url.replace("bowongai-dev.modal.run", "cdn.roasmax.cn");
        }

        // 如果是S3格式 (s3://bucket/key)，转换为CDN格式
        if url.starts_with("s3://") {
            let url_without_prefix = &url[5..]; // 移除 "s3://"
            if let Some(first_slash) = url_without_prefix.find('/') {
                let remaining = &url_without_prefix[first_slash + 1..];
                if let Some(second_slash) = remaining.find('/') {
                    let key = &remaining[second_slash + 1..];
                    return format!("https://cdn.roasmax.cn/{}", key);
                }
            }
        }

        // 如果是完整的S3 HTTPS URL，提取key部分
        if url.contains("amazonaws.com") || url.contains("s3.") {
            if let Some(key_start) = url.find(".com/") {
                let key = &url[key_start + 5..];
                return format!("https://cdn.roasmax.cn/{}", key);
            }
        }

        // 如果无法识别格式，返回原URL
        warn!("无法识别URL格式，使用原URL: {}", url);
        url.to_string()
    }

    /// 从URL中提取文件名
    fn extract_filename_from_url(&self, url: &str) -> String {
        use std::path::Path;

        // 从URL中提取路径部分
        let path_part = if let Some(path_start) = url.find("://") {
            // 跳过协议部分
            if let Some(path_start) = url[path_start + 3..].find('/') {
                &url[path_start + 3 + path_start + 1..]
            } else {
                url
            }
        } else {
            url
        };

        // 移除查询参数
        let path_without_query = if let Some(query_start) = path_part.find('?') {
            &path_part[..query_start]
        } else {
            path_part
        };

        // 提取文件名
        let filename = Path::new(path_without_query)
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or("image.jpg")
            .to_string();

        info!("从URL提取文件名: {} -> {}", url, filename);
        filename
    }
}
