#!/usr/bin/env python3
"""Extract only synthetic wake timing and outcomes, excluding paths and machine details.
Usage: runtime-summary.py <checkout> <thread-id> <label>
"""
import json,sqlite3,sys,re
from pathlib import Path
checkout,thread,label=sys.argv[1:]
home=Path(checkout)/'.t3/userdata'
print(label)
print('All timestamps UTC. Synthetic project and real Claude Haiku 5.5.\n')
log=home/'logs/provider'/('events.'+thread.replace(':','-')+'.log')
rows=[]
for line in log.open():
 if '] NTIVE: ' not in line:continue
 stamp,raw=line.split('] NTIVE: ',1)
 s=json.loads(raw); p=s.get('event',{}).get('payload',{})
 typ=p.get('type');sub=p.get('subtype')
 if typ=='system' and sub=='init': rows.append((stamp[1:],'Native root init'))
 if typ=='result':rows.append((stamp[1:],'Native result '+str(sub)+' num_turns='+str(p.get('num_turns'))+' usage='+json.dumps(p.get('usage',{}))+' result='+re.sub(r'\[[^\]]+\]\(t3-thread://[^)]+\)', '[child thread]', str(p.get('result')))))
 if typ=='assistant' and p.get('parent_tool_use_id') is None:
  for part in p.get('message',{}).get('content',[]):
   if part.get('type')=='tool_use':
    name=part.get('name','')
    if name.endswith('delegate_task'): rows.append((stamp[1:],'Native delegate_task request: '+json.dumps({k:v for k,v in part.get('input',{}).items() if k in ['task','mode','target']})))
c=sqlite3.connect('file:'+str(home/'statev2.sqlite')+'?mode=ro',uri=True)
for (raw,) in c.execute('select payload_json from orchestration_v2_projection_runs where thread_id=?',(thread,)):
 r=json.loads(raw)
 for key in ['startedAt','completedAt']:
  if r.get(key): rows.append((r[key],f"App run {r['ordinal']} {key}; final status={r['status']}"))
for (raw,) in c.execute("select payload_json from orchestration_v2_projection_turn_items where thread_id=? and type='dynamic_tool'",(thread,)):
 r=json.loads(raw); name=str(r.get('toolName',r.get('title','')))
 out=str(r.get('output',''))
 if 'parent_not_active' in out:
  rows.append((r['updatedAt'],'App tool returned parent_not_active: The calling provider no longer owns an active thread run.'))
 elif 'childThreadId' in out:
  try:
   o=json.loads(out); data=o.get('structuredContent',{})
   rows.append((r['updatedAt'],'App delegation outcome: '+json.dumps({k:v for k,v in data.items() if k in ['status','timedOut','result','output','next']})))
  except Exception: pass
for (raw,) in c.execute('select payload_json from orchestration_v2_projection_provider_turns where thread_id=?',(thread,)):
 r=json.loads(raw)
 rows.append((r['startedAt'],f"Provider turn {r['ordinal']} adapter attached"))
 if r.get('completedAt'):
  rows.append((r['completedAt'],f"Provider turn {r['ordinal']} complete; billed token usage="+json.dumps(r.get('turnTokenUsage'))))
for stamp,event in sorted(rows):print(stamp,event)
