#!/usr/bin/env python3
"""Read-only summary of synthetic reproduction state; emits no paths or model identifiers.
Usage: inspect-runtime.py BASE_HOME HEAD_HOME
"""
import json
import pathlib
import sqlite3
import subprocess
import sys

result = {}
for side, argument in zip(['base', 'head'], sys.argv[1:]):
    home = pathlib.Path(argument)
    db = sqlite3.connect(f'file:{home}/userdata/statev2.sqlite?mode=ro', uri=True)
    runs = []
    for run_id, ordinal, status in db.execute('select run_id,ordinal,status from orchestration_v2_projection_runs order by ordinal'):
        row = dict(runOrdinal=ordinal, status=status, checkpoints=[])
        for kind in ['run_interrupt_request', 'run_interrupt_result']:
            row[kind] = db.execute('select count(*) from orchestration_v2_projection_turn_items where run_id=? and type=?', (run_id, kind)).fetchone()[0]
        for checkpoint_status, payload in db.execute('select status,payload_json from orchestration_v2_projection_checkpoints where run_id=?', (run_id,)):
            ref = json.loads(payload)['ref']
            exists = subprocess.run(['git', '-C', str(home/'workspaces/handoff-demo'), 'show-ref', '--verify', '--quiet', ref]).returncode == 0
            row['checkpoints'].append(dict(status=checkpoint_status, ref=ref, gitRefExists=exists))
        runs.append(row)
    thread = json.loads(db.execute('select payload_json from orchestration_v2_projection_threads limit 1').fetchone()[0])
    worktree = thread['worktreePath']
    branch = subprocess.check_output(['git', '-C', worktree, 'branch', '--show-current'], text=True).strip()
    result[side] = dict(destinationBranch=branch, movedToWorktree=worktree != str(home/'workspaces/handoff-demo'), runs=runs)
    db.close()
print(json.dumps(result, indent=2))
