# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-litmus-refusal-calibration-as-a-scoring-integrity-boundary-rather-than-a-policy-tuning-knob.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-litmus-refusal-calibration-as-a-scoring-integrity-boundary-rather-than-a-policy-tuning-knob.warrant.json
# Markdown SHA-256:   c18066298f9635f41cec55b4d77e0ac90f05be7b5478de6a2735de07e5b09c55
# Code AST SHA-256:   d3ac39fce398dc41d9a3d128dfaf8850710c0abf2e7af7c987d2b7af312d399f
# Verified Classes:   RefusalCalibrationError, Divergence, RefusalLabel
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum


class RefusalCalibrationError(RuntimeError):
    """Raised when a refusal label cannot be soundly bound to its context state."""


class Divergence(str, Enum):
    CONSISTENT = "consistent"
    DIVERGENT_IMMATERIAL = "divergent_immaterial"
    DIVERGENT_MATERIAL = "divergent_material"


@dataclass(frozen=True)
class RefusalLabel:
    trajectory_id: str
    refusal_step: int
    refusal_basis: str          # e.g. "tool_result:fetch_url:step9:span3"
    context_digest: str         # sha256 of pinned context at labeled step
    label: str                  # "REFUSE" | "PROCEED" | "PARTIAL"


def digest_context(pinned_context: str) -> str:
    return hashlib.sha256(pinned_context.encode("utf-8")).hexdigest()


def classify_replay(
    original: RefusalLabel,
    replayed_step: int,
    replayed_basis: str,
    replayed_digest: str,
) -> Divergence:
    if replayed_digest == original.context_digest:
        return Divergence.CONSISTENT
    if replayed_step != original.refusal_step:
        # Step moved: the labeled state no longer exists on replay.
        return Divergence.DIVERGENT_MATERIAL
    if replayed_basis != original.refusal_basis:
        # Same step, different cue: label valid as refusal, basis re-bucketed.
        return Divergence.DIVERGENT_IMMATERIAL
    return Divergence.DIVERGENT_MATERIAL


def admit_to_calibration(
    original: RefusalLabel, divergence: Divergence
) -> bool:
    """
    Returns True iff the label may enter the calibration set.
    Never relabels from replay; material divergence quarantines.
    """
    if divergence is Divergence.CONSISTENT:
        return True
    if divergence is Divergence.DIVERGENT_IMMATERIAL:
        # Admissible, but caller must re-bucket by refusal_basis.
        return True
    raise RefusalCalibrationError(
        f"trajectory {original.trajectory_id}: material replay divergence at "
        f"step {original.refusal_step}; label quarantined, not relabeled. "
        f"Basis={original.refusal_basis!r} digest={original.context_digest[:12]}"
    )


def derive_threshold(admitted_scores: list[float]) -> float:
    if not admitted_scores:
        raise RefusalCalibrationError(
            "no labels survived quarantine; threshold undefined"
        )
    return sum(admitted_scores) / len(admitted_scores)
