import os,sys,json,time,subprocess,pathlib,socket,signal
root=pathlib.Path(sys.argv[1]).resolve(); out=pathlib.Path(sys.argv[2]).resolve(); out.mkdir(parents=True)
data=out/'data'; (data/'userdata').mkdir(parents=True)
project=out/'project'; project.mkdir(); subprocess.run(['git','init','-q',str(project)])
shadow=out/'shadow'; shadow.mkdir()
# The unrelated program from the reported reproduction; it does not implement a provider.
(shadow/'codex').write_text('#!/bin/sh\nprintf "unrelated console program, not JSON\\n"\n'); (shadow/'codex').chmod(0o755)
settings={'providerInstances':{'codex':{'driver':'codex','enabled':True,'binaryPath':'/usr/local/bin/codex'}}}
(data/'userdata/settings.json').write_text(json.dumps(settings))
env=dict(os.environ,T3CODE_DEV_SEED='0',PATH=str(shadow)+':'+os.environ['PATH'])
sock=socket.socket(); sock.bind(('127.0.0.1',0)); port=sock.getsockname()[1]; sock.close()
log=open(out/'server-private.log','w'); start=time.monotonic(); events=[]
def clean(s):
 for a,b in [(str(out),'$RUN'),(str(root),'$CHECKOUT'),(str(pathlib.Path.home()),'$HOME')]: s=s.replace(a,b)
 return s
def emit(s):
 s=clean(s); print(s,flush=True); events.append([round(time.monotonic()-start,3),'o',s+'\r\n'])
def cli(args):
 emit('$ t3 '+' '.join(args).replace(str(data),'$DATA').replace(str(project),'$PROJECT'))
 p=subprocess.run(['node',str(root/'apps/server/src/bin.ts'),*args,'--base-dir',str(data)],cwd=project,env=env,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,timeout=180)
 emit(p.stdout.strip()); emit('exit code: '+str(p.returncode)); return p
server=subprocess.Popen(['node','apps/server/src/bin.ts','serve','--base-dir',str(data),'--port',str(port)],cwd=root,env=env,stdout=log,stderr=log)
try:
 for _ in range(120):
  try:
   with socket.create_connection(('127.0.0.1',port),timeout=.2): break
  except OSError:
   if server.poll() is not None: raise RuntimeError('server exited')
   time.sleep(.5)
 emit('Linux / real T3 Code server and CLI / fresh database / Codex CLI 0.172.0')
 emit('Commit: '+subprocess.check_output(['git','rev-parse','HEAD'],cwd=root,text=True).strip())
 emit('settings.json: '+json.dumps(settings)); emit('PATH: unrelated console program named codex first; real Codex explicitly selected at /usr/local/bin/codex')
 cli(['project','add',str(project)])
 cli(['thread','start',str(project),'Reply with exactly the word READY','--provider','codex','--model','gpt-6-luna','--wait'])
 emit('Settings after run: '+(data/'userdata/settings.json').read_text())
finally:
 server.terminate()
 try: server.wait(timeout=15)
 except subprocess.TimeoutExpired: server.kill(); server.wait()
 log.close()
 (out/'transcript.txt').write_text('\n'.join(e[2].strip() for e in events)+'\n')
 (out/'terminal.cast').write_text(json.dumps({'version':2,'width':120,'height':32,'timestamp':int(time.time()),'title':'Issue 46837 real CLI reproduction'})+'\n'+'\n'.join(json.dumps(e) for e in events)+'\n')
