"""Usage: python3 extract.py TRACE_NDJSON COMMIT OUTPUT_TEXT.
Exports only SQL and operation names; excludes bindings, environment and provider metadata.
"""
import collections,json,sys
source,commit,out=sys.argv[1:]
spans=[json.loads(line) for line in open(source)]
by_id={s['spanId']:s for s in spans}
def ancestry(s):
    result=[]
    for i in range(30):
        result.append(s['name'])
        s=by_id.get(s.get('parentSpanId'))
        if s is None:break
    return result
starts=[s for s in spans if s['name']=='ProviderTurnStartService.start']
recoveries=[s for s in spans if s['name']=='ProjectionStore.getRuntimeRecoveryProjection' and 'ProviderTurnStartService.start' in ancestry(s)]
keyed=[s for s in spans if 'WHERE run_id = ? AND thread_id = ?' in s.get('attributes',{}).get('db.query.text','') and 'ProviderTurnStartService.start' in ancestry(s)]
prs=[s for s in spans if 'SELECT t.payload_json FROM orchestration_v2_projection_threads t' in s.get('attributes',{}).get('db.query.text','') and 'ProjectionStore.getPullRequestSnapshot' in ancestry(s)]
with open(out,'w') as f:
    def line(s=''):print(s,file=f)
    line('REAL SERVER TRACE CAPTURE — synthetic replay workload')
    line('Commit: '+commit)
    line('Environment: Linux; separate fresh worktree database; dev server; no live-data seed.')
    line('Driver: three simultaneous thread starts, then five sequential prompts in one thread; one preliminary greeting turn.')
    line('No tests or mock services. Each replay turn traverses the real adapter, orchestration and SQLite.')
    line('ProviderTurnStartService.start spans: '+str(len(starts)))
    line('Recovery reads below provider turn start: '+str(len(recoveries)))
    line('Keyed run reads below provider turn start: '+str(len(keyed)))
    line('These counts include inherited-background recovery reads which this fix intentionally retains.')
    line('No claim about user-visible latency, long histories or archived PR-linked data.')
    line('\nPR discovery SQL (as captured; built-in trace truncation retained):')
    for q in dict.fromkeys(s['attributes']['db.query.text'] for s in prs):line(q)
    line('\nChronological runtime trace excerpts:')
    for s in sorted(recoveries+keyed+prs,key=lambda x:int(x['startTimeUnixNano'])):
        line(json.dumps({'startTimeUnixNano':s['startTimeUnixNano'],'name':s['name'],'spanId':s['spanId'],'traceId':s['traceId'],'durationMs':s['durationMs'],'callChain':ancestry(s)[:6],'sql':s.get('attributes',{}).get('db.query.text'),'exit':s.get('exit')}))
