# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-s-replay-diverge-counterfactual-auditing-of-agentic-traces-under-opentelemetry-genai-schemas.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-s-replay-diverge-counterfactual-auditing-of-agentic-traces-under-opentelemetry-genai-schemas.warrant.json
# Markdown SHA-256:   254479c39fb64a9cebf5f56c23e85168f8d6bec682ceb796a99a97c90b55ca31
# Code AST SHA-256:   dc420dfe0790334a1d64cc26939e2796685ec15b7aee7da104cb048148f96f9f
# Verified Classes:   ReplayFidelityViolation, RequestFingerprint
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Any


class ReplayFidelityViolation(RuntimeError):
    """Raised when a trace cannot be replayed under the Replay Fidelity Invariant."""


@dataclass(frozen=True)
class RequestFingerprint:
    system_prompt: str
    tool_schemas: list[dict[str, Any]]
    messages: list[dict[str, Any]]
    sampling_params: dict[str, Any]
    model_snapshot: str

    def digest(self) -> str:
        canonical = json.dumps(
            {
                "system_prompt": self.system_prompt,
                "tool_schemas": self.tool_schemas,
                "messages": self.messages,
                "sampling_params": self.sampling_params,
                "model_snapshot": self.model_snapshot,
            },
            sort_keys=True,
            separators=(",", ":"),
        )
        return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


REQUIRED_SAMPLING_KEYS = ("temperature", "top_p", "seed", "max_tokens")


def reconstruct_fingerprint(span: dict[str, Any]) -> RequestFingerprint:
    """Rebuild the request tuple from a GenAI span. Fail closed on any gap."""
    attrs = span.get("attributes", {})
    sampling = {}

    for key in REQUIRED_SAMPLING_KEYS:
        otel_key = f"gen_ai.request.{key}"
        if otel_key not in attrs:
            raise ReplayFidelityViolation(
                f"span {span.get('span_id')!r} omits load-bearing sampling param "
                f"{otel_key!r}; replay would default it and silently re-sample"
            )
        sampling[key] = attrs[otel_key]

    if "gen_ai.request.model_snapshot" not in attrs:
        raise ReplayFidelityViolation(
            f"span {span.get('span_id')!r} names model alias "
            f"{attrs.get('gen_ai.request.model')!r} but not a pinned snapshot; "
            "provider may have rolled the alias, so divergence is uninterpretable"
        )

    events = span.get("events", [])
    messages = [e["attributes"] for e in events if e.get("name") == "gen_ai.content.prompt"]
    if not messages:
        raise ReplayFidelityViolation(
            f"span {span.get('span_id')!r} carries no prompt message events; "
            "cannot reconstruct request bytes"
        )

    for msg in messages:
        if msg.get("gen_ai.message.truncated") is True:
            raise ReplayFidelityViolation(
                f"span {span.get('span_id')!r} has a truncated message part; "
                "replay would branch on content the original run never lacked"
            )

    return RequestFingerprint(
        system_prompt=attrs.get("gen_ai.system_prompt", ""),
        tool_schemas=attrs.get("gen_ai.tool.definitions", []),
        messages=messages,
        sampling_params=sampling,
        model_snapshot=attrs["gen_ai.request.model_snapshot"],
    )


def admit_to_counterfactual_cohort(
    span: dict[str, Any], capture_digest: str
) -> RequestFingerprint:
    """Admit a trace to a counterfactual cohort only if fingerprints match."""
    fp = reconstruct_fingerprint(span)
    if fp.digest() != capture_digest:
        raise ReplayFidelityViolation(
            f"span {span.get('span_id')!r} replay fingerprint {fp.digest()[:12]} "
            f"!= capture fingerprint {capture_digest[:12]}; trace is a fresh "
            "sample under an unknown distribution, not a counterfactual sample"
        )
    return fp
