package cn.van.business.util.ds;

/**
 * @author Leo
 * @version 1.0
 * @create 2025/5/8 22:19
 * @description：
 */

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.HashMap;
import java.util.Map;

@Component
public class GPTClientUtil {
    // logger
    private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(GPTClientUtil.class);

    private static final String GPT_API_URL = "https://api.openai.com/v1/chat/completions"; // GPT API 地址
    private static final String GPT_API_KEY = "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"; // 替换为你的 GPT API 密钥
    private static final ObjectMapper objectMapper = new ObjectMapper(); // Jackson JSON 解析器
    private static final String PROXY_HOST = "192.168.8.9"; // 本地代理地址
    private static final int PROXY_PORT = 1070; // 本地代理端口

    /**
     * 调用 GPT API 并返回第一次回复的文本内容
     *
     * @param inputText 用户输入的文本
     * @return API 返回的第一个回复内容
     * @throws IOException              如果网络请求或 JSON 解析失败
     * @throws IllegalArgumentException 如果输入为空或过长
     */
    public String getGPTResponse(String inputText) throws IOException {
        // 1. 输入校验
        if (inputText == null || inputText.trim().isEmpty()) {
            throw new IllegalArgumentException("输入文本不能为空");
        }
        if (inputText.length() > 10000) {
            throw new IllegalArgumentException("输入文本过长");
        }

        // 2. 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "gpt-4o");
        requestBody.put("messages", new Map[]{
                Map.of("role", "user", "content", inputText)
        });
        requestBody.put("temperature", 0.7);

        String jsonBody = objectMapper.writeValueAsString(requestBody);

        // 3. 使用 Hutool HTTP 发送请求，设置代理
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_HOST, PROXY_PORT));
        HttpRequest request = HttpRequest.of(GPT_API_URL)
                .method(Method.POST)
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer " + GPT_API_KEY)
                .header("Accept", "application/json")
                .body(jsonBody)
                .setProxy(proxy)
                .timeout(30000); // 设置超时时间为30秒

        logger.info("请求 GPT API: URL={}, Body={}", GPT_API_URL, jsonBody);

        HttpResponse response = request.execute();

        // 4. 检查 HTTP 状态码
        if (response.getStatus() != 200) {
            logger.error("GPT API 调用失败！状态码={}, 响应={}", response.getStatus(), response.body());
            throw new IOException("API 调用失败，HTTP 状态码: " + response.getStatus());
        }

        // 5. 解析 JSON 响应
        JsonNode rootNode = objectMapper.readTree(response.body());
        JsonNode choices = rootNode.path("choices");
        if (choices.isEmpty()) {
            throw new IOException("API 返回数据格式异常，未找到回复内容");
        }

        return choices.get(0)
                .path("message")
                .path("content")
                .asText();
    }
}
