import subprocess,time,sys,json
from pathlib import Path
side,mode=sys.argv[1:3]
out=Path(__file__).parent/(side+'-'+mode+'-'+time.strftime('%Y%m%d-%H%M%S'));out.mkdir()
log=[]
def ad(*args):
 r=subprocess.run(['agent-device',*args,'--session','proof39562'],capture_output=True,text=True);log.append({'args':args,'output':r.stdout,'error':r.stderr,'code':r.returncode});(out/'driver-log.json').write_text(json.dumps(log,indent=2));print(r.stdout,r.stderr,flush=True)
 if r.returncode: raise RuntimeError(args)
 return r.stdout
def press(label):ad('press',label,'--settle')
# Start with the branch sheet open on the initiating thread.
ad('fill','text="feature/mobile-thread"','demo/'+mode,'--settle')
ad('back','--settle') # dismiss software keyboard
ad('record','start',str(out/'flow.mp4'),'--scope','device','--hide-touches')
ad('press','label="Create worktree"')
if mode!='focused':
 ad('press','label="Close"')
 if mode=='reopen':
  ad('press','label="Git controls"')
  ad('press','text="More"')
  ad('press','text="Branches & worktrees"')
time.sleep(13)
ad('snapshot','-i')
# Stable still: two identical frames separated by at least 500 ms.
for i in range(4):
 ad('screenshot',str(out/f'stable-{i}.png'))
 if i and (out/f'stable-{i}.png').read_bytes()==(out/f'stable-{i-1}.png').read_bytes():
  (out/'result.png').write_bytes((out/f'stable-{i}.png').read_bytes());break
 time.sleep(.5)
ad('record','stop')
print('OUTPUT',out)
