#!/usr/bin/env python3
"""Read only synthetic evidence state. No runtime identifiers are exported.
Arguments: database filename, coordinator thread id, output filename.
"""
import json, sqlite3, sys
from pathlib import Path
con = sqlite3.connect('file:'+str(Path(sys.argv[1]).resolve())+'?mode=ro',uri=True)
parent = sys.argv[2]
rows = [json.loads(r[0]) for r in con.execute('select payload_json from orchestration_v2_projection_messages order by created_at')]
children = {r['threadId'] for r in rows if r.get('senderThreadId') == parent}
items = [json.loads(r[0]) for r in con.execute('select payload_json from orchestration_v2_projection_turn_items')]
out=[]
for r in rows:
    if r['threadId'] != parent and r['threadId'] not in children: continue
    text = r.get('text','')
    side = 'coordinator' if r['threadId']==parent else 'worker'
    if text in ('WAITING','FINAL'):
        out.append({'at':r['createdAt'],'thread':side,'event':'answer','text':text})
    elif text.startswith('Monitor ') and text.endswith('stream ended'):
        out.append({'at':r['createdAt'],'thread':side,'event':'monitor ended'})
    elif r.get('delegatedCompletion'):
        out.append({'at':r['createdAt'],'thread':side,'event':'delegated completion wake','answer':text.splitlines()[-1]})
for r in items:
    if r.get('threadId') in children and r.get('toolName')=='Monitor':
        out.append({'at':r['startedAt'],'thread':'worker','event':'Monitor tool','input':r.get('input')})
result={'observed':sorted(out,key=lambda x:x['at'])}
Path(sys.argv[3]).write_text(json.dumps(result,indent=2)+'\n')
print(json.dumps(result,indent=2))
