import pathlib, subprocess, os, time, json, socket, threading, urllib.request, urllib.error, statistics, sys, datetime
ROOT=pathlib.Path(__file__).parent
OUT=pathlib.Path(sys.argv[2]) if len(sys.argv)>2 else ROOT/('runs-'+datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')); OUT.mkdir(exist_ok=True)
SIDES={'base':pathlib.Path.home()/'wt/factory-issue-46615-evidence-1-base','head':pathlib.Path.home()/'wt/factory-issue-46615-evidence-1'}

def run(side,n):
 d=OUT/f'{side}-{n}'
 if d.exists(): d=OUT/f'{side}-{n}-retry'
 d.mkdir(); repo=d/'repo'; repo.mkdir()
 for i in range(3000): (repo/f'file-{i:04d}.txt').write_text(('original line %04d abcdefghijklmnopqrstuvwxyz0123456789\n'%i)*240)
 (repo/'rewrite.py').write_text("from pathlib import Path\nfor p in Path('.').glob('file-*.txt'):\n p.write_text(p.read_text().replace('original', 'rewritten'))\nprint('rewrote 3000 files')\n")
 def git(*args): return subprocess.check_output(['git','-C',str(repo),*args],stderr=subprocess.STDOUT,text=True)
 git('init','-q'); git('add','.'); git('-c','user.name=Synthetic','-c','user.email=synthetic@example.com','commit','-qm','Seed 3000 files')
 home=d/'t3'; (home/'userdata').mkdir(parents=True)
 (home/'userdata/settings.json').write_text(json.dumps({'providerInstances':{'opencode':{'driver':'opencode','enabled':True,'config':{'binaryPath':'opencode1'}}}}))
 env=os.environ.copy(); env.update(T3CODE_DEV_SEED='0',XDG_DATA_HOME=str(d/'opencode-data'),T3CODE_HOME=str(home))
 s=socket.socket(); s.bind(('127.0.0.1',0)); port=s.getsockname()[1]; s.close()
 cwd=SIDES[side]; cli=['node',str(cwd/'apps/server/src/bin.ts')]
 log=open(d/'server.private.log','w'); server=subprocess.Popen(cli+['serve','--host','127.0.0.1','--port',str(port),'--base-dir',str(home)],cwd=cwd,env=env,stdout=log,stderr=log)
 probes=[]; stop=threading.Event()
 def probe():
  while not stop.is_set():
   start=time.monotonic(); status='ok'
   try:
    with urllib.request.urlopen(f'http://127.0.0.1:{port}/api/health',timeout=6) as r: r.read()
   except urllib.error.HTTPError as e: e.read(); status='http_'+str(e.code)
   except Exception as e: status=type(e).__name__
   probes.append({'at':round(start-begin,3),'seconds':round(time.monotonic()-start,6),'status':status})
   stop.wait(.5)
 begin=time.monotonic()
 try:
  for _ in range(180):
   try:
    urllib.request.urlopen(f'http://127.0.0.1:{port}/api/health',timeout=1).read(); break
   except urllib.error.HTTPError: break
   except Exception:
    if server.poll() is not None: raise RuntimeError('server exited; inspect private log')
    time.sleep(1)
  else: raise RuntimeError('startup timed out')
  time.sleep(3)
  add=subprocess.run(cli+['project','add',str(repo),'--base-dir',str(home)],cwd=cwd,env=env,capture_output=True,text=True,timeout=120)
  if add.returncode: raise RuntimeError('project add failed: '+add.stdout[-500:]+add.stderr[-500:])
  thread=threading.Thread(target=probe); thread.start(); time.sleep(3)
  turn_start=time.monotonic()
  turn=subprocess.run(cli+['thread','start','--base-dir',str(home),'--provider','opencode','--model','openai/gpt-5.6-luna','--wait','--json',str(repo),"Run exactly this bash command once and then reply 'done': python3 rewrite.py"],cwd=cwd,env=env,capture_output=True,text=True,timeout=900)
  elapsed=time.monotonic()-turn_start; time.sleep(3); stop.set(); thread.join()
  changed=len(git('diff','--name-only').splitlines()); content_ok=all('rewritten' in p.read_text() and 'original' not in p.read_text() for p in repo.glob('file-*.txt'))
  # Raw CLI output can include local paths; keep private and publish only outcome.
  (d/'turn.private.txt').write_text(turn.stdout+'\n'+turn.stderr)
  result={'side':side,'run':n,'run_dir':d.name,'sha':subprocess.check_output(['git','rev-parse','HEAD'],cwd=cwd,text=True).strip(),'platform':'Linux x86_64','opencode':'1.19.6','model':'openai/gpt-5.6-luna','files':3000,'bytes_after':sum(len(p.read_bytes()) for p in repo.glob('file-*.txt')),'turn_exit':turn.returncode,'turn_seconds':round(elapsed,3),'changed_files':changed,'content_ok':content_ok,'reply_done':'done' in turn.stdout.lower(),'max_health_seconds':max(p['seconds'] for p in probes),'median_health_seconds':statistics.median(p['seconds'] for p in probes),'over_1s':sum(p['seconds']>1 for p in probes),'timeouts':sum(p['status'] not in ['ok','http_503'] for p in probes),'probes':probes}
  (d/'measurement.json').write_text(json.dumps(result,indent=2)); print(json.dumps({k:v for k,v in result.items() if k!='probes'}),flush=True)
  return result
 finally:
  stop.set()
  server.terminate()
  try: server.wait(timeout=20)
  except subprocess.TimeoutExpired: server.kill(); server.wait()
  log.close()
results=json.loads((OUT/'measurements.json').read_text()) if (OUT/'measurements.json').exists() else []
for n in range(1,int(sys.argv[1] if len(sys.argv)>1 else 3)+1):
 for side in ['base','head']:
  if any(m['side']==side and m['run']==n for m in results): continue
  results.append(run(side,n)); (OUT/'measurements.json').write_text(json.dumps(results,indent=2))
print('OUTPUT',OUT,flush=True)
