"""Drive the offline proof from the task list with one attachment-only draft.
Usage: python3 offline-flow.py SESSION OUTPUT_ROOT RUNNER_PID SERVER_PID
PIDs must belong to this disposable backend, captured at startup or verified by its port and cwd.
"""
import subprocess,sys,time,datetime,pathlib,os,signal
from PIL import Image,ImageChops
session,root,runner,server=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,crop=None):
 for attempt in range(3):
  paths=[out/f'{name}-{attempt}-{n}.png' for n in range(2)]
  device('screenshot',paths[0],'--normalize-status-bar'); time.sleep(.5)
  device('screenshot',paths[1],'--normalize-status-bar')
  images=[Image.open(p).convert('RGB') for p in paths]
  if crop: images=[im.crop(crop) for im in images]
  if ImageChops.difference(*images).getbbox() is None:
   images[1].save(out/f'{name}.png'); return
 raise RuntimeError('Screen did not settle')
stable('draft')
device('record','start',out/'offline.mp4','--hide-touches')
try:
 device('press','label="1 attachment"','--settle')
 for pid in [runner,server]: os.kill(int(pid),signal.SIGTERM)
 device('wait','label="Queue"','20000')
 device('press','label="Queue"','--settle')
 device('wait','label="Terminal"','15000')
 stable('pending-header',(0,0,1080,230))
 device('press','label="Navigate up"','--settle')
 stable('queued-row')
finally: device('record','stop')
