"""Agent Lens as a LiteLLM guardrail (F29): every tool call a model returns through the LiteLLM
proxy is decided before the agent sees it -- whatever framework the agent is written in.

The model proposes tool calls in its response; the agent executes them after the response
arrives. So this runs post_call: each tool call goes to /v1/pre-action, and

  allow   passes through untouched
  review  the response is held until a person answers in the Agent Lens console (the agent's
          HTTP request to LiteLLM stays open, as with the MCP gateway); approved passes, anything
          else is treated as refused
  block   on_refusal=rewrite (default): the call is removed from the response and the model's
          message says why, so the agent continues with a reason instead of crashing;
          on_refusal=block: the whole response fails with LiteLLM's GuardrailRaisedException

What each tool returned arrives on the agent's next request as a `tool` message; those are
reported to /v1/post-action, so the trace shows results as it does for the gateway.

LiteLLM proxy config.yaml:

    guardrails:
      - guardrail_name: agentlens
        litellm_params:
          guardrail: agentlens_guardrail.AgentLensGuardrail   # this file on the proxy's path
          mode: post_call
          default_on: true
          api_base: os.environ/AGENTLENS_URL        # default https://api.neuronlens.com
          api_key: os.environ/AGENTLENS_API_KEY     # X-API-Key, when backend auth is on
          on_refusal: rewrite                       # or block
          fail_mode: open                           # gate unreachable: open | closed

Agent id: the LiteLLM virtual key's alias (or team alias, or end user), else `litellm-agent`.
Run id: the request's `litellm_session_id` / `metadata.session_id`, else one per trace id.
Streamed responses too: text streams through; tool-call chunks are held until decided.
"""
from __future__ import annotations

import asyncio
import json
import os
import time
from typing import Any, Dict, List, Optional, Tuple

import httpx
from litellm._logging import verbose_proxy_logger
from litellm.exceptions import GuardrailRaisedException
from litellm.integrations.custom_guardrail import CustomGuardrail
from litellm.types.guardrails import GuardrailEventHooks
from litellm.types.utils import Choices, ModelResponse

CLAIM_KEYS = ("recommendation", "summary", "justification", "reason", "message", "report", "text", "body")
PROTOCOL = "litellm"


def _get(obj: Any, key: str, default: Any = None) -> Any:
    return obj.get(key, default) if isinstance(obj, dict) else getattr(obj, key, default)


class AgentLensGuardrail(CustomGuardrail):
    def __init__(self, api_base: Optional[str] = None, api_key: Optional[str] = None,
                 on_refusal: str = "rewrite", fail_mode: str = "open", review_timeout_s: float = 300,
                 poll_interval_s: float = 1.0, timeout_s: float = 60, **kwargs: Any):
        self.api_base = (api_base or os.getenv("AGENTLENS_URL") or "https://api.neuronlens.com").rstrip("/")
        self.api_key = api_key or os.getenv("AGENTLENS_API_KEY")
        self.on_refusal = str(on_refusal).lower()
        self.fail_mode = str(fail_mode).lower()
        self.review_timeout_s = float(review_timeout_s)
        self.poll_interval_s = float(poll_interval_s)
        self.timeout_s = float(timeout_s)
        self._reported: set = set()
        self._refused: set = set()        # removed from a response: the agent never received them
        self._registered: set = set()     # (agent, hash of the offered tool list) already sent
        kwargs.setdefault("supported_event_hooks", [GuardrailEventHooks.post_call])
        super().__init__(**kwargs)

    # ─── talking to Agent Lens ───────────────────────────────────────────────

    def _headers(self) -> Dict[str, str]:
        return {"X-API-Key": self.api_key} if self.api_key else {}

    async def _call(self, method: str, path: str, body: Optional[dict] = None, timeout: Optional[float] = None) -> dict:
        async with httpx.AsyncClient(timeout=timeout or self.timeout_s) as c:
            r = await c.request(method, self.api_base + path, json=body, headers=self._headers())
            r.raise_for_status()
            return r.json()

    async def _wait_for_human(self, action_id: str) -> dict:
        deadline = time.monotonic() + self.review_timeout_s
        while time.monotonic() < deadline:
            await asyncio.sleep(self.poll_interval_s)
            try:
                d = await self._call("GET", f"/v1/decisions/{action_id}", timeout=10)
            except httpx.HTTPStatusError as e:
                if e.response.status_code in (401, 403):
                    raise
                continue
            except Exception:                                 # noqa: BLE001
                continue
            if d.get("status") not in ("pending", "unknown"):
                return d
        return {"status": "expired", "decision": "block", "reason": "no reviewer answered before the hold expired"}

    # ─── reading the request ─────────────────────────────────────────────────

    @staticmethod
    def agent_id(data: dict, user_api_key_dict: Any) -> str:
        for k in ("key_alias", "team_alias"):
            v = _get(user_api_key_dict, k)
            if v:
                return str(v)
        md = data.get("metadata") or {}
        if md.get("agent_id"):
            return str(md["agent_id"])
        for k in ("end_user_id", "user_id"):
            v = _get(user_api_key_dict, k)
            # A proxy without virtual keys fills in this placeholder for every caller.
            if v and v != "default_user_id":
                return str(v)
        return str(data.get("user") or "litellm-agent")

    @staticmethod
    def run_id(data: dict) -> Optional[str]:
        md = data.get("metadata") or {}
        rid = data.get("litellm_session_id") or md.get("session_id") or md.get("litellm_session_id")
        if rid:
            return str(rid)
        trace = data.get("litellm_trace_id") or md.get("trace_id")
        return f"llm-{trace}" if trace else None

    @staticmethod
    def goal(messages: List[Any]) -> Optional[str]:
        for m in reversed(messages or []):
            if _get(m, "role") != "user":
                continue
            c = _get(m, "content")
            if isinstance(c, str) and c.strip():
                return c[:4000]
            if isinstance(c, list):
                text = " ".join(str(_get(b, "text") or "") for b in c if _get(b, "type") == "text")
                if text.strip():
                    return text[:4000]
        return None

    async def _report_results(self, messages: List[Any]) -> None:
        """Tool results the agent sends back on its next turn -> /v1/post-action (best effort)."""
        for m in messages or []:
            if _get(m, "role") != "tool" or not _get(m, "tool_call_id"):
                continue
            aid = f"llm-{_get(m, 'tool_call_id')}"
            if aid in self._reported or aid in self._refused:
                continue
            c = _get(m, "content")
            text = c if isinstance(c, str) else json.dumps(c, default=str)
            try:
                await self._call("POST", "/v1/post-action", {"action_id": aid, "result": (text or "")[:4000]}, timeout=10)
                self._reported.add(aid)
            except Exception as e:                            # noqa: BLE001
                verbose_proxy_logger.debug(f"Agent Lens: result for {aid} not reported: {e}")
        if len(self._reported) > 50_000:
            self._reported.clear()
        if len(self._refused) > 50_000:
            self._refused.clear()

    async def _register_tools(self, data: dict, agent: str) -> None:
        """The tools the request offered the model are this agent's advertised tools -- LiteLLM's
        equivalent of MCP tools/list. Without this every tool would be unknown (F6) and held."""
        offered = []
        for t in data.get("tools") or []:
            fn = _get(t, "function") or {}
            if _get(fn, "name"):
                offered.append({"name": _get(fn, "name"), "description": _get(fn, "description") or "",
                                "inputSchema": _get(fn, "parameters") or {}})
        if not offered:
            return
        key = (agent, hash(json.dumps(offered, sort_keys=True, default=str)))
        if key in self._registered:
            return
        try:
            await self._call("POST", "/v1/tools/observed", {"agent_id": agent, "upstream": "litellm", "tools": offered},
                             timeout=10)
            self._registered.add(key)
        except Exception as e:                                # noqa: BLE001
            verbose_proxy_logger.debug(f"Agent Lens: offered tools not registered: {e}")

    @staticmethod
    def usage(response: Any) -> Optional[Dict[str, float]]:
        """Tokens and, when LiteLLM priced it, cost of this response (token / spend ceilings)."""
        out: Dict[str, float] = {}
        tokens = _get(_get(response, "usage"), "total_tokens")
        if isinstance(tokens, (int, float)):
            out["tokens"] = tokens
        cost = (getattr(response, "_hidden_params", None) or {}).get("response_cost")
        if isinstance(cost, (int, float)):
            out["cost_usd"] = cost
        return out or None

    # ─── the hook ────────────────────────────────────────────────────────────

    async def decide(self, tool_call: Any, content: Optional[str], data: dict, user_api_key_dict: Any,
                     usage: Optional[Dict[str, float]] = None) -> Dict[str, Any]:
        """{decision: allow|block, reason}. Holds while a person reviews."""
        fn = _get(tool_call, "function") or {}
        name = _get(fn, "name") or "unknown_tool"
        raw = _get(fn, "arguments") or "{}"
        try:
            args = json.loads(raw) if isinstance(raw, str) else dict(raw)
            if not isinstance(args, dict):
                args = {"value": args}
        except (TypeError, ValueError):
            args = {"text": str(raw)[:20_000]}
        claim = next((args[k] for k in CLAIM_KEYS if isinstance(args.get(k), str) and args[k].strip()), None) or content
        body = {"action": {"tool": name, "arguments": args, "claim_text": claim},
                "agent": {"id": self.agent_id(data, user_api_key_dict), "framework": "litellm", "protocol": PROTOCOL},
                "run_id": self.run_id(data), "action_id": f"llm-{_get(tool_call, 'id')}" if _get(tool_call, "id") else None,
                "user_goal": self.goal(data.get("messages") or [])}
        if usage:
            body["usage"] = usage
        try:
            v = await self._call("POST", "/v1/pre-action", body)
        except httpx.HTTPStatusError as e:
            if e.response.status_code in (401, 403):
                return {"decision": "block", "reason": "Agent Lens rejected the guardrail's credentials (set api_key)"}
            return self._unreachable(e)
        except Exception as e:                                # noqa: BLE001
            return self._unreachable(e)
        decision, reason = v.get("decision", "allow"), v.get("reason") or ""
        if decision == "review":
            verbose_proxy_logger.info(f"Agent Lens: HELD {name} ({reason}), waiting for a reviewer")
            try:
                d = await self._wait_for_human(v["action_id"])
            except Exception:                                 # noqa: BLE001
                return {"decision": "block", "reason": "Agent Lens rejected the guardrail's credentials"}
            if d.get("decision") == "allow":
                return {"decision": "allow", "reason": f"approved by {d.get('by') or 'reviewer'}"}
            return {"decision": "block", "reason": d.get("reason") or reason}
        return {"decision": "block" if decision == "block" else "allow", "reason": reason}

    def _unreachable(self, exc: Exception) -> Dict[str, Any]:
        if self.fail_mode == "closed":
            return {"decision": "block", "reason": f"Agent Lens unreachable and fail_mode=closed ({type(exc).__name__})"}
        verbose_proxy_logger.warning(f"Agent Lens unreachable, failing open: {exc}")
        return {"decision": "allow", "reason": "gate unreachable (fail_mode=open)"}

    async def _decide_all(self, tool_calls: List[Any], content: Optional[str], data: dict, user_api_key_dict: Any,
                          usage: Optional[Dict[str, float]]) -> Tuple[List[Any], List[str]]:
        """(kept tool calls, refusal messages) for one choice; raises under on_refusal=block."""
        kept, refused = [], []
        for tc in tool_calls:
            d = await self.decide(tc, content, data, user_api_key_dict, usage)
            usage = None                          # counted once: on the first tool call of the response
            if d["decision"] == "allow":
                kept.append(tc)
                continue
            msg = f"Agent Lens refused the tool call {_get(_get(tc, 'function'), 'name')}: {d['reason']}"
            if self.on_refusal == "block":
                raise GuardrailRaisedException(guardrail_name=self.guardrail_name, message=msg)
            refused.append(msg)
            self._refused.add(f"llm-{_get(tc, 'id')}")
        return kept, refused

    async def async_post_call_success_hook(self, data: dict, user_api_key_dict: Any, response: Any) -> Any:
        if not isinstance(response, ModelResponse):
            return response
        if not self.should_run_guardrail(data=data, event_type=GuardrailEventHooks.post_call):
            return response
        await self._report_results(data.get("messages") or [])
        await self._register_tools(data, self.agent_id(data, user_api_key_dict))
        usage = self.usage(response)              # counted once: on the first tool call of the response
        for choice in response.choices:
            if not isinstance(choice, Choices) or not choice.message.tool_calls:
                continue
            content = choice.message.content if isinstance(choice.message.content, str) else None
            kept, refused = await self._decide_all(choice.message.tool_calls, content, data, user_api_key_dict, usage)
            usage = None
            if refused:
                choice.message.tool_calls = kept or None
                choice.message.content = "\n\n".join([*(filter(None, [content])), *refused])
                if not kept and choice.finish_reason == "tool_calls":
                    choice.finish_reason = "stop"
        return response

    async def async_post_call_streaming_iterator_hook(self, user_api_key_dict: Any, response: Any, request_data: dict):
        """Streamed responses: text streams through as it arrives. From the first tool-call fragment
        of a choice on, its chunks are held; at the end of the stream the assembled calls are decided
        and the held chunks released -- refused calls' fragments removed, the remaining calls
        renumbered, the refusal reasons added as text (or, under on_refusal=block, the stream fails).
        So the agent never receives a refused call, but does wait for the decision, as unstreamed."""
        if not self.should_run_guardrail(data=request_data, event_type=GuardrailEventHooks.post_call):
            async for chunk in response:
                yield chunk
            return
        data = request_data or {}
        await self._report_results(data.get("messages") or [])
        await self._register_tools(data, self.agent_id(data, user_api_key_dict))
        held: List[Any] = []
        text: Dict[int, str] = {}
        calls: Dict[int, Dict[int, Dict[str, Any]]] = {}     # choice -> tool index -> {id, name, arguments}
        usage = None
        async for chunk in response:
            usage = self.usage(chunk) or usage
            holding = bool(held)
            for ch in _get(chunk, "choices") or []:
                delta = _get(ch, "delta")
                c = _get(delta, "content")
                if isinstance(c, str):
                    text[_get(ch, "index", 0)] = text.get(_get(ch, "index", 0), "") + c
                for tc in _get(delta, "tool_calls") or []:
                    holding = True
                    acc = calls.setdefault(_get(ch, "index", 0), {}).setdefault(
                        _get(tc, "index", 0), {"id": None, "name": "", "arguments": ""})
                    fn = _get(tc, "function")
                    acc["id"] = _get(tc, "id") or acc["id"]
                    acc["name"] += _get(fn, "name") or ""
                    acc["arguments"] += _get(fn, "arguments") or ""
            if holding:
                held.append(chunk)
            else:
                yield chunk
        if not held:
            return
        drop: Dict[int, Dict[int, Optional[int]]] = {}         # choice -> old tool index -> new index (None: removed)
        notes: Dict[int, List[str]] = {}
        for ci, by_index in calls.items():
            order = sorted(by_index)
            tcs = [{"id": by_index[i]["id"], "type": "function",
                    "function": {"name": by_index[i]["name"], "arguments": by_index[i]["arguments"] or "{}"}}
                   for i in order]
            kept, refused = await self._decide_all(tcs, text.get(ci) or None, data, user_api_key_dict, usage)
            usage = None
            kept_ids = [k["id"] for k in kept]
            drop[ci] = {i: (kept_ids.index(by_index[i]["id"]) if by_index[i]["id"] in kept_ids else None) for i in order}
            if refused:
                notes[ci] = refused
        noted = set()
        for chunk in held:
            for ch in _get(chunk, "choices") or []:
                ci = _get(ch, "index", 0)
                if ci not in notes:
                    continue
                delta = ch.delta
                if delta.tool_calls:
                    kept_frags = []
                    for tc in delta.tool_calls:
                        new = drop[ci].get(tc.index)
                        if new is not None:
                            tc.index = new
                            kept_frags.append(tc)
                    delta.tool_calls = kept_frags or None
                if ci not in noted:
                    sep = "\n\n" if text.get(ci) else ""
                    delta.content = (delta.content or "") + sep + "\n\n".join(notes[ci])
                    noted.add(ci)
                if ch.finish_reason == "tool_calls" and not any(v is not None for v in drop[ci].values()):
                    ch.finish_reason = "stop"
        for chunk in held:
            yield chunk
