"""Record a real Claude Plan turn; pass browser binary, session, checkout, side, output root.
Run seed.py first, pair the browser, open Plan approval proof, and close thread details.
No provider events or approvals are mocked. Every approval uses the visible UI.
"""
import sys,subprocess,sqlite3,json,time,datetime,pathlib
ab,session,checkout,side,output=sys.argv[1:]
out=pathlib.Path(output)/f"{side}-{datetime.datetime.now().strftime('%Y%m%d-%H%M%S')}"
out.mkdir(parents=True)
def browser(*args):
 r=subprocess.run([ab,"--session",session,*args],capture_output=True,text=True,check=True)
 return r.stdout
c=sqlite3.connect(f"file:{checkout}/.t3/userdata/statev2.sqlite?mode=ro",uri=True)
tid=c.execute("select thread_id from orchestration_v2_projection_threads where title='Plan approval proof' order by created_at desc limit 1").fetchone()[0]
browser("record","start",str(out/f"{side}.mp4"),"--fps","10","--cursor")
approved=set()
try:
 deadline=time.monotonic()+240
 while time.monotonic()<deadline:
  rows=c.execute("select runtime_request_id,status from orchestration_v2_projection_runtime_requests where thread_id=? order by created_at",(tid,)).fetchall()
  pending=[r[0] for r in rows if r[1]=='pending' and r[0] not in approved]
  if pending:
   browser("find","role","button","click","--name","More approval options")
   if len(approved)==1:
    a=out/f"{side}-repeat-a.png"; b=out/f"{side}-repeat.png"
    browser("screenshot",str(a)); time.sleep(.5); browser("screenshot",str(b))
    print("Repeat capture identical:",a.read_bytes()==b.read_bytes(),flush=True)
   browser("find","role","menuitem","click","--name","Always allow this session")
   approved.add(pending[0]); print("Session approvals:",len(approved),flush=True)
  result=c.execute("select payload_json from orchestration_v2_projection_turn_items where thread_id=? and type='assistant_message'",(tid,)).fetchall()
  if any('FOUR READS COMPLETE' in x[0] for x in result):
   print("FOUR READS COMPLETE; session approvals:",len(approved),flush=True)
   break
  time.sleep(.5)
 else: raise RuntimeError("Turn did not finish within capture window")
finally:
 browser("record","stop")
 print("Captures:",out,flush=True)
