package com.dora.service.provider.impl;

import com.alibaba.fastjson.JSON;
import com.dora.dto.provider.*;
import com.dora.dto.suchuang.*;
import com.dora.service.provider.AIProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 速创API适配器
 * 
 * <p>特点：
 * - 统一的Sora2接口，通过参数区分功能
 * - 有url参数 = 图生视频，无url参数 = 文生视频
 * - 异步API，需要轮询查询结果
 * 
 * @author 1818AI
 * @since 2025-10-23
 */
@Slf4j
@Service("suChuangProvider")
public class SuChuangProviderImpl implements AIProvider {

    private final RestTemplate restTemplate;
    
    @Value("${ai.providers.suchuang.api-url:https://api.wuyinkeji.com}")
    private String apiUrl;
    
    @Value("${ai.providers.suchuang.api-key}")
    private String apiKey;
    
    public SuChuangProviderImpl(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @Override
    public ProviderTaskResponse submitTask(ProviderTaskRequest request) {
        log.info("SuChuang Provider - 提交任务，模型: {}", request.getModelName());
        
        try {
            // 1. 从providerConfig中解析配置，如果为null则使用默认值
            Map<String, Object> config = request.getProviderConfig();
            String aspectRatio = "9:16";  // 默认竖屏
            String duration = "10";       // 默认10秒
            String size = "small";        // 默认小尺寸
            String taskType = "text2video"; // 默认文生视频
            
            if (config != null) {
                aspectRatio = (String) config.getOrDefault("aspectRatio", aspectRatio);
                duration = String.valueOf(config.getOrDefault("duration", duration));
                size = (String) config.getOrDefault("size", size);
                taskType = (String) config.getOrDefault("taskType", taskType);
            }
            
            // 新增：判断是否为 nanoBanana-pro 模型（手办生成）
            boolean isNanoBananaPro = isNanoBananaProModel(request.getModelName());
            if (isNanoBananaPro) {
                String imgAspectRatio = "auto";
                String imageSize = "1K";
                if (config != null) {
                    String ar = (String) config.get("aspectRatio");
                    if (ar != null && Arrays.asList("auto", "1:1", "16:9", "9:16", "4:3", "3:4", "3:2", "2:3", "5:4", "4:5", "21:9").contains(ar)) {
                        imgAspectRatio = ar;
                    }
                    String is = (String) config.get("imageSize");
                    if (is != null && Arrays.asList("1K", "2K", "4K").contains(is.toUpperCase())) {
                        imageSize = is.toUpperCase();
                    }
                }
                return submitNanoBananaProTask(request, imgAspectRatio, imageSize);
            }
            
            // 新增：判断是否为生图任务（img/draw）
            boolean isImageDraw = isImageDrawTask(taskType, request.getModelName());
            if (isImageDraw) {
                // 生图接口的 size 含义为输出比例：auto/1:1/2:3/3:2
                String imgSize = "auto";
                if (config != null) {
                    String ar = (String) config.get("aspectRatio");
                    if (ar != null && Arrays.asList("auto", "1:1", "2:3", "3:2").contains(ar)) {
                        imgSize = ar;
                    } else if (config.get("imgSize") != null) {
                        imgSize = String.valueOf(config.get("imgSize"));
                    }
                }
                return submitImageDrawTask(request, imgSize);
            }
            
            // 判断是否为 sora2pro 模型
            boolean isSora2Pro = isSora2ProModel(request.getModelName());
            
            // 2. 判断是否为图生视频（支持多种格式）
            boolean isImage2Video = "image2video".equals(taskType) || "image_to_video".equals(taskType);
            String imageUrl = "";
            if (isImage2Video) {
                imageUrl = request.getImageUrl();
                if (imageUrl == null || imageUrl.trim().isEmpty()) {
                    throw new IllegalArgumentException("图生视频任务必须提供imageUrl");
                }
            }
            
            // 3. 构建POST请求（使用表单提交，避免中文乱码）
            // sora2pro 使用不同的接口
            String requestUrl = isSora2Pro ? apiUrl + "/api/sora2pro/submit" : apiUrl + "/api/sora2-new/submit";
            
            // 4. 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.valueOf("application/x-www-form-urlencoded;charset=UTF-8"));
            headers.set("Authorization", apiKey);
            
            // 5. 构建表单参数
            MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
            formData.add("prompt", request.getPrompt());
            formData.add("aspectRatio", aspectRatio);
            formData.add("duration", duration);
            // sora2pro 接口不需要 size 参数（25秒只能标清，15秒通过配置区分高清/标清）
            if (!isSora2Pro) {
                formData.add("size", size);
            }
            if (isImage2Video && imageUrl != null && !imageUrl.isEmpty()) {
                formData.add("url", imageUrl);
            }
            
            // 处理续作参数
            boolean isContinueTask = false;
            String pidParam = null;
            if (request.getExtraParams() != null && request.getExtraParams().containsKey("sourcePid")) {
                String sourcePid = (String) request.getExtraParams().get("sourcePid");
                if (sourcePid != null && !sourcePid.isEmpty()) {
                    // 注意：速创续作接口要求使用 remixTargetId 字段承载上一条视频的 pid（大小写敏感）
                    formData.add("remixTargetId", sourcePid);
                    isContinueTask = true;
                    pidParam = sourcePid;
                }
            }
            
            // 详细记录提交请求的负载数据
            log.info("=== SuChuang Provider 提交任务负载数据（POST） ===");
            log.info("请求类型: {}", isContinueTask ? "【续作任务】" : "【普通任务】");
            log.info("请求URL: {}", requestUrl);
            log.info("模型类型: {}", isSora2Pro ? "sora2pro" : "sora2");
            log.info("任务类型: {}", taskType);
            log.info("是否图生视频: {}", isImage2Video);
            if (isContinueTask) {
                log.info("续作来源: {}", pidParam);
            }
            log.info("提示词: {}", request.getPrompt());
            log.info("参考图片URL: {}", isImage2Video ? imageUrl : "N/A (文生视频)");
            log.info("宽高比: {}", aspectRatio);
            log.info("时长: {} 秒", duration);
            if (!isSora2Pro) {
                log.info("尺寸: {}", size);
            }
            log.info("API密钥: {}***", apiKey.length() > 6 ? apiKey.substring(0, 6) : apiKey);
            log.info("=======================================");
            
            // 6. 发送POST请求
            HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(formData, headers);
            ResponseEntity<SuChuangSubmitResponse> response = restTemplate.postForEntity(
                    requestUrl, entity, SuChuangSubmitResponse.class
            );
            
            SuChuangSubmitResponse submitResponse = response.getBody();
            
            // 打印完整响应
            log.info("SuChuang Provider - 提交任务响应: {}", JSON.toJSONString(submitResponse));
            
            // 5. 解析响应
            if (submitResponse == null || submitResponse.getCode() != 200) {
                String errorMsg = submitResponse != null ? submitResponse.getMsg() : "响应为空";
                log.error("SuChuang Provider - 提交失败: code={}, msg={}", 
                         submitResponse != null ? submitResponse.getCode() : null, errorMsg);
                return ProviderTaskResponse.builder()
                        .status(ProviderTaskResponse.TaskSubmitStatus.FAILED)
                        .errorMessage("速创API提交失败: " + errorMsg)
                        .build();
            }
            
            String taskId = submitResponse.getData().getId();
            log.info("SuChuang Provider - 任务已提交成功，taskId: {}", taskId);
            
            // 6. 构建响应
            Map<String, Object> rawResponse = new HashMap<>();
            rawResponse.put("taskId", taskId);
            rawResponse.put("exec_time", submitResponse.getExec_time());
            
            return ProviderTaskResponse.builder()
                    .providerTaskId(taskId)
                    .status(ProviderTaskResponse.TaskSubmitStatus.PROCESSING)
                    .rawResponse(rawResponse)
                    .build();
            
        } catch (Exception e) {
            log.error("SuChuang Provider - 提交任务异常: {}", e.getMessage(), e);
            return ProviderTaskResponse.builder()
                    .status(ProviderTaskResponse.TaskSubmitStatus.FAILED)
                    .errorMessage("提交速创API任务失败: " + e.getMessage())
                    .build();
        }
    }

    @Override
    public ProviderTaskStatus queryTaskStatus(String providerTaskId) {
        log.info("SuChuang Provider - 查询任务状态，taskId: {}", providerTaskId);
        
        try {
            // 生图任务的ID为纯数字；视频任务ID通常为UUID
            if (isNumericId(providerTaskId)) {
                return queryImageDrawStatus(providerTaskId);
            }

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", apiKey);
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            
            HttpEntity<?> entity = new HttpEntity<>(headers);
            
            String url = apiUrl + "/api/sora2/detail?id=" + providerTaskId;
            log.info("SuChuang Provider - 查询状态请求: URL={}, taskId={}", url, providerTaskId);
            
            // 先获取原始响应用于调试
            ResponseEntity<String> rawResponse = restTemplate.exchange(
                    url, HttpMethod.GET, entity, String.class
            );
            
            // 打印原始响应
            log.info("SuChuang Provider - 查询状态原始响应: {}", rawResponse.getBody());
            
            // 解析JSON响应
            SuChuangDetailResponse detailResponse;
            try {
                detailResponse = JSON.parseObject(rawResponse.getBody(), SuChuangDetailResponse.class);
                
                // 对返回数据中的URL编码字段进行解码处理
                if (detailResponse != null && detailResponse.getData() != null) {
                    decodeResponseData(detailResponse.getData());
                    log.info("SuChuang Provider - 查询状态解析后（已解码）: taskId={}, status={}, content={}", 
                             providerTaskId, detailResponse.getData().getStatus(), detailResponse.getData().getContent());
                } else {
                    log.info("SuChuang Provider - 查询状态解析后: {}", JSON.toJSONString(detailResponse));
                }
            } catch (Exception e) {
                log.error("SuChuang Provider - JSON解析失败: {}, 原始响应: {}", e.getMessage(), rawResponse.getBody());
                throw new RuntimeException("解析速创API响应失败: " + e.getMessage());
            }
            
            if (detailResponse == null || detailResponse.getCode() != 200) {
                log.warn("SuChuang Provider - 查询状态失败: code={}, msg={}", 
                         detailResponse != null ? detailResponse.getCode() : null,
                         detailResponse != null ? detailResponse.getMsg() : "响应为空");
                return ProviderTaskStatus.builder()
                        .providerTaskId(providerTaskId)
                        .status(ProviderTaskStatus.Status.UNKNOWN)
                        .errorMessage(detailResponse != null ? detailResponse.getMsg() : "查询失败")
                        .build();
            }
            
            // 映射状态：0-排队中，1-成功，2-失败，3-生成中
            Integer scStatus = detailResponse.getData().getStatus();
            ProviderTaskStatus.Status mappedStatus = mapSuChuangStatus(scStatus);
            
            // 错误信息处理：友好提示 + 原始错误信息
            String errorMessage = null;
            if (scStatus != null && scStatus == 2) {
                // 状态为2（失败）时，组合友好提示和速创返回的fail_reason
                String failReason = detailResponse.getData().getFail_reason();
                if (failReason != null && !failReason.trim().isEmpty() && !"null".equalsIgnoreCase(failReason)) {
                    errorMessage = "生成失败，积分已退回。错误原因：" + failReason;
                } else {
                    errorMessage = "生成失败，积分已退回。请稍后重试";
                }
            } else if (detailResponse.getData().getFail_reason() != null 
                       && !detailResponse.getData().getFail_reason().trim().isEmpty()
                       && !"null".equalsIgnoreCase(detailResponse.getData().getFail_reason())) {
                errorMessage = detailResponse.getData().getFail_reason();
            }
            
            log.info("SuChuang Provider - 任务状态: taskId={}, scStatus={}, mappedStatus={}, error={}", 
                     providerTaskId, scStatus, mappedStatus, errorMessage);
            
            return ProviderTaskStatus.builder()
                    .providerTaskId(providerTaskId)
                    .status(mappedStatus)
                    .errorMessage(errorMessage)
                    .build();
            
        } catch (Exception e) {
            log.error("SuChuang Provider - 查询状态异常: {}", e.getMessage(), e);
            return ProviderTaskStatus.builder()
                    .providerTaskId(providerTaskId)
                    .status(ProviderTaskStatus.Status.UNKNOWN)
                    .errorMessage(e.getMessage())
                    .build();
        }
    }

    @Override
    public ProviderTaskResult getTaskResult(String providerTaskId) {
        log.info("SuChuang Provider - 获取任务结果，taskId: {}", providerTaskId);
        
        try {
            // 生图任务的ID为纯数字；视频任务ID通常为UUID
            if (isNumericId(providerTaskId)) {
                return getImageDrawResult(providerTaskId);
            }

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", apiKey);
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            
            HttpEntity<?> entity = new HttpEntity<>(headers);
            
            String url = apiUrl + "/api/sora2/detail?id=" + providerTaskId;
            log.info("SuChuang Provider - 获取结果请求: URL={}, taskId={}", url, providerTaskId);
            
            // 先获取原始响应用于调试
            ResponseEntity<String> rawResponse = restTemplate.exchange(
                    url, HttpMethod.GET, entity, String.class
            );
            
            // 打印原始响应
            log.info("SuChuang Provider - 获取结果原始响应: {}", rawResponse.getBody());
            
            // 解析JSON响应
            SuChuangDetailResponse detailResponse;
            try {
                detailResponse = JSON.parseObject(rawResponse.getBody(), SuChuangDetailResponse.class);
                
                // 对返回数据中的URL编码字段进行解码处理
                if (detailResponse != null && detailResponse.getData() != null) {
                    decodeResponseData(detailResponse.getData());
                }
                
                log.info("SuChuang Provider - 获取结果解析后（已解码）: {}", JSON.toJSONString(detailResponse));
            } catch (Exception e) {
                log.error("SuChuang Provider - JSON解析失败: {}, 原始响应: {}", e.getMessage(), rawResponse.getBody());
                throw new RuntimeException("解析速创API响应失败: " + e.getMessage());
            }
            
            if (detailResponse == null || detailResponse.getCode() != 200) {
                log.error("SuChuang Provider - 获取结果失败: code={}, msg={}", 
                          detailResponse != null ? detailResponse.getCode() : null,
                          detailResponse != null ? detailResponse.getMsg() : "响应为空");
                return ProviderTaskResult.builder()
                        .providerTaskId(providerTaskId)
                        .success(false)
                        .errorMessage(detailResponse != null ? detailResponse.getMsg() : "获取结果失败")
                        .build();
            }
            
            // 检查状态是否为成功
            if (detailResponse.getData().getStatus() != 1) {
                Integer status = detailResponse.getData().getStatus();
                String errorMsg;
                if (status != null && status == 2) {
                    // 状态为2（失败）时，组合友好提示和速创返回的fail_reason
                    String failReason = detailResponse.getData().getFail_reason();
                    if (failReason != null && !failReason.trim().isEmpty() && !"null".equalsIgnoreCase(failReason)) {
                        errorMsg = "生成失败，积分已退回。错误原因：" + failReason;
                    } else {
                        errorMsg = "生成失败，积分已退回。请稍后重试";
                    }
                } else {
                    errorMsg = "任务未完成，状态: " + status;
                }
                log.error("SuChuang Provider - 任务未完成，状态: {}, 错误: {}", status, errorMsg);
                return ProviderTaskResult.builder()
                        .providerTaskId(providerTaskId)
                        .success(false)
                        .errorMessage(errorMsg)
                        .build();
            }
            
            // 获取结果URL
            String resultUrl = detailResponse.getData().getRemote_url();
            if (resultUrl == null || resultUrl.trim().isEmpty()) {
                log.error("SuChuang Provider - 结果URL为空");
                return ProviderTaskResult.builder()
                        .providerTaskId(providerTaskId)
                        .success(false)
                        .errorMessage("结果URL为空")
                        .build();
            }
            
            // 构建文件列表
            List<ProviderTaskResult.ResultFile> files = new ArrayList<>();
            files.add(ProviderTaskResult.ResultFile.builder()
                    .fileUrl(resultUrl)
                    .fileType("mp4")
                    .build());
            
            log.info("SuChuang Provider - 成功获取结果文件: {}", resultUrl);
            
            // 获取PID（如果存在）
            String pid = detailResponse.getData().getPid();
            
            return ProviderTaskResult.builder()
                    .providerTaskId(providerTaskId)
                    .success(true)
                    .files(files)
                    .pid(pid)
                    .build();
            
        } catch (Exception e) {
            log.error("SuChuang Provider - 获取结果异常: {}", e.getMessage(), e);
            return ProviderTaskResult.builder()
                    .providerTaskId(providerTaskId)
                    .success(false)
                    .errorMessage(e.getMessage())
                    .build();
        }
    }

    @Override
    public String getProviderName() {
        return "suchuang";
    }

    @Override
    public boolean isAsyncProvider() {
        return true;  // 速创API是异步API
    }

    /**
     * 映射速创API状态到统一状态
     * 0-排队中，1-成功，2-失败，3-生成中
     */
    private ProviderTaskStatus.Status mapSuChuangStatus(Integer scStatus) {
        if (scStatus == null) {
            return ProviderTaskStatus.Status.UNKNOWN;
        }
        
        switch (scStatus) {
            case 0:
                return ProviderTaskStatus.Status.QUEUED;
            case 3:
                return ProviderTaskStatus.Status.RUNNING;
            case 1:
                return ProviderTaskStatus.Status.SUCCESS;
            case 2:
                return ProviderTaskStatus.Status.FAILED;
            default:
                return ProviderTaskStatus.Status.UNKNOWN;
        }
    }
    
    /**
     * 生图(img/draw)任务：状态映射
     * 0:排队中，1:生成中，2:成功，3:失败
     */
    private ProviderTaskStatus.Status mapSuChuangDrawStatus(Integer scStatus) {
        if (scStatus == null) {
            return ProviderTaskStatus.Status.UNKNOWN;
        }
        switch (scStatus) {
            case 0:
                return ProviderTaskStatus.Status.QUEUED;
            case 1:
                return ProviderTaskStatus.Status.RUNNING;
            case 2:
                return ProviderTaskStatus.Status.SUCCESS;
            case 3:
                return ProviderTaskStatus.Status.FAILED;
            default:
                return ProviderTaskStatus.Status.UNKNOWN;
        }
    }
    
    /**
     * 解码响应数据中的URL编码字段
     */
    private void decodeResponseData(SuChuangDetailResponse.DetailData data) {
        if (data == null) {
            return;
        }
        
        try {
            // 解码content字段（中文内容）
            if (data.getContent() != null && !data.getContent().isEmpty()) {
                String decodedContent = URLDecoder.decode(data.getContent(), StandardCharsets.UTF_8);
                data.setContent(decodedContent);
            }
            
            // 解码url字段（参考图片URL）
            if (data.getUrl() != null && !data.getUrl().isEmpty()) {
                String decodedUrl = URLDecoder.decode(data.getUrl(), StandardCharsets.UTF_8);
                data.setUrl(decodedUrl);
            }
            
            // 注意：remote_url 为带签名的Azure存储URL，必须保持原样，不能解码
            // 解码会破坏URL中的签名参数，导致下载时403认证失败
            // remote_url 保持原始URL编码格式，直接使用
            
        } catch (Exception e) {
            log.warn("解码响应数据字段时出错: {}", e.getMessage());
        }
    }

    // ====================== 生图(img/draw)专用实现 ======================

    /**
     * 判断是否为 sora2pro 模型
     */
    private boolean isSora2ProModel(String modelName) {
        if (modelName == null) {
            return false;
        }
        String mn = modelName.toLowerCase();
        return mn.contains("sora2pro") || mn.contains("sora2_pro");
    }
    
    /**
     * 判断是否为 nanoBanana-pro 模型（手办生成）
     */
    private boolean isNanoBananaProModel(String modelName) {
        if (modelName == null) {
            return false;
        }
        String mn = modelName.toLowerCase();
        return mn.contains("nanobanana") || mn.contains("nano_banana") || mn.contains("nano-banana")
                || mn.contains("nanobanner") || mn.contains("nano_banner") || mn.contains("nano-banner");
    }
    
    private boolean isImageDrawTask(String taskType, String modelName) {
        if (taskType == null) {
            taskType = "";
        }
        String tt = taskType.toLowerCase();
        String mn = modelName != null ? modelName.toLowerCase() : "";
        // 参考以往约定的别名统一识别为生图
        // 支持：text_to_image, text2image, txt2img, image_generation, image, draw, img_draw, image_to_image, img2img
        if ("sora-image".equals(mn)) {
            return true;
        }
        return tt.equals("text_to_image")
                || tt.equals("text2image")
                || tt.equals("txt2img")
                || tt.equals("image_generation")
                || tt.equals("image")
                || tt.equals("draw")
                || tt.equals("img_draw")
                || tt.equals("image_to_image")
                || tt.equals("img2img");
    }

    private boolean isNumericId(String providerTaskId) {
        if (providerTaskId == null || providerTaskId.isEmpty()) return false;
        for (int i = 0; i < providerTaskId.length(); i++) {
            if (!Character.isDigit(providerTaskId.charAt(i))) return false;
        }
        return true;
    }

    private ProviderTaskResponse submitImageDrawTask(ProviderTaskRequest request, String size) {
        String requestUrl = apiUrl + "/api/img/draw";

        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.valueOf("application/json;charset=UTF-8"));
            headers.set("Authorization", apiKey);

            Map<String, Object> payload = new HashMap<>();
            payload.put("model", "sora-image");
            payload.put("prompt", request.getPrompt());
            if (size != null && !size.isEmpty()) {
                // 文档 size 为 1:1/2:3/3:2/auto
                payload.put("size", size);
            }
            if (request.getImageUrl() != null && !request.getImageUrl().trim().isEmpty()) {
                // img_url 支持 string 或 array：
                // - 若传入为JSON数组字符串，则按数组提交
                // - 否则按单字符串提交
                String iu = request.getImageUrl().trim();
                if ((iu.startsWith("[") && iu.endsWith("]"))) {
                    try {
                        @SuppressWarnings("unchecked")
                        List<String> urls = JSON.parseObject(iu, List.class);
                        if (urls != null && !urls.isEmpty()) {
                            payload.put("img_url", urls);
                        }
                    } catch (Exception ignore) {
                        payload.put("img_url", request.getImageUrl());
                    }
                } else {
                    payload.put("img_url", request.getImageUrl());
                }
            }

            HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(payload), headers);

            log.info("=== SuChuang Image Draw 提交任务负载数据（POST JSON） ===");
            log.info("请求URL: {}", requestUrl);
            log.info("payload: {}", JSON.toJSONString(payload));
            log.info("API密钥: {}***", apiKey.length() > 6 ? apiKey.substring(0, 6) : apiKey);
            log.info("====================================================");

            ResponseEntity<String> response = restTemplate.postForEntity(requestUrl, entity, String.class);
            String body = response.getBody();
            log.info("SuChuang Image Draw - 提交任务响应: {}", body);

            @SuppressWarnings("unchecked")
            Map<String, Object> resp = JSON.parseObject(body, Map.class);
            if (resp == null || !Integer.valueOf(200).equals(resp.get("code"))) {
                String msg = resp != null ? String.valueOf(resp.get("msg")) : "响应为空";
                return ProviderTaskResponse.builder()
                        .status(ProviderTaskResponse.TaskSubmitStatus.FAILED)
                        .errorMessage("速创生图提交失败: " + msg)
                        .build();
            }

            @SuppressWarnings("unchecked")
            Map<String, Object> data = (Map<String, Object>) resp.get("data");
            if (data == null || data.get("id") == null) {
                return ProviderTaskResponse.builder()
                        .status(ProviderTaskResponse.TaskSubmitStatus.FAILED)
                        .errorMessage("速创生图提交失败: 未返回任务ID")
                        .build();
            }

            String taskId = String.valueOf(data.get("id"));
            Map<String, Object> rawResponse = new HashMap<>();
            rawResponse.put("taskId", taskId);

            return ProviderTaskResponse.builder()
                    .providerTaskId(taskId)
                    .status(ProviderTaskResponse.TaskSubmitStatus.PROCESSING)
                    .rawResponse(rawResponse)
                    .build();
        } catch (Exception e) {
            log.error("SuChuang Image Draw - 提交任务异常: {}", e.getMessage(), e);
            return ProviderTaskResponse.builder()
                    .status(ProviderTaskResponse.TaskSubmitStatus.FAILED)
                    .errorMessage("提交速创生图任务失败: " + e.getMessage())
                    .build();
        }
    }

    private ProviderTaskStatus queryImageDrawStatus(String providerTaskId) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", apiKey);
            headers.setContentType(MediaType.APPLICATION_JSON);

            HttpEntity<?> entity = new HttpEntity<>(headers);

            String url = apiUrl + "/api/img/drawDetail?id=" + providerTaskId;
            log.info("SuChuang Image Draw - 查询状态请求: URL={}, taskId={}", url, providerTaskId);

            ResponseEntity<String> rawResponse = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
            String body = rawResponse.getBody();
            log.info("SuChuang Image Draw - 查询状态原始响应: {}", body);

            @SuppressWarnings("unchecked")
            Map<String, Object> resp = JSON.parseObject(body, Map.class);
            if (resp == null || !Integer.valueOf(200).equals(resp.get("code"))) {
                String msg = resp != null ? String.valueOf(resp.get("msg")) : "查询失败";
                return ProviderTaskStatus.builder()
                        .providerTaskId(providerTaskId)
                        .status(ProviderTaskStatus.Status.UNKNOWN)
                        .errorMessage(msg)
                        .build();
            }

            @SuppressWarnings("unchecked")
            Map<String, Object> data = (Map<String, Object>) resp.get("data");
            Integer status = data != null ? (data.get("status") instanceof Number ? ((Number) data.get("status")).intValue() : null) : null;
            String failReason = data != null ? String.valueOf(data.getOrDefault("fail_reason", null)) : null;

            ProviderTaskStatus.Status mapped = mapSuChuangDrawStatus(status);
            String errorMessage = null;
            if (status != null && status == 3) { // 3: 失败
                // 组合友好提示和速创返回的fail_reason
                if (failReason != null && !"null".equalsIgnoreCase(failReason) && !failReason.trim().isEmpty()) {
                    errorMessage = "图片生成失败，积分已退回。错误原因：" + failReason;
                } else {
                    errorMessage = "图片生成失败，积分已退回。请稍后重试";
                }
            } else if (failReason != null && !"null".equalsIgnoreCase(failReason) && !failReason.trim().isEmpty()) {
                errorMessage = failReason;
            }

            return ProviderTaskStatus.builder()
                    .providerTaskId(providerTaskId)
                    .status(mapped)
                    .errorMessage(errorMessage)
                    .build();
        } catch (Exception e) {
            log.error("SuChuang Image Draw - 查询状态异常: {}", e.getMessage(), e);
            return ProviderTaskStatus.builder()
                    .providerTaskId(providerTaskId)
                    .status(ProviderTaskStatus.Status.UNKNOWN)
                    .errorMessage(e.getMessage())
                    .build();
        }
    }

    private ProviderTaskResult getImageDrawResult(String providerTaskId) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", apiKey);
            headers.setContentType(MediaType.APPLICATION_JSON);

            HttpEntity<?> entity = new HttpEntity<>(headers);

            String url = apiUrl + "/api/img/drawDetail?id=" + providerTaskId;
            log.info("SuChuang Image Draw - 获取结果请求: URL={}, taskId={}", url, providerTaskId);

            ResponseEntity<String> rawResponse = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
            String body = rawResponse.getBody();
            log.info("SuChuang Image Draw - 获取结果原始响应: {}", body);

            @SuppressWarnings("unchecked")
            Map<String, Object> resp = JSON.parseObject(body, Map.class);
            if (resp == null || !Integer.valueOf(200).equals(resp.get("code"))) {
                String msg = resp != null ? String.valueOf(resp.get("msg")) : "获取结果失败";
                return ProviderTaskResult.builder()
                        .providerTaskId(providerTaskId)
                        .success(false)
                        .errorMessage(msg)
                        .build();
            }

            @SuppressWarnings("unchecked")
            Map<String, Object> data = (Map<String, Object>) resp.get("data");
            Integer status = data != null ? (data.get("status") instanceof Number ? ((Number) data.get("status")).intValue() : null) : null;
            if (status == null || status != 2) { // 2: 成功
                return ProviderTaskResult.builder()
                        .providerTaskId(providerTaskId)
                        .success(false)
                        .errorMessage("任务未完成，状态: " + status)
                        .build();
            }

            String imageUrl = data.get("image_url") != null ? String.valueOf(data.get("image_url")) : null;
            if (imageUrl == null || imageUrl.trim().isEmpty()) {
                return ProviderTaskResult.builder()
                        .providerTaskId(providerTaskId)
                        .success(false)
                        .errorMessage("结果URL为空")
                        .build();
            }

            List<ProviderTaskResult.ResultFile> files = new ArrayList<>();
            files.add(ProviderTaskResult.ResultFile.builder()
                    .fileUrl(imageUrl)
                    .fileType("png")
                    .build());

            return ProviderTaskResult.builder()
                    .providerTaskId(providerTaskId)
                    .success(true)
                    .files(files)
                    .build();
        } catch (Exception e) {
            log.error("SuChuang Image Draw - 获取结果异常: {}", e.getMessage(), e);
            return ProviderTaskResult.builder()
                    .providerTaskId(providerTaskId)
                    .success(false)
                    .errorMessage(e.getMessage())
                    .build();
        }
    }

    // ====================== nanoBanana-pro 手办生成专用实现 ======================

    /**
     * 提交 nanoBanana-pro 手办生成任务
     * 
     * @param request 任务请求
     * @param aspectRatio 输出图像比例：auto/1:1/16:9/9:16/4:3/3:4/3:2/2:3/5:4/4:5/21:9
     * @param imageSize 输出图像大小：1K/2K/4K
     */
    private ProviderTaskResponse submitNanoBananaProTask(ProviderTaskRequest request, String aspectRatio, String imageSize) {
        String requestUrl = apiUrl + "/api/img/nanoBanana-pro";

        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.valueOf("application/json;charset=UTF-8"));
            headers.set("Authorization", apiKey);

            Map<String, Object> payload = new HashMap<>();
            payload.put("prompt", request.getPrompt());
            
            // 设置输出比例
            if (aspectRatio != null && !aspectRatio.isEmpty()) {
                payload.put("aspectRatio", aspectRatio);
            }
            
            // 设置输出大小
            if (imageSize != null && !imageSize.isEmpty()) {
                payload.put("imageSize", imageSize);
            }
            
            // 处理参考图片URL（支持单个或数组）
            if (request.getImageUrl() != null && !request.getImageUrl().trim().isEmpty()) {
                String iu = request.getImageUrl().trim();
                if ((iu.startsWith("[") && iu.endsWith("]"))) {
                    try {
                        @SuppressWarnings("unchecked")
                        List<String> urls = JSON.parseObject(iu, List.class);
                        if (urls != null && !urls.isEmpty()) {
                            payload.put("img_url", urls);
                        }
                    } catch (Exception ignore) {
                        payload.put("img_url", request.getImageUrl());
                    }
                } else {
                    payload.put("img_url", request.getImageUrl());
                }
            }

            HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(payload), headers);

            log.info("=== SuChuang nanoBanana-pro 提交任务负载数据（POST JSON） ===");
            log.info("请求URL: {}", requestUrl);
            log.info("payload: {}", JSON.toJSONString(payload));
            log.info("API密钥: {}***", apiKey.length() > 6 ? apiKey.substring(0, 6) : apiKey);
            log.info("====================================================");

            ResponseEntity<String> response = restTemplate.postForEntity(requestUrl, entity, String.class);
            String body = response.getBody();
            log.info("SuChuang nanoBanana-pro - 提交任务响应: {}", body);

            @SuppressWarnings("unchecked")
            Map<String, Object> resp = JSON.parseObject(body, Map.class);
            if (resp == null || !Integer.valueOf(200).equals(resp.get("code"))) {
                String msg = resp != null ? String.valueOf(resp.get("msg")) : "响应为空";
                return ProviderTaskResponse.builder()
                        .status(ProviderTaskResponse.TaskSubmitStatus.FAILED)
                        .errorMessage("nanoBanana-pro提交失败: " + msg)
                        .build();
            }

            @SuppressWarnings("unchecked")
            Map<String, Object> data = (Map<String, Object>) resp.get("data");
            if (data == null || data.get("id") == null) {
                return ProviderTaskResponse.builder()
                        .status(ProviderTaskResponse.TaskSubmitStatus.FAILED)
                        .errorMessage("nanoBanana-pro提交失败: 未返回任务ID")
                        .build();
            }

            String taskId = String.valueOf(data.get("id"));
            log.info("SuChuang nanoBanana-pro - 任务已提交成功，taskId: {}", taskId);
            
            Map<String, Object> rawResponse = new HashMap<>();
            rawResponse.put("taskId", taskId);

            return ProviderTaskResponse.builder()
                    .providerTaskId(taskId)
                    .status(ProviderTaskResponse.TaskSubmitStatus.PROCESSING)
                    .rawResponse(rawResponse)
                    .build();
        } catch (Exception e) {
            log.error("SuChuang nanoBanana-pro - 提交任务异常: {}", e.getMessage(), e);
            return ProviderTaskResponse.builder()
                    .status(ProviderTaskResponse.TaskSubmitStatus.FAILED)
                    .errorMessage("提交nanoBanana-pro任务失败: " + e.getMessage())
                    .build();
        }
    }
}

