# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-delegated-task-whose-a2a-agent-card-advertises-a-capability-that-the-remote-agent-s-json-rpc-tasks-sen.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-delegated-task-whose-a2a-agent-card-advertises-a-capability-that-the-remote-agent-s-json-rpc-tasks-sen.warrant.json
# Markdown SHA-256:   392392eef7fa66c6f44a817e8754f3f5eb62f8f27795a7708b930b9c43a0487e
# Code AST SHA-256:   dbc3db008493ac37122054ec314e8210919ac34524d843ae05db5ea8916e1496
# Verified Classes:   AgentCardDriftError
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import json
from typing import Any

import jsonschema


class AgentCardDriftError(RuntimeError):
    """Raised when a remote A2A agent's completed task violates the
    output-mode contract advertised in its Agent Card."""


def commit_delegated_task(
    card: dict[str, Any],
    task_response: dict[str, Any],
    accepted_output_modes: list[str],
    schemas_by_mode: dict[str, dict[str, Any]],
) -> dict[str, Any]:
    state = task_response.get("status", {}).get("state")
    if state != "completed":
        return task_response  # failed / working / input-required: not our boundary

    artifacts = task_response.get("artifacts") or []
    if not artifacts:
        raise AgentCardDriftError(
            f"task {task_response.get('id')} completed with no artifacts "
            f"despite card declaring outputModes {card.get('defaultOutputModes')}"
        )

    validated: list[dict[str, Any]] = []
    for art in artifacts:
        for part in art.get("parts", []):
            ptype = part.get("type")
            if ptype == "text" and any(
                m != "text/plain" for m in accepted_output_modes
            ):
                raise AgentCardDriftError(
                    f"skill {card.get('name')} returned TextPart but client "
                    f"accepted {accepted_output_modes}; card-handler drift"
                )
            if ptype != "data":
                continue
            mode = art.get("mimeType") or card.get("defaultOutputModes", [None])[0]
            if mode not in accepted_output_modes:
                raise AgentCardDriftError(
                    f"artifact mode {mode!r} not in accepted {accepted_output_modes}"
                )
            schema = schemas_by_mode.get(mode)
            if schema is None:
                raise AgentCardDriftError(
                    f"no validator bound for declared mode {mode!r}; "
                    f"cannot certify card contract"
                )
            try:
                jsonschema.validate(part["data"], schema)
            except jsonschema.ValidationError as exc:
                raise AgentCardDriftError(
                    f"artifact for mode {mode!r} failed schema at {exc.json_path}: "
                    f"{exc.message}"
                ) from exc
            validated.append(part["data"])

    if not validated:
        raise AgentCardDriftError(
            f"task {task_response.get('id')} completed with zero schema-validated "
            f"data artifacts; refusing to commit"
        )
    task_response["_validated_artifacts"] = validated
    task_response["_committed"] = True
    return task_response
