# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-delegated-aaif-credential-whose-delegation-depth-is-valid-but-whose-scope-intersection-silently-collapsed-to-the-empty.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-delegated-aaif-credential-whose-delegation-depth-is-valid-but-whose-scope-intersection-silently-collapsed-to-the-empty.warrant.json
# Markdown SHA-256:   97fe6a4ba49621cc198951e103f15311a300b48d04f02ca74eaf8ca81b4675db
# Code AST SHA-256:   e31736dd44358528735d24618e517e8fb4ae21a8028a3ef8715c95fd082cbfe7
# Verified Classes:   DelegationScopeError, ScopeAtom, AAIFHop, AAIFChain
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet, List, Optional, Tuple


class DelegationScopeError(RuntimeError):
    """Raised when a delegated AAIF credential's scope cannot satisfy the holder's plan."""


@dataclass(frozen=True)
class ScopeAtom:
    resource: str
    action: str


@dataclass(frozen=True)
class AAIFHop:
    issuer: str
    subject: str
    scope: FrozenSet[ScopeAtom]
    delegation_depth: int
    max_delegation_depth: int
    not_after_epoch: int


@dataclass(frozen=True)
class AAIFChain:
    hops: List[AAIFHop]  # hops[0] is root-issued; hops[-1] is the presented credential

    @property
    def terminal(self) -> AAIFHop:
        return self.hops[-1]

    def ancestor_covering(self, need: FrozenSet[ScopeAtom]) -> Optional[AAIFHop]:
        """Highest ancestor whose scope contains the full need. Under monotone
        attenuation only such an ancestor can re-mint a satisfiable credential."""
        for hop in reversed(self.hops[:-1]):
            if need.issubset(hop.scope):
                return hop
        return None


def admit_credential(
    chain: AAIFChain,
    plan_requirements: FrozenSet[ScopeAtom],
    now_epoch: int,
) -> None:
    """Pre-flight admission. Raises DelegationScopeError on any boundary violation."""
    term = chain.terminal

    # Structural checks (these are what a naive verifier stops at).
    if term.delegation_depth > term.max_delegation_depth:
        raise DelegationScopeError(
            f"depth {term.delegation_depth} exceeds max {term.max_delegation_depth}"
        )
    if term.not_after_epoch <= now_epoch:
        raise DelegationScopeError("terminal credential expired")

    # THE BOUNDARY: empty intersection is not a weak credential, it is no credential.
    if not term.scope:
        repair = chain.ancestor_covering(plan_requirements)
        if repair is not None:
            raise DelegationScopeError(
                f"inert-but-repairable: scope collapsed to empty at depth "
                f"{term.delegation_depth}; escalate to {repair.issuer} with original need"
            )
        raise DelegationScopeError(
            f"inert-and-unrepairable: empty scope at depth {term.delegation_depth} "
            f"and no ancestor covers {sorted((a.resource, a.action) for a in plan_requirements)}"
        )

    # Plan-coverage containment, not mere presence.
    missing = plan_requirements - term.scope
    if missing:
        repair = chain.ancestor_covering(plan_requirements)
        detail = (
            f"escalate to {repair.issuer}" if repair else "no ancestor can repair; re-plan"
        )
        raise DelegationScopeError(
            f"plan requires {sorted((a.resource, a.action) for a in missing)} "
            f"absent from terminal scope; {detail}"
        )
    # Admitted: scope non-empty and covers the plan.
