import subprocess, json, sys, pathlib, time, re
side, seed, out = sys.argv[1:]
out=pathlib.Path(out);out.mkdir(parents=True,exist_ok=True)
data=json.load(open(seed))
def call(*args):
    p=subprocess.run(['agent-device',*args,'--session','bom-proof'],text=True,capture_output=True)
    with open(out/'driver.log','a') as f:f.write(' '.join(args)+'\n'+p.stdout+p.stderr+'\n')
    if p.returncode:raise RuntimeError(p.stderr)
    return p.stdout

def shot(label):
    path=out/(label+'.png'); previous=out/(label+'-stability.png')
    call('wait','stable','500','10000')
    call('screenshot',str(previous),'--normalize-status-bar')
    for attempt in range(4):
        time.sleep(.5)
        call('screenshot',str(path),'--normalize-status-bar')
        result=subprocess.run(['compare','-metric','AE',str(previous),str(path),'null:'],capture_output=True,text=True)
        if result.stderr.strip()=='0':
            print('Stable capture',label,flush=True);return
        previous.write_bytes(path.read_bytes())
    raise RuntimeError('Capture never stabilized: '+label)

for item in data['threads']:
    label=f"{side}-{item['name']}-{'bom' if item['bom'] else 'plain'}"
    call('open','com.t3tools.t3code.dev',f"t3code-dev://threads/{data['env']}/{item['threadId']}")
    call('wait','text','Copy message','30000')
    snapshot=call('snapshot','-i')
    (out/(label+'.txt')).write_text(snapshot)
    shot(label)
    if item['name']=='details':
        call('record','start',str(out/(label+'.mp4')),'--hide-touches')
        fold='Details' if item['bom'] and side=='base' else 'Long details'
        call('click',f'label="{fold}"','--settle')
        shot(label+'-expanded')
        call('record','stop')
print('Finished',side,flush=True)
