package shop.alien.util.common.safe;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import java.io.IOException;

public class DeepseekClient {
    private final String apiKey;
    private final OkHttpClient client;

    public DeepseekClient(String apiKey) {
        this.apiKey = apiKey;
        this.client = new OkHttpClient();
    }

    public String generateText(String prompt) throws IOException {
        // 创建请求体
        JSONObject messages = new JSONObject();
        messages.put("role", "user");
        messages.put("content", prompt);

        JSONObject requestBody = new JSONObject();
        requestBody.put("model", "deepseek-chat");
        requestBody.put("messages", JSON.parseArray(messages.toJSONString(), Object.class));
        requestBody.put("stream", false);

        Request request = new Request.Builder()
                .url("https://api.deepseek.com/chat/completions")
                .post(RequestBody.create(MediaType.get("application/json"), requestBody.toJSONString()))
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer " + apiKey)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            JSONObject responseBody = JSON.parseObject(response.body().string());
            return responseBody.getJSONArray("choices").getJSONObject(0).getJSONObject("message").getString("content");
        }
    }
}
