# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-v1-0-capability-negotiation-deadlock-hidden-inside-a-successful-agent-card-fetch.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-v1-0-capability-negotiation-deadlock-hidden-inside-a-successful-agent-card-fetch.warrant.json
# Markdown SHA-256:   806e9e0da0a4a868e79a0a1dd44541b8dc98eb3dcee29d008d3ac2e1e7fb8485
# Code AST SHA-256:   ecaae168f9886ea6901935f967089330bc968144db27cd33eda6a5c20e3237a8
# Verified Classes:   CapabilityAmbiguityError, TerminalNegotiationRejection, NegotiationPlan
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class CapabilityAmbiguityError(RuntimeError):
    """Raised when a fetched agent card cannot yield an unambiguous
    admissible-method set for the requested skill. This is a discovery
    failure even though the HTTP fetch and schema validation succeeded."""


class TerminalNegotiationRejection(RuntimeError):
    """Raised when the server terminally rejects a well-formed task with a
    JSON-RPC error that must NOT be retried and must NOT trigger re-routing."""


# JSON-RPC error codes that are terminal for task admission. Retrying these
# is what converts a negotiation failure into a silent misroute.
TERMINAL_JSONRPC_CODES = {-32600, -32601, -32602}


@dataclass
class NegotiationPlan:
    peer_id: str
    skill_id: str
    admissible_methods: set[str] = field(default_factory=set)
    preserved_extensions: dict[str, Any] = field(default_factory=dict)


def derive_negotiation_plan(
    card: dict[str, Any],
    requested_skill_id: str,
    *,
    preserve_extensions: bool = True,
) -> NegotiationPlan:
    """Project a raw agent card into a negotiation plan for one skill.

    The plan is the ONLY artifact that authorizes task submission. A card that
    validates but cannot produce a plan for the requested skill is ambiguous.
    """
    if card.get("protocolVersion") != "1.0":
        raise CapabilityAmbiguityError(
            f"peer {card.get('name')!r}: unsupported protocolVersion "
            f"{card.get('protocolVersion')!r}; cannot derive plan"
        )

    skills = {s.get("id"): s for s in card.get("skills", [])}
    skill = skills.get(requested_skill_id)
    if skill is None:
        raise CapabilityAmbiguityError(
            f"peer {card.get('name')!r}: skill {requested_skill_id!r} not advertised"
        )

    caps = card.get("capabilities", {}) or {}
    plan = NegotiationPlan(peer_id=card.get("name", "<unnamed>"), skill_id=requested_skill_id)

    # Base admissible set from standard fields.
    plan.admissible_methods.add("tasks/send")
    if caps.get("streaming") is True:
        plan.admissible_methods.add("tasks/sendSubscribe")

    # Preserve non-standard extensions that may gate admission. Dropping these
    # is the lossy-projection condition that precedes the deadlock.
    if preserve_extensions:
        for k, v in skill.items():
            if k.startswith("x-"):
                plan.preserved_extensions[k] = v
        for k, v in caps.items():
            if k.startswith("x-"):
                plan.preserved_extensions[k] = v

    # Apply extension-derived gates.
    if plan.preserved_extensions.get("x-requires-streaming") is True:
        plan.admissible_methods.discard("tasks/send")
        plan.admissible_methods.add("tasks/sendSubscribe")

    if not plan.admissible_methods:
        raise CapabilityAmbiguityError(
            f"peer {plan.peer_id!r} skill {requested_skill_id!r}: "
            f"no admissible task method after applying extensions "
            f"{sorted(plan.preserved_extensions)}"
        )

    return plan


def classify_admission_response(plan: NegotiationPlan, http_status: int, body: str) -> None:
    """Classify a server response to a task submission.

    Terminal JSON-RPC rejections must raise TerminalNegotiationRejection so the
    orchestrator fails fast instead of retrying into a misroute.
    """
    if http_status < 400:
        return
    try:
        payload = json.loads(body)
    except json.JSONDecodeError:
        return  # transport-level; caller's retry policy owns this

    err = payload.get("error") or {}
    code = err.get("code")
    if code in TERMINAL_JSONRPC_CODES:
        raise TerminalNegotiationRejection(
            f"peer {plan.peer_id!r} skill {plan.skill_id!r}: terminal JSON-RPC "
            f"code {code} ({err.get('message')!r}); do NOT retry, do NOT re-route. "
            f"Admissible methods were {sorted(plan.admissible_methods)}."
        )


def submit_task(plan: NegotiationPlan, method: str, http_status: int, body: str) -> None:
    if method not in plan.admissible_methods:
        raise CapabilityAmbiguityError(
            f"refusing to submit {method!r} to {plan.peer_id!r} skill "
            f"{plan.skill_id!r}; not in admissible set {sorted(plan.admissible_methods)}"
        )
    classify_admission_response(plan, http_status, body)
