"""Scoped, revocable agent credentials with an audit trail.

A minimal reference for the "revocation drill": every agent gets its own
credential, every tool call is checked at call time, and every decision is
logged with the agent's identity and the human it acts for.

Standard library only. Python 3.10+.
"""
from __future__ import annotations

import json
import secrets
import time
from dataclasses import dataclass, field
from typing import Callable


class AccessDenied(Exception):
    """Raised when a tool call is refused. `reason` is machine-readable."""

    def __init__(self, reason: str):
        super().__init__(reason)
        self.reason = reason


@dataclass(frozen=True)
class Credential:
    token_id: str
    agent_id: str
    on_behalf_of: str
    scopes: frozenset[str]
    expires_at: float


@dataclass
class RevocationReceipt:
    token_id: str
    revoked_by: str
    revoked_at: float
    reason: str


class CredentialBroker:
    """Issues short-lived, scoped credentials and records revocations."""

    def __init__(self, clock: Callable[[], float] = time.monotonic):
        self._clock = clock
        self._issued: dict[str, Credential] = {}
        self._revoked: dict[str, RevocationReceipt] = {}

    def issue(self, agent_id: str, on_behalf_of: str, scopes: set[str],
              ttl_seconds: float = 900) -> Credential:
        cred = Credential(
            token_id=secrets.token_hex(8),
            agent_id=agent_id,
            on_behalf_of=on_behalf_of,
            scopes=frozenset(scopes),
            expires_at=self._clock() + ttl_seconds,
        )
        self._issued[cred.token_id] = cred
        return cred

    def revoke(self, token_id: str, revoked_by: str, reason: str) -> RevocationReceipt:
        if token_id not in self._issued:
            raise KeyError(f"unknown token {token_id}")
        receipt = RevocationReceipt(token_id, revoked_by, self._clock(), reason)
        self._revoked[token_id] = receipt
        return receipt

    def check(self, cred: Credential, scope: str) -> None:
        """Raise AccessDenied unless the credential is valid for this scope now."""
        if cred.token_id not in self._issued:
            raise AccessDenied("unknown_token")
        if cred.token_id in self._revoked:
            raise AccessDenied("revoked")
        if self._clock() >= cred.expires_at:
            raise AccessDenied("expired")
        if scope not in cred.scopes:
            raise AccessDenied("out_of_scope")


@dataclass
class AuditLog:
    events: list[dict] = field(default_factory=list)

    def record(self, **event) -> None:
        self.events.append(event)

    def to_jsonl(self) -> str:
        return "\n".join(json.dumps(e, sort_keys=True) for e in self.events)


class ToolGateway:
    """The single checkpoint every agent tool call passes through.

    Checks the credential and the pause flag on EVERY call. Nothing is cached.
    """

    def __init__(self, broker: CredentialBroker, log: AuditLog,
                 clock: Callable[[], float] = time.monotonic):
        self._broker = broker
        self._log = log
        self._clock = clock
        self._tools: dict[str, tuple[str, Callable[..., object]]] = {}
        self._paused: dict[str, str] = {}  # agent_id -> reason

    def register(self, name: str, scope: str, fn: Callable[..., object]) -> None:
        self._tools[name] = (scope, fn)

    def pause(self, agent_id: str, reason: str) -> None:
        """Wire alerts here. An alert should pause the agent, not open a ticket."""
        self._paused[agent_id] = reason

    def resume(self, agent_id: str, approved_by: str) -> None:
        self._paused.pop(agent_id, None)
        self._log.record(t=self._clock(), event="resume", agent=agent_id,
                         approved_by=approved_by)

    def call(self, cred: Credential, tool: str, **kwargs) -> object:
        scope, fn = self._tools[tool]
        base = dict(t=self._clock(), agent=cred.agent_id,
                    on_behalf_of=cred.on_behalf_of, token=cred.token_id,
                    tool=tool, scope=scope)
        try:
            if cred.agent_id in self._paused:
                raise AccessDenied("paused")
            self._broker.check(cred, scope)
        except AccessDenied as exc:
            self._log.record(**base, decision="deny", reason=exc.reason)
            raise
        self._log.record(**base, decision="allow")
        return fn(**kwargs)


class SessionCachingGateway(ToolGateway):
    """ANTI-PATTERN, for the drill to catch.

    Validates the credential once per agent session and trusts it afterwards.
    Common in real code because it saves a lookup per call.
    """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._validated: set[str] = set()

    def call(self, cred: Credential, tool: str, **kwargs) -> object:
        if cred.token_id in self._validated:
            scope, fn = self._tools[tool]
            self._log.record(t=self._clock(), agent=cred.agent_id,
                             on_behalf_of=cred.on_behalf_of, token=cred.token_id,
                             tool=tool, scope=scope, decision="allow",
                             reason="session_cache")
            return fn(**kwargs)
        result = super().call(cred, tool, **kwargs)
        self._validated.add(cred.token_id)
        return result


@dataclass
class DrillResult:
    passed: bool
    first_call_allowed: bool
    retry_denied: bool
    deny_reason: str | None
    revoke_to_stop_seconds: float | None


def revocation_drill(gateway: ToolGateway, broker: CredentialBroker, log: AuditLog,
                     tool: str, scope: str, clock: Callable[[], float] = time.monotonic,
                     **tool_kwargs) -> DrillResult:
    """Grant, act, revoke, retry. Pass only if the retry is denied and logged."""
    cred = broker.issue("drill-agent", on_behalf_of="drill-owner", scopes={scope})

    try:
        gateway.call(cred, tool, **tool_kwargs)
        first_ok = True
    except AccessDenied:
        first_ok = False

    receipt = broker.revoke(cred.token_id, revoked_by="drill-owner", reason="drill")

    deny_reason = None
    try:
        gateway.call(cred, tool, **tool_kwargs)
        retry_denied = False
    except AccessDenied as exc:
        retry_denied = True
        deny_reason = exc.reason

    stop_event = next((e for e in log.events
                       if e.get("token") == cred.token_id and e.get("decision") == "deny"),
                      None)
    revoke_to_stop = (stop_event["t"] - receipt.revoked_at) if stop_event else None

    passed = first_ok and retry_denied and deny_reason == "revoked" and stop_event is not None
    return DrillResult(passed, first_ok, retry_denied, deny_reason, revoke_to_stop)
