# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-verify-a-delegated-oauth-scope-before-every-tool-invocation-and-why-the-aaif-token-s-exp-claim-is-not-the-invariant-that-pro.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-verify-a-delegated-oauth-scope-before-every-tool-invocation-and-why-the-aaif-token-s-exp-claim-is-not-the-invariant-that-pro.warrant.json
# Markdown SHA-256:   a8cc4b49ade4b3fc41ff9ca18dcebc33da564eac2fa8fcce75f7365b37871140
# Code AST SHA-256:   16d8d14e829ca964e2353ec151da6f3cf67cbb85ec1bafa1b233ef1c2a5a626b
# Verified Classes:   DelegationAuthorizationError, Credential, DelegationChain
# Defensive Guards:   9 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class DelegationAuthorizationError(RuntimeError):
    """Raised when an instance attempts a tool call whose delegation
    chain cannot be proven live-authorized at invocation time."""
    pass


@dataclass
class Credential:
    issuer: str
    subject: str
    scope: str
    delegation_depth: int
    expires_at: float
    status_list_url: str


@dataclass
class DelegationChain:
    credentials: list  # ordered root -> leaf
    root_depth_ceiling: int = 2


def _resolve_status(url: str, now: float, cache: dict, ttl: float) -> bool:
    """Return True iff the credential is currently live. Fail closed on
    any resolution error or cache miss past TTL."""
    entry = cache.get(url)
    if entry is not None and (now - entry["fetched_at"]) <= ttl:
        return entry["live"]
    # Cache miss / expired: must fetch. Any failure -> fail closed.
    try:
        live = _fetch_status(url)
    except Exception:
        return False  # never treat resolution failure as "valid"
    cache[url] = {"live": live, "fetched_at": now}
    return live


def _fetch_status(url: str) -> bool:
    # Placeholder for the status-list endpoint round-trip.
    raise NotImplementedError


def authorize_tool_call(
    chain: DelegationChain,
    required_scope: str,
    now: float,
    status_cache: dict,
    status_ttl: float = 30.0,
) -> None:
    creds = chain.credentials
    if not creds:
        raise DelegationAuthorizationError("empty delegation chain")

    # 1. Local, offline structural checks.
    if len(creds) > chain.root_depth_ceiling:
        raise DelegationAuthorizationError(
            f"chain length {len(creds)} exceeds root depth ceiling "
            f"{chain.root_depth_ceiling}: intermediary may be minting "
            f"unauthorized sub-delegations"
        )
    for i, c in enumerate(creds):
        if c.delegation_depth != i + 1:
            raise DelegationAuthorizationError(
                f"credential {i} asserts depth {c.delegation_depth}, "
                f"expected {i + 1}: chain is not a contiguous delegation"
            )
        if c.expires_at <= now:
            raise DelegationAuthorizationError(
                f"credential {i} expired at {c.expires_at}, now {now}"
            )

    # 2. The non-obvious part: depth >= 2 means the leaf is outside the
    #    root issuer's revocation surface. Token validity is NOT sufficient.
    multi_hop = len(creds) >= 2
    if multi_hop:
        for i, c in enumerate(creds):
            if not _resolve_status(c.status_list_url, now, status_cache, status_ttl):
                raise DelegationAuthorizationError(
                    f"credential {i} ({c.issuer}->{c.subject}) is not "
                    f"live-authorized at invocation time; refusing tool call "
                    f"for scope {required_scope!r}"
                )

    # 3. Resolved-scope check on the leaf, not lexical match on the string.
    leaf = creds[-1]
    if required_scope not in leaf.scope.split():
        raise DelegationAuthorizationError(
            f"leaf scope {leaf.scope!r} does not cover {required_scope!r}"
        )


def invoke_tool(chain, scope, status_cache):
    try:
        authorize_tool_call(chain, scope, time.time(), status_cache)
    except DelegationAuthorizationError:
        raise
    except Exception as exc:
        # Any unexpected failure in the auth path must not fall through
        # to execution.
        raise DelegationAuthorizationError(
            f"authorization resolution failed closed: {exc}"
        ) from exc
    return _execute_tool(scope)


def _execute_tool(scope: str):
    return {"executed": True, "scope": scope}
