"""Read only this reproduction's databases. Usage: collect-evidence.py BASE_DB HEAD_DB OUTPUT_DIR"""
import json, pathlib, sqlite3, sys
base, head, dest = map(pathlib.Path, sys.argv[1:])
def collect(db):
    con = sqlite3.connect(f'file:{db}?mode=ro', uri=True)
    con.row_factory = sqlite3.Row
    queries = {
      'projects': 'select project_id,title,deleted_at from projection_projects',
      'threads': 'select thread_id,title,deleted_at from orchestration_v2_projection_threads',
      'runtimeRequests': 'select runtime_request_id,thread_id,provider_turn_id,kind,status,created_at,resolved_at from orchestration_v2_projection_runtime_requests',
      'providerTurns': 'select provider_turn_id,thread_id,ordinal,status,started_at,completed_at from orchestration_v2_projection_provider_turns',
    }
    result = {name: [dict(r) for r in con.execute(query)] for name, query in queries.items()}
    result['sleepCommands'] = [json.loads(r[0]) for r in con.execute("select payload_json from orchestration_v2_projection_turn_items where type='command_execution' and payload_json like '%sleep 30%'")]
    result['visibleTopLevelThreads'] = [t for t in result['threads'] if t['deleted_at'] is None and not t['thread_id'].startswith('thread:subagent:')]
    result['activePendingRequests'] = sum(r['status']=='pending' for r in result['runtimeRequests'])
    return result
before = collect(base)
after = collect(head)
pending = json.loads((dest/'head-pending-runtime-raw.json').read_text())
after['afterParentCompletionBeforeAnswer'] = {
    'runtimeRequests': pending['requests'],
    'providerTurns': [{k:v for k,v in t.items() if k != 'payload_json'} for t in pending['turns']]
}
before['nativePendingFormsAfterParentCompletion'] = json.loads((dest/'base-runtime-raw.json').read_text())['openCodeChildPendingForm']
after['nativePendingFormsAfterAnswerAndCompletion'] = json.loads((dest/'head-completed-runtime-raw.json').read_text())['openCodeChildPendingForm']
result = {
 'baseSha':'2579c3c4dd25c2a8572af53724b7cd6e87643483',
 'headSha':'ebcad39182b6f64230ef492d6e6935a173efdf58',
 'environment': {'surface':'web dev', 'browser':'Chromium through T3 preview', 'viewportCss':'1440x1000', 'deviceScaleFactor':2, 'theme':'dark', 'provider':'OpenCode 2.3.0', 'model':'anthropic/claude-haiku-5-5', 'seeding':'T3CODE_DEV_SEED=0; own database and OpenCode XDG dirs per side; one synthetic Color demo git project; no existing conversations'},
 'initialStateAccounting':'Each dev server auto-created a server project and an empty New thread. Both were removed through project remove --force before capture. Their deleted rows are included below. Each recording starts with no active thread and creates exactly one parent thread and its one background child. Titles are generated by the live model and differ between runs. There are no earlier color-question attempts in either database.',
 'base':before,'head':after,
 'visualVerification': {'base':'Question visible before LAUNCHED; disappears at parent completion; child remains Running and Waiting with no answer control.', 'head':'Question stays visible after LAUNCHED; clicking Red submits immediately; child finishes CHILD-PICKED=Red; parent replies PARENT-GOT-Red. Exactly one sidebar thread, no Input badge, also checked after reload.', 'completedScreenshotStablePairPixelDifference':0},
}
(dest/'runtime-evidence.json').write_text(json.dumps(result,indent=2)+'\n')
print(json.dumps({'baseTopLevelThreads':len(before['visibleTopLevelThreads']), 'headTopLevelThreads':len(after['visibleTopLevelThreads']), 'baseRequestStatus':before['runtimeRequests'][0]['status'],'headRequestStatus':after['runtimeRequests'][0]['status'], 'headPendingRequests':after['activePendingRequests']}))
