package com.example.cuida.services;

import android.os.Handler;
import android.os.Looper;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Gemini {
    private static final String API_KEY = "AIzaSyBYar6Yv0rhrZX8cIQQxd77TLERHRsjAtY";
    private static final String MODEL_NAME = "gemini-2.0-flash"; 
    private static final String API_URL = "https://generativelanguage.googleapis.com/v1beta/models/" + MODEL_NAME + ":generateContent?key=" + API_KEY;
    private final OkHttpClient client;
    private final Handler mainHandler;

    public Gemini() {
        this.client = new OkHttpClient();
        this.mainHandler = new Handler(Looper.getMainLooper());
    }

    public interface GeminiCallback {
        void onSuccess(String result);
        void onError(Throwable t);
    }

    public void fazerPergunta(String promptUtilizador, GeminiCallback callback) {
        try {
            JSONObject jsonBody = new JSONObject();
            JSONArray contents = new JSONArray();
            JSONObject content = new JSONObject();
            JSONArray parts = new JSONArray();
            JSONObject part = new JSONObject();

            part.put("text", promptUtilizador);
            parts.put(part);
            content.put("parts", parts);
            contents.put(content);
            jsonBody.put("contents", contents);

            RequestBody body = RequestBody.create(jsonBody.toString(), MediaType.parse("application/json; charset=utf-8"));
            Request request = new Request.Builder()
                    .url(API_URL)
                    .post(body)
                    .build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    mainHandler.post(() -> callback.onError(e));
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        try {
                            String responseBody = response.body().string();
                            JSONObject jsonObject = new JSONObject(responseBody);
                            JSONArray candidates = jsonObject.getJSONArray("candidates");
                            JSONObject firstCandidate = candidates.getJSONObject(0);
                            JSONObject contentObj = firstCandidate.getJSONObject("content");
                            JSONArray partsArr = contentObj.getJSONArray("parts");
                            String textResult = partsArr.getJSONObject(0).getString("text");

                            mainHandler.post(() -> callback.onSuccess(textResult));
                        } catch (Exception e) {
                            mainHandler.post(() -> callback.onError(new Exception("Erro ao ler resposta da IA", e)));
                        }
                    } else {
                        String errorBody = response.body() != null ? response.body().string() : "Unknown error";
                        mainHandler.post(() -> callback.onError(new Exception("Erro da API HTTP " + response.code() + ": " + errorBody)));
                    }
                }
            });

        } catch (Exception e) {
            mainHandler.post(() -> callback.onError(e));
        }
    }
}
