#!/usr/bin/env python3
"""Extract only synthetic reproduction protocol facts; never publish full provider logs."""
import argparse, json, pathlib, sqlite3
p=argparse.ArgumentParser();p.add_argument('checkout');p.add_argument('thread');p.add_argument('output');a=p.parse_args()
root=pathlib.Path(a.checkout); rows=[]; rollout=None
log=root/'.t3/userdata/logs/provider'/('events.'+a.thread.replace(':','-')+'.log')
for line in log.read_text().splitlines():
 if 'NTIVE: ' not in line: continue
 e=json.loads(line.split('NTIVE: ',1)[1])['event'];f=e.get('payload',{});m=f.get('method');q=f.get('params',{})
 if e.get('stage') not in ['decoded','sent']:continue
 t=f.get('result',{}).get('thread',{})
 if t.get('path'):rollout=t['path']
 row={'at':line[1:25],'source':'Codex protocol','direction':e.get('direction'),'method':m}
 if m=='turn/start':row.update(serviceTier=q.get('serviceTier'),model=q.get('model'),settings=q.get('collaborationMode',{}).get('settings',{}))
 elif m=='thread/settings/update':row['serviceTier']=q.get('serviceTier')
 elif m=='thread/settings/updated':row['serviceTier']=q.get('threadSettings',{}).get('serviceTier')
 elif m in ['turn/started','turn/completed']:row['status']=q.get('turn',{}).get('status')
 elif m in ['item/started','item/completed'] and q.get('item',{}).get('type')=='commandExecution':
  row['command']=q['item'].get('command');row['status']=q['item'].get('status')
 elif e.get('direction')=='outgoing': row['paramsOmitted']=True
 else:continue
 rows.append(row)
con=sqlite3.connect('file:'+str(root/'.t3/userdata/statev2.sqlite')+'?mode=ro',uri=True)
for at,payload in con.execute("select occurred_at,payload_json from orchestration_events where event_type='thread.model-selection-updated'"):
 d=json.loads(payload)
 if d.get('id')==a.thread:rows.append({'at':at,'source':'T3 persisted picker','method':'thread.model-selection-updated','modelSelection':d['modelSelection']})
if rollout:
 for line in pathlib.Path(rollout).read_text().splitlines():
  d=json.loads(line);q=d.get('payload',{})
  if q.get('type')=='thread_settings_applied':rows.append({'at':d['timestamp'],'source':'Codex native rollout','method':q['type'],'serviceTier':q.get('thread_settings',{}).get('service_tier')})
rows.sort(key=lambda r:r['at'])
pathlib.Path(a.output).write_text(json.dumps(rows,indent=2)+'\n')
print('Extracted',len(rows),'events')
