import pathlib, subprocess, sys, re, time, json, datetime
root, thread, session, output = sys.argv[1:]
run_dir = pathlib.Path(output) / datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')
run_dir.mkdir(parents=True)
def device(*args):
    return subprocess.run(['agent-device', *args, '--session', session], cwd=root, text=True, capture_output=True)
def snap():
    return device('snapshot', '-i').stdout
record = run_dir / 'interaction.mp4'
assert device('record', 'start', str(record)).returncode == 0
sent = subprocess.run(['node', 'apps/server/src/bin.ts', 'thread', 'send', thread, 'Stream grouped commands again', '--base-dir', '.t3', '--json'], cwd=root, text=True, capture_output=True)
assert sent.returncode == 0
start = time.monotonic()
time.sleep(7)
device('scroll', 'bottom')
clicks = []
crashed = False
while time.monotonic() - start < 85:
    screen = snap()
    if 'Maximum update depth' in screen or "conversation couldn't be displayed" in screen:
        crashed = True
        break
    rows = re.findall(r'(@e\d+) \[button\] "echo ', screen)
    if rows:
        ref = rows[len(rows)//2]
    elif '"Stop agent"' in screen:
        groups = re.findall(r'(@e\d+) \[button\] "Running echo"', screen)
        if not groups:
            continue
        ref = groups[-1]
    else:
        break
    result = device('press', ref)
    clicks.append({'seconds': round(time.monotonic()-start,1), 'success': result.returncode == 0})
    print(f'Interaction {len(clicks)} at {clicks[-1]["seconds"]}s',flush=True)
stop = device('record', 'stop')
print(stop.stdout,flush=True)
(run_dir / 'outcome.json').write_text(json.dumps({'crashed':crashed,'clicks':clicks},indent=2))
print(json.dumps({'crashed':crashed,'interactionCount':len(clicks),'output':str(run_dir)}),flush=True)
