"""Agent Lens in a LangChain / LangGraph agent: every tool call is decided before it runs.

Uses the tool-call interceptor both libraries share (langchain >= 1.0, langgraph >= 1.0), so the
call is decided in the agent's own process, with the run's messages at hand:

    from agentlens_langgraph import AgentLensMiddleware

    guard = AgentLensMiddleware(agent_id="research-agent")
    agent = create_agent(model, tools, middleware=[guard])                # langchain
    node = ToolNode(tools, wrap_tool_call=guard.wrap_tool_call,           # a hand-built graph
                    awrap_tool_call=guard.awrap_tool_call)

  allow   the tool runs; what it returned goes to /v1/post-action for the trace
  review  held until someone answers in the Agent Lens console (review="refuse" refuses at once)
  block   the tool does not run; the model gets an error ToolMessage with the reason, so the
          agent continues with a reason instead of crashing

Run id: the graph's `thread_id` (config["configurable"]), else one id per guard. Task: the
last human message. Reasoning: the text of the AI message that proposed the call, verbatim.
Gate settings and fail modes: agentlens_client.py.
"""
from __future__ import annotations

import asyncio
import os
import sys
import uuid
from typing import Any, Dict, List, Optional

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from agentlens_client import Gate, as_text  # noqa: E402

from langchain_core.messages import ToolMessage  # noqa: E402

try:                                                          # langchain's create_agent
    from langchain.agents.middleware import AgentMiddleware as _Base
except ImportError:                                           # langgraph only: ToolNode(wrap_tool_call=...)
    _Base = object


def _messages(state: Any) -> List[Any]:
    if isinstance(state, dict):
        return list(state.get("messages") or [])
    if isinstance(state, list):
        return state
    return list(getattr(state, "messages", None) or [])


def _text(content: Any) -> str:
    if isinstance(content, str):
        return content
    if isinstance(content, list):
        return " ".join(b.get("text", "") if isinstance(b, dict) else str(b) for b in content
                        if not isinstance(b, dict) or b.get("type") in (None, "text"))
    return ""


def _goal(msgs: List[Any]) -> Optional[str]:
    for m in reversed(msgs):
        if getattr(m, "type", None) == "human":
            t = _text(m.content).strip()
            if t:
                return t
    return None


def _reasoning(msgs: List[Any], call_id: Optional[str]) -> Optional[str]:
    for m in reversed(msgs):
        if getattr(m, "type", None) == "ai" and any(c.get("id") == call_id for c in getattr(m, "tool_calls", None) or []):
            return _text(m.content).strip() or None
    return None


def _run_id(runtime: Any) -> Optional[str]:
    cfg = getattr(runtime, "config", None) or {}
    tid = (cfg.get("configurable") or {}).get("thread_id") if isinstance(cfg, dict) else None
    return str(tid) if tid else None


class AgentLensMiddleware(_Base):
    def __init__(self, agent_id: Optional[str] = None, **gate: Any):
        if _Base is not object:
            super().__init__()
        self.gate = Gate(agent_id or os.getenv("AGENTLENS_AGENT_ID", "langgraph-agent"), "langgraph", **gate)
        self._run = f"lg-{uuid.uuid4().hex[:12]}"

    def _decide(self, request: Any) -> Dict[str, Any]:
        call = request.tool_call
        msgs = _messages(request.state)
        cid = call.get("id")
        ok, reason, aid = self.gate.decide(
            call.get("name"), call.get("args") or {}, run_id=_run_id(request.runtime) or self._run,
            action_id=f"lg-{cid}" if cid else None, user_goal=_goal(msgs), reasoning=_reasoning(msgs, cid))
        return {"ok": ok, "reason": reason, "aid": aid}

    @staticmethod
    def _refusal(request: Any, reason: str) -> ToolMessage:
        call = request.tool_call
        return ToolMessage(content=reason, tool_call_id=call.get("id") or "", name=call.get("name"), status="error")

    def _report(self, aid: Optional[str], out: Any) -> None:
        if isinstance(out, ToolMessage):
            self.gate.report(aid, _text(out.content) or as_text(out.content), out.status == "error")
        else:                                                 # a Command: report the messages it carries
            update = getattr(out, "update", None)
            msgs = _messages(update) if update is not None else []
            self.gate.report(aid, " ".join(_text(getattr(m, "content", "")) for m in msgs) or repr(out))

    def wrap_tool_call(self, request: Any, handler: Any) -> Any:
        d = self._decide(request)
        if not d["ok"]:
            return self._refusal(request, d["reason"])
        out = handler(request)
        self._report(d["aid"], out)
        return out

    async def awrap_tool_call(self, request: Any, handler: Any) -> Any:
        d = await asyncio.to_thread(self._decide, request)    # a review hold must not block the loop
        if not d["ok"]:
            return self._refusal(request, d["reason"])
        out = await handler(request)
        await asyncio.to_thread(self._report, d["aid"], out)
        return out
