#!/usr/bin/env python3
"""Capture real dev-runner routing. Run after each checkout's built client is ready.
Start each checkout with T3CODE_DEV_SEED=0 vp run dev --share --built --host localhost.
Usage: capture-routing.py LABEL COMMIT SERVER_PORT SHARE_PORT RUNNER_LOG OUTPUT_DIRECTORY
The original hostname and pairing credentials are never written to public output.
"""
import datetime
import json
import pathlib
import re
import subprocess
import sys
import time

label, commit, server_port, share_port, log_path, out_root = sys.argv[1:]
out = pathlib.Path(out_root) / (label + '-' + datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ'))
out.mkdir(parents=True)
lines = []
events = []
started = time.monotonic()
def emit(value):
    lines.append(value)
    events.append([round(time.monotonic() - started, 3), 'o', value + '\r\n'])
    print(value, flush=True)
def run(args):
    return subprocess.run(args, capture_output=True, text=True)

emit(label.upper() + ' | commit ' + commit)
emit('Environment: Linux, Node ' + run(['node', '--version']).stdout.strip() + ', real Tailscale Serve, fresh isolated T3 home; no seeded data.')
emit('$ T3CODE_DEV_SEED=0 vp run dev --share --built --host localhost')
log = pathlib.Path(log_path).read_text()
listening = re.search(r'Listening on http://\[::1\]:' + server_port, log)
if not listening:
    raise RuntimeError('Expected backend listener was not logged')
emit(listening.group(0))
config = json.loads(run(['tailscale', 'serve', 'status', '--json']).stdout)
host, handler = next((h, v['Handlers']['/']) for h, v in config['Web'].items() if h.endswith(':' + share_port))
url = 'https://' + host
emit('$ tailscale serve status --json  # selected route; hostname redacted')
emit('https://<tailnet-host>:' + share_port + '/ -> ' + handler['Proxy'])
emit('$ ss -H -ltn (selected backend port)')
sockets = run(['ss', '-H', '-ltn', '( sport = :' + server_port + ' )']).stdout.strip()
emit(sockets)
for address in ['127.0.0.1', '[::1]']:
    target = 'http://' + address + ':' + server_port + '/'
    emit('$ curl --noproxy "*" -sS -o /dev/null -w "HTTP %{http_code}" ' + target)
    r = run(['curl', '--noproxy', '*', '-sS', '-o', '/dev/null', '-w', 'HTTP %{http_code}', '--max-time', '15', target])
    emit(r.stdout + '; curl exit ' + str(r.returncode))
    if r.stderr:
        emit(r.stderr.strip())
for path in ['/', '/pair']:
    emit('$ curl --noproxy "*" -sS -D headers -o body https://<tailnet-host>:' + share_port + path)
    r = run(['curl', '--noproxy', '*', '-sS', '-i', '--max-time', '15', url + path])
    header, _, body = r.stdout.partition('\r\n\r\n')
    if not body:
        header, _, body = r.stdout.partition('\n\n')
    emit(header.splitlines()[0] + '; curl exit ' + str(r.returncode))
    title = re.search(r'<title>([^<]+)</title>', body)
    emit('Response body: ' + (('HTML title: ' + title.group(1)) if title else ('empty' if not body.strip() else str(len(body)) + ' characters')))
(out / 'transcript.txt').write_text('\n'.join(lines) + '\n')
with (out / 'terminal.cast').open('w') as f:
    f.write(json.dumps({'version': 2, 'width': 130, 'height': 34, 'title': label + ': real dev-runner and Tailscale Serve'}) + '\n')
    for event in events:
        f.write(json.dumps(event) + '\n')
print('Saved sanitized capture:', out)
