#!/usr/bin/env python3
"""Replay the captured native keeper empty-net goal, pause, resume and real save.

The state is from immediately before an actual keeper goal in retained match2473.
No positions, scores, clocks, RNG or ownership are written. This is a regression
fixture, never credited as a fresh strength match.
"""
from pathlib import Path
import argparse, hashlib, json, os, shutil, subprocess

ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument('rom', type=Path)
ap.add_argument('output', type=Path)
ap.add_argument('--state', type=Path, required=True)
ap.add_argument('--seed', type=Path, required=True)
a = ap.parse_args()
h = Path(__file__).resolve().parent
o = a.output.resolve()
o.mkdir(parents=True, exist_ok=True)
shutil.copyfile(a.seed, o/'battery.srm')
(o/'commands.txt').write_text(f'1 load {a.state.resolve()}\n300 press 1 Start 5\n350 snap\n450 snap\n500 press 1 Start 5\n600 snap\n6000 exit\n')
env = {k:v for k,v in os.environ.items() if not k.startswith('GPGX_')}
env.update(GPGX_HOOK=str(h/'testcases/keeper_attack_gameplay_hook.py'),
           GPGX_SRM=str(o/'battery.srm'), CASE_DIR=str(o),
           FULL_CPU_HOOK=str(h/'testcases/full_cpu_hook.py'))
with (o/'log.txt').open('w') as log:
    subprocess.run(['python3', str(h/'test_core.py'), str(a.rom.resolve()), str(o/'commands.txt'), str(o)], env=env, stdout=log, stderr=log, check=True, timeout=120)
proof = json.loads((o/'saved-positive-proof.json').read_text())
events = json.loads((o/'events.json').read_text())
for f in (350, 450):
    row = next(x for x in events if x['frame'] == f and x.get('event') == 'pause-observation')
    assert row['key'][0] == 14 and row['key'][3] & 0x8000, ('actual native pause missing', row)
row = next(x for x in events if x['frame'] == 600 and x.get('event') == 'pause-observation')
assert not row['key'][3] & 0x8000, ('native resume missing', row)
assert proof['all32teams_valid'] and proof['saved'] == [1,1,0,0,13]
sha = lambda p: hashlib.sha256(p.read_bytes()).hexdigest()
(o/'results.json').write_text(json.dumps(dict(rom_sha256=sha(a.rom), state_sha256=sha(a.state), seed_sha256=sha(a.seed), actual_keeper_G_SOG=[1,1], saved_defensive_GA_SA=[0,13], native_pause_resume=True, all32_teams_skaters_keepers_league_checksum_valid=True, counters_survive_5998_observed_frames_and_foreign_highlights=True), indent=2)+'\n')
print('PASS actual native keeper goal/SOG, exact defensive save, all32-team accounting, visible pause/resume and highlight lifetime')
