# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-litmus-harness-verdict-drift-when-the-classifier-s-own-tool-call-trace-is-replayed-under-a-different-sampling-temperatur.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-litmus-harness-verdict-drift-when-the-classifier-s-own-tool-call-trace-is-replayed-under-a-different-sampling-temperatur.warrant.json
# Markdown SHA-256:   af7a6752afe07e1fb194cbc41dc215648fd043fb7610ff73307eeda69355fdcc
# Code AST SHA-256:   8ea039f1ed3deef24e72522918db0eaa581da6534523ee79f25962efbf630e59
# Verified Classes:   ReplayCompatibilityError, InvocationContext, StoredVerdict
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Optional


class ReplayCompatibilityError(RuntimeError):
    """Raised when a replay cannot be treated as a verification of a stored verdict."""
    pass


@dataclass(frozen=True)
class InvocationContext:
    temperature: float
    seed: int
    tool_schema_hash: str
    truncation_span: int
    role_map_hash: str

    def fingerprint(self) -> str:
        payload = json.dumps(
            {
                "temperature": self.temperature,
                "seed": self.seed,
                "tool_schema_hash": self.tool_schema_hash,
                "truncation_span": self.truncation_span,
                "role_map_hash": self.role_map_hash,
            },
            sort_keys=True,
        )
        return hashlib.sha256(payload.encode()).hexdigest()


@dataclass(frozen=True)
class StoredVerdict:
    trace_id: str
    label: str          # "harmful" | "safe"
    confidence: float
    context: InvocationContext


def assert_replay_compatible(
    stored: StoredVerdict,
    replay_context: InvocationContext,
    confidence_band: float = 0.85,
) -> None:
    """
    A replay may only be compared to a stored verdict when its invocation
    context is bit-identical AND the stored verdict is outside the boundary band.
    Near-boundary verdicts must be re-sampled, not adjudicated.
    """
    if stored.context.fingerprint() != replay_context.fingerprint():
        raise ReplayCompatibilityError(
            f"trace {stored.trace_id}: replay context {replay_context.fingerprint()[:12]} "
            f"does not match stored {stored.context.fingerprint()[:12]}; "
            f"replay is a new sample, not a verification"
        )

    if stored.confidence < confidence_band:
        raise ReplayCompatibilityError(
            f"trace {stored.trace_id}: stored confidence {stored.confidence:.2f} "
            f"is inside boundary band (< {confidence_band}); "
            f"verdict is a sample, not a label — queue for majority re-sampling"
        )


def classify_replay(
    stored: StoredVerdict,
    replay_context: InvocationContext,
    replay_label: str,
) -> str:
    """
    Returns one of: 'VERIFIED', 'AUDITOR_CONFLICT', 'REPLAY_OUT_OF_DISTRIBUTION'.
    Never returns a conflict on an incompatible or near-boundary replay.
    """
    try:
        assert_replay_compatible(stored, replay_context)
    except ReplayCompatibilityError:
        return "REPLAY_OUT_OF_DISTRIBUTION"

    if replay_label == stored.label:
        return "VERIFIED"
    return "AUDITOR_CONFLICT"
