# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a2a-v1-0-agent-card-discovery-as-a-non-idempotent-versioned-handshake-rather-than-a-stateless-capability-look.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a2a-v1-0-agent-card-discovery-as-a-non-idempotent-versioned-handshake-rather-than-a-stateless-capability-look.warrant.json
# Markdown SHA-256:   b4a78a5e0369fbfe340eba2eb5efbaaa7178c2e3eca04b9e1916cdbfb11f7485
# Code AST SHA-256:   6cd5bf62a80e4d111f9e8b2df4cde0787428c0e9a427ddf72edddd3cce6a3cd9
# Verified Classes:   TaskContractDrift, AgentCard, PinnedTask
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class TaskContractDrift(RuntimeError):
    """Raised when the live Agent Card no longer describes the pinned task contract."""


@dataclass
class AgentCard:
    skills: list
    capabilities: dict
    security_schemes: dict

    def contract_hash(self) -> str:
        # Only the fields that govern the task state machine are hashed.
        payload = {
            "skills": sorted(s.get("id") for s in self.skills),
            "capabilities": {
                k: self.capabilities.get(k)
                for k in ("streaming", "pushNotifications", "stateTransitionHistory")
            },
            "securitySchemes": sorted(self.security_schemes.keys()),
        }
        return hashlib.sha256(
            json.dumps(payload, sort_keys=True).encode()
        ).hexdigest()


@dataclass
class PinnedTask:
    task_id: str
    card: AgentCard
    card_hash: str = field(init=False)

    def __post_init__(self):
        self.card_hash = self.card.contract_hash()


def validate_resume(pinned: PinnedTask, live_card: AgentCard) -> None:
    """Called on every input-required resume and on any TaskNotFound.

    Raises if the live card's contract hash diverges from the pinned one;
    the caller must NOT retry or re-send human input in that case.
    """
    live_hash = live_card.contract_hash()
    if live_hash != pinned.card_hash:
        raise TaskContractDrift(
            f"task {pinned.task_id}: pinned card {pinned.card_hash[:12]} "
            f"!= live card {live_hash[:12]}; task is orphaned, "
            f"do not resend human input"
        )


def handle_task_error(pinned: PinnedTask, live_card: AgentCard, error_code: int) -> str:
    if error_code == -32001:  # TaskNotFound
        # Ambiguous: transient OR contract drift. Re-validate before deciding.
        validate_resume(pinned, live_card)
        return "retry"
    return "retry"
