# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-aaif-delegation-chain-as-structurally-valid-but-semantically-expired-before-executing-a-delegated-tool.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-aaif-delegation-chain-as-structurally-valid-but-semantically-expired-before-executing-a-delegated-tool.warrant.json
# Markdown SHA-256:   6911ce37122a68be1ae11715c938287ffef82ebb984e42b7e9c08f2e9be18981
# Code AST SHA-256:   1002caf2362c8aee62e7c5083e99b524c3d757d3836b69e0172603be768082ad
# Verified Classes:   DelegationSemanticallyExpired, CachedVerification, Warrant, DelegationGate
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class DelegationSemanticallyExpired(RuntimeError):
    """Raised when a structurally valid AAIF chain is no longer valid at use."""

    def __init__(self, warrant_id: str, hop: str, reason: str, detail: str):
        self.warrant_id = warrant_id
        self.hop = hop
        self.reason = reason
        self.detail = detail
        super().__init__(
            f"warrant {warrant_id} hop {hop} semantically expired: {reason} ({detail})"
        )


@dataclass
class CachedVerification:
    warrant_digest: str
    epoch_at_verify: int
    verified_at: float


@dataclass
class Warrant:
    warrant_id: str
    not_after: float
    issued_epoch: int
    scope: str
    max_subordinates: int
    subordinates_used: int = 0


class DelegationGate:
    """Enforces: structural validity is cached; semantic expiry is per-invocation."""

    EPSILON = 0.5  # seconds; below this, cached epoch is trusted

    def __init__(self, epoch_provider):
        # epoch_provider() -> current revocation epoch of the root issuer
        self._epoch = epoch_provider
        self._cache: dict[str, CachedVerification] = {}

    def record_structural_verification(self, warrant: Warrant, digest: str) -> None:
        # Called once after verify_chain() returns True. This is the ONLY
        # place structural validity is established; it is not re-derived here.
        self._cache[warrant.warrant_id] = CachedVerification(
            warrant_digest=digest,
            epoch_at_verify=self._epoch(),
            verified_at=time.monotonic(),
        )

    def authorize_use(self, warrant: Warrant, intended_scope: str) -> None:
        """Must be called immediately before every gated tool invocation."""
        cached = self._cache.get(warrant.warrant_id)
        if cached is None:
            raise DelegationSemanticallyExpired(
                warrant.warrant_id, "leaf", "unverified",
                "no structural verification on record for this warrant",
            )

        # 1. Action must be a strict subset of the delegated scope.
        if not _scope_covers(warrant.scope, intended_scope):
            raise DelegationSemanticallyExpired(
                warrant.warrant_id, "leaf", "scope_drift",
                f"intended {intended_scope!r} not covered by {warrant.scope!r}",
            )

        # 2. Leaf TTL must not have elapsed at use time.
        if time.time() >= warrant.not_after:
            raise DelegationSemanticallyExpired(
                warrant.warrant_id, "leaf", "ttl_elapsed",
                f"not_after={warrant.not_after} now={time.time():.3f}",
            )

        # 3. Epoch must be current; re-query if the cached window is stale.
        if time.monotonic() - cached.verified_at > self.EPSILON:
            current_epoch = self._epoch()
            if current_epoch != cached.epoch_at_verify:
                raise DelegationSemanticallyExpired(
                    warrant.warrant_id, "root", "epoch_stale",
                    f"verified at epoch {cached.epoch_at_verify}, "
                    f"issuer now at {current_epoch}",
                )

        # 4. Intent envelope: subordinate budget.
        if warrant.subordinates_used >= warrant.max_subordinates:
            raise DelegationSemanticallyExpired(
                warrant.warrant_id, "leaf", "subordinate_budget_exhausted",
                f"used {warrant.subordinates_used}/{warrant.max_subordinates}",
            )

    def record_use(self, warrant: Warrant) -> None:
        warrant.subordinates_used += 1


def _scope_covers(granted: str, intended: str) -> bool:
    # Simplified subset check: granted "search:read" covers "search:read";
    # does not cover "search:read+write". Real impl parses verb sets.
    return set(intended.split(":")) <= set(granted.split(":"))


def execute_gated_tool(gate: DelegationGate, warrant: Warrant, intended_scope: str,
                       tool_fn, *args, **kwargs):
    # Semantic check happens here, at the moment of use -- never earlier.
    gate.authorize_use(warrant, intended_scope)
    result = tool_fn(*args, **kwargs)
    gate.record_use(warrant)
    return result
