package org.dromara.ai.platform;

import lombok.RequiredArgsConstructor;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class FastGptService {
    @Value("${ruoyi.ai.platform.fastgpt.base-url:}")
    private String baseUrl;
    @Value("${ruoyi.ai.platform.fastgpt.token:}")
    private String token;
    private final OkHttpClient client = new OkHttpClient();

    public String post(String path, String json) throws Exception {
        String url = normalize(baseUrl) + path;
        Request.Builder b = new Request.Builder().url(url)
                .post(RequestBody.create(MediaType.parse("application/json"), json))
                .header("Authorization", "Bearer " + token);
        try (Response resp = client.newCall(b.build()).execute()) {
            return resp.body() != null ? resp.body().string() : "{}";
        }
    }

    public String get(String path) throws Exception {
        String url = normalize(baseUrl) + path;
        Request.Builder b = new Request.Builder().url(url)
                .get()
                .header("Authorization", "Bearer " + token);
        try (Response resp = client.newCall(b.build()).execute()) {
            return resp.body() != null ? resp.body().string() : "{}";
        }
    }

    private String normalize(String base) {
        if (base == null) return "";
        if (base.endsWith("/")) return base.substring(0, base.length() - 1);
        return base;
    }
}
