import subprocess, sys, time, json, shutil
from pathlib import Path
from datetime import datetime, timezone
root=Path(__file__).parent
ab=str(root/'browser/node_modules/.bin/agent-browser')
session='proof35574-59497abe5521'
side=sys.argv[1]
out=root/(side+'-'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ'))
out.mkdir()
log=[]
def run(*args):
    p=subprocess.run([ab,'--session',session,*args],text=True,capture_output=True)
    log.append({'command':list(args),'stdout':p.stdout,'stderr':p.stderr,'exit':p.returncode})
    (out/'actions.json').write_text(json.dumps(log,indent=2))
    if p.returncode: raise RuntimeError(p.stderr or p.stdout)
    return p.stdout.strip()
def button(name): run('find','role','button','click','--name',name,'--exact')
def stable(label):
    run('eval','document.activeElement?.blur()')
    previous=None
    for i in range(8):
        shot=out/f'{label}-{i}.png'
        run('screenshot',str(shot))
        if previous and subprocess.run(["compare", "-metric", "AE", str(previous), str(shot), "null:"], capture_output=True).returncode == 0:
            shutil.copyfile(shot,out/f'{label}.png')
            return
        previous=shot
        time.sleep(.5)
    raise RuntimeError('Capture did not settle: '+label)
if '--resume' not in sys.argv:
    run('record','start',str(out/'questionnaire.mp4'),'--cursor')
    run('find','role','textbox','click','--name','Message Garden answer proof','--exact')
    run('keyboard','type','Plant lavender beside the blue gate')

time.sleep(.7)
button('Sunny patio 1')
run('wait','--text','Which flowers should we grow?')
button('Previous question')
run('wait','--text','Where should we plant the garden?')
run('find','role','textbox','click','--name','Message Garden answer proof','--exact')
for _ in range(6):
    run('press','Control+z')
    value=run('get','text','[data-testid="composer-editor"]')
    if value.strip()=='Plant lavender beside the blue gate': break
else: raise RuntimeError('Undo did not restore custom answer')

time.sleep(.7)
button('Next')
run('wait','--text','Which flowers should we grow?')
button('Marigolds 1')
run('wait','--text','When should we water?')
run('find','role','textbox','click','--name','Message Garden answer proof','--exact')
run('keyboard','type','Morning')
button('Submit')
run('wait','--text','plan questions fixture complete')
button('Dismiss notification')
button('Toggle thread details panel')
button('Where should we plant the garden? · Which flowers should we grow? · When should we water?: Plant lavender beside the blue gate · Marigolds · Morning')
stable('after-submission')
time.sleep(1)
composer=run('get','text','[data-testid="composer-editor"]')
(out/'observation.json').write_text(json.dumps({'composerAfterSubmission':composer},indent=2))
run('find','role','textbox','click','--name','Message Garden answer proof','--exact')
run('press','Enter')
# Completion of the resumed replay is already visible. Capture the resulting message or unchanged empty composer.
if composer.strip():
    run('wait','--text','Where should we plant the garden?')
time.sleep(1)
run('snapshot','-i')
run('record','stop')
print(out)
