#!/usr/bin/env python3
import sys, subprocess, json, time, pathlib, datetime, re
ROOT=pathlib.Path('/tmp/lead-29075-r1/recapture-android')
session,run,action,*args=sys.argv[1:]
out=ROOT/run
out.mkdir(parents=True,exist_ok=True)
def ad(*cmd):
 start=time.time(); p=subprocess.run(['agent-device',*cmd,'--session',session],text=True,capture_output=True)
 with (out/'driver.jsonl').open('a') as f:f.write(json.dumps({'utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'command':['agent-device',*cmd,'--session',session],'seconds':time.time()-start,'status':p.returncode,'stdout':re.sub(r'/home/ubuntu/\.(?:simlock|agent-device)/[^\s]+','[device-session-local-path]',p.stdout),'stderr':re.sub(r'/home/ubuntu/\.(?:simlock|agent-device)/[^\s]+','[device-session-local-path]',p.stderr)})+'\n')
 print(p.stdout,end='');print(p.stderr,end='',file=sys.stderr)
 if p.returncode:raise SystemExit(p.returncode)
 return p.stdout
if action=='still':
 name=args[0]
 for attempt in range(5):
  ad('screenshot',str(out/f'{name}-settle-a.png'),'--no-stabilize')
  time.sleep(.5)
  ad('screenshot',str(out/f'{name}.png'),'--no-stabilize')
  p=subprocess.run(['compare','-metric','AE',str(out/f'{name}-settle-a.png'),str(out/f'{name}.png'),'null:'],capture_output=True,text=True)
  with (out/'settled.jsonl').open('a') as f:f.write(json.dumps({'name':name,'attempt':attempt,'AE':p.stderr})+'\n')
  if p.returncode==0:print('PIXEL IDENTICAL');break
 else:raise SystemExit('did not settle')
elif action=='record-start':
 target=__import__('os').environ.get('CDP_TARGET')
 if target:
  p=subprocess.run(['node',str(ROOT/'freeze-clock.mjs'),target],capture_output=True,text=True,check=True)
  (out/'clock-freeze.json').write_text(p.stdout)
 ad('record','start',str(out/(args[0]+'.mp4')),'--scope','device','--hide-touches')
elif action=='record-stop':
 try: ad('record','stop')
 except SystemExit: ad('record','stop')
else:ad(action,*args)
