import subprocess,sys,time,re
from pathlib import Path
from PIL import Image,ImageChops
session=sys.argv[1];out=Path(sys.argv[2]);out.mkdir(parents=True,exist_ok=True)
files=['data.json','main.py','app.tsx','demo.luau','demo.xsl','demo.xslt','demo.asm','demo.s','DATA.JSON','MAIN.PY','APP.TSX']
def command(*args):
 r=subprocess.run(['agent-device',*args,'--session',session],capture_output=True,text=True)
 with (out/'driver.log').open('a') as log: log.write(r.stdout+r.stderr)
 if r.returncode: raise RuntimeError(f'{args[0]} failed: {r.stderr[-300:]}')
 return r.stdout
for name in (sys.argv[3:] or files):
 print('Opening',name,flush=True)
 command('tap','role=button label="Open files"','--settle')
 command('fill','role=search label="Search files"',name)
 tree=command('snapshot','-i')
 ref=next(m.group(1) for m in re.finditer(r'(@\S+) \[button\] "([^"\n]+)"',tree) if m.group(2)==name)
 command('tap',ref,'--settle')
 # Read the rendered surface before capturing, then require two identical frames.
 tree=command('snapshot','-i')
 if f'[navigation-bar] "{name}"' not in tree or 'source-native-code-view' not in tree: raise RuntimeError(f'{name} preview did not open')
 previous=out/f'probe-{name}.png'; final=out/f'mobile-preview-{name}.png'
 command('screenshot',str(previous))
 for attempt in range(5):
  time.sleep(.5)
  command('screenshot',str(final))
  if ImageChops.difference(Image.open(previous).convert('RGB'),Image.open(final).convert('RGB')).getbbox() is None: break
  previous.write_bytes(final.read_bytes())
 else: raise RuntimeError(f'{name} did not settle')
 print('Captured',name,flush=True)
 command('tap','role=button label="Back"','--settle')
