import sqlite3,json,sys,pathlib,datetime
side,root,thread,stage=sys.argv[1:]
t3=sqlite3.connect(f'file:{root}/.t3/userdata/statev2.sqlite?mode=ro',uri=True)
title=t3.execute('select title from orchestration_v2_projection_threads where thread_id=?',(thread,)).fetchone()[0]
payload=json.loads(t3.execute('select payload_json from orchestration_v2_projection_provider_threads where thread_id=?',(thread,)).fetchone()[0])
native=payload['nativeThreadRef']['nativeId']
codex=sqlite3.connect(f'file:{pathlib.Path.home()}/.codex/state_5.sqlite?mode=ro',uri=True)
name,rollout=codex.execute('select name,rollout_path from threads where id=?',(native,)).fetchone()
names=[]
for line in pathlib.Path(rollout).read_text().splitlines():
    item=json.loads(line)
    if item.get('type')=='event_msg' and item.get('payload',{}).get('type')=='thread_name': names.append(item)
print(json.dumps({'side':side,'stage':stage,'observedAt':datetime.datetime.now(datetime.timezone.utc).isoformat(),'t3Title':title,'nativeThreadId':native,'nativeName':name,'threadNameEvents':names},indent=2))
