# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-a2a-v1-0-agent-card-as-a-non-authoritative-snapshot-rather-than-a-capability-contract-and-what-breaks.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-a2a-v1-0-agent-card-as-a-non-authoritative-snapshot-rather-than-a-capability-contract-and-what-breaks.warrant.json
# Markdown SHA-256:   415fe936331a7f1b30df5b4625e38f436a4289dba2f23a4ca15a945d71985221
# Code AST SHA-256:   5989d5c9a2e3131ff8d8c36b71469a56ce076ebc87f1418ab7f79eca331f2b4a
# Verified Classes:   CardStalenessError, CachedCard, StalenessBreaker
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class CardStalenessError(RuntimeError):
    """Raised when a task response contradicts the cached Agent Card.

    A successful RPC whose artifact mimeType is absent from the card's
    outputModes is a staleness event, not a success. A -32601 on a
    skill-pinned task is a staleness event, not a transport fault.
    """


@dataclass(frozen=True)
class CachedCard:
    url: str
    skills: dict[str, dict[str, Any]]  # skill_id -> {inputModes, outputModes}
    card_hash: str

    @classmethod
    def from_json(cls, url: str, raw: dict[str, Any]) -> "CachedCard":
        skills = {
            s["id"]: {
                "inputModes": s.get("inputModes", []),
                "outputModes": s.get("outputModes", []),
            }
            for s in raw.get("skills", [])
        }
        digest = hashlib.sha256(
            json.dumps(raw, sort_keys=True).encode()
        ).hexdigest()[:16]
        return cls(url=url, skills=skills, card_hash=digest)


def delegate(card: CachedCard, skill_id: str, payload: dict[str, Any], rpc) -> dict[str, Any]:
    """Issue a skill-pinned tasks/send and validate the response against the card.

    rpc is a callable(skill_id, payload, card_hash) -> dict with keys
    'error' (JSON-RPC error code or None) and 'artifacts' (list of {mimeType}).
    """
    if skill_id not in card.skills:
        raise CardStalenessError(
            f"skill {skill_id!r} not in cached card {card.card_hash}; re-fetch required"
        )

    resp = rpc(skill_id, payload, card.card_hash)
    code = resp.get("error")

    if code in (-32601, -32602):
        # Method/params mismatch on a pinned skill == card is stale.
        raise CardStalenessError(
            f"JSON-RPC {code} on pinned skill {skill_id!r} "
            f"(card {card.card_hash}); invalidate cache and re-plan"
        )
    if code is not None:
        raise RuntimeError(f"transport/rpc fault: {code}")

    allowed = set(card.skills[skill_id]["outputModes"])
    for art in resp.get("artifacts", []):
        mt = art.get("mimeType")
        if mt not in allowed:
            # Silent success with off-contract output: still a staleness event.
            raise CardStalenessError(
                f"artifact mimeType {mt!r} not in outputModes {sorted(allowed)} "
                f"for skill {skill_id!r} (card {card.card_hash})"
            )
    return resp


class StalenessBreaker:
    """Circuit breaker: N schema/method mismatches force a synchronous re-fetch."""

    def __init__(self, threshold: int = 2) -> None:
        self.threshold = threshold
        self._hits = 0

    def record(self, exc: CardStalenessError) -> bool:
        self._hits += 1
        if self._hits >= self.threshold:
            self._hits = 0
            return True  # caller must re-fetch card and re-plan
        return False
