import pathlib, subprocess, sys, time
binary, session, thread_url, output = sys.argv[1:]
out = pathlib.Path(output)
out.mkdir(parents=True, exist_ok=True)
def browser(*args):
    return subprocess.run([binary, '--session', session, *args], check=True, capture_output=True, text=True).stdout
browser('open', thread_url)
browser('wait', '--text', 'Reply with just the word ok.')
browser('set', 'viewport', '1280', '800')
# This driver starts with Context window enabled, after the initial UI setup.
browser('click', '[aria-label="Thread details"]', '--button', 'right')
time.sleep(.7)
browser('find', 'role', 'menuitemcheckbox', 'click', '--name', 'Context window')
browser('press', 'Escape')
browser('record', 'start', str(out / 'context.mp4'))
time.sleep(.7)
browser('click', '[aria-label="Thread details"]', '--button', 'right')
time.sleep(.7)
browser('find', 'role', 'menuitemcheckbox', 'click', '--name', 'Context window')
browser('press', 'Escape')
browser('find', 'role', 'heading', 'click', '--name', 'Unicode settings proof')
browser('press', 'Escape')
time.sleep(.7)
browser('find', 'label', 'Context: 3% used', 'hover')
browser('wait', '--text', 'of 1,000,000 tokens')
previous = out / 'previous.png'
final = out / 'context.png'
for attempt in range(5):
    browser('screenshot', str(previous))
    time.sleep(.5)
    browser('screenshot', str(final))
    if previous.read_bytes() == final.read_bytes():
        break
else:
    raise RuntimeError('Screen did not settle')
time.sleep(1)
browser('record', 'stop')
print('Captured two identical screenshots 500 ms apart and a recording.')
