# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-the-litmus-benchmark-s-adversarial-item-pool-before-it-can-serve-as-a-regression-gate.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-the-litmus-benchmark-s-adversarial-item-pool-before-it-can-serve-as-a-regression-gate.warrant.json
# Markdown SHA-256:   f140b31d2e0575070f87c796a174a66898d1d62f74286ba1e38063605ed39a3a
# Code AST SHA-256:   bf821a16b69528e82c7ef647345430b99472ef4a65f8f7694f953e18c3bd26b6
# Verified Classes:   GateInvalidError, GateVerdict, LitmusGate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class GateInvalidError(RuntimeError):
    """Raised when a LITMUS regression gate is asked to compare across unpinned pools."""


def pool_hash(items: list[dict]) -> str:
    payload = json.dumps(sorted(items, key=lambda x: x["id"]), sort_keys=True)
    return hashlib.sha256(payload.encode()).hexdigest()


@dataclass
class GateVerdict:
    status: str  # "pass" | "fail" | "gate-invalid"
    candidate_score: float
    baseline_score: float
    pool_hash: str
    reason: str = ""


@dataclass
class LitmusGate:
    tolerance: float = 2.0
    version: str = "v0"
    gating_pool: list[dict] = field(default_factory=list)
    baseline_pool_hash: Optional[str] = None
    baseline_score: Optional[float] = None
    shadow_pool: list[dict] = field(default_factory=list)

    def _current_hash(self) -> str:
        return pool_hash(self.gating_pool)

    def establish_baseline(self, score: float) -> None:
        """Must be called at every version boundary after re-scoring the prior release."""
        self.baseline_pool_hash = self._current_hash()
        self.baseline_score = score

    def promote_shadow(self, item: dict, discriminating: bool) -> None:
        if not discriminating:
            return  # stays in shadow; never contaminates the gate
        self.shadow_pool.append(item)

    def bump_version(self, new_version: str, promoted_items: list[dict]) -> None:
        """Version boundary: absorb promoted items, then require baseline re-establishment."""
        if not promoted_items:
            self.version = new_version
            return
        self.gating_pool.extend(promoted_items)
        self.version = new_version
        # Invalidate baseline; caller MUST re-score prior release and call establish_baseline.
        self.baseline_pool_hash = None
        self.baseline_score = None

    def evaluate(self, candidate_score: float) -> GateVerdict:
        cur = self._current_hash()
        if self.baseline_pool_hash is None or self.baseline_score is None:
            raise GateInvalidError(
                f"version {self.version}: no baseline established for pool {cur[:12]}; "
                "re-score prior release on this pool before gating"
            )
        if cur != self.baseline_pool_hash:
            raise GateInvalidError(
                f"version {self.version}: pool hash {cur[:12]} != baseline "
                f"{self.baseline_pool_hash[:12]}; comparison crosses an unpinned pool"
            )
        delta = candidate_score - self.baseline_score
        if delta < -self.tolerance:
            return GateVerdict("fail", candidate_score, self.baseline_score, cur,
                               f"delta {delta:+.2f} below -{self.tolerance}")
        return GateVerdict("pass", candidate_score, self.baseline_score, cur,
                           f"delta {delta:+.2f} within tolerance")
