#!/usr/bin/env python3
"""Run against two already-started isolated T3 dev servers. No database writes.
Usage: python3 drive.py BASE_CHECKOUT HEAD_CHECKOUT EMPTY_PROJECT OUTPUT_DIR
Enable Pi in each server's settings, pointing binaryPath at pi-capture.py first.
Start servers using T3CODE_DEV_SEED=0 vp run dev. Requires pi on PATH.
"""
import sys,subprocess,sqlite3,json,time,pathlib,threading,datetime
base,head,project,out=sys.argv[1:];out=pathlib.Path(out);out.mkdir(parents=True,exist_ok=True)
for side,checkout in [('before',base),('after',head)]:
 db=sqlite3.connect(f'file:{checkout}/.t3/userdata/statev2.sqlite?mode=ro',uri=True)
 records=[];seen=set();stop=threading.Event()
 def watch():
  conn=sqlite3.connect(f'file:{checkout}/.t3/userdata/statev2.sqlite?mode=ro',uri=True)
  while not stop.is_set():
   for tid,payload in conn.execute('select thread_id,payload_json from orchestration_v2_projection_provider_turns'):
    p=json.loads(payload);u=p.get('tokenUsage');key=(tid,p['ordinal'],p['status'],json.dumps(u,sort_keys=True))
    if u and key not in seen:
     seen.add(key);records.append({'thread':tid,'turn':p['ordinal'],'status':p['status'],'tokenUsage':u})
   stop.wait(.001)
  conn.close()
 logpath=pathlib.Path(__file__).with_name('pi-raw.jsonl');offset=logpath.stat().st_size if logpath.exists() else 0
 t=threading.Thread(target=watch);t.start()
 cli=['node','apps/server/src/bin.ts'];commands=[]
 def run(args):
  r=subprocess.run(cli+args+['--base-dir','.t3'],cwd=checkout,text=True,capture_output=True)
  commands.append({'command':'t3 '+' '.join(args).replace(project,'<empty-project>'),'exit':r.returncode,'stdout':r.stdout,'stderr':r.stderr})
  if r.returncode:raise RuntimeError(r.stderr)
  return r.stdout
 try:
  start=json.loads(run(['thread','start',project,'Reply with the single word ok.','--provider','pi','--model','default','--wait','--json']))
  tid=start['threadId']
  run(['thread','send',tid,'Reply with the single word ok.','--wait','--json'])
 finally:
  stop.set();t.join()
 usage=[r for r in records if r['thread']==tid]
 for r in usage:r.pop('thread')
 final=[{'turn':p['ordinal'],'status':p['status'],'model':p.get('model'),'tokenUsage':p.get('tokenUsage')} for (payload,) in db.execute('select payload_json from orchestration_v2_projection_provider_turns where thread_id=? order by ordinal',(tid,)) for p in [json.loads(payload)]]
 raw=logpath.read_text()[offset:]
 data={'side':side,'commit':subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip(),'environment':'Linux; real T3 dev server and CLI; fresh isolated database; Pi 1.6.0; default anthropic/claude-opus-5-5; empty project; no replay','commands':commands,'observedProjectionTransitions':usage,'completedTurns':final,'nativePiUsage':[json.loads(l) for l in raw.splitlines()]}
 (out/f'{side}.json').write_text(json.dumps(data,indent=2)+'\n')
 print(side,json.dumps(final),flush=True)
