#!/usr/bin/env python3
"""Read only the isolated reproduction database; export synthetic timing evidence."""
import datetime, json, pathlib, sqlite3, sys
side, database, destination = sys.argv[1:]
c = sqlite3.connect('file:' + str(pathlib.Path(database).resolve()) + '?mode=ro', uri=True)
out = {'observedAt': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'side': side, 'tasks': [], 'messages': [], 'background': []}
for (s,) in c.execute('select payload_json from orchestration_v2_projection_subagents'):
    t = json.loads(s)
    out['tasks'].append({k: t.get(k) for k in ['status', 'prompt', 'result', 'startedAt', 'completedAt']})
for (s,) in c.execute('select payload_json from orchestration_v2_projection_messages order by created_at'):
    m = json.loads(s)
    out['messages'].append({k: m.get(k) for k in ['role', 'text', 'createdAt', 'updatedAt']})
for (s,) in c.execute('select payload_json from orchestration_v2_projection_provider_threads'):
    t = json.loads(s)
    out['background'] += [{k: b.get(k) for k in ['command', 'taskId', 'awaited', 'runId']} for b in t.get('pendingBackgroundTasks', [])]
pathlib.Path(destination).write_text(json.dumps(out, indent=2))
