# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-an-a2a-v1-0-agent-card-as-a-stale-capability-claim-rather-than-a-live-contract-during-cross-vendor-delegation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-an-a2a-v1-0-agent-card-as-a-stale-capability-claim-rather-than-a-live-contract-during-cross-vendor-delegation.warrant.json
# Markdown SHA-256:   39073568bfeaaeadaab1decc816889065477f8c09fcf91467bebab8a3ea78370
# Code AST SHA-256:   597cda80429bf6fb3953fcd97e6a3d0e63f2090181f9df904700fe3db0c6779a
# Verified Classes:   ArtifactModalityMismatch, StaleCardQuarantine, AgentCard, TaskResponse
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

import json
from dataclasses import dataclass
from typing import Any


class ArtifactModalityMismatch(RuntimeError):
    """Raised when a remote agent returns an artifact whose type was not
    negotiated in acceptedOutputModes. This is a protocol violation, not a
    parse error: the card advertised one contract, the envelope delivered
    another, and the client must fail closed rather than coerce."""


class StaleCardQuarantine(RuntimeError):
    """Raised when a skill is quarantined due to a prior modality mismatch
    and the caller attempts to re-delegate before the quarantine TTL expires.
    Retrying against a lenient server reproduces the same substitution."""


@dataclass(frozen=True)
class AgentCard:
    name: str
    revision: str | None
    default_output_modes: tuple[str, ...]
    skills: tuple[dict[str, Any], ...]


@dataclass(frozen=True)
class TaskResponse:
    task_id: str
    state: str
    artifacts: tuple[dict[str, Any], ...]


def dispatch_artifacts(
    response: TaskResponse,
    accepted_output_modes: tuple[str, ...],
    skill_id: str,
    quarantine: dict[str, float],
    now: float,
    quarantine_ttl: float = 1800.0,
) -> list[dict[str, Any]]:
    """Parse artifacts by their declared type, never by the card.

    The card is consulted only for routing (see `should_delegate`), never
    for deserialization. A response artifact whose `type` is outside the
    negotiated set is a protocol violation and quarantines the skill.
    """
    if skill_id in quarantine and now < quarantine[skill_id]:
        raise StaleCardQuarantine(
            f"skill {skill_id!r} quarantined until {quarantine[skill_id]:.0f}; "
            f"remote previously substituted modality outside "
            f"{accepted_output_modes!r}"
        )

    parsed: list[dict[str, Any]] = []
    for artifact in response.artifacts:
        artifact_type = artifact.get("type")
        if artifact_type not in accepted_output_modes:
            quarantine[skill_id] = now + quarantine_ttl
            raise ArtifactModalityMismatch(
                f"skill {skill_id!r}: remote returned artifact type "
                f"{artifact_type!r} but accepted_output_modes was "
                f"{accepted_output_modes!r}; card is stale or server is "
                f"non-conformant. Quarantined for {quarantine_ttl:.0f}s."
            )
        if artifact_type == "application/json":
            raw = artifact.get("data")
            if isinstance(raw, str):
                # Some remotes wrap JSON in a text envelope; the envelope
                # check above already passed, so this is a schema concern,
                # not a modality concern. Surface it distinctly.
                try:
                    parsed.append(json.loads(raw))
                except json.JSONDecodeError as exc:
                    raise ArtifactModalityMismatch(
                        f"skill {skill_id!r}: artifact typed application/json "
                        f"but body is not parseable JSON: {exc}"
                    ) from exc
            else:
                parsed.append(raw)
        else:
            parsed.append({"type": artifact_type, "raw": artifact.get("data")})
    return parsed


def should_delegate(card: AgentCard, skill_id: str, input_mode: str) -> bool:
    """Routing-only use of the card. Staleness here wastes a round-trip;
    it cannot corrupt output because dispatch_artifacts re-checks the
    envelope. Returns False if the skill or input mode is absent."""
    for skill in card.skills:
        if skill.get("id") == skill_id:
            return input_mode in skill.get("inputModes", ())
    return False
