"""Observe the typed qualifier after choosing Me and reopening search.
Usage: python capture-reselect.py SESSION OUTPUT_PARENT SIDE
"""
import sys,subprocess,time,re,shutil
from pathlib import Path
from PIL import Image,ImageChops
session,parent,side=sys.argv[1:];out=Path(parent)/(side+'-reselect-'+time.strftime('%Y%m%d-%H%M%S'));out.mkdir()
def run(*args):
 r=subprocess.run(['agent-device',*args,'--session',session],capture_output=True,text=True,timeout=90)
 if r.returncode:raise RuntimeError(r.stdout+r.stderr)
 return r.stdout
def capture(label):
 for i in range(8):
  a=out/f'{label}-{i}-a.png';b=out/f'{label}-{i}-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:shutil.copyfile(b,out/(label+'.png'));return
 raise RuntimeError('Unstable '+label)
run('record','start',str(out/'interaction.mp4'),'--hide-touches')
try:
 if '[search]' not in run('snapshot','-i'):run('press','label="Search"','--settle')
 run('fill','role="search"','author:@me','--delay-ms','80','--settle');run('keyboard','enter')
 if 'Filter by author' not in run('snapshot','-i'):run('swipe','365','133','90','133')
 run('press','label="Filter by author"','--settle');menu=run('snapshot','-i');ref=re.search(r'^(@\S+) \[button\] "Me"(?: |$)',menu,re.M).group(1)
 run('press',ref,'--settle');run('press','label="Chats"','--settle');run('press','label="PRs"','--settle')
 if '[search]' not in run('snapshot','-i'):run('press','label="Search"','--settle')
 state=run('snapshot','-i')
 if '[keyboard]' in state:run('keyboard','enter')
 state=run('snapshot','-i');(out/'observed.txt').write_text(state)
finally:print(run('record','stop'))
print('OUTPUT',out)
