# Usage: python3 reproduce.py BASE_CHECKOUT HEAD_CHECKOUT
# Place the supplied systemd-inhibit wrapper in ./wrapper/ first.
import os, subprocess, time, signal, pathlib, re, sys
root=pathlib.Path(__file__).parent
for side,suffix in [('before','-base'),('after','')]:
 cwd=pathlib.Path(sys.argv[1 if side == 'before' else 2]).resolve()
 env=os.environ.copy();env['PATH']=str(root/'wrapper')+':'+env['PATH'];env['T3CODE_DEV_SEED']='0'
 log=root/(side+'-raw.log')
 with log.open('w') as out:
  p=subprocess.Popen(['vp','run','dev'],cwd=cwd,env=env,stdout=out,stderr=subprocess.STDOUT,start_new_session=True)
  try:
   for i in range(240):
    text=log.read_text()
    if 'pairingUrl:' in text:break
    if p.poll() is not None:raise RuntimeError(text[-4000:])
    time.sleep(1)
   else:raise RuntimeError('startup timeout '+text[-4000:])
   print(side,'ready',flush=True)
   for args in [['project','add','--base-dir','.t3',str(cwd)],['thread','start','--base-dir','.t3','--provider','devReplay','--model','showcase',str(cwd),'go']]:
    r=subprocess.run(['node','apps/server/src/bin.ts']+args,cwd=cwd,env=env,capture_output=True,text=True,timeout=90)
    (root/(side+'-cli.log')).open('a').write(r.stdout+r.stderr)
    print(side,args[0],r.returncode,r.stdout[:500],r.stderr[:500],flush=True)
    if r.returncode:raise RuntimeError('CLI failed')
   time.sleep(18)
   text=log.read_text();print(side, '\n'.join(x for x in text.splitlines() if 'keep-awake' in x or 'InhibitorExited' in x or 'connect to bus' in x),flush=True)
  finally:
   os.killpg(p.pid,signal.SIGTERM)
   try:p.wait(timeout=15)
   except subprocess.TimeoutExpired:os.killpg(p.pid,signal.SIGKILL);p.wait()
