# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-delegated-aaif-warrants-from-outliving-their-issuer-s-attestation-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-delegated-aaif-warrants-from-outliving-their-issuer-s-attestation-epoch.warrant.json
# Markdown SHA-256:   cb0d6dd8daac0aaaf2b128977824db4c781c000c6edbb830c34bff2e5035b6f2
# Code AST SHA-256:   92fc54ab00456640324344f19ba6312a6fff5df8c6f95e2bed6e5a3780d8feea
# Verified Classes:   EpochLineageError, AttestationEpoch, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class EpochLineageError(RuntimeError):
    """Raised when a warrant's recorded epoch is not an ancestor of the current root epoch,
    or when a supersession tombstone on that path removes a scope the warrant relies on."""


@dataclass(frozen=True)
class AttestationEpoch:
    ordinal: int
    parent_hash: Optional[str]
    scope: frozenset[str]
    superseded_at: Optional[float] = None  # None => still current


@dataclass(frozen=True)
class Warrant:
    issuer_epoch: int
    issuer_epoch_hash: str
    scope: frozenset[str]
    delegation_depth: int
    not_after: float


def _hash(epoch: AttestationEpoch) -> str:
    return hashlib.sha256(
        f"{epoch.ordinal}|{epoch.parent_hash}|{sorted(epoch.scope)}".encode()
    ).hexdigest()


def verify_warrant(
    warrant: Warrant,
    epoch_chain: dict[int, AttestationEpoch],
    current_root_ordinal: int,
    now: float,
    tombstone_retention_horizon: float,
) -> bool:
    if now > warrant.not_after:
        raise EpochLineageError(f"warrant expired at {warrant.not_after}, now={now}")

    # 1. Descendant-closure: walk the Merkle chain from recorded epoch up to root.
    cursor = warrant.issuer_epoch
    seen_scope = set(warrant.scope)
    path_hashes = []
    while cursor != current_root_ordinal:
        epoch = epoch_chain.get(cursor)
        if epoch is None:
            raise EpochLineageError(f"epoch {cursor} missing from chain (GC'd?)")
        path_hashes.append(_hash(epoch))
        # 2. Tombstone check: a supersession on the path must not remove scope.
        if epoch.superseded_at is not None:
            removed = seen_scope - set(epoch.scope)
            if removed:
                raise EpochLineageError(
                    f"epoch {cursor} superseded at {epoch.superseded_at} "
                    f"removes scopes {sorted(removed)} required by warrant"
                )
            seen_scope &= set(epoch.scope)
        nxt = epoch_chain.get(cursor + 1)
        if nxt is None or nxt.parent_hash != path_hashes[-1]:
            raise EpochLineageError(
                f"lineage break: epoch {cursor} does not hash-link to {cursor + 1}"
            )
        cursor += 1

    # 3. Retention horizon guard: refuse to honor a warrant whose lifetime could
    #    outlast the tombstone record it depends on.
    if warrant.not_after > now + tombstone_retention_horizon:
        raise EpochLineageError(
            f"warrant not_after={warrant.not_after} exceeds tombstone retention horizon"
        )

    # 4. Final scope intersection against current root scope.
    root_scope = set(epoch_chain[current_root_ordinal].scope)
    if not seen_scope <= root_scope:
        raise EpochLineageError(
            f"scope intersection empty: {sorted(seen_scope - root_scope)} not in root"
        )
    return True
