# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-reuses-a-cached-agent-card-across-a-redeploy-that-silently-widens-a-skill-s-inputmodes-schema.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-reuses-a-cached-agent-card-across-a-redeploy-that-silently-widens-a-skill-s-inputmodes-schema.warrant.json
# Markdown SHA-256:   5212777b8f9bb94b15a2f45caa858caca2ce08b7f927d247d9a122d3ebfeaba8
# Code AST SHA-256:   46d162c095e1104d702c359886fe1748f37729cafd16eb4f57ffa008b23de625
# Verified Classes:   StaleAgentCardError, CachedCard
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class StaleAgentCardError(RuntimeError):
    """Raised when a cached Agent Card's content hash no longer matches the live card."""


@dataclass
class CachedCard:
    raw: dict[str, Any]
    content_hash: str
    skill_template: dict[str, Any] = field(default_factory=dict)


def canonical_hash(card: dict[str, Any]) -> str:
    # Canonical JSON: sorted keys, no whitespace, UTF-8. Must match server-side
    # canonicalization or the hash is meaningless.
    blob = json.dumps(card, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
    return hashlib.sha256(blob.encode("utf-8")).hexdigest()


def cache_card(card: dict[str, Any]) -> CachedCard:
    return CachedCard(raw=card, content_hash=canonical_hash(card))


def revalidate_on_failure(
    cached: CachedCard,
    live_card: dict[str, Any],
    last_status: str,
) -> CachedCard:
    """
    Invariant: on any terminal 'failed' or 'rejected' status that is NOT a
    structured InvalidParams error, revalidate the cached card against the
    live card before permitting any retry.

    Returns a fresh CachedCard if the card changed (caller must re-plan).
    Raises StaleAgentCardError if the card changed AND the caller attempts
    to reuse the old template — this is the tripwire that prevents replay storms.
    """
    if last_status not in ("failed", "rejected"):
        return cached

    live_hash = canonical_hash(live_card)
    if live_hash == cached.content_hash:
        # Card unchanged: failure is genuine, retry policy may proceed.
        return cached

    # Card changed under us. The cached skill_template is now suspect.
    # Do NOT replay with it.
    raise StaleAgentCardError(
        f"Agent Card changed during task lifecycle: "
        f"cached={cached.content_hash[:12]} live={live_hash[:12]}. "
        f"Re-plan required; replay with stale template is forbidden."
    )


def dispatch_with_revalidation(
    cached: CachedCard,
    live_card: dict[str, Any],
    payload: dict[str, Any],
    send_fn,
) -> dict[str, Any]:
    status = send_fn(payload)
    if status.get("state") in ("failed", "rejected"):
        # Structured InvalidParams is handled by the caller's normal error path;
        # only unstructured failures trigger revalidation.
        if status.get("error", {}).get("code") != "InvalidParams":
            try:
                cached = revalidate_on_failure(cached, live_card, status["state"])
            except StaleAgentCardError:
                # Re-derive template from live card and retry exactly once.
                cached = cache_card(live_card)
                payload = rebuild_payload(cached, payload)
                return send_fn(payload)
    return status


def rebuild_payload(cached: CachedCard, old_payload: dict[str, Any]) -> dict[str, Any]:
    # Placeholder: real implementation re-derives from cached.skill_template.
    # Must not copy field shapes from old_payload — that is the whole bug.
    raise StaleAgentCardError(
        "Cannot rebuild payload from stale template; re-plan from live card."
    )
