# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-survive-silent-artifact-schema-drift-during-a2a-v1-0-delegated-task-resumption.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-survive-silent-artifact-schema-drift-during-a2a-v1-0-delegated-task-resumption.warrant.json
# Markdown SHA-256:   85281ba3f88a53b3d93db92da3ab89322d040ef6c069ea480751a63d4b0fff72
# Code AST SHA-256:   cdfbc8beea5270351f543fcb3a933ed60a0458578d05775bb9ab2038455a4f7b
# Verified Classes:   ArtifactSchemaDriftError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from typing import Any


class ArtifactSchemaDriftError(RuntimeError):
    """Raised when a resumed A2A artifact violates its delegation-time contract."""


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


def validate_resumed_artifact(
    artifact: dict[str, Any],
    pinned_schema: dict[str, Any],
    interrupted: bool,
) -> None:
    if not interrupted:
        # Same-session completion: no drift window, trust the artifact.
        return

    # Required keys must be present exactly as pinned. A missing key after an
    # interruption boundary is a schema-drift signal, never a default-to-empty.
    required = pinned_schema.get("required", [])
    missing = [k for k in required if k not in artifact]
    if missing:
        raise ArtifactSchemaDriftError(
            f"resumed artifact missing required keys {missing}; "
            f"pinned schema digest {_digest(pinned_schema)[:12]}"
        )

    # If the server echoes a schema_version, it must match the pinned one.
    pinned_version = pinned_schema.get("schema_version")
    if pinned_version is not None:
        observed = artifact.get("schema_version")
        if observed != pinned_version:
            raise ArtifactSchemaDriftError(
                f"schema_version drift: pinned {pinned_version}, observed {observed}"
            )

    # Type-shape check on top-level fields guards against silent restructures
    # (e.g. {"entities": [...]} -> {"items": [...]}) that keep valid JSON.
    for key, expected_type in pinned_schema.get("types", {}).items():
        value = artifact.get(key)
        if not isinstance(value, _resolve(expected_type)):
            raise ArtifactSchemaDriftError(
                f"field {key!r} type drift: expected {expected_type}, "
                f"got {type(value).__name__}"
            )


def _resolve(name: str) -> type:
    return {"list": list, "dict": dict, "str": str, "float": float, "int": int}[name]
