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 ClaudeApi {
    private static final String API_URL = "https://api.anthropic.com/v1/messages";
    private static final String API_KEY = "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";
    private static final String MODEL = "claude-3-5-haiku-20241022";

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

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

          
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("model", MODEL);
        jsonBody.put("max_tokens", 4096);   

          
        jsonBody.put("messages", new org.json.JSONArray()
                .put(new JSONObject().put("role", "user").put("content", prompt))
        );

          
        jsonBody.put("temperature", 0.7);
        jsonBody.put("top_p", 0.9);

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

        Request request = new Request.Builder()
                .url(API_URL)
                .addHeader("x-api-key", API_KEY)   
                .addHeader("Content-Type", "application/json")
                .addHeader("anthropic-version", "2023-06-01")   
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.onFailure("Error de conexión: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    String errorBody = response.body() != null ? response.body().string() : "Sin detalles";
                    callback.onFailure("Error HTTP " + response.code() + ": " + errorBody);
                    return;
                }

                String responseBody = response.body().string();
                try {
                    JSONObject json = new JSONObject(responseBody);

                      
                    String result = json.getJSONArray("content")
                            .getJSONObject(0)
                            .getString("text");

                    callback.onSuccess(result);

                } catch (JSONException e) {
                    callback.onFailure("Error al procesar respuesta de Claude: " + e.getMessage());
                }
            }
        });
    }

      
    public static void enviarPromptPersonalizado(String prompt, int maxTokens, double temperature, ClaudeCallback callback) throws JSONException {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.MINUTES)
                .writeTimeout(10, TimeUnit.MINUTES)
                .build();

        JSONObject jsonBody = new JSONObject();
        jsonBody.put("model", MODEL);
        jsonBody.put("max_tokens", maxTokens);
        jsonBody.put("messages", new org.json.JSONArray()
                .put(new JSONObject().put("role", "user").put("content", prompt))
        );
        jsonBody.put("temperature", temperature);
        jsonBody.put("top_p", 0.9);

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

        Request request = new Request.Builder()
                .url(API_URL)
                .addHeader("x-api-key", API_KEY)
                .addHeader("Content-Type", "application/json")
                .addHeader("anthropic-version", "2023-06-01")
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.onFailure("Error de conexión: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    String errorBody = response.body() != null ? response.body().string() : "Sin detalles";
                    callback.onFailure("Error HTTP " + response.code() + ": " + errorBody);
                    return;
                }

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

      
    public static void verificarConexion(ClaudeCallback callback) {
        try {
            enviarPrompt("Hola, ¿estás funcionando correctamente? Responde solo con 'Sí'.", new ClaudeCallback() {
                @Override
                public void onSuccess(String jsonResponse) {
                    if (jsonResponse.toLowerCase().contains("sí") || jsonResponse.toLowerCase().contains("si")) {
                        callback.onSuccess("Conexión exitosa con Claude API");
                    } else {
                        callback.onSuccess("Conectado, pero respuesta inesperada: " + jsonResponse);
                    }
                }

                @Override
                public void onFailure(String error) {
                    callback.onFailure("Fallo en verificación: " + error);
                }
            });
        } catch (JSONException e) {
            callback.onFailure("Error en verificación: " + e.getMessage());
        }
    }

      
    public static boolean isApiKeyConfigured() {
        return API_KEY != null &&
                !API_KEY.isEmpty() &&
                !API_KEY.equals("TU_CLAUDE_API_KEY_AQUI");
    }

      
    public static String getModelInfo() {
        return "Modelo: " + MODEL + "\n" +
                "Provider: Anthropic Claude\n" +
                "Configuración: Optimizado para generación de planes de fitness";
    }
}