# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-signed-agent-card-whose-capability-claims-diverge-from-the-negotiated-json-rpc-method-set.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-signed-agent-card-whose-capability-claims-diverge-from-the-negotiated-json-rpc-method-set.warrant.json
# Markdown SHA-256:   56235e17e42f9c8c16f793898f08e66dc0a36c6ea870432618ff5eea25a1a7fa
# Code AST SHA-256:   879f1ca9034492d7571f401626b3931ce93554b2fbc97756774b13e7542d368f
# Verified Classes:   CapabilityDivergenceError, SignedCard, SessionCapabilityTrust, JsonRpcMethodNotFound
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class CapabilityDivergenceError(RuntimeError):
    """Raised when a signed Agent Card claims a capability the live
    JSON-RPC dispatcher does not honor. This is a hard stop for the
    session, not a retryable transport error."""


@dataclass
class SignedCard:
    payload: dict[str, Any]
    jws: str
    verified: bool
    expires_at: float

    def card_hash(self) -> str:
        canonical = json.dumps(self.payload, sort_keys=True, separators=(",", ":"))
        return hashlib.sha256(canonical.encode()).hexdigest()


@dataclass
class SessionCapabilityTrust:
    """Per-session record of which signed capabilities were actually
    confirmed by a live probe. Never persisted across sessions."""
    confirmed: set[str] = field(default_factory=set)
    rejected: set[str] = field(default_factory=set)


# Maps a signed capability claim to the JSON-RPC method that must exist
# on the dispatcher for the claim to be honorable.
CAPABILITY_PROBE = {
    "streaming": "message/stream",
    "pushNotifications": "tasks/pushNotification/set",
    "stateTransitionHistory": "tasks/get",
}


def negotiate(
    card: SignedCard,
    now: float,
    rpc_call: Callable[[str, dict[str, Any]], dict[str, Any]],
    trust: SessionCapabilityTrust,
) -> SessionCapabilityTrust:
    if not card.verified:
        raise CapabilityDivergenceError(
            f"card {card.card_hash()[:12]} failed JWS verification; cannot negotiate"
        )
    if now >= card.expires_at:
        raise CapabilityDivergenceError(
            f"card {card.card_hash()[:12]} expired at {card.expires_at}; re-fetch required"
        )

    caps = card.payload.get("capabilities", {})
    for cap_name, enabled in caps.items():
        if not enabled:
            continue
        method = CAPABILITY_PROBE.get(cap_name)
        if method is None:
            # Unknown capability: cannot probe, do not trust it.
            trust.rejected.add(cap_name)
            continue
        try:
            rpc_call(method, {"probe": True})
        except JsonRpcMethodNotFound:
            trust.rejected.add(cap_name)
            raise CapabilityDivergenceError(
                f"signed card claims '{cap_name}' but dispatcher returned "
                f"-32601 for '{method}'; signer and runtime are out of sync "
                f"(card {card.card_hash()[:12]})"
            )
        trust.confirmed.add(cap_name)

    return trust


class JsonRpcMethodNotFound(Exception):
    pass
