package com.example.system.common;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.stereotype.Component;

@Component
public class AiPost {

    private static final String baseUrl = "https://openai.933999.xyz";
    private static final String apiKey = "sk-1PBIyxIdJ42yyC11XRNqbEXYDt2eZRNVNbd8XxmKjnPXGh5S";
    private static final String model = "gpt-4o-mini";

    /**
     * 发送消息并获取AI响应
     * @param message 用户消息
     * @param maxTokens 最大token数
     * @return AI响应内容
     * @throws Exception 发送请求异常
     */
    public String sendMessageAndGetResponse(String message, int maxTokens) throws Exception {
        // 构造 messages 数组
        JSONArray messagesArray = new JSONArray();
        JSONObject userMessage = new JSONObject();
        userMessage.put("role", "user");
        userMessage.put("content", message);
        messagesArray.add(userMessage);

        // 构造请求体
        JSONObject requestBody = new JSONObject();
        requestBody.put("model", model);
        requestBody.put("messages", messagesArray);
//        requestBody.put("max_tokens", maxTokens);
//        requestBody.put("temperature", 0.2); // 更稳定输出

        // 打印请求体
        System.out.println("请求地址：" + baseUrl + "/v1/chat/completions");
        System.out.println("请求体：" + requestBody.toStringPretty());

        try {
            HttpResponse response = HttpRequest.post(baseUrl + "/v1/chat/completions")
                    .timeout(60_000) // 60秒超时
                    .header("Authorization", "Bearer " + apiKey)
                    .header("Content-Type", "application/json")
                    .body(requestBody.toString())
                    .execute();

            String responseText = response.body();

            System.out.println("响应状态码：" + response.getStatus());
            System.out.println("响应内容：" + responseText);

            if (response.getStatus() != 200) {
                throw new RuntimeException("AI服务请求失败：" + responseText);
            }

            // 安全解析响应
            if (!JSONUtil.isJsonObj(responseText)) {
                throw new RuntimeException("返回不是合法JSON：" + responseText);
            }

            JSONObject responseJson = JSONUtil.parseObj(responseText);
            JSONArray choices = responseJson.getJSONArray("choices");

            if (choices == null || choices.isEmpty()) {
                throw new RuntimeException("AI响应为空：" + responseText);
            }

            JSONObject messageObj = choices.getJSONObject(0).getJSONObject("message");
            return messageObj.getStr("content");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("调用AI接口发生错误", e);
        }
    }
}

