# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-re-advertised-a2a-agent-card-when-the-remote-task-lifecycle-has-already-crossed-the-working-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-re-advertised-a2a-agent-card-when-the-remote-task-lifecycle-has-already-crossed-the-working-boundary.warrant.json
# Markdown SHA-256:   bc1f26b09920dae0b92de5f35eafd0c5707053067938b20d16203cee0c52a238
# Code AST SHA-256:   ebf253110e51f0a6cc9e2c3910d147570a0443b994fc45b82ce57cc572ffdfa2
# Verified Classes:   CapabilitySnapshotUnavailable, MidTaskRenegotiationAttempt, PinnedCard
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Optional


class CapabilitySnapshotUnavailable(RuntimeError):
    """Raised when a task continuation cannot be resolved against its admitting card snapshot."""
    pass


class MidTaskRenegotiationAttempt(RuntimeError):
    """Raised when code tries to apply a newer card to a non-terminal task."""
    pass


@dataclass(frozen=True)
class PinnedCard:
    task_id: str
    snapshot_hash: str
    protocol_version: str
    input_modes: tuple
    skill_ids: tuple


def hash_card(card: dict) -> str:
    consumed = {
        "protocolVersion": card.get("protocolVersion"),
        "defaultInputModes": sorted(card.get("defaultInputModes", [])),
        "defaultOutputModes": sorted(card.get("defaultOutputModes", [])),
        "skills": sorted(s.get("id") for s in card.get("skills", [])),
        "capabilities": card.get("capabilities", {}),
    }
    return hashlib.sha256(json.dumps(consumed, sort_keys=True).encode()).hexdigest()


def admit_task(task_id: str, card: dict) -> PinnedCard:
    return PinnedCard(
        task_id=task_id,
        snapshot_hash=hash_card(card),
        protocol_version=card["protocolVersion"],
        input_modes=tuple(sorted(card.get("defaultInputModes", []))),
        skill_ids=tuple(sorted(s.get("id") for s in card.get("skills", []))),
    )


def resolve_continuation(pinned: Optional[PinnedCard], task_state: str, latest_card: dict) -> PinnedCard:
    if task_state in ("completed", "failed", "canceled"):
        # Terminal: safe to renegotiate for future dispatch, but this call has no continuation to bind.
        return admit_task(pinned.task_id if pinned else "unknown", latest_card)

    if pinned is None:
        raise CapabilitySnapshotUnavailable(
            "no admitting card snapshot for task in non-terminal state; refusing to "
            "fall back to latest card (would be unguarded renegotiation)"
        )

    if hash_card(latest_card) != pinned.snapshot_hash:
        # Card changed mid-task. Do NOT cancel, do NOT adopt. Continue under pinned snapshot.
        return pinned

    return pinned


def continue_task(pinned: Optional[PinnedCard], task_state: str, latest_card: dict, payload: dict) -> dict:
    resolved = resolve_continuation(pinned, task_state, latest_card)
    required_mode = payload.get("mode", "application/json")
    if required_mode not in resolved.input_modes:
        raise MidTaskRenegotiationAttempt(
            f"payload mode {required_mode!r} not in admitting snapshot "
            f"{resolved.input_modes} for task {resolved.task_id}"
        )
    return {"taskId": resolved.task_id, "snapshotHash": resolved.snapshot_hash, "accepted": True}
