import datetime, hashlib, json, pathlib, subprocess, sys, time
browser, session, origin, home, side = sys.argv[1:]
root = pathlib.Path('/tmp/factory-pr-23251-a2-evidence-1')
output = root / (side + '-' + datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ'))
output.mkdir()
project = root / 'terminal-recovery'
def b(*args, stdin=None):
    result = subprocess.run([browser, '--session', session, *args], input=stdin, text=True, capture_output=True)
    if result.returncode:
        raise RuntimeError(result.stderr + result.stdout)
    return result.stdout

def capture(label):
    previous = None
    for i in range(20):
        path = output / f'{label}-stability-{i}.png'
        b('screenshot', str(path))
        digest = hashlib.sha256(path.read_bytes()).digest()
        if digest == previous:
            final = output / f'{label}.png'
            final.write_bytes(path.read_bytes())
            return str(final)
        previous = digest
        time.sleep(0.5)
    raise RuntimeError('Screenshot did not settle')

b('set', 'viewport', '1920', '900')
b('set', 'media', 'light')
b('open', origin + pathlib.Path(home, 'pairing-path').read_text().strip())
b('eval', 'localStorage.clear()')
b('reload')
b('wait', '--text', 'Terminal recovery')
b('click', '[data-testid=sidebar-row-card]')
b('wait', '--text', 'first fixture turn complete')
b('eval', '--stdin', stdin='''(async () => {
  const { GhosttyTerminalSurface } = await import('/src/terminal/ghostty/surface.ts');
  const original = GhosttyTerminalSurface.prototype.write;
  window.__terminalProof = '';
  GhosttyTerminalSurface.prototype.write = function(data) {
    window.__terminalProof += data;
    return original.call(this, data);
  };
})()''')
b('record', 'start', str(output / 'flow.mp4'))
try:
    project.rename(str(project) + '-moved')
    b('find', 'role', 'button', 'click', '--name', 'Toggle terminal drawer')
    b('wait', '--fn', "window.__terminalProof.includes('does not exist:')")
    b('click', '[data-thread-terminal-drawer] canvas')
    missing = capture('missing-folder')
    guidance = b('eval', 'window.__terminalProof')
    time.sleep(1)
finally:
    pathlib.Path(str(project) + '-moved').rename(project)
b('click', 'button[aria-label^="New Terminal"]')
b('wait', '--fn', "window.__terminalProof.includes('demo$')")
b('focus', 'textarea[aria-label="Terminal input"]')
b('keyboard', 'type', "printf 'RECOVERY_OK\\n'")
b('press', 'Enter')
b('wait', '--fn', "/(?:^|[\\r\\n])RECOVERY_OK\\r?\\n/.test(window.__terminalProof)")
restored = capture('restored-folder')
time.sleep(1)
b('record', 'stop')
result = {'side': side, 'guidance': guidance, 'missing': missing, 'restored': restored, 'video': str(output / 'flow.mp4')}
(output / 'observations.json').write_text(json.dumps(result, indent=2))
print(json.dumps(result, indent=2))
