import sqlite3,json,sys,datetime,subprocess
from pathlib import Path
checkout=Path(sys.argv[1]); thread=sys.argv[2]; output=Path(sys.argv[3])
db=sqlite3.connect(f"file:{checkout}/.t3/userdata/statev2.sqlite?mode=ro",uri=True)
db.row_factory=sqlite3.Row
items=[json.loads(r[0]) for r in db.execute("select payload_json from orchestration_v2_projection_turn_items where thread_id=? and type in ('proposed_plan','run_interrupt_result')",(thread,))]
nodes=[dict(r) for r in db.execute("select kind,status,started_at,completed_at from orchestration_v2_projection_nodes where thread_id=? and kind in ('root_turn','plan')",(thread,))]
plans=[json.loads(r[0]) for r in db.execute("select payload_json from orchestration_v2_projection_plans where thread_id=?",(thread,))]
result={"capturedAt":datetime.datetime.now(datetime.timezone.utc).isoformat(),"commit":subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip(),"threadId":thread,"items":items,"nodes":nodes,"plans":plans}
output.write_text(json.dumps(result,indent=2))
print(json.dumps({"commit":result['commit'],"items":[{k:i.get(k) for k in ('type','status','streaming','completedAt')} | {'markdownChars':len(i.get('markdown',''))} for i in items],"nodes":nodes},indent=2))
