# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-conformant-a2a-v1-0-agent-card-is-actually-un-delegatable-at-the-task-handshake-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-conformant-a2a-v1-0-agent-card-is-actually-un-delegatable-at-the-task-handshake-boundary.warrant.json
# Markdown SHA-256:   710ba113a2e0a3485f43784c426378aad170ee11a2a6531cd8639f25d58814a8
# Code AST SHA-256:   eb23a23b27532725d994b0f3be76e0c01ee1bef68a8a161d2a50a055c6031a76
# Verified Classes:   CardRuntimeDivergenceError, ConformanceProbe, DelegationGate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class CardRuntimeDivergenceError(RuntimeError):
    """Raised when an A2A v1.0 agent card's declared surface diverges from the live router."""


@dataclass
class ConformanceProbe:
    skill_id: str
    input_mode: str
    accepted: bool
    task_state: str | None = None
    detail: str = ""


@dataclass
class DelegationGate:
    card: dict[str, Any]
    probes: list[ConformanceProbe] = field(default_factory=list)

    def declared_input_modes(self) -> list[str]:
        return list(self.card.get("defaultInputModes", []))

    def declared_skill_ids(self) -> list[str]:
        return [s.get("id") for s in self.card.get("skills", []) if s.get("id")]

    def record_probe(self, probe: ConformanceProbe) -> None:
        self.probes.append(probe)

    def assert_delegatable(self, intended_skill_id: str) -> None:
        if intended_skill_id not in self.declared_skill_ids():
            raise CardRuntimeDivergenceError(
                f"skill {intended_skill_id!r} not declared in card; refusing delegation"
            )
        relevant = [p for p in self.probes if p.skill_id == intended_skill_id]
        if not relevant:
            raise CardRuntimeDivergenceError(
                f"no conformance probe recorded for skill {intended_skill_id!r}; "
                "card validation alone is insufficient for cross-vendor delegation"
            )
        for probe in relevant:
            if not probe.accepted or probe.task_state not in ("completed", "working"):
                raise CardRuntimeDivergenceError(
                    f"probe for skill={probe.skill_id!r} input_mode={probe.input_mode!r} "
                    f"failed at task level (state={probe.task_state!r}): {probe.detail}; "
                    "declared surface diverges from enforced surface"
                )


def gate_delegation(card_json: str, intended_skill_id: str, probe_results: list[dict[str, Any]]) -> DelegationGate:
    card = json.loads(card_json)
    gate = DelegationGate(card=card)
    for r in probe_results:
        gate.record_probe(
            ConformanceProbe(
                skill_id=r["skill_id"],
                input_mode=r["input_mode"],
                accepted=r["accepted"],
                task_state=r.get("task_state"),
                detail=r.get("detail", ""),
            )
        )
    gate.assert_delegatable(intended_skill_id)
    return gate
