# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-did-key-rotation-from-silently-invalidating-federated-agent-warrants-mid-swarm.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-did-key-rotation-from-silently-invalidating-federated-agent-warrants-mid-swarm.warrant.json
# Markdown SHA-256:   22eab1388f82605a56c52bd32be9fd3e326c5d942482960d2ef40a095bd6de4b
# Code AST SHA-256:   108f7270fe145f0b59e180386c69f027163c9ecdd4ddef8c44bbe222a825c502
# Verified Classes:   WarrantVerificationError, DidKeyEntry, DidLog, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from datetime import datetime, timezone


class WarrantVerificationError(RuntimeError):
    """Raised when a federated warrant cannot be verified under the continuity invariant."""


@dataclass(frozen=True)
class DidKeyEntry:
    key_id: str
    active_from: datetime
    active_until: datetime | None  # None = still active


@dataclass(frozen=True)
class DidLog:
    """Append-only key history. did:web without versioning cannot supply this."""
    did: str
    entries: tuple[DidKeyEntry, ...]

    def key_valid_at(self, key_id: str, when: datetime) -> bool:
        for e in self.entries:
            if e.key_id != key_id:
                continue
            if e.active_from <= when and (e.active_until is None or when < e.active_until):
                return True
        return False


@dataclass(frozen=True)
class Warrant:
    issuer_did: str
    signing_key_id: str
    proof_created: datetime
    signature: bytes


def verify_warrant(warrant: Warrant, log: DidLog, now: datetime) -> dict:
    if log.did != warrant.issuer_did:
        raise WarrantVerificationError(
            f"DID log for {log.did} does not match warrant issuer {warrant.issuer_did}"
        )
    if warrant.proof_created > now:
        raise WarrantVerificationError(
            f"Warrant proof_created {warrant.proof_created} is in the future"
        )

    # Anchor to signing time, not verification time. This is the invariant.
    if not log.key_valid_at(warrant.signing_key_id, warrant.proof_created):
        raise WarrantVerificationError(
            f"Key {warrant.signing_key_id} was not valid at proof_created "
            f"{warrant.proof_created}; possible forgery or pre-dates published history"
        )

    # Signature check would go here against the historical key material.
    currently_active = log.key_valid_at(warrant.signing_key_id, now)
    return {
        "verdict": "accept",
        "rotation_continuity": "current_key" if currently_active else "superseded_key",
        "anchored_at": warrant.proof_created.isoformat(),
    }


def verify_or_reissue_required(warrant: Warrant, log: DidLog | None, now: datetime) -> dict:
    """Degraded mode: no append-only log available (plain did:web)."""
    if log is None:
        # Cannot reason temporally. Only currently-active keys are acceptable.
        raise WarrantVerificationError(
            "No append-only DID log available; cannot verify historical key validity. "
            "Federation must re-issue warrants on rotation before next use."
        )
    return verify_warrant(warrant, log, now)
