# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a2a-v1-0-agent-card-capability-negotiation-as-non-idempotent-when-the-remote-peer-advertises-a-mutable-skills.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a2a-v1-0-agent-card-capability-negotiation-as-non-idempotent-when-the-remote-peer-advertises-a-mutable-skills.warrant.json
# Markdown SHA-256:   a88347b5de0eaf40f8a6ff8ac9543ad41c79dec89fd3a544e44e68c0de1c0be9
# Code AST SHA-256:   d6c22930a88ffd8e6a1b1f74b5322e60d72bda42dddaeaa8b655f61dd617a0bb
# Verified Classes:   CardNegotiationError, NonIdempotentCardError, CardHandlerDesyncError, AgentCard, NegotiationState
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class CardNegotiationError(RuntimeError):
    """Raised when A2A card negotiation state is inconsistent with peer behavior."""
    pass


class NonIdempotentCardError(CardNegotiationError):
    """Peer card mutated between fetch and task dispatch; cached skill set is invalid."""
    pass


class CardHandlerDesyncError(CardNegotiationError):
    """Peer returned 304 on re-fetch but rejected a skill the pinned card advertised."""
    pass


@dataclass
class AgentCard:
    skills: list[str]
    etag: str

    def skill_fingerprint(self) -> str:
        payload = json.dumps(sorted(self.skills)).encode()
        return hashlib.sha256(payload).hexdigest()


@dataclass
class NegotiationState:
    pinned: AgentCard
    invalidated: bool = False
    mutation_log: list[dict] = field(default_factory=list)


def fetch_card(peer) -> AgentCard:
    raw = peer.get_agent_card()
    return AgentCard(skills=raw["skills"], etag=raw["etag"])


def handle_skill_rejection(
    state: NegotiationState,
    peer,
    skill_id: str,
    rpc_error: dict,
) -> NegotiationState:
    """
    Called when tasks/send returns -32602. Decides whether this is a client bug
    or a discovery-invalidation signal. Re-fetches conditionally on the pinned ETag.
    """
    if rpc_error.get("code") != -32602:
        raise CardNegotiationError(f"unexpected error code: {rpc_error.get('code')}")

    offending = (rpc_error.get("data") or {}).get("skillId")
    if offending != skill_id:
        # Error data does not name the skill we sent: this is a client-side bug,
        # not a card mutation. Do not invalidate.
        raise CardNegotiationError(
            f"error data skillId={offending!r} does not match sent skillId={skill_id!r}; "
            "treating as malformed request, not card mutation"
        )

    if skill_id not in state.pinned.skills:
        raise CardNegotiationError(
            f"peer rejected skill {skill_id!r} that was never in pinned card; "
            "client constructed an unknown skillId"
        )

    # Conditional re-fetch against the pinned ETag.
    fresh = peer.get_agent_card(if_none_match=state.pinned.etag)

    if fresh is None:
        # Peer returned 304: card unchanged, but handler rejected a pinned skill.
        # Card and handler are out of sync on the peer side.
        raise CardHandlerDesyncError(
            f"peer returned 304 for etag {state.pinned.etag!r} yet rejected "
            f"skill {skill_id!r} that the pinned card advertises; "
            "peer card projection and skill validation disagree"
        )

    new_card = AgentCard(skills=fresh["skills"], etag=fresh["etag"])
    if new_card.skill_fingerprint() == state.pinned.skill_fingerprint():
        # Same skill set, different ETag: peer is churning ETags without changing
        # capabilities. Safe to keep pinned set; do not re-plan.
        state.pinned = new_card
        return state

    removed = set(state.pinned.skills) - set(new_card.skills)
    added = set(new_card.skills) - set(state.pinned.skills)
    state.mutation_log.append(
        {"removed": sorted(removed), "added": sorted(added), "new_etag": new_card.etag}
    )
    state.pinned = new_card
    state.invalidated = True

    if skill_id in removed:
        raise NonIdempotentCardError(
            f"skill {skill_id!r} removed from peer card mid-session "
            f"(removed={sorted(removed)}, added={sorted(added)}); "
            "cached capability surface was non-idempotent; re-plan required"
        )
    # Skill still present but card mutated elsewhere: invalidate and re-plan,
    # but the specific skill is still dispatchable.
    return state
