from device import ROOT,run
import time,json,sys
from PIL import Image,ImageChops
import numpy as np
side,theme,row=sys.argv[1:4]
out=ROOT/f'{side}-{theme}-{row}-{time.time_ns()}';out.mkdir()
started=time.time();events=[]
def act(*args,check=True):
 start=time.time();p=run(*args,check=check)
 events.append(dict(seconds=round(start-started,3),duration=round(time.time()-start,3),command=list(map(str,args)),code=p.returncode));(out/'steps.json').write_text(json.dumps(events,indent=2));print(args[:3],p.returncode,flush=True);return p

def still(name):
 for attempt in range(3 if name=='first-open' else 1):
  a=out/f'{name}-{attempt}-a.png';b=out/f'{name}-{attempt}-b.png'
  act('screenshot',a,'--normalize-status-bar');time.sleep(1);act('screenshot',b,'--normalize-status-bar')
  da=np.abs(np.asarray(Image.open(a).convert('RGB')).astype(int)-np.asarray(Image.open(b).convert('RGB')).astype(int));mask=da.max(2)>0
  ys,xs=np.where(mask);bbox=[int(xs.min()),int(ys.min()),int(xs.max()+1),int(ys.max()+1)] if len(xs) else None
  events.append(dict(checkpoint=name,attempt=attempt,bounds=bbox,pixels=int(mask.sum()),seconds=round(time.time()-started,3)))
  Image.open(b).save(out/f'{name}.png')
  if bbox is None:break
 (out/f'{name}.json').write_text(act('snapshot','--json').stdout)
 (out/'steps.json').write_text(json.dumps(events,indent=2));print('STILL',name,bbox,int(mask.sum()),flush=True)

trigger='Steer'if row=='A'else'Queue';action='Queue'if row=='A'else'Steer now'
act('record','start',out/f'{row}.mp4','--scope','device','--hide-touches');time.sleep(2)
try:
 act('longpress',f'label="{trigger}"',800);time.sleep(1);still('first-open')
 act('press',4,350);time.sleep(1)
 act('longpress',f'label="{trigger}"',800);time.sleep(1);still('reopen')
 if row=='B':
  for count in [3,4]:
   act('press',4,350);act('longpress',f'label="{trigger}"',800);time.sleep(1);still(f'open{count}')
  act('back');time.sleep(1);act('snapshot','--json')
  act('back');time.sleep(1)
  snap=json.loads(act('snapshot','--json').stdout);field=next(n for n in snap['data']['nodes']if n.get('editable'))
  act('press','@'+field['ref']);act('longpress',f'label="{trigger}"',800);time.sleep(1);still('open5')
 if row=='A':
  act('back');time.sleep(1);(out/'back-once.json').write_text(act('snapshot','--json').stdout)
  act('back');time.sleep(1);(out/'back-twice.json').write_text(act('snapshot','--json').stdout)
  # Return keyboard to the original focused composer before a third opening.
  act('press','label="Please keep waiting."',check=False)
  act('longpress',f'label="{trigger}"',800,check=False);time.sleep(1)
 p=act('press',f'text="{action}"',check=False);time.sleep(2)
 if row=='B'and p.returncode==0:act('wait','text','And a third line.',20000,check=False)
 still('selected')
finally:
 p=run('record','stop',check=False)
 if p.returncode:p=run('record','stop',check=False)
 (out/'record-export.json').write_text(p.stdout+p.stderr)
 (out/'steps.json').write_text(json.dumps(events,indent=2));print('OUTPUT',out,flush=True)
