"""Run from the checkout being captured after pairing and opening the PR search.
Usage: python capture-mobile.py SESSION OUTPUT_PARENT SIDE
The same driver is used for base and head; no service responses are replaced.
"""
import subprocess,sys,time,re,json,shutil
from pathlib import Path
from PIL import Image,ImageChops
session,parent,side=sys.argv[1:]
out=Path(parent)/(side+'-'+time.strftime('%Y%m%d-%H%M%S'));out.mkdir(parents=True)
log=(out/'driver.log').open('w')
def run(*args):
 r=subprocess.run(['agent-device',*args,'--session',session],text=True,capture_output=True,timeout=90)
 log.write(r.stdout+r.stderr);log.flush()
 if r.returncode:raise RuntimeError(r.stdout+r.stderr)
 return r.stdout

def author_menu():
 state=run('snapshot','-i')
 if 'Filter by author' not in state:run('swipe','365','133','90','133')
 run('press','label="Filter by author"','--settle')

def capture(label):
 if not label.endswith("-menu"):run("swipe","365","133","90","133")
 for n in range(8):
  a=out/f'{label}-stability-{n}-a.png';b=out/f'{label}-stability-{n}-b.png'
  run('screenshot',str(a));time.sleep(.5);run('screenshot',str(b))
  if ImageChops.difference(Image.open(a).convert('RGB'),Image.open(b).convert('RGB')).getbbox() is None:
   dest=out/f'{label}.png';shutil.copyfile(b,dest);return str(dest)
 raise RuntimeError('Screen did not stabilize: '+label)

queries=['author:@me','author:@ME','author:ME','author:me']
results=[]
run('record','start',str(out/'interaction.mp4'),'--hide-touches')
try:
 for i,query in enumerate(queries):
  name=f'{i+1:02d}-'+re.sub('[^a-zA-Z0-9]','-',query)
  state=run('snapshot','-i')
  if '[search]' not in state:run('press','label="Search"','--settle')
  run('fill','role="search"',query,'--delay-ms','80','--settle')
  run('keyboard','enter')
  before=run('snapshot','-i')
  if query not in before:raise RuntimeError('Typed qualifier missing: '+query)
  if 'Filter by author' not in before:run('swipe','365','133','90','133')
  captures=[capture(name+'-chip')]
  author_menu()
  menu=run('snapshot','-i');captures.append(capture(name+'-menu'))
  me_ref=re.search(r'^(@\S+) \[button\] \"Me\"(?: |$)',menu,re.M).group(1)
  run('press',me_ref,'--settle')
  after=run('snapshot','-i');captures.append(capture(name+'-after-select-me'))
  if i==0:
   run('press','label="Chats"','--settle')
   run('press','label="PRs"','--settle')
   restored=run('snapshot','-i')
   captures.append(capture(name+'-after-return-to-prs'))
   author_menu()
   run('press','label="All authors"','--settle')
   captures.append(capture(name+'-after-all-authors'))
  results.append({'query':query,'before':before,'menu':menu,'after':after,'captures':captures})
  (out/'observations.json').write_text(json.dumps(results,indent=2))
  print(side,query,'captured',flush=True)
finally:
 print(run('record','stop'),flush=True)
print('OUTPUT',out,flush=True)
