# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-signed-task-authority-the-moment-its-a2a-agent-card-is-re-fetched-mid-delegation.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-signed-task-authority-the-moment-its-a2a-agent-card-is-re-fetched-mid-delegation.warrant.json
# Markdown SHA-256:   8d86e7e8fa61c50baf77021d8e5c7b96351d717bd08c12367fee689050ff3488
# Code AST SHA-256:   0ba1782811ce6afb4f5b4e68991c315e984534bbbfcf21a0b04dacd733bfe491
# Verified Classes:   CardSkewAuthorityError, CardSnapshot, TaskAuthorityRecord, DelegationAuthority
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CardSkewAuthorityError(RuntimeError):
    """Raised when a task's completion is verified against a card other than its issuance snapshot."""
    pass


@dataclass(frozen=True)
class CardSnapshot:
    card_version: int
    key_id: str
    skills: frozenset[str]
    jws: str


@dataclass
class TaskAuthorityRecord:
    task_id: str
    snapshot: CardSnapshot
    issued_at: float


class DelegationAuthority:
    def __init__(self) -> None:
        self._live_card: Optional[CardSnapshot] = None
        self._records: dict[str, TaskAuthorityRecord] = {}

    def refresh_live_card(self, card: CardSnapshot) -> None:
        # Re-fetch updates admission state ONLY. Never touches task authority.
        self._live_card = card

    def issue_task(self, task_id: str, now: float) -> TaskAuthorityRecord:
        if self._live_card is None:
            raise CardSkewAuthorityError("no card discovered; cannot issue signed task")
        rec = TaskAuthorityRecord(task_id, self._live_card, now)
        self._records[task_id] = rec
        return rec

    def verify_completion(self, task_id: str, result_card_version: int,
                          result_key_id: str, result_skill: str) -> None:
        rec = self._records.get(task_id)
        if rec is None:
            raise CardSkewAuthorityError(f"no authority record for task {task_id}")
        snap = rec.snapshot
        # The decisive check: verify against the SNAPSHOT, not the live card.
        if result_card_version != snap.card_version or result_key_id != snap.key_id:
            raise CardSkewAuthorityError(
                f"task {task_id} completed under card v{result_card_version}/{result_key_id}, "
                f"but was authorized under v{snap.card_version}/{snap.key_id}"
            )
        if result_skill not in snap.skills:
            raise CardSkewAuthorityError(
                f"task {task_id} used skill {result_skill} absent from issuance snapshot"
            )

    def guard_new_task_against_drain(self) -> None:
        # If live card drifted from any in-flight snapshot, refuse NEW tasks.
        in_flight = {r.snapshot.card_version for r in self._records.values()}
        if self._live_card and in_flight and self._live_card.card_version not in in_flight:
            raise CardSkewAuthorityError(
                "card changed mid-flight; drain in-flight tasks before admitting new ones"
            )
