import subprocess,sys,pathlib,time,datetime,json
from PIL import Image,ImageChops
root=pathlib.Path('/tmp/lead-27034-r3/capture')
name,session=sys.argv[1:3]
run=root/('native-'+name+'-'+datetime.datetime.now(datetime.timezone.utc).strftime('%H%M%S'));run.mkdir()
previous=None
seen={}
started=time.monotonic()
for i in range(30):
    path=run/f'frame-{i:02}.png'
    subprocess.run(['agent-device','screenshot',str(path),'--normalize-status-bar','--session',session],check=True,cwd='/home/ubuntu/t3code',stdout=subprocess.DEVNULL)
    current=Image.open(path).convert('RGB')
    pixels=current.tobytes()
    if pixels in seen:
        import shutil
        earlier,earlier_seconds=seen[pixels]
        shutil.copyfile(earlier,root/(name+'-settle-a.png'));shutil.copyfile(path,root/(name+'.png'))
        result={'name':name,'pixelIdentical':True,'attempts':i+1,'run':str(run),'separationSeconds':time.monotonic()-started-earlier_seconds,'matchingFrames':[str(earlier),str(path)]}
        (root/(name+'-settle.json')).write_text(json.dumps(result,indent=2));print(json.dumps(result));break
    seen[pixels]=(path,time.monotonic()-started)
    previous=path
    time.sleep(.5)
else:
    print(json.dumps({'name':name,'pixelIdentical':False,'run':str(run)}));sys.exit(1)
