import os,sys,pathlib,subprocess,time,sqlite3,json,re,datetime
root=pathlib.Path(__file__).parent
run=root/datetime.datetime.now().strftime('%Y%m%d-%H%M%S');run.mkdir()
for side,checkout in [('before',sys.argv[1]),('after',sys.argv[2])]:
 lines=[f'{side.upper()} — Linux x86_64, Node CLI, fresh synthetic state', 'Command: t3 \' project\' --base-dir <fresh-state> --no-browser --port <free-port>']
 for case in (1,2):
  d=run/side/str(case);p=d/'parent';p.mkdir(parents=True);(p/' project').mkdir()
  if case==2:(p/'project').mkdir()
  import socket
  with socket.socket() as sock:sock.bind(('127.0.0.1',0));port=sock.getsockname()[1]
  state=d/'state'; log=d/'raw.log'
  with log.open('w') as f:
   proc=subprocess.Popen(['node',str(pathlib.Path(checkout)/'apps/server/dist/bin.mjs'),' project','--base-dir',str(state),'--no-browser','--port',str(port)],cwd=p,stdout=f,stderr=subprocess.STDOUT,env={**os.environ,'T3CODE_DEV_SEED':'0'})
   rows=[];deadline=time.monotonic()+45
   try:
    while time.monotonic()<deadline:
     for db in state.rglob('*.sqlite'):
      try:
       con=sqlite3.connect(f'file:{db}?mode=ro',uri=True);rows=con.execute('select title,workspace_root from projection_projects').fetchall();con.close()
      except sqlite3.Error:pass
     if rows or proc.poll() is not None:break
     time.sleep(.2)
    code=proc.poll()
   finally:
    if proc.poll() is None:proc.terminate()
    try:proc.wait(timeout=10)
    except subprocess.TimeoutExpired:proc.kill();proc.wait()
  raw=log.read_text();clean=re.sub(r'\x1b\[[0-9;]*m','',raw).replace(str(run),'<run>').replace(checkout,'<checkout>').replace(str(pathlib.Path.home()),'<home>')
  (d/'output.txt').write_text(clean)
  lines+=['',f'Case {case}: '+('only " project" exists' if case==1 else 'both " project" and "project" exist'),f'CLI exit before shutdown: {code if code is not None else "server running"}',f'Persisted project: {json.dumps(rows).replace(str(run),"<run>")}']
  lines += [x for x in clean.splitlines() if 'Unknown command' in x or 'Listening on' in x][:5]
 (run/f'{side}.txt').write_text('\n'.join(lines)+'\n')
print(run)
