import argparse, subprocess, json, time, re
from pathlib import Path
from PIL import Image, ImageChops
p=argparse.ArgumentParser()
p.add_argument('--session',required=True); p.add_argument('--out',required=True); p.add_argument('--pr',required=True); p.add_argument('--organization',required=True)
a=p.parse_args(); out=Path(a.out); out.mkdir(parents=True,exist_ok=False)
def call(args):
 return subprocess.check_output(args,text=True)
def device(*args): return call(['agent-device',*args,'--session',a.session])
body='-\n  [ ] Same\n\n```txt\nseparator\n```\n\n- [ ] Same'
call(['az','repos','pr','update','--id',a.pr,'--organization',a.organization,'--description',body,'-o','none'])
device('press','label="Navigate up"','--settle')
snapshot=device('snapshot','-i')
ref=re.search(r'(@\S+) \[button\] "Pull request '+a.pr+r',',snapshot).group(1)
device('press',ref,'--settle')
device('swipe','540','700','540','1700')
device('wait','label="[ ] Same"')
# Native markdown exposes the whole paragraph, not the checkbox, to Android accessibility.
# This coordinate is the visible final task box on the Pixel 9 at 1080 x 2424.
def stable(label):
 paths=[out/(label+'-raw-1.png'),out/(label+'-raw-2.png')]
 device('screenshot',str(paths[0])); time.sleep(0.5); device('screenshot',str(paths[1]))
 crops=[Image.open(f).crop((0,1240,1080,1840)) for f in paths]
 if ImageChops.difference(*crops).getbbox(): raise RuntimeError('Description changed between captures')
 crops[1].save(out/(label+'.png'))
stable('before-tap')
device('record','start',str(out/'interaction-raw.mp4'),'--hide-touches')
time.sleep(1)
device('press','60','1719','--settle')
stable('after-tap')
result=call(['az','repos','pr','show','--id',a.pr,'--organization',a.organization,'--query','description','-o','json'])
(out/'description.json').write_text(result)
device('record','stop')
call(['ffmpeg','-y','-loglevel','error','-i',str(out/'interaction-raw.mp4'),'-vf','crop=1080:600:0:1240','-c:v','libx264','-pix_fmt','yuv420p','-an',str(out/'interaction.mp4')])
print(json.dumps({'description':json.loads(result),'output':str(out)}))
