"""Validate a saved Jev risk decision and print a review packet. Never execute it."""
import hashlib
import json
import math
import sys
from pathlib import Path

LABELS = {"Read-only candidate", "Human review", "Blocked"}

def preview(sample):
    request, observed = sample["request"], sample["observed"]
    recorded_identity = hashlib.sha256(json.dumps(request, separators=(",", ":"), ensure_ascii=False).encode()).hexdigest()
    if observed.get("requestSha256") != recorded_identity:
        raise ValueError("Changed request requires a fresh observation")
    if set(request["choices"]) != LABELS or len(request["choices"]) != 3:
        raise ValueError("Unexpected risk labels")
    if not all(isinstance(request[k], str) and request[k].strip() for k in ["context", "question"]):
        raise ValueError("Missing action or policy")
    probabilities = observed["probabilities"]
    if set(probabilities) != LABELS:
        raise ValueError("Incomplete distribution")
    values = list(probabilities.values())
    if any(type(v) not in (int, float) or not math.isfinite(v) or not 0 <= v <= 1 for v in values) or not math.isclose(sum(values), 1, abs_tol=0.02):
        raise ValueError("Invalid probabilities")
    leaders = [label for label, value in probabilities.items() if value == max(values)]
    if observed["choice"] not in leaders:
        raise ValueError("Recorded choice is not a maximum")
    selected = leaders[0] if len(leaders) == 1 else None
    status = "blocked" if selected == "Blocked" else "human_review" if selected in (None, "Human review") else "permission_check_required"
    identity = hashlib.sha256(json.dumps(request, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()).hexdigest()
    return {"sample_id": sample["id"], "request_sha256": identity, "status": status,
            "model_label": selected, "permission_granted": False, "executed": False}

if __name__ == "__main__":
    if len(sys.argv) != 2:
        raise SystemExit("Usage: python preview-risk-review.py SAMPLE_ID")
    fixture = json.loads(Path(__file__).with_name("observed-risk.json").read_text(encoding="utf-8"))
    matches = [s for s in fixture["samples"] if s["id"] == sys.argv[1]]
    if len(matches) != 1:
        raise SystemExit("Select one existing sample ID")
    print(json.dumps(preview(matches[0]), indent=2, allow_nan=False))
