package org.tio.sitexxx.server.utils;

import com.google.gson.Gson;
import okhttp3.*;

import java.io.IOException;
import java.util.Collections;

/**
 * <pre>
 *    @author : vagrancy
 *    e-mail : 18050829067@163.com
 *    time   : 2026-03-21 17:27
 *    desc   :
 * </pre>
 */
public class WanJieChatClient {
    private static final String API_URL = "https://maas-openapi.wanjiedata.com/api/v1/chat/completions";
    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
    private static String API_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE4MDU2MTI4NDg3NDMsImlhdCI6MTc3NDA3Njg0OCwia2V5IjoiNUs3NVo4VE5DOUY0SE0zN1A5WTcifQ.3TzX8m1uSc8wzZ8glhztBkZkxOOAUFSNfPfAqSSZ3yM";
    private static String MODEL = "deepseek-v3"; // 如：qwen-max、wanjie-7b 等
    private final OkHttpClient client;
    private final Gson gson;

    public WanJieChatClient() {
        this.client = new OkHttpClient();
        this.gson = new Gson();
    }

    public ChatResponse sendChatMessage(String userMessage) throws IOException {
        // 构建请求体
        ChatRequest request = new ChatRequest();
        request.model = MODEL;
        request.messages = Collections.singletonList(new Message("user", userMessage));
        request.stream = false;

        String jsonBody = gson.toJson(request);
        RequestBody body = RequestBody.create(jsonBody, JSON);

        Request httpRequest = new Request.Builder()
                .url(API_URL)
                .addHeader("Authorization", "Bearer " + API_KEY)
                .addHeader("Content-Type", "application/json")
                .post(body)
                .build();

        try (Response response = client.newCall(httpRequest).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("HTTP error: " + response.code() + " - " + response.body().string());
            }

            String responseBody = response.body().string();
            return gson.fromJson(responseBody, ChatResponse.class);
        }
    }

    // 请求体类
    static class ChatRequest {
        String model;
        java.util.List<Message> messages;
        Boolean stream;
    }

    static class Message {
        String role;
        String content;

        public Message(String role, String content) {
            this.role = role;
            this.content = content;
        }
    }

    // 响应体类（简化版，可根据实际 API 响应结构调整）
    public static class ChatResponse {
        String id;
        String object;
        long created;
        String model;
        java.util.List<Choice> choices;
        Usage usage;

        @Override
        public String toString() {
            if (choices != null && !choices.isEmpty()) {
                return choices.get(0).message.content;
            }
            return "No response";
        }
    }

    static class Choice {
        int index;
        Message message;
        String finish_reason;
    }

    static class Usage {
        int prompt_tokens;
        int completion_tokens;
        int total_tokens;
    }

    // 示例使用
    public static void main(String[] args) {
        WanJieChatClient client = new WanJieChatClient();
        try {
            ChatResponse response = client.sendChatMessage("Hello!");
            System.out.println("AI 回复: " + response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
