"""Capture the online launching shell with an already prepared attachment-only draft.
Usage: python3 capture-flow.py SESSION OUTPUT_ROOT PROXY_ORIGIN
The app must be Connected, with Replay/Showcase selected, and the proxy holding launchThread.
"""
import subprocess,sys,time,datetime,pathlib,urllib.request
from PIL import Image,ImageChops
session,root,proxy=sys.argv[1:]
out=pathlib.Path(root)/datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')
out.mkdir(parents=True)
def device(*args):
 result=subprocess.run(['agent-device',*map(str,args),'--session',session],text=True,capture_output=True,check=True)
 print(result.stdout,flush=True)
 return result.stdout
def stable(name):
 for attempt in range(3):
  a=out/f'{name}-check-{attempt}.png'; b=out/f'{name}-{attempt}.png'
  device('screenshot',a,'--normalize-status-bar'); time.sleep(.5)
  device('screenshot',b,'--normalize-status-bar')
  if ImageChops.difference(Image.open(a).convert('RGB'),Image.open(b).convert('RGB')).getbbox() is None:
   Image.open(b).save(out/f'{name}.png');return
 raise RuntimeError('Screen did not settle')
device('record','start',out/'online.mp4','--hide-touches')
try:
 device('press','label="Send"','--settle')
 device('wait','label="Terminal"','15000')
 device('press','label="Navigate up"','--settle')
 device('press','label="1 working thread"','--settle')
 stable('launch-row')
 urllib.request.urlopen(proxy+'/release').read()
finally:
 device('record','stop')
print('CAPTURES',out,flush=True)
