# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-delegated-a2a-task-whose-agent-card-skills-were-re-advertised-mid-handshake.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-delegated-a2a-task-whose-agent-card-skills-were-re-advertised-mid-handshake.warrant.json
# Markdown SHA-256:   c983f517bf5afedd9567499782ffded3c667f3a3d73f6af0dbaf5b38b697373a
# Code AST SHA-256:   ad8e2286667b4033c2a5fa611d4d9de4685ad77fe8e8bcc1ee9e04c4a599e0ad
# Verified Classes:   CardDriftError, TaskPhase, CardRevision, DelegatedTask
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Optional


class CardDriftError(RuntimeError):
    """Raised when the remote Agent Card revision diverges from the one
    bound to an in-flight task in a way that makes further validation
    unsafe on at least one side of the handshake."""


class TaskPhase(Enum):
    SUBMITTED = "submitted"
    WORKING = "working"
    INPUT_REQUIRED = "input-required"
    TERMINAL = "completed"


@dataclass
class CardRevision:
    version: str
    signature: str
    schema_fingerprint: str  # hash over the validated skill schemas

    @classmethod
    def from_card(cls, card: dict[str, Any]) -> "CardRevision":
        canonical = repr(sorted(card.get("skills", []), key=lambda s: s.get("id", "")))
        return cls(
            version=str(card.get("version", "0")),
            signature=str(card.get("signature", "")),
            schema_fingerprint=hashlib.sha256(canonical.encode()).hexdigest(),
        )

    def is_additive_superset_of(self, other: "CardRevision") -> bool:
        # Conservative: only identical fingerprints are treated as compatible.
        # A real implementation would diff skill schemas field-by-field.
        return self.schema_fingerprint == other.schema_fingerprint


@dataclass
class DelegatedTask:
    task_id: str
    pinned_card: CardRevision
    phase: TaskPhase = TaskPhase.SUBMITTED
    schema_bound_message_consumed: bool = False
    input_required_rounds: int = 0
    max_rounds: int = 3
    remote_canceled: bool = False


def on_input_required(
    task: DelegatedTask,
    live_card: dict[str, Any],
    reply_payload: dict[str, Any],
) -> dict[str, Any]:
    """Validate an inbound input-required against the pinned card revision.
    Aborts the task if the live card has drifted incompatibly."""
    live = CardRevision.from_card(live_card)

    if live.version != task.pinned_card.version and not live.is_additive_superset_of(task.pinned_card):
        # Incompatible republish mid-task. If we have already consumed a
        # schema-bound message, rebinding is unsafe: abort and re-delegate.
        if task.schema_bound_message_consumed:
            task.phase = TaskPhase.TERMINAL
            raise CardDriftError(
                f"task {task.task_id}: card drifted {task.pinned_card.version}->{live.version} "
                f"after schema-bound message consumed; aborting to avoid input-required "
                f"oscillation (rounds={task.input_required_rounds})"
            )
        # Safe window: rebind before any schema-bound message.
        task.pinned_card = live

    task.input_required_rounds += 1
    if task.input_required_rounds > task.max_rounds:
        task.phase = TaskPhase.TERMINAL
        raise CardDriftError(
            f"task {task.task_id}: exceeded {task.max_rounds} input-required rounds "
            f"against pinned card {task.pinned_card.version}; likely schema-drift loop"
        )

    # Validate reply against the PINNED revision, never the live one.
    required = {"ocr_mode"}  # derived from pinned card schema in real code
    if not required.issubset(reply_payload):
        raise CardDriftError(
            f"task {task.task_id}: reply missing fields {required - set(reply_payload)} "
            f"under pinned card {task.pinned_card.version}"
        )
    task.schema_bound_message_consumed = True
    task.phase = TaskPhase.WORKING
    return reply_payload


def on_local_failure(task: DelegatedTask, send_cancel) -> None:
    """A locally failed task does not cancel on the remote. Do it explicitly,
    or the peer holds the task in 'working' indefinitely."""
    if task.phase is TaskPhase.TERMINAL and not task.remote_canceled:
        send_cancel(task.task_id)
        task.remote_canceled = True
