#!/usr/bin/env python3
"""Whole-screen still: require two equal frames 500 ms apart, ignoring only the clock."""
import os,subprocess,time,pathlib,sys,datetime,json
root=pathlib.Path('/tmp/lead-32936-r1/capture2');session,name=sys.argv[1:3]
run=root/('frames-'+datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S%f'));run.mkdir()
def command(args):
 with (root/'driver-transcript.jsonl').open('a') as f:f.write(json.dumps({'at':datetime.datetime.now(datetime.timezone.utc).isoformat(),'session':session,'args':args})+'\n')
 return subprocess.run(['agent-device',*args,'--session',session],capture_output=True,text=True,check=True,env={**os.environ,'NODE_OPTIONS':'--import=/tmp/lead-32936-r1/capture2/cached-health.mjs'})
for n in range(6):
 a=run/f'{name}-{n}-a.png';b=run/f'{name}-{n}-b.png'
 command(['screenshot',str(a)]);time.sleep(.5);command(['screenshot',str(b)])
 ca=run/f'{name}-{n}-a-body.png';cb=run/f'{name}-{n}-b-body.png'
 width=int(subprocess.check_output(['identify','-format','%w',str(a)]))
 rect='20,0 80,24' if width>1100 else '0,0 65,20' if width>500 else '35,15 85,40' if width>400 else '20,12 75,32'
 for src,dst in [(a,ca),(b,cb)]:subprocess.run(['convert',str(src),'-fill','black','-draw','rectangle '+rect,str(dst)],check=True)
 r=subprocess.run(['compare','-metric','AE',str(ca),str(cb),'null:'],capture_output=True,text=True)
 print(name,'attempt',n,'body pixel differences',r.stderr,flush=True)
 if r.returncode==0:
  final=root/(name+'.png');final.write_bytes(b.read_bytes());print(final);break
else:raise SystemExit('UNSETTLED: no identical frame pair')
