# Read only the synthetic thread's session lifecycle and preview tool calls.
# Usage: python3 collect.py <database> <thread-id> <output-json>
import sqlite3,json,sys,datetime
con=sqlite3.connect('file:'+sys.argv[1]+'?mode=ro',uri=True)
thread=sys.argv[2]
sessions=[{'id':r[0],'status':r[1],'updatedAt':r[2]} for r in con.execute('select provider_session_id,status,updated_at from orchestration_v2_projection_provider_sessions where thread_id=?',(thread,))]
events=[]
for typ,at,payload in con.execute('select event_type,occurred_at,payload_json from orchestration_events where stream_id=? order by sequence',(thread,)):
 data=json.loads(payload)
 if 'session' in typ.lower(): events.append({'type':typ,'at':at,'data':{k:v for k,v in data.items() if k in ['id','status','reason','stopReason','model','driver','providerInstanceId','updatedAt']}})
tools=[]
for payload, in con.execute("select payload_json from orchestration_v2_projection_turn_items where thread_id=? and type='dynamic_tool' order by ordinal",(thread,)):
 data=json.loads(payload)
 if 'preview' in data.get('toolName',''):
  tools.append({k:data.get(k) for k in ['toolName','startedAt','completedAt','status','input','output','error']})
result={'capturedAt':datetime.datetime.now(datetime.timezone.utc).isoformat(),'sessions':sessions,'sessionEvents':events,'previewTools':tools}
open(sys.argv[3],'w').write(json.dumps(result,indent=2))
print(json.dumps({'capturedAt':result['capturedAt'],'sessions':sessions,'sessionEvents':len(events),'previewTools':len(tools)},indent=2))
