"""Synthetic desktop reproduction. Requires a seeded Replay question, desktop CDP connection,
main tab t1, Product preview tab t2, and a 1440x960 X11 window at 0,0.
Run with SESSION OUT_DIR DISPLAY XAUTHORITY supplied by the capture harness.
"""
import os,subprocess,pathlib,time,hashlib,re
session=os.environ['SESSION'];out=pathlib.Path(os.environ['OUT_DIR']);out.mkdir(parents=True,exist_ok=True)
note='FIRST NOTE: this features section looks too bare and like a placeholder; add three feature cards with icons, concise descriptions, and clear links. Keep the blue background and make the cards responsive. FINAL DETAIL: preserve this complete sentence.'
def ab(*args):
    p=subprocess.run(['npx','--yes','agent-browser','--session',session,*args],text=True,capture_output=True)
    print(p.stdout,flush=True)
    if p.returncode: raise RuntimeError(p.stderr)
    return p.stdout

def capture(label):
    def shot(path):
        subprocess.run(['import','-window','root','-crop',('1440x960+0+0' if label=='agent-received' else '1440x760+0+200'),str(path)],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,check=True)
    previous=out/(label+'-stability.png'); target=out/(label+'.png')
    for _ in range(12):
        shot(previous);time.sleep(.5);shot(target)
        if subprocess.check_output(['convert',str(previous),'-depth','8','rgb:-']) == subprocess.check_output(['convert',str(target),'-depth','8','rgb:-']): return
    raise RuntimeError('Screenshot did not settle: '+label)

ab('tab','t1')
ab('find','role','textbox','click','--name','Message Preview annotation answer')
ab('press','Control+a')
ab('keyboard','inserttext','Here are my notes: ')
ab('find','role','button','click','--name','Annotate preview')
ab('tab','t2')
ab('click','#features')
snapshot=ab('snapshot','-i')
ref=re.search(r'textbox \"Describe the change…\" \[ref=(e\d+)\]',snapshot).group(1)
ab('fill','@'+ref,note)
snapshot=ab('snapshot','-i')
expand=re.search(r'button \"Expand annotation editor\".*?ref=(e\d+)',snapshot).group(1)
ab('click','@'+expand)
ab('press','Tab')
print(ab('snapshot','-i'))
capture('annotation-entered')
snapshot=ab('snapshot','-i')
ref=re.search(r'textbox \"Describe the change…\" \[ref=(e\d+)\]',snapshot).group(1)
ab('focus','@'+ref)
ab('press','Enter')
ab('tab','t1')
ab('wait','--fn',"document.querySelector('[data-testid=\"composer-editor\"]')?.innerText.includes('FIRST NOTE')")
ab('press','Tab')
capture('answer-before-submit')
ab('find','role','button','click','--name','Submit')
ab('wait','--text','plan questions fixture complete')
ab('find','role','button','click','--name','Toggle right panel')
capture('agent-received')
(out/'visible-result.txt').write_text(ab('get','text','body'))
(out/'result.json').write_text(__import__('json').dumps({'fullComment':note,'receivedVisibleText':ab('get','text','body')},indent=2))
