# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-stale-a2a-v1-0-agent-card-is-being-trusted-during-task-negotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-stale-a2a-v1-0-agent-card-is-being-trusted-during-task-negotiation.warrant.json
# Markdown SHA-256:   3666b713ac2a10fb5736de5b23505c9becd2fff16f2a0a457d405f1baacb0da6
# Code AST SHA-256:   12ecd9a83bc8ba118b81b901d43340f742da77bc694b2c883e9c5378be612bd5
# Verified Classes:   StaleAgentCardError, CachedCard
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class StaleAgentCardError(RuntimeError):
    """Raised when a cached A2A agent card no longer matches the live
    negotiation surface for the fields a specific task depends on."""


# Fields whose change invalidates negotiation (not identity/routing).
NEGOTIATION_FIELDS = (
    "capabilities",
    "skills",
    "defaultInputModes",
    "defaultOutputModes",
    "extensions",
)


def negotiation_digest(card: Mapping[str, Any]) -> str:
    """Digest only the fields that gate task negotiation."""
    subset = {k: card.get(k) for k in NEGOTIATION_FIELDS}
    canonical = json.dumps(subset, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


@dataclass(frozen=True)
class CachedCard:
    card: Mapping[str, Any]
    digest: str


def negotiate_task(
    cached: CachedCard,
    live_card: Mapping[str, Any],
    task_envelope: Mapping[str, Any],
) -> Mapping[str, Any]:
    """Validate that the cached card's negotiation surface still matches the
    live card before allowing task creation. Fail closed on mismatch."""
    live_digest = negotiation_digest(live_card)
    if live_digest != cached.digest:
        # Identify which dependency drifted for attribution.
        drifted = [
            field
            for field in NEGOTIATION_FIELDS
            if cached.card.get(field) != live_card.get(field)
        ]
        raise StaleAgentCardError(
            "cached agent card negotiation surface is stale; "
            f"drifted fields={drifted}; "
            f"cached_digest={cached.digest[:12]} live_digest={live_digest[:12]}"
        )

    # Cached surface is valid for this task; safe to emit the Task.
    return {
        "task": task_envelope,
        "negotiated_against_digest": live_digest,
        "card_version": live_card.get("cardVersion"),
    }


def create_task_or_fail(
    cached: CachedCard,
    fetch_live_card,
    task_envelope: Mapping[str, Any],
) -> Mapping[str, Any]:
    """Revalidate at task-creation time, then negotiate. Never negotiate
    against a card that could not be revalidated."""
    live_card = fetch_live_card()
    if live_card is None:
        raise StaleAgentCardError(
            "cannot revalidate agent card at task creation; refusing to "
            "negotiate against unverified cached surface"
        )
    return negotiate_task(cached, live_card, task_envelope)
