# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-capability-grant-that-is-transitively-valid-but-locally-unverifiable.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-capability-grant-that-is-transitively-valid-but-locally-unverifiable.warrant.json
# Markdown SHA-256:   88b13bfd7986f0671e09bfeea5caad6fdaf2784b0a0a9bc74d39aed1f2d29e52
# Code AST SHA-256:   b2b797213b40b8423b31c4fc53110ca69d903a27640f5c7eda3dc6546f0d53e7
# Verified Classes:   FederationAuthorityError, Verdict, Hop, Grant
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Optional


class FederationAuthorityError(RuntimeError):
    """Raised when a delegated grant cannot be authorized, only authenticated."""


class Verdict(Enum):
    EXECUTE = "execute"
    REFUSE = "refuse"
    DEFER = "defer"


@dataclass
class Hop:
    issuer: str
    scope_set: frozenset
    parent_scope_hash: Optional[str]  # committed subset proof, None if format is flat


@dataclass
class Grant:
    chain: list  # list[Hop], root first
    ttl_seconds: int


def evaluate_grant(
    grant: Grant,
    anchor_resolver,          # issuer -> bool, raises TimeoutError
    policy_resolver,          # (issuer, scope) -> bool, raises TimeoutError
    resolver_budget_ms: int,
) -> Verdict:
    # 1. Anchor resolution for every issuer. Unresolvable -> REFUSE, not EXECUTE.
    for hop in grant.chain:
        try:
            if not anchor_resolver(hop.issuer):
                return Verdict.REFUSE
        except TimeoutError:
            # Authority unknown. Must NOT fall through to signature-only execution.
            return Verdict.DEFER

    # 2. Scope must be a committed subset of the parent hop, not merely equal.
    for i in range(1, len(grant.chain)):
        child, parent = grant.chain[i], grant.chain[i - 1]
        if child.parent_scope_hash is None:
            # Flat format: offline subset proof impossible; must consult owner.
            try:
                if not policy_resolver(parent.issuer, child.scope_set):
                    return Verdict.REFUSE
            except TimeoutError:
                return Verdict.DEFER
        elif not child.scope_set.issubset(parent.scope_set):
            # Lateral or widening change without committed proof.
            return Verdict.REFUSE

    # 3. Resource-owner policy confirmation for the terminal scope.
    try:
        if not policy_resolver(grant.chain[-1].issuer, grant.chain[-1].scope_set):
            return Verdict.REFUSE
    except TimeoutError:
        return Verdict.DEFER

    return Verdict.EXECUTE


def execute_federated_export(grant: Grant, anchor_resolver, policy_resolver, budget_ms):
    verdict = evaluate_grant(grant, anchor_resolver, policy_resolver, budget_ms)
    if verdict is Verdict.DEFER:
        raise FederationAuthorityError(
            "grant authority unresolvable within budget; parked for re-attestation, "
            "not executed on signature-only path"
        )
    if verdict is Verdict.REFUSE:
        raise FederationAuthorityError(
            f"grant refused: chain {[h.issuer for h in grant.chain]} failed "
            "anchor or scope-subset authorization"
        )
    return "export_executed"
