# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-litmus-safety-score-that-is-statistically-valid-but-operationally-stale-the-freshness-confidence-divergence-at-the-ci-c.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-litmus-safety-score-that-is-statistically-valid-but-operationally-stale-the-freshness-confidence-divergence-at-the-ci-c.warrant.json
# Markdown SHA-256:   1550f8f695c5f37dcf044ef0667ce8bed1da03eabe8e055f44c9cea728b3f79c
# Code AST SHA-256:   7e5ddd77e869792ed1e64a8471ec0910d9feff009a57eca42955bf35d1994c45
# Verified Classes:   StaleSafetyScoreError, SafetyScore, CandidateArtifact
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass


class StaleSafetyScoreError(RuntimeError):
    """Raised when a LITMUS-derived safety score cannot serve as a promotion predicate."""


@dataclass(frozen=True)
class SafetyScore:
    value: float
    ci_low: float
    ci_high: float
    corpus_hash: str
    agent_fingerprint: str
    computed_at: float  # unix seconds
    probe_vector_hash: str


@dataclass(frozen=True)
class CandidateArtifact:
    weights_hash: str
    prompt_hash: str
    tool_schema_hash: str
    retrieval_index_hash: str

    def fingerprint(self) -> str:
        h = hashlib.sha256()
        for part in (self.weights_hash, self.prompt_hash,
                     self.tool_schema_hash, self.retrieval_index_hash):
            h.update(part.encode())
            h.update(b"\x00")
        return h.hexdigest()


def evaluate_gate(
    score: SafetyScore,
    artifact: CandidateArtifact,
    expected_corpus_hash: str,
    ttl_seconds: float,
    threshold_ci_low: float,
    now: float | None = None,
) -> str:
    now = time.time() if now is None else now

    if score.corpus_hash != expected_corpus_hash:
        raise StaleSafetyScoreError(
            f"corpus mismatch: score={score.corpus_hash} expected={expected_corpus_hash}"
        )

    if artifact.fingerprint() != score.agent_fingerprint:
        # Artifact changed since scoring. Not a threshold problem -- a category error.
        if now - score.computed_at <= ttl_seconds:
            return "RESCORE"
        raise StaleSafetyScoreError(
            "agent fingerprint drift and scoring TTL exceeded; "
            "score describes a different artifact"
        )

    if now - score.computed_at > ttl_seconds:
        raise StaleSafetyScoreError(
            f"score age {now - score.computed_at:.0f}s exceeds TTL {ttl_seconds:.0f}s"
        )

    if score.ci_low < threshold_ci_low:
        raise StaleSafetyScoreError(
            f"ci_low {score.ci_low:.3f} below gate {threshold_ci_low:.3f}"
        )

    return "PROMOTE"
