#!/usr/bin/env python3
"""Both human teams retain actual physical shooter pools through tied Quickgame OT.

All four distributions, P3/P4 input response, native attempt rotation and finish.
Only the tied clock and isolated winning-puck geometry are fixture writes.
"""
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor
import os,json,subprocess,hashlib,argparse
ap=argparse.ArgumentParser(description=__doc__);ap.add_argument('rom',type=Path);ap.add_argument('output',type=Path);ap.add_argument('--case',type=int,choices=range(4));ap.add_argument('--cpu-only',action='store_true');ap.add_argument('--allstar',action='store_true');a=ap.parse_args()
h=Path(__file__).resolve().parent;o=a.output.resolve();o.mkdir(parents=True,exist_ok=True)
has_allstar=a.rom.read_bytes()[0x22c000:0x22c002]!=b'\xff\xff'
left_inputs=['1100 press 1 Left 5']+(['1250 press 1 Left 5']if has_allstar and not a.allstar else [])
if a.allstar:assert has_allstar

def one(case):
 split,action=case;p=o/f'split{split}-{action}';p.mkdir(exist_ok=True);(p/'spec.json').write_text('{"captures":{}}\n');(p/'battery.srm').write_bytes(bytes(65536))
 lines=left_inputs+['1400 press 1 Down 5']+[f'{1550+150*i} press 1 Right 5'for i in range(split)]+['2300 press 1 Up 5']+[f'{2500+700*i} press 1 Start 5'for i in range(4)]+['25000 exit'];(p/'commands.txt').write_text('\n'.join(lines)+'\n')
 env={k:v for k,v in os.environ.items()if not k.startswith('GPGX_')};env.update(GPGX_DEV='1281',GPGX_DEV2='1281',GPGX_SRM=str(p/'battery.srm'),GPGX_HOOK=str(h/('testcases/quickgame_cpu_shootout_hook.py'if a.cpu_only else 'testcases/quickgame_shootout_hook.py')),QUICK_SPLIT=str(split),EXPECT_ALLSTAR=str(int(a.allstar)),QUICK_SO_ACTION=action)
 with(p/'log').open('w')as log:subprocess.run(['python3',str(h/'test_core.py'),str(a.rom.resolve()),str(p/'commands.txt'),str(p)],env=env,stdout=log,stderr=log,check=True,timeout=100)
 return json.loads((p/'result.json').read_text())
with ThreadPoolExecutor(max_workers=3)as pool:results=list(pool.map(one,[(split,action)for split in ([4]if a.cpu_only else range(4) if a.case is None else [a.case])for action in ['direction','shot']]))
(o/'results.json').write_text(json.dumps(dict(rom_sha256=hashlib.sha256(a.rom.read_bytes()).hexdigest(),scope=__doc__,cases=results),indent=2)+'\n');print('PASS',len(results),('human-vs-CPU OT direction/shot variants, autonomous CPU, P1 control and native wins'if a.cpu_only else 'human-vs-human OT direction/shot variants, actual pad inputs and native wins'))
