# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-agent-card-is-syntactically-valid-but-semantically-non-delegable-across-vendors.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-agent-card-is-syntactically-valid-but-semantically-non-delegable-across-vendors.warrant.json
# Markdown SHA-256:   235197cf1715538e803794c81bf0603d10d66194cf25c743886645222e76be0a
# Code AST SHA-256:   1019ba1843dbdefc6941198f44507e848be5b4024ef59dd2a13a86ff367aa47f
# Verified Classes:   NonDelegableSkillError, ProbeResult
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import json
import time
from dataclasses import dataclass
from typing import Any


class NonDelegableSkillError(RuntimeError):
    """Raised when an Agent Card skill passes matching but fails probe-time verification."""


@dataclass
class ProbeResult:
    skill_id: str
    mode: str
    transitioned: bool
    elapsed_s: float
    detail: str


def probe_skill(
    remote_send: callable,
    skill_id: str,
    mode: str,
    timeout_s: float = 5.0,
) -> ProbeResult:
    """Send a trivial payload in `mode` and require a terminal transition within timeout_s.

    A `failed` terminal state is a successful probe: it proves the mode is not
    silently stubbed. A missing transition is the Vendor C failure.
    """
    start = time.monotonic()
    try:
        task = remote_send(skill_id=skill_id, mode=mode, payload=_trivial_payload(mode))
    except Exception as exc:  # transport-level rejection is also informative
        return ProbeResult(skill_id, mode, False, time.monotonic() - start, f"transport: {exc}")

    deadline = start + timeout_s
    while time.monotonic() < deadline:
        state = task.get("status", {}).get("state")
        if state in ("completed", "failed"):
            return ProbeResult(skill_id, mode, True, time.monotonic() - start, f"terminal={state}")
        time.sleep(0.1)

    return ProbeResult(skill_id, mode, False, time.monotonic() - start, "no terminal transition (hang)")


def delegate(
    card: dict[str, Any],
    remote_send: callable,
    skill_id: str,
    mode: str,
    payload: Any,
    probe_timeout_s: float = 5.0,
) -> dict[str, Any]:
    skills = {s["id"]: s for s in card.get("skills", [])}
    skill = skills.get(skill_id)
    if skill is None:
        raise NonDelegableSkillError(f"skill {skill_id!r} not present in card")

    if mode not in skill.get("inputModes", []):
        raise NonDelegableSkillError(
            f"mode {mode!r} not advertised for skill {skill_id!r}; "
            f"advertised={skill.get('inputModes')}"
        )

    # Multi-mode or unexercised mode: probe before committing real work.
    if len(skill.get("inputModes", [])) > 1:
        probe = probe_skill(remote_send, skill_id, mode, timeout_s=probe_timeout_s)
        if not probe.transitioned:
            raise NonDelegableSkillError(
                f"probe for skill={skill_id!r} mode={mode!r} did not reach terminal state "
                f"within {probe_timeout_s}s ({probe.detail}); card is declarative, not contractual"
            )

    result = remote_send(skill_id=skill_id, mode=mode, payload=payload)

    # Output-mode honesty check: application/json must actually parse.
    if "application/json" in skill.get("outputModes", []):
        raw = result.get("artifacts", [{}])[0].get("parts", [{}])[0].get("text", "")
        try:
            json.loads(raw)
        except (TypeError, json.JSONDecodeError) as exc:
            raise NonDelegableSkillError(
                f"skill {skill_id!r} advertised application/json but returned non-JSON: {exc}"
            ) from exc

    return result


def _trivial_payload(mode: str) -> Any:
    return {"text/plain": "ping", "application/json": {"ping": True}}.get(mode, "ping")
