# detalles_de_sala.py
import os
import logging
import asyncio
import aiohttp
from livekit import rtc

ROOM = "mi_sala_prueba"
USER = "agente_tts"
TOKEN_URL = "http://127.0.0.1:8000/token"
LIVEKIT_URL = "ws://192.168.1.131:7880"


async def get_token():
    """Solicita el token JWT al backend FastAPI"""
    print("🔍 Solicitando token al backend FastAPI...")
    try:
        async with aiohttp.ClientSession() as session:
            async with session.get(f"{TOKEN_URL}?room={ROOM}&user={USER}") as resp:
                print(f"📡 Respuesta del backend: {resp.status}")
                if resp.status != 200:
                    print(f"❌ Error al obtener token: {await resp.text()}")
                    raise Exception(f"Error HTTP {resp.status} al solicitar token")
                data = await resp.json()
                token = data.get("token")
                if not token:
                    print("⚠️ Respuesta no contiene campo 'token'")
                    raise Exception("Respuesta inválida del backend /token")
                print("✅ Token recibido correctamente")
                print(f"🧾 Token (primeros 60 chars): {token[:60]}...")
                return token
    except Exception as e:
        print(f"🚨 Error en get_token(): {e}")
        raise


async def main():
    print("🚀 Iniciando script LiveKit Client")
    print(f"🌍 Servidor LiveKit: {LIVEKIT_URL}")
    print(f"🔑 URL de Token: {TOKEN_URL}")
    print(f"🏠 Sala: {ROOM}, 👤 Usuario: {USER}")

    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)
    room = rtc.Room()

    print("⚙️ Configurando eventos del Room...")

    @room.on("participant_connected")
    def on_participant_connected(participant: rtc.RemoteParticipant):
        print(f"🟢 Participante conectado: {participant.identity} ({participant.sid})")
        logger.info("🟢 Participant connected: %s (%s)", participant.identity, participant.sid)

    @room.on("participant_disconnected")
    def on_participant_disconnected(participant: rtc.RemoteParticipant):
        print(f"🔴 Participante desconectado: {participant.identity} ({participant.sid})")
        logger.info("🔴 Participant disconnected: %s (%s)", participant.identity, participant.sid)

    @room.on("track_subscribed")
    def on_track_subscribed(track: rtc.Track, publication: rtc.RemoteTrackPublication, participant: rtc.RemoteParticipant):
        print(f"🎥 Track suscrito de {participant.identity}: {publication.sid} ({track.kind})")
        logger.info("🎥 Track subscribed from %s: %s", participant.identity, publication.sid)

    @room.on("disconnected")
    def on_disconnected():
        print("⚠️ Desconectado del servidor LiveKit.")
        logger.warning("⚠️ Room disconnected.")

    # 🔑 Obtener token
    token = await get_token()

    print("🧩 Intentando conectar al servidor LiveKit...")
    try:
        await room.connect(LIVEKIT_URL, token)
        print(f"✅ Conectado exitosamente a la sala: {room.name}")
    except Exception as e:
        print(f"🚨 Error al conectar a LiveKit: {e}")
        raise

    print("🕓 Conexión activa. Esperando eventos...")
    try:
        while True:
            await asyncio.sleep(2)
            print("⏳ Manteniendo conexión viva...")
    except KeyboardInterrupt:
        print("🛑 Interrupción manual detectada. Cerrando sesión...")
        await room.disconnect()
        print("👋 Desconectado correctamente.")


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except Exception as e:
        print(f"💥 Error fatal: {e}")
