# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-verifiable-presentation-whose-revocation-status-is-fresh-enough-but-whose-issuer-key-rotated-mid-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-verifiable-presentation-whose-revocation-status-is-fresh-enough-but-whose-issuer-key-rotated-mid-chain.warrant.json
# Markdown SHA-256:   11e6e4cdd158e478c762469fdbfb418a7b3f221b8b4b50f5d8e93b5f1ef095d6
# Code AST SHA-256:   2aa478446a8b725f434530928cd0aa3c939f0e825de7762e6aeeac92287578b9
# Verified Classes:   AttestationTemporalError, KeyAuthority, StatusSnapshot, Credential
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from datetime import datetime


class AttestationTemporalError(RuntimeError):
    """Raised when a VP's delegation chain violates temporal containment
    against issuer key-authority intervals or status-snapshot ordering."""


@dataclass(frozen=True)
class KeyAuthority:
    key_id: str
    not_before: datetime
    retired_at: datetime  # exclusive upper bound of signing authority


@dataclass(frozen=True)
class StatusSnapshot:
    valid_from: datetime
    valid_until: datetime
    revoked_bits: frozenset  # subject ids with bit set


@dataclass(frozen=True)
class Credential:
    issuer_key_id: str
    subject_id: str
    signed_at: datetime  # MUST come from inside the signed envelope


def verify_chain(
    chain: list[Credential],
    keys: dict[str, KeyAuthority],
    snapshots: list[StatusSnapshot],
    now: datetime,
) -> None:
    for cred in chain:
        key = keys.get(cred.issuer_key_id)
        if key is None:
            raise AttestationTemporalError(
                f"unknown issuer key {cred.issuer_key_id}"
            )

        # Clause 1: key-authority interval must contain the signing instant.
        if not (key.not_before <= cred.signed_at < key.retired_at):
            raise AttestationTemporalError(
                f"credential {cred.subject_id} signed at {cred.signed_at} "
                f"outside authority interval "
                f"[{key.not_before}, {key.retired_at}) for key {key.key_id}"
            )

        # Clause 2: a snapshot must be valid at signing AND at verification.
        probative = [
            s for s in snapshots
            if s.valid_from <= cred.signed_at and s.valid_until >= now
        ]
        if not probative:
            raise AttestationTemporalError(
                f"no status snapshot is probative for credential "
                f"{cred.subject_id} signed at {cred.signed_at}: "
                f"snapshots valid at signing predate verification or vice versa"
            )

        # Use the most recent probative snapshot (latest valid_from).
        snap = max(probative, key=lambda s: s.valid_from)
        if cred.subject_id in snap.revoked_bits:
            raise AttestationTemporalError(
                f"credential {cred.subject_id} revoked in snapshot "
                f"valid_from={snap.valid_from}"
            )


def accept_presentation(
    chain: list[Credential],
    keys: dict[str, KeyAuthority],
    snapshots: list[StatusSnapshot],
    now: datetime,
) -> bool:
    try:
        verify_chain(chain, keys, snapshots, now)
    except AttestationTemporalError:
        # Distinguish false-accept risk from generic failure upstream.
        raise
    return True
