#!/usr/bin/env python3
"""Export raw settle/SQL spans, omitting application logs and unrelated trace attributes.
Usage: python3 extract-traces.py SERVER_TRACE_NDJSON PUBLIC_NDJSON
"""
import sys,json
trace_ids=set()
for line in open(sys.argv[1]):
 try:s=json.loads(line)
 except json.JSONDecodeError:continue
 if s.get('type')=='effect-span' and s.get('name')=='ThreadHandoff.settle':trace_ids.add(s['traceId'])
fields=['type','name','traceId','spanId','parentSpanId','startTimeUnixNano','endTimeUnixNano','durationMs','exit']
allowed={'ThreadHandoff.settle','ThreadManagementService.getThreadRecords','OrchestratorV2.getThreadRecords','ProjectionStore.readCanonicalProjection','sql.transaction','sqlite','BEGIN','COMMIT'}
with open(sys.argv[2],'w') as out:
 for line in open(sys.argv[1]):
  try:s=json.loads(line)
  except json.JSONDecodeError:continue
  if s.get('type')!='effect-span' or s.get('traceId') not in trace_ids or s.get('name') not in allowed:continue
  public={k:s[k] for k in fields if k in s}
  public['attributes']={k:v for k,v in s.get('attributes',{}).items() if k in ['db.query.text','db.connection','db.lock_wait_ms','db.client.connection.wait_time_ms']}
  out.write(json.dumps(public)+'\n')
print('Exported',len(trace_ids),'settle traces')
