package org.dromara.chat.client;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class ChatSdk {
    private final HttpClient client = HttpClient.newHttpClient();
    private final String baseUrl;
    private String token;

    public ChatSdk(String baseUrl) {
        this.baseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl;
    }

    public ChatSdk withToken(String token) {
        this.token = token;
        return this;
    }

    public String chat(String jsonBody) {
        HttpRequest.Builder b = HttpRequest.newBuilder()
                .uri(URI.create(baseUrl + "/api/ai/chat"))
                .header("Content-Type", "application/json");
        if (token != null && !token.isEmpty()) {
            b.header("Authorization", token);
        }
        HttpRequest req = b.POST(HttpRequest.BodyPublishers.ofString(jsonBody)).build();
        try {
            HttpResponse<String> resp = client.send(req, HttpResponse.BodyHandlers.ofString());
            return resp.body();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

