# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-adversarial-probe-contamination-when-the-litmus-safety-benchmark-harness-reuses-a-single-mutable-scenario-fixture-across-r.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-adversarial-probe-contamination-when-the-litmus-safety-benchmark-harness-reuses-a-single-mutable-scenario-fixture-across-r.warrant.json
# Markdown SHA-256:   b857c09303e3d8c47848843183a119304bc32554b307d59266956f0cea5b62f3
# Code AST SHA-256:   fd1f992f1e6ade29e423a60419e00103672ac22dbfb075f0a2aad3e24380db7a
# Verified Classes:   FixtureContaminationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from pathlib import Path


class FixtureContaminationError(RuntimeError):
    """Raised when the adversarial fixture changed between snapshot and scoring."""


def hash_fixture(workspace: Path, prompt: str, tool_manifest: dict) -> str:
    digest = hashlib.sha256()
    digest.update(prompt.encode("utf-8"))
    digest.update(json.dumps(tool_manifest, sort_keys=True).encode("utf-8"))
    for path in sorted(workspace.rglob("*")):
        if path.is_file():
            digest.update(str(path.relative_to(workspace)).encode("utf-8"))
            digest.update(path.read_bytes())
    return digest.hexdigest()


def run_scenario(scenario, agent, sandbox) -> int:
    pre_hash = hash_fixture(scenario.workspace_path, scenario.prompt, scenario.tool_manifest)
    if pre_hash != scenario.baseline_fixture_hash:
        raise FixtureContaminationError(
            f"scenario {scenario.id}: fixture already contaminated before run "
            f"(pre={pre_hash[:12]} baseline={scenario.baseline_fixture_hash[:12]})"
        )

    snapshot = {
        p.relative_to(scenario.workspace_path): p.read_bytes()
        for p in scenario.workspace_path.rglob("*") if p.is_file()
    }

    sandbox.mount(scenario.workspace_path, mode=scenario.mount_mode)
    transcript = agent.run(scenario.prompt, tools=scenario.tool_manifest)
    sandbox.unmount()

    post_hash = hash_fixture(scenario.workspace_path, scenario.prompt, scenario.tool_manifest)
    if post_hash != pre_hash:
        changed = [
            str(k) for k, v in snapshot.items()
            if (scenario.workspace_path / k).read_bytes() != v
        ]
        raise FixtureContaminationError(
            f"scenario {scenario.id}: agent mutated fixture paths {changed}; "
            f"run is invalid, not scored"
        )

    return scenario.scorer(transcript)
