# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-reject-a-delegated-credential-it-can-cryptographically-verify-the-audience-narrowing-invariant-in-aaif-delegated-credential-excha.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-reject-a-delegated-credential-it-can-cryptographically-verify-the-audience-narrowing-invariant-in-aaif-delegated-credential-excha.warrant.json
# Markdown SHA-256:   dd5eb68daac0ed48b8130646458f9867233fb9ded168e9546464ea1977b6f93a
# Code AST SHA-256:   f602ac61754a357dc2e3400f830a5cdbeafce7fbf86e8eef9c0d2d3147c2199b
# Verified Classes:   DelegationChainError, DelegatedToken
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class DelegationChainError(RuntimeError):
    """Raised when a delegated credential violates the AAIF chain invariant."""
    pass


@dataclass
class DelegatedToken:
    audience: str
    scope: frozenset
    chain: list
    narrowing_proof: str


def _proof(parent: DelegatedToken, child: DelegatedToken) -> str:
    material = f"{parent.audience}|{child.audience}|{sorted(child.scope)}|{parent.narrowing_proof}"
    return hashlib.sha256(material.encode()).hexdigest()


def validate_delegation(presenter: str, token: DelegatedToken, parent: DelegatedToken) -> None:
    # Invariant 1: audience must equal the presenting instance.
    if token.audience != presenter:
        raise DelegationChainError(
            f"AUDIENCE_NOT_ME: token aud={token.audience!r} presented by {presenter!r}"
        )
    # Invariant 2: scope must be monotonically non-increasing.
    if not token.scope.issubset(parent.scope):
        raise DelegationChainError(
            f"SCOPE_WIDENED_AT_HOP: child scope {sorted(token.scope)} "
            f"not subset of parent {sorted(parent.scope)}"
        )
    # Invariant 3: narrowing proof must bind this specific (parent, child) pair.
    expected = _proof(parent, token)
    if token.narrowing_proof != expected:
        raise DelegationChainError(
            f"DELEGATION_PROOF_MISMATCH: expected {expected[:12]}… got {token.narrowing_proof[:12]}…"
        )


def re_delegate(parent: DelegatedToken, actor: str, next_audience: str, requested: frozenset) -> DelegatedToken:
    # Only the audience of the parent may re-delegate, and only by narrowing.
    if parent.audience != actor:
        raise DelegationChainError(
            f"NOT_AUDIENCE: {actor!r} cannot re-delegate token aud={parent.audience!r}"
        )
    narrowed = requested & parent.scope
    if not narrowed:
        raise DelegationChainError("EMPTY_SCOPE: delegation would grant nothing")
    child = DelegatedToken(
        audience=next_audience,
        scope=frozenset(narrowed),
        chain=parent.chain + [actor],
        narrowing_proof="",
    )
    child.narrowing_proof = _proof(parent, child)
    return child
