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}-retry.mp4'),'--hide-touches')
try:
 open_commit();press('beta.txt');capture('005-selected-for-successful-retry')
 ad('fill',find('Commit message','text-view'),'only alpha retry','--settle');ad('scroll','down','300','--settle')
 (repo/'.git/hooks/pre-commit').write_text('#!/bin/sh\nexit 0\n')
 press('Commit changes','button')
 press('Git controls','button');press('More');press('Commit,','button');ad('wait','text','beta.txt');ad('wait','text','1 of 1 selected');capture('006-successful-retry-remaining-beta')
 committed=git('show','--format=','--name-only','HEAD').strip();remaining=git('diff','--name-only','HEAD').strip()
 (out/'repository-result.json').write_text(json.dumps({'committed':committed,'remaining':remaining},indent=2))
 if committed!='alpha.txt' or remaining!='beta.txt':raise RuntimeError('Unexpected partial commit result')
 press('Cancel commit','button')
finally:
 ad('record','stop')
print('Captured successful native retry: '+side)
