# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-countersigned-intent-attestation-was-minted-against-a-superseded-manifest-version.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-countersigned-intent-attestation-was-minted-against-a-superseded-manifest-version.warrant.json
# Markdown SHA-256:   720d2209be5b61c7070073bb34961c72da45c52c3b9edaefd3c258f4f028897b
# Code AST SHA-256:   734ca2674e5e193e7558e9ec78c566ef244d00a079370d8019a72dbc2363dadd
# Verified Classes:   SupersededManifestError, ManifestRef, Via, SupersessionWaiver
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from datetime import datetime, timezone


class SupersededManifestError(RuntimeError):
    """Raised when a VIA references a manifest version that is no longer
    authoritative at verification time and no supersession waiver covers it.
    The signature chain may be fully valid; the authorization predicate is void."""


@dataclass(frozen=True)
class ManifestRef:
    org: str
    version: int
    digest: str


@dataclass(frozen=True)
class Via:
    intent: dict
    manifest_ref: ManifestRef
    issuer_sig_ok: bool
    countersig_ok: bool
    minted_at: datetime


@dataclass(frozen=True)
class SupersessionWaiver:
    issuer_org: str
    covers_versions: frozenset[int]
    covers_mint_range: tuple[datetime, datetime]
    countersigned: bool


def verify_via(
    via: Via,
    current_manifest_version: int,
    current_manifest_digest: str,
    waivers: list[SupersessionWaiver],
    now: datetime | None = None,
) -> dict:
    now = now or datetime.now(timezone.utc)

    # 1. Cryptographic chain must be sound before anything else.
    if not (via.issuer_sig_ok and via.countersig_ok):
        raise SupersededManifestError("signature chain invalid; cannot evaluate currency")

    # 2. Digest must match the referenced version's document (else it's a forgery,
    #    a different failure — surface as supersession-adjacent for logging).
    expected = via.manifest_ref  # digest already validated upstream against cached doc

    # 3. Currency check: is the referenced version still authoritative?
    if via.manifest_ref.version == current_manifest_version:
        return {"decision": "accept", "annotation": None}

    # 4. Superseded. Look for a countersigned waiver covering this mint time
    #    and version. Waiver must be countersigned — an uncountersigned waiver is
    #    issuer-unilateral and does not bind the verifier's trust decision.
    for w in waivers:
        if (
            w.issuer_org == via.manifest_ref.org
            and w.countersigned
            and via.manifest_ref.version in w.covers_versions
            and w.covers_mint_range[0] <= via.minted_at < w.covers_mint_range[1]
        ):
            return {"decision": "accept", "annotation": "stale_manifest_waived"}

    # 5. No waiver. Reject even if the action would pass under the *current*
    #    (narrower) manifest — the VIA does not assert authorization under it.
    raise SupersededManifestError(
        f"VIA for {via.manifest_ref.org} references manifest v{via.manifest_ref.version}, "
        f"current is v{current_manifest_version}; minted_at={via.minted_at.isoformat()}; "
        f"no countersigned supersession waiver covers this mint window. "
        f"Bounce to issuer for re-attestation against current version."
    )


def handle_handoff(via: Via, current_version: int, current_digest: str, waivers: list) -> dict:
    try:
        return verify_via(via, current_version, current_digest, waivers)
    except SupersededManifestError as e:
        # Fail closed: do not execute, do not cache-accept, request re-attestation.
        return {"decision": "bounce_for_reattestation", "reason": str(e)}
