# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-reject-a-hardware-rooted-attestation-whose-endorsement-chain-crosses-a-trust-anchor-epoch-boundary-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-reject-a-hardware-rooted-attestation-whose-endorsement-chain-crosses-a-trust-anchor-epoch-boundary-mid-handoff.warrant.json
# Markdown SHA-256:   6443ee7cc8d11e641e5f1fa602a1883ab4bd7881e8b741ff3a9ea9af9428c1ed
# Code AST SHA-256:   4544240bb7f8b9b3cc3ba46a1a00454be3e7bf304d4f8627ae54f1aa7353e339
# Verified Classes:   AnchorEpochMismatch, AnchorStatus, AnchorRecord, Attestation, TrustStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class AnchorEpochMismatch(RuntimeError):
    """Raised when an attestation chain is cryptographically valid but terminates
    at a trust anchor that is not active at evaluation time."""
    pass


class AnchorStatus(Enum):
    ACTIVE = "active"
    RETIRED = "retired"
    SUSPENDED = "suspended"
    REVOKED = "revoked"
    UNKNOWN = "unknown"


@dataclass
class AnchorRecord:
    fingerprint: str
    status: AnchorStatus
    status_changed_at: float
    superseded_by: Optional[str] = None


@dataclass
class Attestation:
    instance_id: str
    chain: list  # ordered leaf -> root; each element has .fingerprint and .valid_at(t)
    terminal_anchor_fp: str
    quote_nonce: str
    quote_issued_at: float


class TrustStore:
    def __init__(self, staleness_bound_s: float = 5.0):
        self._anchors: dict[str, list[AnchorRecord]] = {}
        self._staleness_bound_s = staleness_bound_s
        self._last_refresh = 0.0

    def add(self, rec: AnchorRecord) -> None:
        self._anchors.setdefault(rec.fingerprint, []).append(rec)

    def resolve(self, fingerprint: str, as_of: float) -> AnchorRecord:
        # Reject if the store has not been refreshed recently enough to trust
        # a status resolution at as_of.
        if as_of - self._last_refresh > self._staleness_bound_s:
            raise AnchorEpochMismatch(
                f"trust store stale: last refresh {self._last_refresh:.1f}, "
                f"evaluation at {as_of:.1f}, bound {self._staleness_bound_s}s"
            )
        history = self._anchors.get(fingerprint)
        if not history:
            return AnchorRecord(fingerprint, AnchorStatus.UNKNOWN, as_of)
        # Most recent status transition at or before as_of.
        applicable = [r for r in history if r.status_changed_at <= as_of]
        if not applicable:
            return AnchorRecord(fingerprint, AnchorStatus.UNKNOWN, as_of)
        return max(applicable, key=lambda r: r.status_changed_at)

    def refresh(self, now: float) -> None:
        self._last_refresh = now


def verify_attestation(
    att: Attestation,
    store: TrustStore,
    now: float,
    freshness_window_s: float = 30.0,
) -> None:
    # 1. Cryptographic validity at T.
    for link in att.chain:
        if not link.valid_at(now):
            raise AnchorEpochMismatch(
                f"chain link {link.fingerprint} invalid at {now:.1f}"
            )
    if now - att.quote_issued_at > freshness_window_s:
        raise AnchorEpochMismatch(
            f"quote stale: issued {att.quote_issued_at:.1f}, evaluated {now:.1f}"
        )

    # 2. Anchor currency at T — the gate the observed system lacked.
    anchor = store.resolve(att.terminal_anchor_fp, as_of=now)
    if anchor.status is not AnchorStatus.ACTIVE:
        raise AnchorEpochMismatch(
            f"terminal anchor {att.terminal_anchor_fp} is {anchor.status.value} "
            f"at {now:.1f} (changed at {anchor.status_changed_at:.1f}); "
            f"superseded_by={anchor.superseded_by}"
        )


def admit_handoff(
    att: Attestation,
    store: TrustStore,
    now: float,
    checkpoint_produced_at: float,
) -> None:
    # Re-evaluate at the state-transfer boundary, not at session open.
    verify_attestation(att, store, now=now)

    # 3. Epoch consistency: if the anchor was retired after the checkpoint was
    # produced, the checkpoint predates retirement and may be admissible only
    # via successor re-attestation; otherwise the checkpoint was produced under
    # a retired anchor and must not be imported.
    anchor = store.resolve(att.terminal_anchor_fp, as_of=now)
    if anchor.status_changed_at < checkpoint_produced_at:
        raise AnchorEpochMismatch(
            f"checkpoint produced at {checkpoint_produced_at:.1f} under anchor "
            f"{att.terminal_anchor_fp} which was retired at "
            f"{anchor.status_changed_at:.1f}; re-attestation required"
        )
