# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-an-a2a-v1-0-artifact-whose-mediatype-it-can-parse-but-whose-declared-parts-mimetype-semantics-diverge-fr.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-an-a2a-v1-0-artifact-whose-mediatype-it-can-parse-but-whose-declared-parts-mimetype-semantics-diverge-fr.warrant.json
# Markdown SHA-256:   eed14c50b703453e40e85a3046383fd5acebf9be44b2f084587c53a0f38b701a
# Code AST SHA-256:   6ae8aff818d03b5d2c54a355c816eb7e15a04079ac2cd7064fb9f2d94c304d55
# Verified Classes:   ArtifactProfileDivergence, HistoryTupleMutation, ArtifactPart, Artifact, Runtime
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Literal, Optional


class ArtifactProfileDivergence(RuntimeError):
    """Raised when an A2A artifact is parseable but its declared mimeType
    profile cannot be honored by this runtime without silent substitution."""


class HistoryTupleMutation(RuntimeError):
    """Raised when re-emission or checkpointing would mutate the
    (artifactId, mimeType, contentHash) identity tuple of a stored artifact."""


@dataclass(frozen=True)
class ArtifactPart:
    mime_type: str          # full mimeType incl. profile parameter
    payload: bytes


@dataclass(frozen=True)
class Artifact:
    artifact_id: str
    media_type: str         # base type only, e.g. application/json
    parts: tuple[ArtifactPart, ...]

    def identity_tuple(self) -> tuple[str, str, str]:
        h = hashlib.sha256()
        for p in self.parts:
            h.update(p.mime_type.encode())
            h.update(b"\x00")
            h.update(p.payload)
        return (self.artifact_id, self.parts[0].mime_type, h.hexdigest())


@dataclass
class Runtime:
    name: str
    registered_profiles: dict[str, str] = field(default_factory=dict)  # profile -> validator_id
    profile_preservation: Literal["strict", "normalizing", "none"] = "strict"
    accept_unverified: bool = False


def _resolve_profile(mime_type: str, payload: bytes) -> Optional[str]:
    # profile parameter wins; fall back to self-describing $schema
    for param in mime_type.split(";")[1:]:
        k, _, v = param.strip().partition("=")
        if k == "profile":
            return v.strip('"')
    try:
        doc = json.loads(payload)
    except Exception:
        return None
    return doc.get("$schema")


def ingest_artifact(rt: Runtime, art: Artifact) -> dict:
    """Type-identity gate. Returns an admission record or raises."""
    part = art.parts[0]
    profile = _resolve_profile(part.mime_type, part.payload)

    if profile is None:
        # no profile claim: base-type only, admissible under base validator
        return {"state": "accepted", "profile": None,
                "validator": rt.registered_profiles.get(art.media_type)}

    validator = rt.registered_profiles.get(profile)
    if validator is None:
        if not rt.accept_unverified:
            raise ArtifactProfileDivergence(
                f"runtime={rt.name} cannot honor profile={profile!r} on "
                f"artifact={art.artifact_id}; no validator registered and "
                f"acceptUnverified=false. Quarantine, do not substitute base validator."
            )
        return {"state": "quarantined", "profile": profile,
                "validator": None, "verification": "unresolved"}

    if rt.profile_preservation != "strict":
        raise ArtifactProfileDivergence(
            f"runtime={rt.name} declares profilePreservation={rt.profile_preservation!r}; "
            f"accepting profiled artifact={art.artifact_id} would risk silent "
            f"normalization on re-emission. Refuse or negotiate strict peer."
        )

    return {"state": "accepted", "profile": profile, "validator": validator}


def reemit_artifact(rt: Runtime, art: Artifact, prior: Artifact) -> Artifact:
    """Forwarding/checkpoint path. Must preserve identity tuple or refuse."""
    if art.identity_tuple() != prior.identity_tuple():
        raise HistoryTupleMutation(
            f"re-emission of artifact={art.artifact_id} mutated identity tuple: "
            f"{prior.identity_tuple()} -> {art.identity_tuple()}"
        )
    if rt.profile_preservation != "strict" and "profile=" in art.parts[0].mime_type:
        raise ArtifactProfileDivergence(
            f"runtime={rt.name} cannot re-emit profiled artifact={art.artifact_id} "
            f"under profilePreservation={rt.profile_preservation!r} without stripping "
            f"the profile parameter."
        )
    return art
