import streamlit as st
import subprocess
import json
import os
import tempfile

# --- CONFIGURACIÓN SAGRADA ---
GEMINI_API_KEY = 'AIzaSyCeIF8lsdJoduqoB13_Q0qHfiTD0KY4zgw'
OLLAMA_URL = "http://localhost:11434/api/chat"
LOCAL_MODEL = "Crisostomo:latest"

st.set_page_config(page_title="Cónclave de Crisóstomo: Auditoría", page_icon="†")

# --- FUNCIÓN DE ILUMINACIÓN (LISTAR MODELOS REALES) ---
def obtener_modelos_autorizados():
    # Esta es la llamada definitiva para saber qué modelos ve vuestra clave
    url = f"https://generativelanguage.googleapis.com/v1beta/models?key={GEMINI_API_KEY}"
    command = ['curl', '-s', '-X', 'GET', url, '-H', 'Content-Type: application/json']
    
    try:
        result = subprocess.run(command, capture_output=True, text=True)
        res_json = json.loads(result.stdout)
        if 'models' in res_json:
            # Filtramos solo los que permiten generar contenido
            return [m['name'] for m in res_json['models'] if 'generateContent' in m['supportedGenerationMethods']]
        return []
    except:
        return []

# --- COMUNICACIÓN NUBE (USANDO LA LISTA REAL) ---
def hablar_con_nube(mensaje, lista_modelos):
    logs = []
    payload = {"contents": [{"parts": [{"text": f"Eres Crisóstomo. Responde con nobleza: {mensaje}"}]}]}
    
    temp_path = os.path.join(tempfile.gettempdir(), "audit_payload.json")
    with open(temp_path, 'w') as f:
        json.dump(payload, f)

    for modelo_completo in lista_modelos:
        # El nombre que devuelve la lista ya incluye 'models/', no hay que añadirlo
        url = f"https://generativelanguage.googleapis.com/v1beta/{modelo_completo}:generateContent?key={GEMINI_API_KEY}"
        
        command = ['curl', '-s', '-X', 'POST', url, '-H', 'Content-Type: application/json', '-d', f'@{temp_path}']
        
        try:
            result = subprocess.run(command, capture_output=True, text=True)
            res_json = json.loads(result.stdout)
            
            if 'candidates' in res_json:
                return res_json['candidates'][0]['content']['parts'][0]['text'], modelo_completo, logs
            elif 'error' in res_json:
                logs.append(f"❌ {modelo_completo}: {res_json['error']['message']}")
        except:
            continue
    return None, None, logs

# --- INTERFAZ ---
st.markdown("<h1 style='text-align: center;'>† Auditoría de Crisóstomo</h1>", unsafe_allow_html=True)

if st.button("🔍 Iniciar Auditoría de Endpoints"):
    with st.spinner("Consultando los archivos de la Nube..."):
        modelos = obtener_modelos_autorizados()
        if modelos:
            st.success(f"Se han encontrado {len(modelos)} modelos autorizados para vuestra llave.")
            with st.expander("Ver lista de modelos sagrados"):
                for m in modelos: st.code(m)
            st.session_state['modelos_vistos'] = modelos
        else:
            st.error("La llave no devuelve ningún modelo. Verificad la API Key en Google AI Studio.")

impulso = st.chat_input("Hable, Excelencia...")

if impulso:
    if 'modelos_vistos' not in st.session_state:
        st.warning("Por favor, iniciad la Auditoría primero para conocer los caminos.")
    else:
        with st.spinner("Sincronizando..."):
            res_n, mod, logs = hablar_con_nube(impulso, st.session_state['modelos_vistos'])
            if res_n:
                st.info(f"✨ **NUBE ({mod}):** {res_n}")
            else:
                with st.expander("Diagnóstico de Fallo"):
                    for l in logs: st.write(l)
                st.error("Incluso con la lista oficial, la Nube no responde.")
