"""The Agent Lens gate, as the in-process framework adapters call it (LangGraph / LangChain,
Google ADK). Standard library only.

    gate = Gate(agent_id="research-agent", framework="langgraph")
    ok, reason, aid = gate.decide(tool, args, run_id=..., action_id=..., user_goal=...)
    ...run the tool if ok...
    gate.report(aid, result_text, is_error)

decide() answers (allowed, reason, action_id):
  allow   (True, ...)
  review  held until a person answers in the Agent Lens console (review="wait", the default;
          the adapter's thread waits, as the agent's HTTP call does at the MCP gateway): approved
          runs, anything else is refused. review="refuse" refuses at once, with the reason.
  block   (False, reason)
Gate unreachable: fail_mode open (default, as the gateway) runs the tool; closed refuses.
A gate that answers 401/403 is up and refusing us: that always refuses, whatever the fail mode.

Environment (constructor arguments win): AGENTLENS_URL (default https://api.neuronlens.com),
AGENTLENS_API_KEY (X-API-Key when backend auth is on), AGENTLENS_FAIL_MODE, AGENTLENS_REVIEW
(wait | refuse), AGENTLENS_TIMEOUT_S (default 60), AGENTLENS_REVIEW_TIMEOUT_S (default 300).
"""
from __future__ import annotations

import json
import logging
import os
import time
import urllib.error
import urllib.request
from typing import Any, Dict, List, Optional, Tuple

log = logging.getLogger("agentlens")

# The model's own words inside a tool's arguments -- what the probes read.
CLAIM_KEYS = ("recommendation", "summary", "justification", "reason", "message", "report", "text", "body",
              "description")
MAX_TEXT = 4000


class GateRefused(Exception):
    """401/403: misconfigured credentials. Never fail open on this."""


def claim_text(args: Dict[str, Any]) -> Optional[str]:
    for k in CLAIM_KEYS:
        v = args.get(k) if isinstance(args, dict) else None
        if isinstance(v, str) and v.strip():
            return v
    return None


def as_text(result: Any) -> str:
    text = result if isinstance(result, str) else json.dumps(result, default=str)
    return text[:MAX_TEXT]


class Gate:
    def __init__(self, agent_id: str, framework: str, url: Optional[str] = None, api_key: Optional[str] = None,
                 fail_mode: Optional[str] = None, review: Optional[str] = None,
                 timeout_s: Optional[float] = None, review_timeout_s: Optional[float] = None,
                 available_tools: Optional[List[str]] = None, kit_tools: Optional[Dict[str, str]] = None):
        self.agent_id, self.framework = agent_id, framework
        self.url = (url or os.getenv("AGENTLENS_URL", "https://api.neuronlens.com")).rstrip("/")
        self.api_key = api_key or os.getenv("AGENTLENS_API_KEY")
        self.fail_mode = (fail_mode or os.getenv("AGENTLENS_FAIL_MODE", "open")).lower()
        self.review = (review or os.getenv("AGENTLENS_REVIEW", "wait")).lower()
        self.timeout_s = float(timeout_s or os.getenv("AGENTLENS_TIMEOUT_S", "60"))
        self.review_timeout_s = float(review_timeout_s or os.getenv("AGENTLENS_REVIEW_TIMEOUT_S", "300"))
        self.available_tools, self.kit_tools = available_tools, kit_tools

    def _call(self, method: str, path: str, body: Optional[Dict[str, Any]] = None,
              timeout: Optional[float] = None) -> Dict[str, Any]:
        headers = {"Content-Type": "application/json"}
        if self.api_key:
            headers["X-API-Key"] = self.api_key
        req = urllib.request.Request(self.url + path, method=method, headers=headers,
                                     data=None if body is None else json.dumps(body, default=str).encode())
        try:
            with urllib.request.urlopen(req, timeout=timeout or self.timeout_s) as r:
                return json.loads(r.read() or b"{}")
        except urllib.error.HTTPError as e:
            if e.code in (401, 403):
                raise GateRefused(f"Agent Lens rejected the credentials (HTTP {e.code}); set AGENTLENS_API_KEY")
            raise

    def _wait(self, aid: str) -> Dict[str, Any]:
        deadline = time.monotonic() + self.review_timeout_s
        while time.monotonic() < deadline:
            time.sleep(1.0)
            try:
                d = self._call("GET", f"/v1/decisions/{aid}", timeout=10)
            except GateRefused:
                raise
            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"}

    def decide(self, tool: str, args: Dict[str, Any], run_id: Optional[str] = None,
               action_id: Optional[str] = None, user_goal: Optional[str] = None,
               reasoning: Optional[str] = None) -> Tuple[bool, str, Optional[str]]:
        body: Dict[str, Any] = {
            "action": {"tool": tool or "unknown_tool", "arguments": args or {}, "claim_text": claim_text(args or {}),
                       **({"reasoning": reasoning[:MAX_TEXT]} if reasoning else {})},
            "agent": {"id": self.agent_id, "framework": self.framework, "protocol": "sdk"},
            "run_id": run_id, "action_id": action_id,
            "user_goal": user_goal[:MAX_TEXT] if user_goal else None,
        }
        if self.available_tools:
            body["available_tools"] = list(self.available_tools)
        if self.kit_tools:
            body["kit_tools"] = dict(self.kit_tools)
        try:
            v = self._call("POST", "/v1/pre-action", body)
        except GateRefused as e:
            return False, str(e), action_id
        except Exception as e:                                # noqa: BLE001
            if self.fail_mode == "closed":
                return False, f"Agent Lens unreachable and fail_mode=closed ({type(e).__name__})", action_id
            log.warning("[agentlens] gate unreachable, failing open: %s", e)
            return True, "gate unreachable (fail open)", action_id
        decision, reason, aid = v.get("decision", "allow"), v.get("reason") or "", v.get("action_id") or action_id
        if decision == "block":
            return False, f"Agent Lens refused this call: {reason}", aid
        if decision == "review":
            if self.review != "wait" or not aid:
                return False, f"Agent Lens held this call for review: {reason}", aid
            try:
                d = self._wait(aid)
            except GateRefused as e:
                return False, str(e), aid
            if d.get("decision") == "allow":
                return True, d.get("reason") or "approved", aid
            return False, f"Agent Lens: not approved ({d.get('reason') or reason})", aid
        return True, reason, aid

    def report(self, action_id: Optional[str], result: Any, is_error: bool = False) -> None:
        """What the tool returned, for the trace (never raises)."""
        if not action_id:
            return
        try:
            self._call("POST", "/v1/post-action", {"action_id": action_id, "result": as_text(result),
                                                   "is_error": bool(is_error)}, timeout=10)
        except Exception as e:                                # noqa: BLE001
            log.warning("[agentlens] result not reported: %s", e)
