package org.dromara.ai.painting.provider;

import okhttp3.*;
import org.dromara.ai.painting.PaintingProvider;
import org.dromara.ai.painting.PaintingTask;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class DallE3Provider implements PaintingProvider {
    @Value("${ruoyi.ai.external-ai.openai.base-url:https://api.openai.com}")
    private String openaiBaseUrl;
    @Value("${ruoyi.ai.external-ai.openai.api-key:}")
    private String openaiApiKey;
    private final OkHttpClient client = new OkHttpClient();

    @Override
    public String name() {
        return "dall-e-3";
    }

    @Override
    public void submit(PaintingTask task) {
    }

    @Override
    public List<String> create(String prompt, Map<String, Object> params) throws Exception {
        String size = String.valueOf(params.getOrDefault("size", "1024x1024"));
        String url = normalize(openaiBaseUrl) + "/v1/images/generations";
        String body = "{\"model\":\"dall-e-3\",\"prompt\":\"" + prompt.replace("\"", "\\\"") + "\",\"size\":\"" + size + "\"}";
        Request.Builder b = new Request.Builder().url(url)
                .post(RequestBody.create(MediaType.parse("application/json"), body.getBytes(StandardCharsets.UTF_8)))
                .header("Authorization", "Bearer " + openaiApiKey);
        try (Response resp = client.newCall(b.build()).execute()) {
            String respBody = resp.body() != null ? resp.body().string() : "{}";
            List<String> images = new ArrayList<>();
            images.add(respBody);
            return images;
        }
    }

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

