# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-delegated-aaif-credential-chain-whose-scope-narrowing-appears-valid-but-whose-attenuation-proof-was-mi.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-delegated-aaif-credential-chain-whose-scope-narrowing-appears-valid-but-whose-attenuation-proof-was-mi.warrant.json
# Markdown SHA-256:   ea22d54359afa3d52f3d08d500c49b949ea22a97a8717f0664e5fd6b2c31d447
# Code AST SHA-256:   1adca85edb2c9a46cd6428f2f9617554a0c3663e2a4ec124be6c83ed52ef3c01
# Verified Classes:   StaleSnapshotChainError, UnverifiableChainError, Snapshot, SnapshotPin, AttenuationProof, DelegatedChain
# Defensive Guards:   11 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field
from typing import Optional


class StaleSnapshotChainError(RuntimeError):
    """Raised when a delegated chain's attenuation proof is anchored to a
    superseded capability snapshot with no licensing pin covering it."""
    pass


class UnverifiableChainError(RuntimeError):
    """Raised when the verifier cannot establish snapshot currency because
    the authority is unreachable and no pin is present. Distinct from
    StaleSnapshotChainError: the chain may be valid, but is not provable."""
    pass


@dataclass
class Snapshot:
    snapshot_id: str
    epoch: int
    scopes: frozenset
    status: str  # "CURRENT" | "SUPERSEDED" | "REVOKED"
    content_hash: str


@dataclass
class SnapshotPin:
    snapshot_id: str
    issued_by: str
    not_after: float
    signature_valid: bool


@dataclass
class AttenuationProof:
    parent_scopes: frozenset
    child_scopes: frozenset
    snapshot_id: str
    snapshot_content_hash: str
    signature_valid: bool


@dataclass
class DelegatedChain:
    proofs: list  # list[AttenuationProof], root-first
    pins: list = field(default_factory=list)  # list[SnapshotPin]


def verify_chain(
    chain: DelegatedChain,
    authority_snapshots: dict,  # snapshot_id -> Snapshot
    authority_reachable: bool,
    now: Optional[float] = None,
) -> bool:
    now = now if now is not None else time.time()

    # Condition 1: local subset + content-hash soundness at every hop.
    for p in chain.proofs:
        if not p.signature_valid:
            raise StaleSnapshotChainError("attenuation proof signature invalid")
        if not p.child_scopes.issubset(p.parent_scopes):
            raise StaleSnapshotChainError(
                f"scope escalation: {p.child_scopes} not subset of {p.parent_scopes}"
            )
        snap = authority_snapshots.get(p.snapshot_id)
        if snap is None and authority_reachable:
            raise UnverifiableChainError(
                f"referenced snapshot {p.snapshot_id} unknown to authority"
            )
        if snap is not None and snap.content_hash != p.snapshot_content_hash:
            raise StaleSnapshotChainError(
                f"content hash mismatch for {p.snapshot_id}"
            )

    deepest = chain.proofs[-1]
    snap = authority_snapshots.get(deepest.snapshot_id)

    # Condition 2a: licensed staleness via pin.
    pin = next(
        (q for q in chain.pins if q.snapshot_id == deepest.snapshot_id),
        None,
    )
    if pin is not None:
        if not pin.signature_valid:
            raise StaleSnapshotChainError("snapshot pin signature invalid")
        if now > pin.not_after:
            raise StaleSnapshotChainError(
                f"snapshot pin for {deepest.snapshot_id} expired at {pin.not_after}"
            )
        # Pin licenses use; accept.
        return True

    # Condition 2b: no pin -> require authority reachability + currency.
    if not authority_reachable or snap is None:
        raise UnverifiableChainError(
            f"no pin and authority unreachable; cannot establish currency of "
            f"{deepest.snapshot_id}"
        )
    if snap.status == "SUPERSEDED":
        raise StaleSnapshotChainError(
            f"attenuation anchored to superseded snapshot {deepest.snapshot_id}"
        )
    if snap.status == "REVOKED":
        raise StaleSnapshotChainError(
            f"attenuation anchored to revoked snapshot {deepest.snapshot_id}"
        )

    # Condition 3: cross-snapshot attenuation must be epoch-ordered.
    prev_epoch = None
    for p in chain.proofs:
        s = authority_snapshots.get(p.snapshot_id)
        if s is None:
            raise UnverifiableChainError(
                f"cannot order snapshot {p.snapshot_id}: unknown to authority"
            )
        if prev_epoch is not None and s.epoch < prev_epoch:
            raise StaleSnapshotChainError(
                f"non-monotone snapshot epoch: {s.epoch} < {prev_epoch}"
            )
        prev_epoch = s.epoch

    return True
