package com.borjabolufer.elevate.utils;

import okhttp3.*;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class ChatGptApi {
    private static final String API_URL = "https://api.openai.com/v1/chat/completions";
    private static final String API_KEY = "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";

    public interface ChatGptCallback {
        void onSuccess(String jsonResponse);
        void onFailure(String error);
    }

    public static void enviarPrompt(String prompt, ChatGptCallback callback) throws JSONException {
          
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)       
                .readTimeout(10, TimeUnit.MINUTES)          
                .writeTimeout(10, TimeUnit.MINUTES)         
                .build();

          
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("model", "gpt-4o");
        jsonBody.put("messages", new org.json.JSONArray()
                .put(new JSONObject().put("role", "user").put("content", prompt))
        );
        jsonBody.put("temperature", 0.7);

        RequestBody body = RequestBody.create(jsonBody.toString(), MediaType.parse("application/json"));

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

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.onFailure(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    callback.onFailure("Error HTTP: " + response.code());
                    return;
                }

                String responseBody = response.body().string();
                JSONObject json;
                try {
                    json = new JSONObject(responseBody);
                    String result = json.getJSONArray("choices")
                            .getJSONObject(0)
                            .getJSONObject("message")
                            .getString("content");
                    callback.onSuccess(result);
                } catch (JSONException e) {
                    callback.onFailure("Error al procesar JSON: " + e.getMessage());
                }
            }
        });
    }
}
