package com.borjabolufer.elevate.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import org.json.JSONException;

public class AiProviderManager {
    private static final String TAG = "AiProviderManager";
    private static final String PREFS_NAME = "AiProviderPrefs";
    private static final String KEY_SELECTED_PROVIDER = "selected_provider";

    public enum AiProvider {
        CHATGPT("ChatGPT", "OpenAI GPT-3.5 Turbo"),
        CLAUDE("Claude", "Anthropic Claude 3 Sonnet");

        private final String displayName;
        private final String description;

        AiProvider(String displayName, String description) {
            this.displayName = displayName;
            this.description = description;
        }

        public String getDisplayName() { return displayName; }
        public String getDescription() { return description; }
    }

    public interface AiCallback {
        void onSuccess(String response);
        void onFailure(String error);
    }

    private final Context context;
    private AiProvider currentProvider;

    public AiProviderManager(Context context) {
        this.context = context;
        this.currentProvider = getSelectedProvider();
    }


    public void enviarPrompt(String prompt, AiCallback callback) {
        Log.d(TAG, "Enviando prompt usando: " + currentProvider.getDisplayName());

        try {
            switch (currentProvider) {
                case CLAUDE:
                    if (ClaudeApi.isApiKeyConfigured()) {
                        ClaudeApi.enviarPrompt(prompt, new ClaudeApi.ClaudeCallback() {
                            @Override
                            public void onSuccess(String jsonResponse) {
                                Log.d(TAG, "Claude respondió exitosamente");
                                callback.onSuccess(jsonResponse);
                            }

                            @Override
                            public void onFailure(String error) {
                                Log.e(TAG, "Claude falló: " + error);
                                  
                                intentarConChatGPT(prompt, callback);
                            }
                        });
                    } else {
                        Log.w(TAG, "Claude API no configurada, usando ChatGPT");
                        intentarConChatGPT(prompt, callback);
                    }
                    break;
                case CHATGPT:
                    if (ChatGptApi.class != null) {
                        ChatGptApi.enviarPrompt(prompt, new ChatGptApi.ChatGptCallback() {
                            @Override
                            public void onSuccess(String jsonResponse) {
                                Log.d(TAG, "ChatGPT respondió exitosamente");
                                callback.onSuccess(jsonResponse);
                            }

                            @Override
                            public void onFailure(String error) {
                                Log.e(TAG, "ChatGPT falló: " + error);
                                  
                                if (ClaudeApi.isApiKeyConfigured()) {
                                    Log.d(TAG, "Intentando fallback a Claude...");
                                    intentarConClaude(prompt, callback);
                                } else {
                                    callback.onFailure("ChatGPT falló: " + error);
                                }
                            }
                        });
                    }
                    break;
            }
        } catch (JSONException e) {
            Log.e(TAG, "Error en JSON: " + e.getMessage());
            callback.onFailure("Error en configuración: " + e.getMessage());
        }
    }


    private void intentarConClaude(String prompt, AiCallback callback) {
        try {
            ClaudeApi.enviarPrompt(prompt, new ClaudeApi.ClaudeCallback() {
                @Override
                public void onSuccess(String jsonResponse) {
                    Log.d(TAG, "Fallback a Claude exitoso");
                    callback.onSuccess(jsonResponse);
                }

                @Override
                public void onFailure(String error) {
                    Log.e(TAG, "Fallback a Claude también falló: " + error);
                    callback.onFailure("Ambos proveedores fallaron. ChatGPT y Claude no disponibles.");
                }
            });
        } catch (JSONException e) {
            callback.onFailure("Error en fallback a Claude: " + e.getMessage());
        }
    }

    private void intentarConChatGPT(String prompt, AiCallback callback) {
        try {
            ChatGptApi.enviarPrompt(prompt, new ChatGptApi.ChatGptCallback() {
                @Override
                public void onSuccess(String jsonResponse) {
                    Log.d(TAG, "Fallback a ChatGPT exitoso");
                    callback.onSuccess(jsonResponse);
                }

                @Override
                public void onFailure(String error) {
                    Log.e(TAG, "Fallback a ChatGPT también falló: " + error);
                    callback.onFailure("Ambos proveedores fallaron. Claude y ChatGPT no disponibles.");
                }
            });
        } catch (JSONException e) {
            callback.onFailure("Error en fallback a ChatGPT: " + e.getMessage());
        }
    }


    public void setProvider(AiProvider provider) {
        this.currentProvider = provider;
        saveSelectedProvider(provider);
        Log.d(TAG, "Proveedor cambiado a: " + provider.getDisplayName());
    }

    public AiProvider getCurrentProvider() {
        return currentProvider;
    }

      
    private void saveSelectedProvider(AiProvider provider) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        prefs.edit().putString(KEY_SELECTED_PROVIDER, provider.name()).apply();
    }

    private AiProvider getSelectedProvider() {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        String providerName = prefs.getString(KEY_SELECTED_PROVIDER, AiProvider.CHATGPT.name());

        try {
            return AiProvider.valueOf(providerName);
        } catch (IllegalArgumentException e) {
            Log.w(TAG, "Proveedor no reconocido, usando ChatGPT por defecto");
            return AiProvider.CHATGPT;
        }
    }

      
    public boolean isChatGptAvailable() {
          
        return ChatGptApi.class != null;   
    }

    public boolean isClaudeAvailable() {
        return ClaudeApi.isApiKeyConfigured();
    }

    public String getProviderStatus() {
        StringBuilder status = new StringBuilder();
        status.append("Proveedor actual: ").append(currentProvider.getDisplayName()).append("\n");
        status.append("ChatGPT disponible: ").append(isChatGptAvailable() ? "Sí" : "No").append("\n");
        status.append("Claude disponible: ").append(isClaudeAvailable() ? "Sí" : "No").append("\n");
        return status.toString();
    }


    public void verificarConectividad(AiCallback callback) {
        String promptPrueba = "Responde solo con 'OK' para confirmar que estás funcionando.";

        enviarPrompt(promptPrueba, new AiCallback() {
            @Override
            public void onSuccess(String response) {
                if (response.toLowerCase().contains("ok")) {
                    callback.onSuccess("Conectividad verificada con " + currentProvider.getDisplayName());
                } else {
                    callback.onSuccess("Conectado con " + currentProvider.getDisplayName() +
                            " pero respuesta inesperada: " + response);
                }
            }

            @Override
            public void onFailure(String error) {
                callback.onFailure("Fallo en verificación de conectividad: " + error);
            }
        });
    }
}