# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-a2a-task-before-its-capability-card-s-declared-schema-has-been-reconciled-with-the-caller-s-expected-artifact.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-a2a-task-before-its-capability-card-s-declared-schema-has-been-reconciled-with-the-caller-s-expected-artifact.warrant.json
# Markdown SHA-256:   cb311b5227d11f000639e92c2deba39a7e60faf70c929796eab850362fbe321c
# Code AST SHA-256:   2d4256f9dcc7f78024767a8742fb58d725663af469710e6dd13b0b07b5784e26
# Verified Classes:   SchemaMismatchError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from typing import Any


class SchemaMismatchError(RuntimeError):
    """Raised when a callee's declared output schema is not a structural
    subtype of the caller's bound artifact contract, at A2A admission time.
    Must fire BEFORE the callee transitions submitted -> working."""

    def __init__(self, caller_contract_id: str, callee_schema_id: str, divergences: list[str]):
        self.caller_contract_id = caller_contract_id
        self.callee_schema_id = callee_schema_id
        self.divergences = divergences
        super().__init__(
            f"output contract {caller_contract_id} incompatible with "
            f"callee schema {callee_schema_id}: {divergences}"
        )


def _schema_hash(schema: dict[str, Any]) -> str:
    canonical = json.dumps(schema, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode()).hexdigest()


def _structural_divergences(
    caller_contract: dict[str, Any], callee_schema: dict[str, Any]
) -> list[str]:
    """Minimal subtype check: every required field in the caller's contract
    must exist in the callee's schema with a compatible type."""
    out: list[str] = []
    caller_props = caller_contract.get("properties", {})
    callee_props = callee_schema.get("properties", {})
    for field, spec in caller_props.items():
        if field not in callee_props:
            out.append(f"missing field: {field}")
            continue
        if spec.get("type") != callee_props[field].get("type"):
            out.append(
                f"type mismatch on {field}: "
                f"caller={spec.get('type')} callee={callee_props[field].get('type')}"
            )
    return out


def admit_delegated_task(
    caller_contract: dict[str, Any],
    callee_capability_card: dict[str, Any],
    skill_id: str,
) -> str:
    """Gate called on the callee side before transitioning submitted -> working.
    Returns the task state to set ('working') or raises SchemaMismatchError."""
    skill = next(
        (s for s in callee_capability_card.get("skills", []) if s["id"] == skill_id),
        None,
    )
    if skill is None:
        raise SchemaMismatchError(
            caller_contract.get("$id", "<anon>"), "<absent>", [f"unknown skill {skill_id}"]
        )

    callee_schema = skill.get("outputSchema", {})
    if _schema_hash(caller_contract) == _schema_hash(callee_schema):
        return "working"

    divergences = _structural_divergences(caller_contract, callee_schema)
    if divergences:
        raise SchemaMismatchError(
            caller_contract.get("$id", "<anon>"),
            callee_schema.get("$id", "<anon>"),
            divergences,
        )
    return "working"
