#!/usr/bin/env python3
"""Extract only discovery spans from a real dev-server trace; never emits private paths.
Usage: python3 capture-discovery.py TRACE OUTPUT_DIR SIDE COMMIT
Start each checkout with T3CODE_DEV_SEED=0 vp run dev, pair its web client,
open /settings/source-control, idle > 65 seconds, click Rescan server environment.
Run this script after discovery completes. This is a runtime capture, not a test.
"""
import sys,json,re,datetime,collections,pathlib
trace,out,side,commit=sys.argv[1:]
out=pathlib.Path(out);out.mkdir(parents=True,exist_ok=True)
ds=[json.loads(l) for l in open(trace) if l.strip()]
roots=[d for d in ds if d.get('name')=='ws.rpc.server.discoverSourceControl']
index={d.get('spanId'):d for d in ds}
def belongs(d,root):
    seen=set()
    while d and d.get('spanId') not in seen:
        if d.get('spanId')==root['spanId']: return True
        seen.add(d.get('spanId'));d=index.get(d.get('parentSpanId'))
    return False
def stamp(d):return datetime.datetime.fromtimestamp(int(d['startTimeUnixNano'])/1e9,datetime.UTC).isoformat(timespec='milliseconds')
lines=[f'{side.upper()} — {commit}', 'Real Linux dev server; fresh database; Chrome 1280x800; light theme.', 'git, gh, glab available; tea, fj, cafe, origin, jj absent.', 'Settings → Source control & issues; idle, then explicit Rescan.', 'Only discovery span metadata and first-line errors are exported. No auth output.', '']
selected=[]
for n,root in enumerate(roots,1):
    members=[d for d in ds if belongs(d,root)]
    errors=[d for d in members if d.get('name')=='VcsProcess.run' and 'VcsProcessSpawnError' in str(d.get('exit'))]
    commands=collections.Counter(d.get('attributes',{}).get('process.command') for d in members if d.get('name')=='processRunner.runProcessCore')
    lines += [f'Sweep {n}: {stamp(root)}; RPC {root["exit"]["_tag"]}; missing-tool spawn errors: {len(errors)}', 'Spawned commands: '+json.dumps(dict(commands),sort_keys=True)]
    for d in sorted(errors,key=lambda d:d['startTimeUnixNano']):
        error=re.sub(r' \([^)]*\)$','',d['exit']['cause'].splitlines()[0])
        lines.append('  '+stamp(d)+' '+error)
    lines.append('')
    for d in members:
        attrs=d.get('attributes',{})
        if d is root or d.get('name')=='VcsProcess.run' or 'process.command' in attrs or d.get('name','').endswith('.discovery'):
            entry={k:d[k] for k in ['name','traceId','spanId','parentSpanId','startTimeUnixNano','endTimeUnixNano','durationMs'] if k in d}
            entry['exit']={'_tag':d.get('exit',{}).get('_tag')}
            if 'VcsProcessSpawnError' in str(d.get('exit')):entry['exit']['cause']=re.sub(r' \([^)]*\)$','',d['exit']['cause'].splitlines()[0])
            if 'process.command' in attrs:entry['command']=attrs['process.command']
            selected.append(entry)
(out/f'{side}.txt').write_text('\n'.join(lines)+'\n')
(out/f'{side}.ndjson').write_text(''.join(json.dumps(d)+'\n' for d in selected))
print('\n'.join(lines))
