# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-silently-truncated-artifact-in-a2a-v1-0-when-the-remote-agent-card-advertises-a-content-encoding-the-local-runtime-norma.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-silently-truncated-artifact-in-a2a-v1-0-when-the-remote-agent-card-advertises-a-content-encoding-the-local-runtime-norma.warrant.json
# Markdown SHA-256:   ee5bbaacaa3f0796b421d0130ba7767e81d9d0f89df85a1addcce8b8e3a5c206
# Code AST SHA-256:   5a39a62b4a237a9b6fa7304081749afd5a396c969b74246f15759cef995abb58
# Verified Classes:   ArtifactLayer, ArtifactVerificationError, ArtifactEnvelope
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum


class ArtifactLayer(Enum):
    WIRE = "wire"
    DECODED = "decoded"


class ArtifactVerificationError(RuntimeError):
    """Raised when an A2A artifact cannot be validated at the layer it was hashed at."""


@dataclass(frozen=True)
class ArtifactEnvelope:
    declared_byte_length: int      # length of the byte sequence the producer hashed
    declared_sha256: str
    hashed_layer: ArtifactLayer    # layer the producer computed the digest over
    content_encoding: str | None   # e.g. "gzip", or None for identity


def verify_artifact(envelope: ArtifactEnvelope,
                    payload: bytes,
                    payload_layer: ArtifactLayer) -> None:
    # Category error guard: never compare bytes from one layer against a digest
    # computed at another. This is the invariant that the naive length check missed.
    if payload_layer != envelope.hashed_layer:
        raise ArtifactVerificationError(
            f"layer mismatch: envelope hashed at {envelope.hashed_layer.value} "
            f"but consumer holds {payload_layer.value} bytes; "
            f"re-fetch with decode disabled or request identity encoding"
        )

    # Length check is only meaningful within the same layer.
    if len(payload) != envelope.declared_byte_length:
        raise ArtifactVerificationError(
            f"length mismatch at {payload_layer.value} layer: "
            f"declared {envelope.declared_byte_length}, got {len(payload)}"
        )

    actual = hashlib.sha256(payload).hexdigest()
    if actual != envelope.declared_sha256:
        raise ArtifactVerificationError(
            f"digest mismatch at {payload_layer.value} layer: "
            f"declared {envelope.declared_sha256}, got {actual}"
        )


def handle_incoming_artifact(envelope: ArtifactEnvelope,
                             raw_body: bytes,
                             transport_decoded: bool) -> str:
    # transport_decoded is True when the HTTP layer stripped Content-Encoding
    # before the artifact handler ran. The handler must not assume wire bytes.
    payload_layer = ArtifactLayer.DECODED if transport_decoded else ArtifactLayer.WIRE

    if transport_decoded and envelope.content_encoding not in (None, "identity"):
        # We cannot validate the producer's digest over bytes we never saw.
        # Do not transition to completed; block verification.
        raise ArtifactVerificationError(
            f"encoding_not_preserved: envelope content-encoding="
            f"{envelope.content_encoding!r} was decoded by transport; "
            f"cannot validate wire-layer digest"
        )

    verify_artifact(envelope, raw_body, payload_layer)
    return "completed"


# Replay of the observed 18422-byte gzip case:
if __name__ == "__main__":
    env = ArtifactEnvelope(
        declared_byte_length=18422,
        declared_sha256="9f3c" + "0" * 60,
        hashed_layer=ArtifactLayer.WIRE,
        content_encoding="gzip",
    )
    # Transport decoded the body to 61104 bytes before the handler ran.
    try:
        handle_incoming_artifact(env, b"x" * 61104, transport_decoded=True)
    except ArtifactVerificationError as e:
        print(f"verification-blocked: {e}")
