# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-litmus-red-team-verdicts-as-non-transferable-across-prompt-revisions-and-why-does-verdict-caching-silently-in.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-litmus-red-team-verdicts-as-non-transferable-across-prompt-revisions-and-why-does-verdict-caching-silently-in.warrant.json
# Markdown SHA-256:   820c2c4886374cf0f9b8cf8dd4c448c365ec34028f1bcf02c6f83af15c706cd5
# Code AST SHA-256:   5bd23fb448cb24447e0d9f561adadb33a1abbb2577bbeb69ff99bbc9c989c306
# Verified Classes:   VerdictStateMismatch, AgentState, CachedVerdict
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class VerdictStateMismatch(RuntimeError):
    """Raised when a cached LITMUS verdict cannot be shown to apply to the current agent build."""
    pass


@dataclass(frozen=True)
class AgentState:
    system_prompt: str
    tool_schema: dict
    model_id: str
    model_version: str
    temperature: float
    top_p: float
    max_tokens: int
    retrieval_index_hash: str

    def fingerprint(self) -> str:
        payload = {
            "system_prompt": self.system_prompt,
            # canonicalize: sort keys, no whitespace, stable ordering
            "tool_schema": json.dumps(self.tool_schema, sort_keys=True, separators=(",", ":")),
            "model_id": self.model_id,
            "model_version": self.model_version,
            "temperature": self.temperature,
            "top_p": self.top_p,
            "max_tokens": self.max_tokens,
            "retrieval_index_hash": self.retrieval_index_hash,
        }
        blob = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()
        return hashlib.sha256(blob).hexdigest()


@dataclass(frozen=True)
class CachedVerdict:
    probe_id: str
    probe_hash: str
    state_fingerprint: str | None  # None => legacy verdict, unconditionally non-transferable
    trajectory_bound: bool
    passed: bool


def resolve_verdict(
    probe_id: str,
    probe_hash: str,
    current: AgentState,
    cache: dict[tuple[str, str], CachedVerdict],
) -> CachedVerdict:
    """
    Return a verdict safe to gate CI on, or raise if the cache cannot support one.
    """
    cached = cache.get((probe_id, probe_hash))

    if cached is None:
        raise VerdictStateMismatch(
            f"no cached verdict for probe {probe_id}; must execute against "
            f"state {current.fingerprint()[:12]}"
        )

    if cached.trajectory_bound:
        raise VerdictStateMismatch(
            f"probe {probe_id} is trajectory-bound; per-probe caching is invalid "
            f"regardless of state fingerprint — re-execute the full multi-turn trajectory"
        )

    if cached.state_fingerprint is None:
        raise VerdictStateMismatch(
            f"probe {probe_id} verdict has no state fingerprint (legacy cache entry); "
            f"treat as UNVERIFIED, not PASS"
        )

    current_fp = current.fingerprint()
    if cached.state_fingerprint != current_fp:
        raise VerdictStateMismatch(
            f"probe {probe_id} verdict was measured against state "
            f"{cached.state_fingerprint[:12]}, current build is {current_fp[:12]}; "
            f"re-execute before gating"
        )

    return cached
