# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-delegated-aaif-credential-rather-than-accept-it-under-scope-narrowing.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-delegated-aaif-credential-rather-than-accept-it-under-scope-narrowing.warrant.json
# Markdown SHA-256:   eb0ee844c756ae2f62e04f1c59da4492239d169f093dca9e8782ea603cdffa84
# Code AST SHA-256:   e90b8a85d1888fc6d69547ab4bf9a18850ad9e1ac356d65b4d2826cc65a518f5
# Verified Classes:   StaleDelegationEpochError, RevocationScopeOverlapError, Grant, RevocationRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class StaleDelegationEpochError(RuntimeError):
    """Raised when a delegated grant's epoch is older than an ancestor's revocation epoch."""


class RevocationScopeOverlapError(RuntimeError):
    """Raised when a grant's scope intersects a revoked scope of a stale ancestor."""


@dataclass(frozen=True)
class Grant:
    agent_id: str
    scope: FrozenSet[str]
    epoch: int
    parent_id: str | None


@dataclass(frozen=True)
class RevocationRecord:
    agent_id: str
    revoked_scopes: FrozenSet[str]
    epoch: int


def accept_delegation(
    grant: Grant,
    ancestors: list[Grant],
    revocations: list[RevocationRecord],
) -> bool:
    """Validate a delegated AAIF grant against the full ancestor chain.

    Returns True if the grant may be accepted (and optionally narrowed).
    Raises on the two non-obvious boundary failures.
    """
    # Condition 1: subset check against immediate parent.
    if ancestors:
        parent = ancestors[-1]
        if not grant.scope.issubset(parent.scope):
            raise PermissionError(
                f"scope {grant.scope} not subset of parent {parent.scope}"
            )

    # Condition 2: epoch floor across the entire ancestor path.
    max_ancestor_epoch = max((a.epoch for a in ancestors), default=0)
    for rev in revocations:
        if rev.epoch > grant.epoch:
            # The ancestor was revoked after this grant was minted.
            if grant.epoch < max_ancestor_epoch or rev.agent_id in {
                a.agent_id for a in ancestors
            }:
                if grant.scope & rev.revoked_scopes:
                    raise RevocationScopeOverlapError(
                        f"grant {grant.agent_id} scope {grant.scope} overlaps "
                        f"revoked scopes {rev.revoked_scopes} of {rev.agent_id} "
                        f"at epoch {rev.epoch} (grant epoch {grant.epoch})"
                    )
                raise StaleDelegationEpochError(
                    f"grant {grant.agent_id} epoch {grant.epoch} is stale "
                    f"relative to revocation of {rev.agent_id} at epoch {rev.epoch}"
                )

    # Condition 3: epoch regression check along the path.
    prev = None
    for a in ancestors:
        if prev is not None and a.epoch < prev.epoch:
            raise StaleDelegationEpochError(
                f"epoch regression in chain: {a.agent_id} epoch {a.epoch} "
                f"< {prev.agent_id} epoch {prev.epoch}"
            )
        prev = a

    return True
