# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-verify-a-cross-org-agent-did-whose-workload-attestation-quote-was-minted-under-a-trust-anchor-that-rotated-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-verify-a-cross-org-agent-did-whose-workload-attestation-quote-was-minted-under-a-trust-anchor-that-rotated-mid-handoff.warrant.json
# Markdown SHA-256:   399b74212baf93779ad3652b2f27a7e62dc610000f9ae5cf00d423aa82525fcd
# Code AST SHA-256:   5003c03722c6c4ebdbaf752b32d8dec5ec6aec2f0e9ce9262476f49688ff8e57
# Verified Classes:   TrustAnchorStatus, TrustAnchor, AttestationQuote, AttestationTrustError
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from enum import Enum


class TrustAnchorStatus(Enum):
    ACTIVE = "active"
    RETIRED = "retired"
    REVOKED = "revoked"


@dataclass(frozen=True)
class TrustAnchor:
    anchor_id: str
    valid_from: float
    valid_until: float
    status: TrustAnchorStatus
    revoked_at: float | None = None
    revoked_retroactively: bool = False


@dataclass(frozen=True)
class AttestationQuote:
    quote_id: str
    anchor_id: str
    minted_at: float          # MUST come from signed TEE/TPM evidence, not sender-set
    minted_at_signed: bool    # whether minted_at is inside the signed payload


class AttestationTrustError(RuntimeError):
    """Raised when a cross-org quote cannot be validated under the anchor-continuity invariant."""


def verify_quote_under_anchor(
    quote: AttestationQuote,
    anchors: dict[str, TrustAnchor],
    now: float,
) -> None:
    if not quote.minted_at_signed:
        # Cannot establish mint time from signed evidence; the interval rule is unenforceable.
        raise AttestationTrustError(
            f"quote {quote.quote_id}: minted_at is not covered by signed evidence; "
            "cannot bind to an anchor validity interval"
        )

    anchor = anchors.get(quote.anchor_id)
    if anchor is None:
        raise AttestationTrustError(
            f"quote {quote.quote_id}: anchor {quote.anchor_id} unknown to receiver trust store"
        )

    # Retroactive revocation overrides everything, including historical quotes.
    if anchor.status is TrustAnchorStatus.REVOKED and anchor.revoked_retroactively:
        raise AttestationTrustError(
            f"quote {quote.quote_id}: anchor {anchor.anchor_id} was revoked retroactively "
            f"at {anchor.revoked_at}; all quotes under it are invalid"
        )

    # Forward revocation: quotes minted after revocation are invalid; earlier ones stand.
    if anchor.status is TrustAnchorStatus.REVOKED and anchor.revoked_at is not None:
        if quote.minted_at >= anchor.revoked_at:
            raise AttestationTrustError(
                f"quote {quote.quote_id}: minted_at {quote.minted_at} >= anchor revocation "
                f"{anchor.revoked_at}; quote is post-revocation"
            )

    # Interval check: the anchor must have been valid at mint time.
    if not (anchor.valid_from <= quote.minted_at <= anchor.valid_until):
        raise AttestationTrustError(
            f"quote {quote.quote_id}: minted_at {quote.minted_at} outside anchor "
            f"{anchor.anchor_id} validity [{anchor.valid_from}, {anchor.valid_until}]"
        )

    # Retirement is NOT a rejection signal: retired anchors still validate pre-retirement quotes.
    # Only the interval + revocation checks above govern acceptance.
    if anchor.status is TrustAnchorStatus.RETIRED and quote.minted_at > anchor.valid_until:
        raise AttestationTrustError(
            f"quote {quote.quote_id}: retired anchor {anchor.anchor_id} cannot validate "
            f"quote minted after valid_until"
        )


def handle_handoff(sender_quote: AttestationQuote, receiver_anchors: dict[str, TrustAnchor]) -> str:
    try:
        verify_quote_under_anchor(sender_quote, receiver_anchors, now=time.time())
    except AttestationTrustError as exc:
        # Rotation-skew vs. compromise is distinguished here for the runbook.
        raise AttestationTrustError(f"handoff rejected: {exc}") from exc
    return "accepted"
