import subprocess,time,sys,json,datetime
from pathlib import Path
from PIL import Image,ImageChops
BASE=Path(__file__).parent;ROOT=Path((BASE/'active-run.txt').read_text());CWD='/home/ubuntu/wt/pr-27671';SESSION='lead27671-capture'
def run(*args):
 args=tuple(map(str,args))
 for attempt in range(2):
  start=time.time();p=subprocess.run(['agent-device',*args,'--session',SESSION,'--json'],cwd=CWD,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
  with (ROOT/'commands.jsonl').open('a') as f:f.write(json.dumps({'utc':datetime.datetime.fromtimestamp(start,datetime.timezone.utc).isoformat(),'args':args,'attempt':attempt+1,'seconds':time.time()-start,'rc':p.returncode,'output':p.stdout})+'\n')
  print(p.stdout,flush=True)
  if not p.returncode:return p.stdout
  if attempt==0 and args[0] in ['wait','screenshot','snapshot','open'] and any(x in p.stdout for x in ['Remote daemon is unavailable','Failed to communicate with daemon']):
   print('Pool transport failed; retrying this command once after 60 seconds.',flush=True);time.sleep(60);continue
  raise RuntimeError(args)

def still(name):
 run('wait','stable',1000,15000)
 for trial in range(5):
  a=ROOT/(name+f'-{trial}-a.png');b=ROOT/(name+f'-{trial}-b.png')
  run('screenshot',a);time.sleep(.5);run('screenshot',b)
  if ImageChops.difference(Image.open(a).convert('RGB'),Image.open(b).convert('RGB')).getbbox() is None:
   (ROOT/(name+'.png')).write_bytes(b.read_bytes());return
 raise RuntimeError('Frames not identical: '+name)

if __name__=='__main__':
 action=sys.argv[1]
 if action=='still':still(sys.argv[2])
 if action=='flick':
  row,side=sys.argv[2:4];x,y,dx,dy,duration=map(int,sys.argv[4:9]);still(row+'-'+side+'-initial')
  run('record','start',ROOT/(row+'-'+side+'.mp4'),'--fps',30)
  run('wait',1000);run('gesture','pan',x,y,dx,dy,duration);run('wait',8000);run('record','stop');still(row+'-'+side+'-settled')
 if action=='route':
  routes=json.loads((BASE/'routes.json').read_text());run('open','com.t3tools.t3code.dev',routes[sys.argv[2]]);run('wait','stable',1000,15000)
 if action=='linked':
  side=sys.argv[2];row=sys.argv[3] if len(sys.argv)>3 else 'P2';still(row+'-'+side+'-initial');run('record','start',ROOT/(row+'-'+side+'.mp4'),'--fps',30);run('wait',1000);run('press','label="Open numbered PDF"','--settle');still(row+'-'+side+'-pdf-initial');run('gesture','pan',200,700,0,-400,80);run('wait',8000);still(row+'-'+side+'-pdf-settled');run('press','role="button" label="Back to document"','--settle');run('wait',1000);still(row+'-'+side+'-returned');run('gesture','pan',200,700,0,-400,80);run('wait',8000);run('record','stop');still(row+'-'+side+'-settled')
 if action=='command':run(*sys.argv[2:])
