import sys, pathlib, sqlite3, subprocess, urllib.parse, time, hashlib, json
browser, session, home, origin, output = sys.argv[1:]
home, output = pathlib.Path(home), pathlib.Path(output)
output.mkdir(parents=True, exist_ok=True)
def run(*cmd):
    p = subprocess.run([browser, '--session', session, *cmd], capture_output=True, text=True)
    if p.returncode: raise RuntimeError(p.stderr)
    return p.stdout
run('set', 'viewport', '1280', '800')
run('open', origin + '/pair')
run('wait', '--fn', "document.body.innerText.includes('Fork project') || document.body.innerText.includes('Pair with this environment')")
snapshot = run('snapshot', '-i')
if 'Pairing token' in snapshot:
    token = urllib.parse.parse_qs(urllib.parse.urlsplit((home/'pairing-path').read_text()).fragment)['token'][0]
    run('find', 'role', 'textbox', 'fill', '--name', 'Pairing token', token)
    run('find', 'role', 'button', 'click', '--name', 'Continue')
    run('wait', '--text', 'Fork project')
with sqlite3.connect(f'file:{home}/userdata/statev2.sqlite?mode=ro', uri=True) as db:
    thread = db.execute("select thread_id from orchestration_v2_projection_threads where title='Fork repository proof'").fetchone()[0]
environment = (home/'userdata/environment-id').read_text().strip()
run('open', f'{origin}/{environment}/{thread}')
run('wait', '--text', 'first fixture turn complete')
run('wait', '--fn', "!document.body.innerText.includes('Syncing messages')")
time.sleep(0.5)
run('record', 'start', str(output/'interaction.mp4'))
run('press', 'Control+k')
run('find', 'role', 'combobox', 'fill', '--name', 'Search commands, projects, and threads...', 'Link pull request to thread')
run('wait', '--fn', "Array.from(document.querySelectorAll('[role=option]')).some(el => el.textContent.trim() === 'Link pull request to thread' && el.hasAttribute('data-highlighted'))")
run('press', 'Enter')
run('wait', 'input[placeholder=\"Pull request URL or #42\"]')
run('find', 'role', 'textbox', 'fill', '--name', 'Pull request URL or #42', '42')
run('wait', '--text', 'github.com/example/')
run('press', 'Tab')
for attempt in range(6):
    first, second = output/f'stable-{attempt}-a.png', output/f'stable-{attempt}-b.png'
    run('screenshot', str(first))
    time.sleep(0.5)
    run('screenshot', str(second))
    if first.read_bytes() == second.read_bytes():
        (output/'selected-repository.png').write_bytes(second.read_bytes())
        break
else: raise RuntimeError('Screenshots did not settle 500 ms apart')
time.sleep(2)
snapshot = run('snapshot')
(output/'screen.txt').write_text(snapshot)
run('record', 'stop')
actual = 'example/parent' if 'github.com/example/parent #42' in snapshot else 'example/fork' if 'github.com/example/fork #42' in snapshot else 'unknown'
print(json.dumps({'actualRepository': actual, 'expectedRepository':'example/fork', 'stableScreenshots':True, 'viewport':'1280x800', 'theme':'light'}))
