# Usage: python3 reproduce.py /path/to/base-checkout /path/to/head-checkout
import sys,socket,os,json,time,subprocess,threading,http.server,pathlib,signal,datetime
root=pathlib.Path(__file__).parent
out=root/datetime.datetime.now().strftime('%Y%m%d-%H%M%S');out.mkdir()
models=[]
class Gateway(http.server.BaseHTTPRequestHandler):
 def do_GET(self):
  body=json.dumps({'object':'list','data':[{'id':m,'object':'model','created':1,'owned_by':'gateway'} for m in models]}).encode();self.send_response(200);self.send_header('Content-Type','application/json');self.end_headers();self.wfile.write(body)
 def log_message(self,*args):pass
gateway=http.server.HTTPServer(('127.0.0.1',0),Gateway);threading.Thread(target=gateway.serve_forever,daemon=True).start()
summary=[]
try:
 for side,checkout,sha in [('before',sys.argv[1],'fc36e5d435'),('after',sys.argv[2],'26d809b364')]:
  folder=out/side;folder.mkdir(); home=folder/'t3home';claude=folder/'claude';claude.mkdir()
  env=os.environ.copy();env.update(T3CODE_DEV_SEED='0',CLAUDE_CONFIG_DIR=str(claude),ANTHROPIC_BASE_URL=f'http://127.0.0.1:{gateway.server_port}',ANTHROPIC_AUTH_TOKEN='fake',CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY='1')
  for launch in range(1,4):
   models[:]=['ccs-claude-gw--alpha:free[1m]','ccs-claude-gw--alpha:free','ccs-claude-gw--beta'] if launch==1 else ['ccs-claude-gw--alpha:free[1m]','ccs-claude-gw--gamma']
   socket_probe=socket.socket();socket_probe.bind(('127.0.0.1',0));port=socket_probe.getsockname()[1];socket_probe.close()
   log=open(folder/f'launch-{launch}.log','w');p=subprocess.Popen(['node','apps/server/src/bin.ts','serve','--base-dir',str(home),'--port',str(port)],cwd=pathlib.Path(checkout),env=env,stdout=log,stderr=subprocess.STDOUT)
   print(side,'launch',launch,'started',flush=True)
   try: p.wait(timeout=75)
   except subprocess.TimeoutExpired:
    p.send_signal(signal.SIGINT)
    try:p.wait(timeout=15)
    except subprocess.TimeoutExpired:p.kill();p.wait()
   log.close()
   files=list(home.rglob('claudeAgent.json'));cache=json.loads(files[0].read_text()) if files else None
   gatewayfiles=list(claude.rglob('gateway-models.json'));gw=json.loads(gatewayfiles[0].read_text()) if gatewayfiles else None
   record={'side':side,'commit':sha,'launch':launch,'gatewayListing':models.copy(),'t3Cache':cache,'claudeGatewayCache':gw}
   (folder/f'snapshot-{launch}.json').write_text(json.dumps(record,indent=2));summary.append(record)
   print(json.dumps({'side':side,'launch':launch,'status':cache and cache['status'],'gatewayModels':[m['slug'] for m in cache['models'] if m['slug'].startswith('ccs-claude-gw--')] if cache else None}),flush=True)
finally:gateway.shutdown()
(out/'evidence.json').write_text(json.dumps(summary,indent=2));print('OUTPUT',out,flush=True)
