package cn.van.business.util.ds;

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.util.HashMap;
import java.util.Map;

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

    private static final String DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions"; // 确认 API 地址
    private static final String DEEPSEEK_API_KEY = "sk-d99b8cc6b7414cc88a5d950a3ff7585e"; // 替换为你的密钥
    private static final ObjectMapper objectMapper = new ObjectMapper(); // Jackson JSON 解析器


    /**
     * 调用 DeepSeek API 并返回第一次回复的文本内容
     *
     * @param inputText 用户输入的文本
     * @return API 返回的第一个回复内容
     * @throws IOException              如果网络请求或 JSON 解析失败
     * @throws IllegalArgumentException 如果输入为空或过长
     */
    public String getDeepSeekResponse(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", "deepseek-chat");
        requestBody.put("messages", new Map[]{
                Map.of("role", "user", "content", inputText)
        });
        requestBody.put("temperature", 0.7);

        String jsonBody = objectMapper.writeValueAsString(requestBody);

        // 3. 使用 Hutool HTTP 发送请求
        HttpRequest request = HttpRequest.of(DEEPSEEK_API_URL)
                .method(Method.POST)
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer " + DEEPSEEK_API_KEY) // 确保格式正确
                .header("Accept", "application/json")
                .body(jsonBody);

        logger.info("请求 DeepSeek API: URL={}, Body={}", DEEPSEEK_API_URL, jsonBody); // 调试日志

        HttpResponse response = request.execute();

        // 4. 检查 HTTP 状态码
        if (response.getStatus() != 200) {
            logger.error("DeepSeek 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();
    }
}
