import subprocess,sys,time,re,hashlib,urllib.request
from pathlib import Path
out=Path(sys.argv[1]);out.mkdir(parents=True,exist_ok=True)
session=sys.argv[2]
def ad(*args):
 start=time.monotonic();print("START",args,flush=True)
 p=subprocess.run(['agent-device',*args,'--session',session],capture_output=True,text=True,check=True)
 print("DONE",round(time.monotonic()-start,2),args,flush=True)
 return p.stdout

def ref(label):
 tree=ad('snapshot','-i')
 (out/'latest-tree.txt').write_text(tree)
 for line in tree.splitlines():
  if label in line:return re.search(r'(@\S+)',line).group(1)
 raise RuntimeError('No control '+label+'\n'+tree)

def still(label):
 for i in range(6):
  a=out/(label+'-settle-a.png');b=out/(label+'-settle-b.png')
  ad('screenshot',str(a));time.sleep(.5);ad('screenshot',str(b))
  if a.read_bytes()==b.read_bytes():
   (out/(label+'.png')).write_bytes(b.read_bytes());return
 raise RuntimeError('Screen never settled '+label)

ad('record','start',str(out/'interaction.mp4'))
ad('click',ref('[cell] "GitHub repository'))
ad('fill',ref('[text-field]'),'example/slow-proof')
ad('click','role=button label="Lookup repository"')
with urllib.request.urlopen('http://127.0.0.1:13997/') as r:
 if r.read()!=b'pending':raise RuntimeError('Lookup was not held')
ad('click','role=button label="Back"')
still('002-sources-before-reply')
with urllib.request.urlopen('http://127.0.0.1:13997/release') as r:print(r.read().decode())
still('003-after-lookup-reply')
print(ad('snapshot','-i'))
ad('record','stop')
