# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-a-delegated-a2a-task-when-the-agent-card-s-declared-capabilities-streaming-and-defaultinputmodes-disagree-with-the-signe.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-a-delegated-a2a-task-when-the-agent-card-s-declared-capabilities-streaming-and-defaultinputmodes-disagree-with-the-signe.warrant.json
# Markdown SHA-256:   ffab4eea566c281bc8d27ace638958e5addda58dc07c0df30bd9dcb8ed891307
# Code AST SHA-256:   9b63995186e07d84532dd6a3dccb61f33bda83f1d745e4d4da82cb065871cc09
# Verified Classes:   OutputModeContractViolation
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class OutputModeContractViolation(RuntimeError):
    """Raised when a returned A2A artifact's mode escapes the verified card ∩ accepted intersection."""
    def __init__(self, task_id: str, returned_mode: str, card_hash: str, allowed: frozenset):
        self.task_id = task_id
        self.returned_mode = returned_mode
        self.card_hash = card_hash
        self.allowed = allowed
        super().__init__(
            f"task {task_id}: returned mode {returned_mode!r} not in "
            f"card∩accepted {sorted(allowed)} (card_hash={card_hash[:12]})"
        )


def ingest_artifact(task_id: str,
                    artifact_part: dict,
                    dispatch_card: dict,
                    dispatch_card_hash: str,
                    accepted_output_modes: frozenset) -> dict:
    # Reconstruct the intersection from the DISPATCH-TIME card, not a fresh fetch.
    card_modes = set(dispatch_card.get("defaultOutputModes", []))
    for skill in dispatch_card.get("skills", []):
        card_modes.update(skill.get("outputModes", []))
    allowed = frozenset(card_modes) & accepted_output_modes

    returned_mode = artifact_part.get("metadata", {}).get("mimeType") \
        or _kind_to_mode(artifact_part.get("kind"))

    if returned_mode not in allowed:
        # Hard boundary: never coerce, never fall back to text parsing.
        raise OutputModeContractViolation(
            task_id=task_id,
            returned_mode=returned_mode,
            card_hash=dispatch_card_hash,
            allowed=allowed,
        )
    return artifact_part


def _kind_to_mode(kind: str) -> str:
    return {"text": "text/plain", "file": "application/octet-stream",
            "data": "application/json"}.get(kind, f"unknown/{kind}")
