package com.seer.teach.teacher.service.platform.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.seer.teach.teacher.service.platform.AiPlatformCallService;
import com.seer.teach.teacher.service.platform.LlmRequest;
import com.seer.teach.teacher.service.platform.LlmResponse;
import com.seer.teach.common.enums.AiPlatformEnum;
import com.volcengine.service.visual.IVisualService;
import com.volcengine.service.visual.impl.VisualServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 火山引擎平台调用服务实现
 */
@Slf4j
@Service
public class VolcEnginePlatformCallServiceImpl implements AiPlatformCallService {


    @Override
    public Optional<LlmResponse> callImageModel(LlmRequest request) {
        IVisualService visualService = VisualServiceImpl.getInstance();
        visualService.setAccessKey(request.getAk());
        visualService.setSecretKey(request.getSk());

        JSONObject req=new JSONObject();
        if(StringUtils.hasText(request.getModel())){
            req.put("req_key",request.getModel());
        }else{
            req.put("req_key","high_aes_general_v30l_zt2i");
        }
        req.put("prompt",request.getPrompt());
        req.put("return_url",true);
        
        // 添加尺寸参数
        if (request.getWidth() != null) {
            req.put("width", request.getWidth());
        }
        if (request.getHeight() != null) {
            req.put("height", request.getHeight());
        }
        
        if (request.getNegativePrompt() != null) {
            req.put("negative_prompt", request.getNegativePrompt());
        }
        try {

            Object response = visualService.text2ImgXLSft(req);
            LlmResponse llmResponse = parseLLMResponse(response);
            return Optional.of(llmResponse);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("VolcEngine callImageModel error:{}", e.getMessage(),e);
        }
        return Optional.empty();
    }

    @Override
    public String getSupportedPlatform() {
        return AiPlatformEnum.VOLC_ENGINE.getCode();
    }

    /**
     * 解析大模型响应数据
     /**
     * 返回示例：
     {
     "code": 10000,
     "data": {
     "mood_board_llm_tag": "",
     "pe_result": "",
     "vlm_result": "",
     "llm_result": "",
     "image_urls": [
     "https://p3-aiop-sign.byteimg.com/tos-cn-i-vuqhorh59i/2025103015381229A5959C1AEC39174387-9681-0~tplv-vuqhorh59i-image-v1.image?rk3s=7f9e702d&x-expires=1761896297&x-signature=tLn5jMukSmMw37OcpRunQgI6HTw%3D"
     ],
     "algorithm_base_resp": {
     "status_message": "Success",
     "status_code": 0
     },
     "mood_board_llm_result": "",
     "rephraser_result": "",
     "request_id": "2ccb55ace9853586a9a8c18538e678f0512fab6cf2fad81b2a7fb96940825cd0",
     "binary_data_base64": [
     ],
     "predict_tags_result": ""
     },
     "time_elapsed": "5.207140776s",
     "message": "Success",
     "request_id": "2025103015381229A5959C1AEC39174387",
     "status": 10000
     }
     * @param response 响应数据
     * @return 解析后的响应数据
     */
    private LlmResponse parseLLMResponse(Object response) {
        LlmResponse llmResponse = new LlmResponse();
        try {
            String responseBody = JSON.toJSONString(response);
            log.debug("原始响应内容: {}", responseBody);

            // 使用 fastjson2 解析
            JSONObject jsonObject = JSON.parseObject(responseBody);

            // 检查根节点
            if (jsonObject == null) {
                log.warn("根节点为空");
                return llmResponse;
            }
            
            // 设置ID
            if (jsonObject.containsKey("request_id")) {
                llmResponse.setId(jsonObject.getString("request_id"));
            }

            // 获取 data 节点
            JSONObject dataNode = jsonObject.getJSONObject("data");
            if (dataNode == null) {
                log.warn("data节点不存在");
                return llmResponse;
            }

            // 获取 image_urls 数组
            com.alibaba.fastjson2.JSONArray imageUrlsArray = dataNode.getJSONArray("image_urls");
            if (imageUrlsArray == null) {
                log.warn("image_urls数组不存在");
                return llmResponse;
            }

            // 构建choices和imageResults
            List<LlmResponse.Choice> choices = new ArrayList<>();
            LlmResponse.Choice choice = new LlmResponse.Choice();
            choice.setIndex(0);
            
            List<LlmResponse.ImageResult> imageResults = new ArrayList<>();
            for (int i = 0; i < imageUrlsArray.size(); i++) {
                Object urlObj = imageUrlsArray.get(i);
                if (urlObj instanceof String) {
                    LlmResponse.ImageResult imageResult = new LlmResponse.ImageResult();
                    imageResult.setUrl((String) urlObj);
                    imageResults.add(imageResult);
                }
            }
            choice.setImageResults(imageResults);
            choices.add(choice);
            llmResponse.setChoices(choices);
            
            // 设置usage
            LlmResponse.Usage usage = new LlmResponse.Usage();
            usage.setImageCount(imageUrlsArray.size());
            llmResponse.setUsage(usage);

            log.info("成功解析到{}个图片URL", imageUrlsArray.size());
            return llmResponse;
        } catch (Exception e) {
            log.error("解析大模型响应时发生异常", e);
            return llmResponse;
        }
    }
}