#!/usr/bin/env python3
"""Export only the selected synthetic delegation's tool results and run milestones."""
import argparse, datetime, json, pathlib, sqlite3

p = argparse.ArgumentParser()
p.add_argument('--home', required=True)
p.add_argument('--child-home')
p.add_argument('--thread', required=True)
p.add_argument('--output', required=True)
a = p.parse_args()

def db(home):
    return sqlite3.connect('file:' + str(pathlib.Path(home, 'userdata/statev2.sqlite')) + '?mode=ro', uri=True)

c = db(a.home)
items = [json.loads(j) for j, in c.execute('select payload_json from orchestration_v2_projection_turn_items where thread_id=? order by ordinal', (a.thread,))]
tools = [{k: x.get(k) for k in ['toolName', 'startedAt', 'completedAt', 'input', 'output']} for x in items if x.get('toolName') in ['t3-code.delegate_task', 't3-code.task_status']]
delegate = tools[0]['output']
child = delegate.get('childThreadId') or delegate['remoteChild']['threadId']
cc = db(a.child_home or a.home)
runs = [json.loads(j) for j, in cc.execute('select payload_json from orchestration_v2_projection_runs where thread_id=? order by ordinal', (child,))]
milestones = [{k: r.get(k) for k in ['id', 'status', 'requestedAt', 'startedAt', 'completedAt']} for r in runs]
events = [{'type': t, 'at': at} for t, at in cc.execute('select event_type,occurred_at from orchestration_v2_events where thread_id=? order by sequence', (child,)) if t in ['run.start-requested', 'run.started', 'run.completed', 'run.status-changed']]
out = {'capturedAt': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'parentThreadId': a.thread, 'childThreadId': child, 'toolResults': tools, 'childRuns': milestones, 'milestones': events}
pathlib.Path(a.output).write_text(json.dumps(out, indent=2) + '\n')
print(json.dumps({'thread': a.thread, 'tools': [[t['toolName'], t['output'].get('status'), t['output'].get('workState')] for t in tools], 'childRuns': milestones}))
