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 MidJourneyProvider implements PaintingProvider {
    @Value("${ruoyi.ai.external-ai.midjourney.base-url:}")
    private String baseUrl;
    @Value("${ruoyi.ai.external-ai.midjourney.token:}")
    private String token;
    private final OkHttpClient client = new OkHttpClient();

    @Override
    public String name() {
        return "midjourney";
    }

    @Override
    public void submit(PaintingTask task) {
    }

    @Override
    public List<String> create(String prompt, Map<String, Object> params) throws Exception {
        if (baseUrl == null || baseUrl.isBlank()) {
            List<String> images = new ArrayList<>();
            images.add("{\"code\":500,\"msg\":\"MIDJOURNEY_NOT_CONFIGURED\"}");
            return images;
        }
        String url = normalize(baseUrl) + "/mj/submit";
        String body = "{\"prompt\":\"" + prompt.replace("\"", "\\\"") + "\"}";
        Request.Builder b = new Request.Builder().url(url)
                .post(RequestBody.create(MediaType.parse("application/json"), body.getBytes(StandardCharsets.UTF_8)))
                .header("Authorization", "Bearer " + token);
        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;
    }
}

