# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-genai-spans-are-semantically-corrupt-when-the-opentelemetry-genai-conventions-permit-attribute-values-the-exp.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-genai-spans-are-semantically-corrupt-when-the-opentelemetry-genai-conventions-permit-attribute-values-the-exp.warrant.json
# Markdown SHA-256:   32d5abd5786e980f8767747585d616d4d508cc050ee3798832f7085f4e670ea2
# Code AST SHA-256:   973eb2bd6c3af8a652e0c63a42c533139c92094443252e345c5eda522407715a
# Verified Classes:   GenAISpanSemanticCorruption, SpanReceipt
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class GenAISpanSemanticCorruption(RuntimeError):
    """Raised when a GenAI span's surviving attributes do not match the
    length/hash invariants recorded at emission time."""
    pass


@dataclass
class SpanReceipt:
    span_id: str
    prompt_len: int
    prompt_hash: str
    completion_len: int
    completion_hash: str
    input_tokens: int
    output_tokens: int


def emit_with_receipt(span, prompt: str, completion: str,
                      input_tokens: int, output_tokens: int) -> SpanReceipt:
    # Emit content plus a length/hash sidecar the collector cannot reorder away
    # because it lives in a single attribute the agent controls.
    span.set_attribute("gen_ai.prompt.0.content", prompt)
    span.set_attribute("gen_ai.completion.0.content", completion)
    span.set_attribute("gen_ai.usage.input_tokens", int(input_tokens))
    span.set_attribute("gen_ai.usage.output_tokens", int(output_tokens))
    span.set_attribute("agent.prompt.len", len(prompt))
    span.set_attribute("agent.prompt.sha256", hashlib.sha256(prompt.encode()).hexdigest())
    span.set_attribute("agent.completion.len", len(completion))
    span.set_attribute("agent.completion.sha256", hashlib.sha256(completion.encode()).hexdigest())
    span.end()
    return SpanReceipt(
        span_id=span.get_span_context().span_id,
        prompt_len=len(prompt),
        prompt_hash=hashlib.sha256(prompt.encode()).hexdigest(),
        completion_len=len(completion),
        completion_hash=hashlib.sha256(completion.encode()).hexdigest(),
        input_tokens=int(input_tokens),
        output_tokens=int(output_tokens),
    )


def verify_readback(span_attrs: dict, receipt: SpanReceipt) -> None:
    """Called before distilling a span into episodic memory. Refuses to
    distill a span whose surviving content violates its own receipt."""
    prompt = span_attrs.get("gen_ai.prompt.0.content", "")
    completion = span_attrs.get("gen_ai.completion.0.content", "")

    if len(prompt) != receipt.prompt_len:
        raise GenAISpanSemanticCorruption(
            f"span {receipt.span_id}: prompt truncated "
            f"({len(prompt)} != {receipt.prompt_len}) — refusing to distill"
        )
    if hashlib.sha256(prompt.encode()).hexdigest() != receipt.prompt_hash:
        raise GenAISpanSemanticCorruption(
            f"span {receipt.span_id}: prompt hash mismatch — collector reordered or mutated content"
        )
    if len(completion) != receipt.completion_len:
        raise GenAISpanSemanticCorruption(
            f"span {receipt.span_id}: completion dropped or truncated "
            f"({len(completion)} != {receipt.completion_len}) — turn would be misread as no-op"
        )
    in_tok = span_attrs.get("gen_ai.usage.input_tokens")
    if not isinstance(in_tok, int):
        raise GenAISpanSemanticCorruption(
            f"span {receipt.span_id}: input_tokens not an int ({type(in_tok).__name__}) — "
            f"budget accounting will undercount"
        )
    if in_tok != receipt.input_tokens:
        raise GenAISpanSemanticCorruption(
            f"span {receipt.span_id}: input_tokens drifted ({in_tok} != {receipt.input_tokens})"
        )
