# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-replay-divergence-when-otel-genai-spans-collapse-non-deterministic-sampling-into-a-single-chosen-trace.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-replay-divergence-when-otel-genai-spans-collapse-non-deterministic-sampling-into-a-single-chosen-trace.warrant.json
# Markdown SHA-256:   18c1b21681eed814318b56deb1c631f1adf4b4d50631827b5b04af6c8b150b3e
# Code AST SHA-256:   d1500bbf0e3826c4a3d13d535fad1cc8a77f300b9cd92739a1e59b9cf9fc6626
# Verified Classes:   TraceInsufficientError, DivergenceClassificationError, GenAISpan
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class TraceInsufficientError(RuntimeError):
    """Raised when a GenAI span cannot support deterministic replay."""


class DivergenceClassificationError(RuntimeError):
    """Raised when a divergence cannot be localized to sampler/transport/logic."""


@dataclass
class GenAISpan:
    prompt_parts: dict[int, str]          # index -> content
    temperature: float
    top_p: float
    seed: int | None
    completion: str
    tool_result_hashes: dict[str, str]    # tool_name -> sha256
    collector_attr_limit: int


def assert_replay_sufficient(span: GenAISpan, expected_part_count: int) -> None:
    # Clause 1: no gaps in prompt indices
    if sorted(span.prompt_parts) != list(range(expected_part_count)):
        raise TraceInsufficientError(
            f"prompt index gap: have {sorted(span.prompt_parts)}, "
            f"expected 0..{expected_part_count - 1}"
        )
    # Clause 2: no attribute truncated at collector limit
    for idx, content in span.prompt_parts.items():
        if len(content.encode("utf-8")) >= span.collector_attr_limit:
            raise TraceInsufficientError(
                f"prompt part {idx} length {len(content)} hits collector limit "
                f"{span.collector_attr_limit}; replay prompt is a prefix, not the original"
            )
    # Clause 3: stochastic spans must carry a seed
    if (span.temperature > 0.0 or span.top_p < 1.0) and span.seed is None:
        raise TraceInsufficientError(
            "stochastic sampling without recorded gen_ai.request.seed; "
            "replay verdict would be uninterpretable"
        )


def verify_tool_results(span: GenAISpan, live_results: dict[str, str]) -> None:
    for name, recorded_hash in span.tool_result_hashes.items():
        live = live_results.get(name)
        if live is None:
            raise DivergenceClassificationError(
                f"tool result {name} missing on replay; cannot distinguish "
                f"retrieval divergence from model divergence"
            )
        live_hash = hashlib.sha256(live.encode("utf-8")).hexdigest()
        if live_hash != recorded_hash:
            raise DivergenceClassificationError(
                f"tool result {name} hash mismatch: recorded {recorded_hash[:12]}, "
                f"live {live_hash[:12]} — retrieval-order divergence, not model drift"
            )


def replay_and_classify(span: GenAISpan, expected_part_count: int,
                        live_results: dict[str, str], model_call) -> str:
    assert_replay_sufficient(span, expected_part_count)
    verify_tool_results(span, live_results)
    reconstructed = "".join(span.prompt_parts[i] for i in range(expected_part_count))
    replayed = model_call(reconstructed, temperature=span.temperature,
                          top_p=span.top_p, seed=span.seed)
    return "MATCH" if replayed == span.completion else "DIVERGENT"
