# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-delegated-task-whose-signed-warrant-chains-to-a-re-published-agent-card.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-delegated-task-whose-signed-warrant-chains-to-a-re-published-agent-card.warrant.json
# Markdown SHA-256:   14aefeb2fda2ea0d16368e0614bcc4787ce4d9b542705fc36dd8cc5854632f90
# Code AST SHA-256:   4750c41f6d01bc11be1f24448771ac47f536804218610581f57f58b559fe777e
# Verified Classes:   UnverifiableWarrantSnapshot, ScopeResurrectionError, Warrant, CardSnapshot, KeyRecord
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from datetime import datetime


class UnverifiableWarrantSnapshot(RuntimeError):
    """Raised when a receiver cannot reconstruct the delegator's card/keyset
    state as of the warrant's issuedAt, and therefore cannot safely decide."""


class ScopeResurrectionError(RuntimeError):
    """Raised when a warrant's scope is not a subset of the capabilities
    attested by the card version pinned in the warrant."""


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    subject_agent_id: str
    card_version: int
    signing_key_id: str
    issued_at: datetime
    scope: frozenset[str]


@dataclass(frozen=True)
class CardSnapshot:
    agent_id: str
    card_version: int
    capabilities: frozenset[str]


@dataclass(frozen=True)
class KeyRecord:
    key_id: str
    valid_from: datetime
    valid_to: datetime | None  # None = still active
    revoked_at: datetime | None


def verify_delegation(
    w: Warrant,
    snapshot: CardSnapshot | None,
    key: KeyRecord | None,
    now: datetime,
) -> None:
    # Fail closed: cannot evaluate against mint-time state.
    if snapshot is None or key is None:
        raise UnverifiableWarrantSnapshot(
            f"warrant {w.warrant_id}: no snapshot for "
            f"{w.subject_agent_id}@v{w.card_version} key {w.signing_key_id}"
        )

    if snapshot.card_version != w.card_version:
        raise UnverifiableWarrantSnapshot(
            f"warrant {w.warrant_id}: pinned v{w.card_version}, "
            f"resolved v{snapshot.card_version}"
        )

    if key.key_id != w.signing_key_id:
        raise UnverifiableWarrantSnapshot(
            f"warrant {w.warrant_id}: key mismatch {key.key_id} != {w.signing_key_id}"
        )

    # Key must have been valid at mint time, not merely present now.
    if not (key.valid_from <= w.issued_at):
        raise UnverifiableWarrantSnapshot(
            f"warrant {w.warrant_id}: key not yet valid at issuedAt"
        )
    if key.valid_to is not None and key.valid_to < w.issued_at:
        raise UnverifiableWarrantSnapshot(
            f"warrant {w.warrant_id}: key already retired at issuedAt"
        )

    # Revocation is unconditional; retirement is not.
    if key.revoked_at is not None and key.revoked_at <= now:
        raise ScopeResurrectionError(
            f"warrant {w.warrant_id}: signing key revoked at {key.revoked_at}"
        )

    # Scope must be subset of the PINNED card, never the current card.
    if not w.scope.issubset(snapshot.capabilities):
        raise ScopeResurrectionError(
            f"warrant {w.warrant_id}: scope {sorted(w.scope)} not attested by "
            f"card v{w.card_version} capabilities {sorted(snapshot.capabilities)}"
        )
