# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-during-an-in-flight-a2a-task-lifecycle.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-during-an-in-flight-a2a-task-lifecycle.warrant.json
# Markdown SHA-256:   c7ce97377870837f7d37a2369220c662c07bc0970d752c20e5bc75b01c953e96
# Code AST SHA-256:   a8f308b21240dc379a86fedcf42b73911d7ff8e3da0f03590e77c7afc01488cc
# Verified Classes:   StaleAgentCardError, UnrebindableTaskError, CachedCard
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class StaleAgentCardError(RuntimeError):
    """Raised when an in-flight A2A task is being driven against a card the remote no longer serves."""
    pass


class UnrebindableTaskError(StaleAgentCardError):
    """Raised when the card delta cannot be reconciled with the live task; task must be canceled and re-opened."""
    pass


@dataclass
class CachedCard:
    raw: dict
    content_hash: str


def card_hash(card: dict) -> str:
    canonical = json.dumps(card, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def rebindable(old: dict, new: dict, used_skill_id: str, used_input_mode: str) -> bool:
    # Skill must still exist and its input schema must not have tightened incompatibly.
    old_skill = next((s for s in old.get("skills", []) if s.get("id") == used_skill_id), None)
    new_skill = next((s for s in new.get("skills", []) if s.get("id") == used_skill_id), None)
    if old_skill is None or new_skill is None:
        return False
    if old_skill.get("inputSchema") != new_skill.get("inputSchema"):
        return False
    # The input mode the client is currently using must still be accepted.
    if used_input_mode not in new.get("defaultInputModes", []):
        return False
    # Streaming must not have been revoked if the client is mid-stream.
    if old.get("capabilities", {}).get("streaming") and not new.get("capabilities", {}).get("streaming"):
        return False
    return True


def check_continuation(
    cached: CachedCard,
    fetched_card: dict,
    used_skill_id: str,
    used_input_mode: str,
) -> Optional[dict]:
    """
    Called before every continuation turn of an in-flight task.
    Returns the card to use for this turn (cached or fresh), or raises if the
    task can no longer be driven against any valid card.
    """
    fresh_hash = card_hash(fetched_card)
    if fresh_hash == cached.content_hash:
        return cached.raw  # no delta; proceed on cached card

    if rebindable(cached.raw, fetched_card, used_skill_id, used_input_mode):
        # Re-bind: continue the task, but re-derive the request shape from the fresh card.
        return fetched_card

    raise UnrebindableTaskError(
        f"agent card rotated incompatibly mid-task: "
        f"skill={used_skill_id!r} input_mode={used_input_mode!r} "
        f"old_hash={cached.content_hash[:12]} new_hash={fresh_hash[:12]}; "
        f"cancel task and re-open against fresh card"
    )


def drive_turn(task_id: str, cached: CachedCard, fetch_card, send_turn, used_skill_id: str, used_input_mode: str) -> Any:
    fetched = fetch_card()
    try:
        card = check_continuation(cached, fetched, used_skill_id, used_input_mode)
    except UnrebindableTaskError:
        # Loud, bounded recovery: cancel and surface, do not silently retry.
        raise
    return send_turn(task_id, card)
