from pathlib import Path
import json,sys
p=Path(outdir); spec=json.loads(os.environ['FIXTURE']); steps=['Down']*9+['Right']*spec['difficulty']+['Up']*7
stage='keys';next_at=1400; started=None; attempts=0

def rw(a):return wram[ram(a)]*256+wram[ram(a+1)]
def rb(a):return wram[ram(a)]
def sw(a):v=rw(a);return v-65536 if v&32768 else v

def test_tick(f):
 global stage,next_at,started,attempts
 if f<next_at and stage!='start':return
 if stage=='keys':
  if steps:held[(0,IDS[steps.pop(0)])]=4;next_at=f+70;return
  stage='team'
 if stage=='team':
  if rw(0xd04c)!=spec['team']:held[(0,IDS['Right'])]=4;next_at=f+70;return
  steps.extend(['Down']*2);stage='periodkeys'
 if stage=='periodkeys':
  if steps:held[(0,IDS[steps.pop(0)])]=4;next_at=f+70;return
  stage='period'
 if stage=='period':
  if rw(0xd050)!=spec['period']:held[(0,IDS['Right'])]=4;next_at=f+70;return
  assert rw(0xf07a)==spec['difficulty'],('difficulty',rw(0xf07a),spec)
  print('MENU',spec,'home/away',rw(0xd04c),rw(0xd04e),'mode',rw(0xd048),'players',rw(0xd04a),flush=True)
  stage='start';next_at=f+120;return
 if stage=='start':
  live=rw(0xc468)>0 and rw(0xc466)<=3 and rw(0xc2e8)>8 and not rb(0xc2ec)&128
  if live and rw(0xc468)<[300,420,600,1200][spec['period']] and not rb(0xc2f2)&4:
   started=f;stage='settle';next_at=f+180;return
  if f<next_at:return
  held[(0,IDS['Start'])]=4;next_at=f+500;attempts+=1
  if attempts>15:raise AssertionError(('start timeout',rw(0xc468),rw(0xc2e8),rb(0xc2ec)))
  return
 if stage=='settle':
  if rb(0xc2ec)&128 or rb(0xc2ea)&17 or rb(0xc2f2)&4 or rw(0xc468)>[300,420,600,1200][spec['period']]-3:
   next_at=f+10;return
  n=core.retro_serialize_size();b=C.create_string_buffer(n);assert core.retro_serialize(b,n);(p/'base.st').write_bytes(b.raw)
  actors=[]
  for i in range(12):
   a=0xb04a+i*128;actors.append(dict(object=i,slot=rb(a+0x66),flags=rb(a+0x62),role=sw(a+0x34),x=sw(a),y=sw(a+0x14),ratings=bytes(rb(a+j) for j in range(0x66,0x76)).hex()))
  report=dict(spec=spec,frame=f,clock=rw(0xc468),home=rw(0xc330),away=rw(0xc332),difficulty=rw(0xf07a),period=rw(0xd050),actors=actors)
  (p/'fixture.json').write_text(json.dumps(report,indent=2));print(json.dumps(report),flush=True);sys.exit(0)
