# backend/src/agent/langgraph_setup.py
# #region AgentChat.LangGraph.Setup [C:4] [TYPE Module] [SEMANTICS agent-chat,langgraph,agent]
# @DEFGROUP AgentChat LangGraph agent setup: create_react_agent with PostgresSaver.
# @PRE LLM provider configured. Priority: 1) llm_config param 2) env vars LLM_API_KEY/LLM_BASE_URL/LLM_MODEL.
# @POST Compiled StateGraph ready for astream_events().
# @SIDE_EFFECT Initializes checkpointer and message history tables on first call.
# @RELATION DEPENDS_ON -> [AgentChat.Tools]
# @RELATION DEPENDS_ON -> [AgentChat.Tools]
# @RELATION DEPENDS_ON -> [AgentChat.Tools]
# @RATIONALE LangGraph create_react_agent provides built-in tool calling + checkpointing + interrupt/resume.
# @REJECTED Using only environment variables for LLM config was rejected — FastAPI API-based config allows runtime switching without restart.

#            RunnableWithMessageHistory wrapper is NOT used — PostgresSaver handles history natively.

import os

from langchain_openai import ChatOpenAI
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.prebuilt import create_react_agent

# ── Dangerous tool names — interrupt_before pauses execution at these nodes ──
# ── Dangerous tool names — interrupt_before pauses execution at these nodes ──
# These tools don't exist yet in the current tool set. When dangerous tools are
# added (deploy, migrate, commit, maintenance), add their names here.
DANGEROUS_TOOLS: list[str] = []

# ── LLM config cache ────────────────────────────────────────────
_llm_config: dict | None = None
_llm_config_ttl: int = 300  # 5 min


def configure_from_api(llm_config: dict) -> None:
    """Update LLM config from FastAPI response. Called at startup."""
    global _llm_config
    _llm_config = llm_config


def create_agent(tools: list):
    """Create the LangGraph agent with checkpointer and message history.

    LLM configuration priority:
        1. llm_config from configure_from_api() (fetched from FastAPI /api/agent/llm-config)
        2. Environment vars: LLM_API_KEY, LLM_BASE_URL, LLM_MODEL
        3. Defaults: gpt-4o, https://api.openai.com/v1

    Returns a RunnableWithMessageHistory wrapper ready for astream_events().
    The graph is compiled with interrupt_before=DANGEROUS_TOOLS to enable HITL.
    """
    if _llm_config and _llm_config.get("configured"):
        api_key = _llm_config["api_key"]
        base_url = _llm_config.get("base_url") or "https://api.openai.com/v1"
        model = _llm_config.get("default_model") or "gpt-4o-mini"
    else:
        api_key = os.getenv("LLM_API_KEY")
        base_url = os.getenv("LLM_BASE_URL", "https://api.openai.com/v1")
        model = os.getenv("LLM_MODEL", "gpt-4o")

    llm = ChatOpenAI(
        model=model,
        base_url=base_url,
        api_key=api_key,
        temperature=0,
    )

    # Checkpointer — InMemorySaver for development (no persistence across restarts).
    # TODO: Replace with AsyncPostgresSaver when langgraph-checkpoint-postgres supports it.
    checkpointer = InMemorySaver()

    graph = create_react_agent(
        model=llm,
        tools=tools,
        checkpointer=checkpointer,
        interrupt_before=DANGEROUS_TOOLS,
    )

    return graph
# #endregion AgentChat.LangGraph.Setup
