"""Scroll the real replay response into view and capture a settled desktop still."""
import os,subprocess,pathlib,re,time
session=os.environ['SESSION'];out=pathlib.Path(os.environ['OUT_DIR']);out.mkdir(parents=True,exist_ok=True)
def ab(*args):
    return subprocess.check_output(['npx','--yes','agent-browser','--session',session,*args],text=True)
ab('tab','t1')
snapshot=ab('snapshot','-i')
ref=re.search(r'heading "Answer received by replay agent".*?ref=(e\d+)',snapshot).group(1)
ab('scrollintoview','@'+ref)
for _ in range(12):
    paths=[out/'stability.png',out/'agent-received.png']
    for i,path in enumerate(paths):
        if i: time.sleep(.5)
        subprocess.run(['import','-window','root','-crop','1440x960+0+0',str(path)],check=True)
    pixels=[subprocess.check_output(['convert',str(p),'-depth','8','rgb:-']) for p in paths]
    if pixels[0]==pixels[1]:break
else:raise RuntimeError('Desktop did not settle')
(out/'answer-visible.txt').write_text(ab('get','text','body'))
