import subprocess,re,sys,json,time,hashlib
from pathlib import Path
from PIL import Image,ImageChops
agent,session,outdir=sys.argv[1:4];out=Path(outdir);out.mkdir(parents=True,exist_ok=True);events=[];start=time.monotonic()
def ad(*args):
 p=subprocess.run([agent,*args,'--session',session],capture_output=True,text=True);events.append({'at':time.monotonic()-start,'args':list(args),'output':p.stdout+p.stderr,'code':p.returncode});(out/'events.json').write_text(json.dumps(events,indent=2))
 if p.returncode: raise RuntimeError(p.stdout+p.stderr)
 return p.stdout

def find(name,role=None,contains=False):
 text=ad('snapshot','-i'); rows=re.findall(r'(@e\d+(?:~s\d+)?)\s+\[([^]]+)\]\s+"([^"]*)"',text)
 found=[r for r in rows if (role is None or r[1]==role) and ((name in r[2]) if contains else r[2].startswith(name))]
 if len(found)!=1:raise RuntimeError(f'Expected one {name}: {found}; {text}')
 return found[0][0]
def press(name,role=None,contains=False): return ad('press',find(name,role,contains),'--settle')
def capture(label):
 for i in range(6):
  a=out/f'{label}-probe-{i}.png';b=out/f'{label}.png';ad('screenshot',str(a));time.sleep(.5);ad('screenshot',str(b))
  if ImageChops.difference(Image.open(a).convert("RGB"),Image.open(b).convert("RGB")).getbbox() is None: return
 raise RuntimeError('Still did not settle: '+label)

side=sys.argv[4];repo=Path(sys.argv[5]);
def git(*args):return subprocess.check_output(['git',*args],cwd=repo,text=True)
def open_commit():
 press('Git controls','button');press('More',contains=False);press('Commit, 2 files changed','button')
 ad('wait','text','beta.txt')

ad('record','start',str(out/f'mobile-{side}.mp4'),'--hide-touches')
try:
 open_commit();press('beta.txt');capture('001-excluded-beta')
 ad('fill',find('Commit message','text-view'),'only alpha','--settle');ad('scroll','down','300','--settle');press('Commit changes','button')
 ad('wait','text','Git action failed')
 open_commit();capture('002-reopened-after-failure')
 press('Cancel commit','button');git('stash','push');git('stash','pop');open_commit();capture('003-stash-restored')
 press('Cancel commit','button');git('checkout','other');open_commit();ad('wait','text','other');capture('004-different-branch')
 press('Cancel commit','button')
finally:
 ad('record','stop')
print('Captured native flow: '+side)
