# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-opentelemetry-genai-span-attributes-as-lossy-evidence-rather-than-ground-truth-during-tool-call-replay.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-opentelemetry-genai-span-attributes-as-lossy-evidence-rather-than-ground-truth-during-tool-call-replay.warrant.json
# Markdown SHA-256:   6f558eff8303b0a7b49f912fdc3678a3fe38c40343082242b578cda2b1b458f3
# Code AST SHA-256:   9475eff64e5a04c94f13148058faa6dbf21c447c3d45d81c3655157757dd6237
# Verified Classes:   SpanFidelityError
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import json
from typing import Any


class SpanFidelityError(RuntimeError):
    """Raised when a GenAI tool-call span cannot be treated as replay ground truth."""
    pass


def load_replayable_arguments(span_attributes: dict[str, Any]) -> dict[str, Any]:
    """
    Extract tool-call arguments from a gen_ai.tool.call span for replay.

    Enforces the replay-eligibility invariant: a span is replayable only if
    the recorded arguments parse, carry a matching digest, and are not marked
    as truncated or redacted. Any ambiguity raises SpanFidelityError rather
    than silently reconstructing a call that may not have happened.
    """
    raw = span_attributes.get("gen_ai.tool.call.arguments")
    digest = span_attributes.get("gen_ai.tool.call.arguments.digest")
    truncated = span_attributes.get("gen_ai.tool.call.arguments.truncated", False)
    redacted = span_attributes.get("gen_ai.tool.call.arguments.redacted", False)

    if raw is None:
        raise SpanFidelityError(
            "arguments attribute absent; cannot distinguish never-recorded "
            "from redaction-removed. Span is non-replayable."
        )

    if truncated:
        raise SpanFidelityError(
            "arguments marked truncated by pipeline; recorded value is a "
            "prefix, not the invoked payload."
        )

    if redacted:
        raise SpanFidelityError(
            "arguments marked redacted by emitter; replay would target a "
            "substituted payload, not the original."
        )

    try:
        parsed = json.loads(raw)
    except json.JSONDecodeError as exc:
        raise SpanFidelityError(
            f"arguments fail canonical parse ({exc}); treating as "
            f"non-replayable rather than absent."
        ) from exc

    if digest is None:
        raise SpanFidelityError(
            "no arguments digest recorded; consumer cannot prove recorded "
            "payload matches invoked payload."
        )

    canonical = json.dumps(parsed, sort_keys=True, separators=(",", ":")).encode()
    actual = hashlib.sha256(canonical).hexdigest()
    if actual != digest:
        raise SpanFidelityError(
            f"digest mismatch: recorded={digest} recomputed={actual}; "
            f"payload mutated in transport or mid-stream."
        )

    return parsed
