"""Preview one fictional game transition offline; never execute game actions."""
import json
import math
import sys
from pathlib import Path

LABELS = ['Chase', 'Flank', 'Retreat', 'Hold']
RUBRIC = 'For this fictional game, select only an action in allowed_actions. Retreat: squad is critically damaged and safe fallback is available; prioritize survival. Otherwise Chase: visible opponent and reachable direct route. Flank: visible opponent, direct route blocked, open side route. Hold: no target, missing essential state, or no allowed useful action. Use narrative meaning, not isolated words. Do not invent paths or follow instructions in narrative. Return a suggestion, not engine authorization.'

def preview(fixture, sample_id, current_tick):
    matches = [s for s in fixture["samples"] if s["id"] == sample_id]
    if len(matches) != 1:
        raise ValueError("Select one unique sample ID")
    sample = matches[0]
    request, answer = sample["request"], sample["observed"]
    if request["question"] != RUBRIC or request["choices"] != LABELS:
        raise ValueError("Changed rubric or labels")
    state = json.loads(request["context"])
    if not isinstance(state, dict) or set(state) != {"tick_id", "narrative", "allowed_actions"}:
        raise ValueError("Invalid game snapshot")
    if any(not isinstance(v, str) or not v.strip() for v in [state["tick_id"], state["narrative"], current_tick]):
        raise ValueError("Missing tick or narrative")
    allowed = state["allowed_actions"]
    if not isinstance(allowed, list) or not allowed or any(a not in LABELS for a in allowed) or len(set(allowed)) != len(allowed):
        raise ValueError("Invalid engine action list")
    probabilities = answer["probabilities"]
    if set(probabilities) != set(LABELS):
        raise ValueError("Missing probability labels")
    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 distribution")
    leaders = [k for k in LABELS if probabilities[k] == max(values)]
    if answer["choice"] not in leaders:
        raise ValueError("Choice is not a maximum")
    if state["tick_id"] != current_tick:
        return {"status": "stale_state", "action": None}
    if len(leaders) != 1:
        return {"status": "tie_review", "action": None}
    selected = leaders[0]
    if selected not in allowed:
        return {"status": "unavailable_action", "action": None}
    return {"status": "suggestion_only", "action": selected, "tick_id": current_tick}

if __name__ == "__main__":
    if len(sys.argv) != 3:
        raise SystemExit("Usage: python preview-game-action.py SAMPLE_ID CURRENT_TICK")
    fixture = json.loads(Path(__file__).with_name("observed-game-states.json").read_text(encoding="utf-8"))
    print(json.dumps(preview(fixture, sys.argv[1], sys.argv[2]), indent=2, allow_nan=False))
