# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-capability-drift-when-a2a-v1-0-agent-cards-are-cached-across-org-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-capability-drift-when-a2a-v1-0-agent-cards-are-cached-across-org-boundaries.warrant.json
# Markdown SHA-256:   c4bbfc19e707f20564d322c3ca204f41d779650c18967a8ae7f37403bb0ffcc4
# Code AST SHA-256:   5cd1c3cc04a1390cfee0756e3eb80e936b203e195e90d2b0c77994760e96a6fd
# Verified Classes:   CardVersionDriftError, LenientDeserializationError, AgentCard, CachedCard
# Defensive Guards:   7 fail-closed invariants (zero external deps)

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


class CardVersionDriftError(RuntimeError):
    """Raised when the card version used to validate a payload does not
    match the version the remote agent executed against."""


class LenientDeserializationError(RuntimeError):
    """Raised when a server accepts a payload that does not conform to the
    currently advertised skill schema (unknown fields or missing required)."""


@dataclass
class AgentCard:
    version: str
    skills: dict[str, dict[str, Any]] = field(default_factory=dict)

    def fingerprint(self) -> str:
        blob = json.dumps(
            {"version": self.version, "skills": self.skills}, sort_keys=True
        ).encode()
        return hashlib.sha256(blob).hexdigest()


@dataclass
class CachedCard:
    card: AgentCard
    fetched_at: float
    ttl_seconds: float

    def is_fresh(self, now: float) -> bool:
        return (now - self.fetched_at) < self.ttl_seconds


def submit_task(
    cached: CachedCard,
    live: AgentCard,
    skill_id: str,
    payload: dict[str, Any],
    now: float,
) -> dict[str, Any]:
    if not cached.is_fresh(now):
        raise CardVersionDriftError(
            f"cached card expired at t={cached.fetched_at + cached.ttl_seconds}, "
            f"now={now}; refusing side-effecting submit"
        )

    if cached.card.fingerprint() != live.fingerprint():
        raise CardVersionDriftError(
            f"card drifted between cache and submit: cached version "
            f"{cached.card.version} != live version {live.version}; "
            f"re-validate payload before resubmission"
        )

    skill = cached.card.skills.get(skill_id)
    if skill is None:
        raise CardVersionDriftError(
            f"skill {skill_id!r} not present in validated card version "
            f"{cached.card.version}"
        )

    required = set(skill.get("schema", {}).get("required", []))
    provided = set(payload.keys())
    missing = required - provided
    if missing:
        # The server MUST reject this; if it does not, it is deserializing
        # leniently and the caller must not trust the result.
        raise LenientDeserializationError(
            f"payload missing required fields {sorted(missing)} for skill "
            f"{skill_id!r}; a compliant server rejects with TaskState.rejected"
        )

    envelope = {
        "skillId": skill_id,
        "payload": payload,
        "metadata": {"cardVersion": cached.card.version,
                     "cardFingerprint": cached.card.fingerprint()},
    }
    return envelope


def verify_task_result(
    envelope: dict[str, Any],
    task: dict[str, Any],
    live: AgentCard,
) -> None:
    echoed = task.get("metadata", {}).get("cardVersion")
    asserted = envelope["metadata"]["cardVersion"]
    if echoed != asserted:
        raise CardVersionDriftError(
            f"server executed against card version {echoed!r} but client "
            f"validated against {asserted!r}; result is not trustworthy"
        )
    if task.get("state") != "completed":
        raise CardVersionDriftError(
            f"task did not complete: state={task.get('state')!r}"
        )
    if live.version != asserted:
        raise CardVersionDriftError(
            f"card changed again after execution: executed {asserted!r}, "
            f"live now {live.version!r}; replay required"
        )
