from .graph import workflow_builder, workflow_compiled
from config.settings import settings
import asyncio

_graph = None

async def get_agent():
    """Inicializa y retorna el grafo con persistencia en Redis (para WhatsApp)."""
    global _graph
    if _graph is None:
        try:
            from langgraph.checkpoint.redis import AsyncRedisSaver
            
            # Configuración de conexión
            redis_url = f"redis://{settings.REDIS_HOST}:{settings.REDIS_PORT}"
            try:
                # Su versión de checkpointer espera explícitamente una URL tipo cadena en lugar del objeto cliente.
                redis_password_str = f":{settings.REDIS_PASSWORD}@" if settings.REDIS_PASSWORD else ""
                redis_url = f"redis://{redis_password_str}{settings.REDIS_HOST}:{settings.REDIS_PORT}/{settings.REDIS_DB}"
                
                checkpointer = AsyncRedisSaver(redis_url)
                await checkpointer.setup()
                
                # IMPORTANTE: Re-compilar usando el BUILDER original (StateGraph)
                # No podemos compilar un grafo ya compilado (workflow_compiled)
                _graph = workflow_builder.compile(checkpointer=checkpointer)
                print(f"✅ LangGraph Agent: Persistencia en Redis activada ({settings.REDIS_HOST}:{settings.REDIS_PORT})")
            except Exception as e:
                print(f"⚠️ Redis falló ({e}). Activando MemorySaver como respaldo seguro.")
                try:
                    from langgraph.checkpoint.memory import MemorySaver
                    _graph = workflow_builder.compile(checkpointer=MemorySaver())
                except Exception:
                    _graph = workflow_compiled
        except ImportError:
            print("⚠️ langgraph-checkpoint-redis no instalado. Usando memoria local de respaldo.")
            try:
                from langgraph.checkpoint.memory import MemorySaver
                _graph = workflow_builder.compile(checkpointer=MemorySaver())
            except Exception:
                _graph = workflow_compiled
        except Exception as e:
            print(f"⚠️ Error cargando agente: {e}")
            _graph = workflow_compiled
            
    return _graph
