import subprocess, sqlite3, pathlib, time, threading, statistics, json, os, sys, platform
scratch=pathlib.Path(sys.argv[1]); root=pathlib.Path(sys.argv[2]); base=pathlib.Path(sys.argv[3])
out=scratch/time.strftime('run-%Y%m%d-%H%M%S'); out.mkdir()
rows=[]; env={**os.environ,'T3CODE_DEV_SEED':'0','NO_COLOR':'1'}
def run(cmd,cwd):
 start=time.perf_counter(); p=subprocess.run(cmd,cwd=cwd,env=env,text=True,capture_output=True)
 return p,round((time.perf_counter()-start)*1000,1)
for label,checkout in [('before',base),('after',root)]:
 home=out/label
 cli=['node','apps/server/src/bin.ts','auth','session','list','--base-dir',str(home)]
 p,ms=run(cli,checkout)
 assert p.returncode==0,p.stderr
 db=home/'userdata/statev2.sqlite'
 assert db.exists(),list(home.rglob('*'))
 con=sqlite3.connect(db)
 history=con.execute('select migration_id,name from effect_sql_migrations order by migration_id').fetchall(); con.close()
 print(label,'sha',subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip(),'migration',history[-1],flush=True)
 for surface in ['CLI','runMigrations']:
  for mode in ['unlocked','release-at-2s','held-through-return']:
   for n in range(7):
    lock=None; timer=None
    if mode!='unlocked':
     lock=sqlite3.connect(db,check_same_thread=False); lock.execute('BEGIN IMMEDIATE')
     if mode=='release-at-2s':
      timer=threading.Timer(2,lock.rollback); timer.start()
    cmd=cli if surface=='CLI' else ['node',str(scratch/'migrations.mjs'),str(checkout),str(db)]
    p,ms=run(cmd,checkout)
    if timer: timer.join()
    if lock: lock.rollback(); lock.close()
    text=p.stdout+p.stderr
    # Public capture contains outcomes, not runtime stacks with private filesystem paths.
    outcome='No active sessions.' if 'No active sessions.' in text else ('database is locked' if 'database is locked' in text else text.strip())
    if surface=='runMigrations':
     candidates=[line for line in p.stdout.splitlines() if line.startswith('{"pending"')]
     if candidates:
      data=json.loads(candidates[-1]); ms=round(data['ms'],2)
      outcome='pending='+str(data['pending']).lower()+'; '+('database is locked' if 'database is locked' in text else json.dumps(data['result'],separators=(',',':')))
    row=dict(side=label,surface=surface,mode=mode,run=n+1,ms=ms,exit=p.returncode,outcome=outcome)
    rows.append(row); print(json.dumps(row),flush=True)
 con=sqlite3.connect(db); assert history==con.execute('select migration_id,name from effect_sql_migrations order by migration_id').fetchall(); con.close()
 print(label,'migration history unchanged',flush=True)
print('Environment:',platform.system(),platform.machine(),'Node',subprocess.check_output(['node','--version'],text=True).strip(),flush=True)
for side in ['before','after']:
 for surface in ['CLI','runMigrations']:
  for mode in ['unlocked','release-at-2s','held-through-return']:
   vals=[r['ms'] for r in rows if (r['side'],r['surface'],r['mode'])==(side,surface,mode)]
   print(side,surface,mode,'median',statistics.median(vals),'range',min(vals),max(vals),flush=True)
(out/'results.json').write_text(json.dumps(rows,indent=2))
