"""Agent Lens in a Google ADK agent: every tool call is decided before it runs.

ADK's tool callbacks run in the agent's process; a dict returned by `before_tool_callback`
replaces the tool's response, so a refused call never runs and the model reads why:

    from agentlens_adk import AgentLensCallbacks

    guard = AgentLensCallbacks()                         # agent id: the ADK agent's name
    agent = LlmAgent(name="research_agent", model=..., tools=[...],
                     before_tool_callback=guard.before_tool,
                     after_tool_callback=guard.after_tool)

  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; its response is {"status": "refused", "error": <reason>}

Run id: the ADK session id, else the invocation id. Task: the user message that started the
invocation. Both callbacks are async (a review hold must not block the event loop) and never
raise. No ADK import here: the callbacks read the objects ADK passes by attribute.
Gate settings and fail modes: agentlens_client.py.
"""
from __future__ import annotations

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

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


def _user_text(ctx: Any) -> Optional[str]:
    content = getattr(ctx, "user_content", None)
    parts = getattr(content, "parts", None) or []
    text = " ".join(getattr(p, "text", None) or "" for p in parts).strip()
    return text or None


def _run_id(ctx: Any) -> Optional[str]:
    session = getattr(ctx, "session", None) or getattr(getattr(ctx, "_invocation_context", None), "session", None)
    sid = getattr(session, "id", None)
    return f"adk-{sid or getattr(ctx, 'invocation_id', None) or 'session'}"


class AgentLensCallbacks:
    def __init__(self, agent_id: Optional[str] = None, **gate: Any):
        self.agent_id = agent_id or os.getenv("AGENTLENS_AGENT_ID")
        self.gate_args = gate
        self._gates: Dict[str, Gate] = {}
        self._pending: Dict[str, Optional[str]] = {}          # function_call_id -> action_id

    def _gate(self, ctx: Any) -> Gate:
        agent = self.agent_id or getattr(ctx, "agent_name", None) or "adk-agent"
        if agent not in self._gates:
            self._gates[agent] = Gate(agent, "google-adk", **self.gate_args)
        return self._gates[agent]

    def _decide(self, tool: Any, args: Dict[str, Any], ctx: Any) -> Optional[Dict[str, Any]]:
        cid = getattr(ctx, "function_call_id", None)
        ok, reason, aid = self._gate(ctx).decide(
            getattr(tool, "name", None) or str(tool), args or {}, run_id=_run_id(ctx),
            action_id=f"adk-{cid}" if cid else None, user_goal=_user_text(ctx))
        if not ok:
            return {"status": "refused", "error": reason}
        if cid:
            self._pending[cid] = aid
        return None

    async def before_tool(self, tool: Any, args: Dict[str, Any], tool_context: Any) -> Optional[Dict[str, Any]]:
        return await asyncio.to_thread(self._decide, tool, args, tool_context)

    async def after_tool(self, tool: Any, args: Dict[str, Any], tool_context: Any,
                         tool_response: Any) -> Optional[Dict[str, Any]]:
        aid = self._pending.pop(getattr(tool_context, "function_call_id", None), None)
        is_error = isinstance(tool_response, dict) and bool(tool_response.get("error"))
        await asyncio.to_thread(self._gate(tool_context).report, aid, tool_response, is_error)
        return None                                           # the response passes unchanged
