# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-survive-agent-card-drift-during-cross-vendor-a2a-v1-0-task-delegation-when-the-remote-card-s-declared-capabilities-i.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-survive-agent-card-drift-during-cross-vendor-a2a-v1-0-task-delegation-when-the-remote-card-s-declared-capabilities-i.warrant.json
# Markdown SHA-256:   bd62e67fb2b76ae52d9b18257e32dab61f4442736b77e3eba092f24f998073f7
# Code AST SHA-256:   a7f85f9c9f3bd3578de3359896de3663f6ebed60627f11f7cd94c6339e630847
# Verified Classes:   SkillContractDrift, SkillIdentityReuse, CardDigest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class SkillContractDrift(RuntimeError):
    """Raised when the live Agent Card no longer matches the card used to build a task payload."""


class SkillIdentityReuse(SkillContractDrift):
    """Raised when a skill id is present but its semantic contract (description/inputModes) changed."""


@dataclass(frozen=True)
class CardDigest:
    skill_id: str
    input_modes: tuple[str, ...]
    output_modes: tuple[str, ...]
    description_hash: str
    auth_scheme_id: str

    def key(self) -> str:
        blob = json.dumps(
            [self.skill_id, self.input_modes, self.output_modes,
             self.description_hash, self.auth_scheme_id],
            sort_keys=True,
        )
        return hashlib.sha256(blob.encode()).hexdigest()


def digest_from_card(card: dict[str, Any], skill_id: str) -> CardDigest:
    skills = {s["id"]: s for s in card.get("skills", [])}
    if skill_id not in skills:
        raise SkillIdentityReuse(f"skill {skill_id!r} absent from live card")
    skill = skills[skill_id]
    scheme = next(iter(card.get("securitySchemes", {})), "")
    return CardDigest(
        skill_id=skill_id,
        input_modes=tuple(skill.get("inputModes", card.get("defaultInputModes", []))),
        output_modes=tuple(skill.get("outputModes", card.get("defaultOutputModes", []))),
        description_hash=hashlib.sha256(
            skill.get("description", "").encode()
        ).hexdigest(),
        auth_scheme_id=scheme,
    )


def dispatch_guarded(
    cached_card: dict[str, Any],
    live_card: dict[str, Any],
    skill_id: str,
    payload: dict[str, Any],
) -> dict[str, Any]:
    cached = digest_from_card(cached_card, skill_id)
    live = digest_from_card(live_card, skill_id)

    if cached.key() != live.key():
        if (cached.description_hash != live.description_hash
                or cached.input_modes != live.input_modes):
            raise SkillIdentityReuse(
                f"skill {skill_id!r} contract mutated between discovery and dispatch; "
                f"cached={cached.key()[:12]} live={live.key()[:12]}"
            )
        raise SkillContractDrift(
            f"skill {skill_id!r} digest drift (auth/modes); "
            f"cached={cached.key()[:12]} live={live.key()[:12]}"
        )

    if payload.get("input_mode") not in live.input_modes:
        raise SkillContractDrift(
            f"payload input_mode {payload.get('input_mode')!r} not in live modes {live.input_modes}"
        )

    # dispatch would occur here against live contract
    return {"status": "dispatched", "contract": live.key()}
