# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-validate-a-peer-agent-s-did-document-when-the-federation-trust-anchor-rotates-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-validate-a-peer-agent-s-did-document-when-the-federation-trust-anchor-rotates-mid-handoff.warrant.json
# Markdown SHA-256:   43ce4290bb8a062fb9bb2890f37ad97596c5036e031ea45e23a11e0a3b10fd30
# Code AST SHA-256:   01d9150fe79c8d394350577dcf23150f2b10d2bb7de195e9569c2e1a51561861
# Verified Classes:   FederationTrustError, VerificationMethod, DIDDocumentVersion, Warrant, AnchorLedger
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class FederationTrustError(RuntimeError):
    """Raised when a peer warrant cannot be validated under the active trust anchor epoch."""
    pass


@dataclass(frozen=True)
class VerificationMethod:
    did_fragment: str          # e.g. "#key-2"
    deactivated_at: Optional[float]  # unix ts, None if still active


@dataclass(frozen=True)
class DIDDocumentVersion:
    did: str
    anchor_epoch: int          # federation root epoch that signed this version
    methods: dict              # fragment -> VerificationMethod


@dataclass(frozen=True)
class Warrant:
    issuer: str                # did of signing agent
    signing_fragment: str      # e.g. "#key-2"
    issued_at: float           # claimed t_i, unix ts
    claimed_epoch: int         # anchor epoch the issuer believes was active at t_i


@dataclass(frozen=True)
class AnchorLedger:
    active_epoch: int
    epoch_start_ts: dict       # epoch -> unix ts at which it became active


def validate_warrant(
    warrant: Warrant,
    resolver,
    ledger: AnchorLedger,
    clock_skew_tolerance: float = 30.0,
) -> bool:
    """
    Dual-epoch verification. Resolves the DID document at the warrant's
    claimed epoch, not at wall-clock now. Refuses if the epoch is unknown
    or if the signing key was deactivated before issuance.
    """
    # 1. The claimed epoch must exist in the monotonic anchor ledger.
    if warrant.claimed_epoch not in ledger.epoch_start_ts:
        raise FederationTrustError(
            f"warrant claims anchor epoch {warrant.claimed_epoch}, "
            f"not present in ledger (active={ledger.active_epoch})"
        )

    # 2. Issuance must fall within the claimed epoch's window.
    epoch_start = ledger.epoch_start_ts[warrant.claimed_epoch]
    next_epoch_start = ledger.epoch_start_ts.get(
        warrant.claimed_epoch + 1, float("inf")
    )
    if not (epoch_start - clock_skew_tolerance
            <= warrant.issued_at
            < next_epoch_start + clock_skew_tolerance):
        raise FederationTrustError(
            f"warrant issued_at={warrant.issued_at} outside epoch "
            f"{warrant.claimed_epoch} window [{epoch_start}, {next_epoch_start})"
        )

    # 3. Resolve the DID document as of the claimed epoch.
    doc: Optional[DIDDocumentVersion] = resolver.resolve_at_epoch(
        warrant.issuer, warrant.claimed_epoch
    )
    if doc is None:
        raise FederationTrustError(
            f"no DID document for {warrant.issuer} at epoch {warrant.claimed_epoch}; "
            f"renegotiate handoff with fresh attestation"
        )

    # 4. The document must be signed by the anchor of the claimed epoch.
    if doc.anchor_epoch != warrant.claimed_epoch:
        raise FederationTrustError(
            f"DID document for {warrant.issuer} is signed by epoch "
            f"{doc.anchor_epoch}, warrant claims {warrant.claimed_epoch}"
        )

    # 5. The signing verification method must exist in that version.
    vm = doc.methods.get(warrant.signing_fragment)
    if vm is None:
        raise FederationTrustError(
            f"verification method {warrant.signing_fragment} absent from "
            f"{warrant.issuer} document at epoch {warrant.claimed_epoch}"
        )

    # 6. Replay guard: key must not have been deactivated before issuance.
    if vm.deactivated_at is not None and vm.deactivated_at <= warrant.issued_at:
        raise FederationTrustError(
            f"replay: {warrant.issuer}{warrant.signing_fragment} deactivated at "
            f"{vm.deactivated_at} but warrant claims issuance at {warrant.issued_at}"
        )

    return True
