import sys,json,subprocess,time,shutil
from pathlib import Path
from urllib.parse import quote
from PIL import Image,ImageChops
home,threads_file,side,out_dir,device=sys.argv[1:]
out=Path(out_dir);out.mkdir(parents=True,exist_ok=True)
def run(*args):
 return subprocess.run([device,*args],check=True,text=True,capture_output=True).stdout
env_id=(Path(home)/'userdata/environment-id').read_text().strip()
for item in json.load(open(threads_file)):
 label=item['label']
 url=f"t3code-dev://threads/{quote(env_id,safe='')}/{quote(item['threadId'],safe='')}"
 run('open','com.t3tools.t3code.dev',url)
 alert=subprocess.run([device,'alert','get'],text=True,capture_output=True).stdout
 if 'Open in' in alert and 'T3 Code' in alert: run('alert','accept')
 run('wait',f'text="{label}"','90000')
 snapshot=run('snapshot','-i')
 if 'Expand user input' in snapshot: run('press','label="Expand user input, 1 question"')
 run('wait','label="Collapse user input"','30000')
 previous=out/f'{side}-{label}-probe-0.png'
 run('screenshot',str(previous),'--normalize-status-bar')
 for attempt in range(1,9):
  time.sleep(.5)
  current=out/f'{side}-{label}-probe-{attempt}.png'
  run('screenshot',str(current),'--normalize-status-bar')
  if ImageChops.difference(Image.open(previous).convert('RGB').crop((0,390,402,850)),Image.open(current).convert('RGB').crop((0,390,402,850))).getbbox() is None:
   final=out/f'{side}-ios-{label}.png'
   shutil.copyfile(current,out/f'{side}-ios-{label}-context.png')
   Image.open(current).crop((0,390,402,850)).save(final)
   print(f'Stable capture: {final.name}',flush=True)
   break
  previous=current
 else:
  raise RuntimeError(f'{label} did not settle')
 time.sleep(2)
