"""Drive an already paired T3 Code web client and capture the terminal reproduction.
Usage: python3 capture-terminal.py SESSION ORIGIN OUTPUT_PARENT
Use each commit's isolated server, fresh CLI-seeded project/thread, and HackGen35 Console NF.
"""
import datetime, json, pathlib, subprocess, sys
session, origin, parent = sys.argv[1:]
out = pathlib.Path(parent) / datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')
out.mkdir(parents=True)

def ab(*args):
    r = subprocess.run(['npx', '--yes', 'agent-browser', '--session', session, *args], capture_output=True, text=True)
    (out / 'driver.log').open('a').write(r.stdout + r.stderr)
    if r.returncode: raise RuntimeError(f'Browser command failed: {args[0]}: {r.stderr}')
    return r.stdout

def still(label):
    for attempt in range(8):
        first = out / f'{label}-stability-{attempt}.png'
        final = out / f'{label}.png'
        ab('batch', f'screenshot {first}', 'wait 500', f'screenshot {final}')
        comparison = subprocess.run(['compare', '-metric', 'AE', str(first), str(final), 'null:'], capture_output=True)
        if comparison.returncode == 0:
            print(f'Stable capture: {label}', flush=True)
            return
    raise RuntimeError(f'Viewport did not stabilize: {label}')

def press(key): ab('press', key)
def type_text(text): ab('keyboard', 'type', text)
canvas = 'canvas:has(+ textarea[aria-label="Terminal input"])'

# Set the reported font through Appearance, including the separate-font preference.
ab('open', origin + '/settings/appearance')
ab('wait', '#typography', '--timeout', '120000')
expanded = ab('eval', "document.querySelector('#typography [data-slot=collapsible-trigger]')?.getAttribute('aria-expanded')").strip()
if 'true' not in expanded:
    ab('click', '#typography [data-slot="collapsible-trigger"]')
checked = ab('eval', 'document.querySelector(\'[role="switch"][aria-label="Separate fonts"]\')?.getAttribute("aria-checked")').strip()
if 'true' not in checked:
    ab('find', 'role', 'switch', 'click', '--name', 'Separate fonts')
ab('find', 'label', 'Terminal font family', 'fill', 'HackGen35 Console NF')
press('Enter')
ab('find', 'role', 'combobox', 'click', '--name', 'Terminal font size')
ab('find', 'role', 'option', 'click', '--name', '18 px')
still('font-settings')
ab('find', 'role', 'button', 'click', '--name', 'Close')
ab('click', '[data-sidebar-row]')
ab('wait', '[aria-label="Message Wide glyph grid"]', '--timeout', '120000')
# The selected thread starts without an open terminal.
try:
    ab('wait', canvas, '--timeout', '1000')
except RuntimeError:
    ab('find', 'role', 'button', 'click', '--name', 'Toggle terminal drawer')
    ab('wait', canvas, '--timeout', '120000')
ab('click', canvas)
press('Control+c')
# A short synthetic prompt and clear screen keep hostnames and paths out of evidence.
type_text("export PS1='$ '; printf '\\033[2 q\\033[2J\\033[H'; printf 'あいうえお¦\\nabcdefghij¦\\n'")
press('Enter')
still('printed-markers')
ab('record', 'start', str(out / 'typing-and-cursors.webm'), '--fps', '10')
type_text('echo あいうえお')
still('five-kana')
type_text('かきくけこ')
still('ten-kana')
press('ArrowLeft')
still('wide-block-cursor')
ab('focus', '[aria-label="Toggle terminal drawer"]')
still('wide-outline-cursor')
ab('click', canvas)
press('Control+c')
type_text("printf '\\033[4 q\\033[2J\\033[H'; printf 'あいうえお¦\\nabcdefghij¦\\n'")
press('Enter')
type_text('echo あいうえおかきくけこ')
press('ArrowLeft')
still('wide-underline-cursor')
ab('record', 'stop')
print(str(out), flush=True)
