import argparse, datetime, pathlib, subprocess, time, hashlib
p=argparse.ArgumentParser()
p.add_argument('side', choices=['base','head'])
p.add_argument('--session', default='proof44080')
a=p.parse_args()
out=pathlib.Path(__file__).parent / (a.side+'-'+datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ'))
out.mkdir()
def run(*args):
    result=subprocess.run(['agent-device',*args,'--session',a.session],text=True,capture_output=True)
    with (out/'driver.log').open('a') as f: f.write('$ agent-device '+' '.join(args)+'\n'+result.stdout+result.stderr+'\n')
    if result.returncode: raise RuntimeError(result.stderr)
    return result.stdout

def shot(label):
    first=out/(label+'-settle.png')
    final=out/(label+'.png')
    for attempt in range(5):
        run('screenshot',str(first))
        time.sleep(.5)
        run('screenshot',str(final))
        # Compare pixels: PNG metadata need not be identical.
        result=subprocess.run(['compare','-metric','AE',str(first),str(final),'null:'],capture_output=True,text=True)
        if result.stderr.strip()=='0': return
    raise RuntimeError('Screen did not settle: '+label)

print(out,flush=True)
run('record','start',str(out/(a.side+'.mp4')),'--hide-touches')
try:
    shot('guide')
    run('press','label="notes.md, Home notes"','--settle')
    (out/'home-snapshot.txt').write_text(run('snapshot','-i'))
    shot('home-result')
    run('back','--settle')
    run('press','label="README.md, Readme"','--settle')
    (out/'relative-snapshot.txt').write_text(run('snapshot','-i'))
    shot('relative-control')
finally:
    run('record','stop')
print('Captured '+str(out),flush=True)
