# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-divergent-agent-card-snapshots-when-a2a-v1-0-capability-negotiation-succeeds-at-discovery-but-the-peer-re-signs-its-c.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-divergent-agent-card-snapshots-when-a2a-v1-0-capability-negotiation-succeeds-at-discovery-but-the-peer-re-signs-its-c.warrant.json
# Markdown SHA-256:   44a3716f0784d415958f596f90592b1af1f8948ba174da1b11f790e3cbcdf7e6
# Code AST SHA-256:   7626e7badba4f22f3dd611d7a795d4361088d7dcfe421cfd2e239fbe7cfc5c76
# Verified Classes:   CapabilityRevokedMidTask, CardDigestMismatch, AgentCard, TaskBinding
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class CapabilityRevokedMidTask(RuntimeError):
    """Raised when the peer's current Agent Card no longer supports a mode
    required by an in-flight task, and the bound card cannot be honored."""


class CardDigestMismatch(RuntimeError):
    """Raised when a fetched card's digest does not match the task's bound
    digest AND the capability diff is not a benign rotation."""


@dataclass
class AgentCard:
    digest: str
    capabilities: dict          # e.g. {"streaming": True}
    skill_input_modes: dict     # e.g. {"summarize": ["text/plain"]}

    @classmethod
    def from_raw(cls, raw: dict) -> "AgentCard":
        blob = json.dumps(raw, sort_keys=True, separators=(",", ":")).encode()
        digest = "sha256:" + hashlib.sha256(blob).hexdigest()
        return cls(
            digest=digest,
            capabilities=raw.get("capabilities", {}),
            skill_input_modes={
                s["id"]: s.get("inputModes", []) for s in raw.get("skills", [])
            },
        )


@dataclass
class TaskBinding:
    task_id: str
    bound_digest: str
    bound_card: AgentCard
    required_modes: dict = field(default_factory=dict)  # skill -> modes still needed


def reconcile_card(
    binding: TaskBinding,
    current_card: AgentCard,
) -> TaskBinding:
    """Apply the decision boundary. Returns a re-pinned binding, or raises."""
    if current_card.digest == binding.bound_digest:
        return binding

    # Digest changed. Classify the diff.
    narrowed = False
    revoked_for_task = False
    for skill, needed_modes in binding.required_modes.items():
        current_modes = set(current_card.skill_input_modes.get(skill, []))
        bound_modes = set(binding.bound_card.skill_input_modes.get(skill, []))
        if current_modes < bound_modes:
            narrowed = True
        for mode in needed_modes:
            if mode in bound_modes and mode not in current_modes:
                revoked_for_task = True

    if not narrowed:
        # Benign rotation or widening: re-pin and continue.
        binding.bound_digest = current_card.digest
        binding.bound_card = current_card
        return binding

    if revoked_for_task:
        raise CapabilityRevokedMidTask(
            f"task {binding.task_id}: peer card {current_card.digest} no longer "
            f"supports a mode required by in-flight work; bound={binding.bound_digest}"
        )

    # Narrowed but not for anything this task still needs: re-pin, log.
    binding.bound_digest = current_card.digest
    binding.bound_card = current_card
    return binding


def send_turn(binding: TaskBinding, skill: str, mode: str, payload: dict) -> dict:
    current_card = _fetch_card()  # network call, fresh each turn
    binding = reconcile_card(binding, current_card)
    if mode not in binding.bound_card.skill_input_modes.get(skill, []):
        raise CapabilityRevokedMidTask(
            f"refusing to send {mode!r} to {skill!r}: not in bound card "
            f"{binding.bound_digest}"
        )
    return _rpc("message/send", {"taskId": binding.task_id, "payload": payload})


def _fetch_card() -> AgentCard:
    ...


def _rpc(method: str, params: dict) -> dict:
    ...
