package com.cmvr.llm.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.cmvr.common.exception.GlobalException;
import com.cmvr.common.utils.http.CallAPIUtil;
import com.cmvr.llm.config.APIProperties;
import com.cmvr.llm.model.CallAgentVO;
import com.cmvr.llm.service.LargeModelRemoteService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class LargeModelRemoteServiceImpl implements LargeModelRemoteService {

    private final APIProperties apiProperties;

    @Override
    public String runSpeechToTextWorkflow(CallAgentVO callAgentVO) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Apikey", apiProperties.getAppKey());

        Map<String, String> body = new HashMap<>();
        body.put("AppKey", apiProperties.getAppKey());
        body.put("AppID", apiProperties.getAppId());
        body.put("InputData", JSON.toJSONString(callAgentVO));
        body.put("UserID", "18888888888");

        String res1 = CallAPIUtil.doPostJson(apiProperties.getWorkFlowUrl(), headers, body);
        JSONObject resObject1 = JSON.parseObject(res1);

        if (resObject1.containsKey("runId")) {
            String processId = resObject1.getString("runId");
            return querySpeechToTextResult(processId);
        } else {
            throw new RuntimeException("未获取到 runId，响应内容：" + res1);
        }
    }

    @Override
    public String querySpeechToTextResult(String processId) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Apikey", apiProperties.getAppKey());

        Map<String, String> body = new HashMap<>();
        body.put("AppKey", apiProperties.getAppKey());
        body.put("AppID", apiProperties.getAppId());
        body.put("RunID", processId);
        body.put("UserID", "18888888888");

        String responseBody;
        JSONObject endNode;
        int failCount = 0;
        int maxFail = 40;

        while (true) {
            responseBody = CallAPIUtil.doPostJson(apiProperties.getQueryResultUrl(), headers, body);
            JSONObject jsonObject = JSON.parseObject(responseBody);

            String status = jsonObject.getString("status");
            if ("success".equals(status)) {
                JSONObject nodes = jsonObject.getJSONObject("nodes");
                if (nodes == null) {
                    throw new RuntimeException("响应中 nodes 为空：" + responseBody);
                }

                endNode = findEndNode(nodes);
                if (endNode != null) {
                    break;
                } else {
                    throw new RuntimeException("未找到 nodeType=end 的节点：" + nodes);
                }
            } else if ("failed".equals(status)) {
                // 如果失败
                throw new GlobalException(responseBody);
            } else {
                // 处理其他状态码
                failCount++;
                if (failCount > maxFail) {
                    throw new GlobalException("达到最大重试次数，API状态仍未成功：" + status);
                }
            }

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException("轮询被中断", e);
            }
        }

        // 解析 output 内容并清洗
        String outputStr = endNode.getString("output");
        JSONObject output = JSON.parseObject(outputStr);
        JSONArray contentArray = output.getJSONArray("content");

        if (contentArray != null) {
            JSONArray cleanedArray = new JSONArray();

            for (Object item : contentArray) {
                if (item instanceof String) {
                    // 清除 [xxx] 样式的标记
                    String cleaned = ((String) item).replaceAll("\\[.*?\\]", "").trim();
                    cleanedArray.add(cleaned);
                } else {
                    cleanedArray.add(item); // 非字符串内容原样保留
                }
            }

            return cleanedArray.toJSONString();
        } else {
            return output.toJSONString(); // 没有 content 字段就返回整个 output
        }
    }

    /**
     * 从 nodes 中提取 nodeType=end 的节点
     */
    private JSONObject findEndNode(JSONObject nodes) {
        for (Map.Entry<String, Object> entry : nodes.entrySet()) {
            JSONObject node = (JSONObject) entry.getValue();
            if ("end".equalsIgnoreCase(node.getString("nodeType"))) {
                return node;
            }
        }
        return null;
    }

}