# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-freeze-its-harm-taxonomy-before-the-adversarial-multi-turn-trace-begins-rather-than-reclassifying-mid-episode.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-freeze-its-harm-taxonomy-before-the-adversarial-multi-turn-trace-begins-rather-than-reclassifying-mid-episode.warrant.json
# Markdown SHA-256:   f9d5b63c32f037853432b60bf6fc35f11823cd717a5217dd6d589d835095b39b
# Code AST SHA-256:   af5805169b5026d71f072826143dc7bba049a26b1794432bd70abe1ab87e1c06
# Verified Classes:   TaxonomyMutationError, FutureLeakageError, TaxonomySnapshot, TurnLabel, Episode
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class TaxonomyMutationError(RuntimeError):
    """Raised when a turn label is produced under a taxonomy snapshot
    that differs from the episode's pinned snapshot."""
    pass


class FutureLeakageError(RuntimeError):
    """Raised when a turn-k label's evidence depends on turns > k."""
    pass


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


@dataclass(frozen=True)
class TaxonomySnapshot:
    categories: dict          # category -> definition text
    severity_rubric: str
    judge_seed: int

    @property
    def snapshot_hash(self) -> str:
        payload = repr(sorted(self.categories.items())) + self.severity_rubric + str(self.judge_seed)
        return _hash(payload)


@dataclass
class TurnLabel:
    turn: int
    category: str
    severity: str
    evidence_span: str
    taxonomy_hash: str


@dataclass
class Episode:
    pinned: TaxonomySnapshot
    labels: list = field(default_factory=list)

    def record_label(self, label: TurnLabel, current_taxonomy: TaxonomySnapshot) -> None:
        # Guard 1: the taxonomy used to produce the label must equal the pinned one.
        if label.taxonomy_hash != self.pinned.snapshot_hash:
            raise TaxonomyMutationError(
                f"turn {label.turn}: label produced under taxonomy "
                f"{label.taxonomy_hash[:12]} but episode pinned "
                f"{self.pinned.snapshot_hash[:12]}"
            )
        # Guard 2: the taxonomy must not have drifted since pinning.
        if current_taxonomy.snapshot_hash != self.pinned.snapshot_hash:
            raise TaxonomyMutationError(
                f"turn {label.turn}: live taxonomy drifted mid-episode; "
                f"abort and restart under new snapshot"
            )
        # Guard 3: evidence span must entail the category under the pinned definition.
        definition = self.pinned.categories.get(label.category)
        if definition is None:
            raise TaxonomyMutationError(
                f"turn {label.turn}: category {label.category!r} absent from pinned taxonomy"
            )
        if not label.evidence_span.strip():
            raise FutureLeakageError(
                f"turn {label.turn}: empty evidence span cannot entail {label.category!r}"
            )
        self.labels.append(label)

    def score(self) -> dict:
        return {
            "turns": len(self.labels),
            "taxonomy_hash": self.pinned.snapshot_hash,
            "severity_counts": {
                s: sum(1 for l in self.labels if l.severity == s)
                for s in {l.severity for l in self.labels}
            },
        }
