#!/usr/bin/env python3
"""Real CLI proof. Usage: python3 reproduce.py CHECKOUT OUTPUT_DIRECTORY PORT
Requires the checkout's apps/server/dist/bin.mjs built with vp run build:bundle.
Creates only synthetic data, runs a fresh isolated server, and stops that server.
"""
import sys, os, pathlib, subprocess, time, socket, json, re
checkout=pathlib.Path(sys.argv[1]).resolve()
out=pathlib.Path(sys.argv[2]).resolve(); out.mkdir(parents=True,exist_ok=False)
port=int(sys.argv[3]); repo=out/'repo'; repo.mkdir(); (repo/'pkg').mkdir(); (repo/'pkg/file.txt').write_text('synthetic proof\n')
env={k:v for k,v in os.environ.items() if not k.startswith('GIT_')}; env['T3CODE_DEV_SEED']='0'
def git(*args):
 subprocess.run(['git',*args],cwd=repo,env=env,check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
git('init'); git('add','.'); git('-c','user.name=Proof','-c','user.email=proof@example.com','commit','-m','Synthetic fixture'); git('worktree','add','-b','feature','../repo-feature')
cli=['node',str(checkout/'apps/server/dist/bin.mjs')]; base=out/'data'
log=open(out/'server.log','w')
server=subprocess.Popen(cli+['serve','--base-dir',str(base),'--port',str(port),'--host','127.0.0.1',str(out)],cwd=checkout,env=env,stdout=log,stderr=log)
rows=[]; events=[]
def add(s):
 rows.extend(s.splitlines()); events.append(list(rows))
def run(args,cwd,extra=None,display=''):
 add('$ '+display)
 p=subprocess.run(cli+args,cwd=cwd,env=env| (extra or {}),capture_output=True,text=True)
 text=p.stdout+p.stderr
 text=re.sub(r'\x1b\[[0-9;]*m','',text).replace(str(out),'<fixture>')
 # Registered project identifiers differ between fresh databases.
 text=re.sub(r'Added project .*? \(repo\)', 'Added project <id> (repo)',text)
 add(text.rstrip()); add('exit '+str(p.returncode)); add('')
 return {'exit':p.returncode,'output':text}
try:
 for i in range(200):
  if server.poll() is not None: raise RuntimeError('Server exited; see local server.log')
  try:
   with socket.create_connection(('127.0.0.1',port),timeout=.2):
    runtime=base/'userdata/server-runtime.json'
    if runtime.exists() and json.loads(runtime.read_text()).get('pid'): break
  except OSError: pass
  time.sleep(.1)
 else: raise RuntimeError('Server did not listen')
 sha=subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip()
 add('T3 Code CLI | Linux x86_64 | Node '+subprocess.check_output(['node','--version'],text=True).strip())
 add('commit '+sha); add('Fresh database; synthetic repo + linked feature worktree'); add('Server: 127.0.0.1 | T3CODE_DEV_SEED=0'); add('')
 result={'sha':sha}
 result['add']=run(['project','add','--base-dir',str(base),'repo'],out,display='t3 project add --base-dir <data> repo')
 result['control']=run(['thread','list','--json','--base-dir',str(base),'--project','../repo-feature/pkg'],repo,display='t3 thread list --json --base-dir <data> --project ../repo-feature/pkg')
 result['relative']=run(['thread','list','--json','--base-dir',str(base),'--project','../repo-feature/pkg'],repo,{'GIT_DIR':'.git'},'GIT_DIR=.git t3 thread list --json --base-dir <data> --project ../repo-feature/pkg')
 (out/'transcript.txt').write_text('\n'.join(rows)+'\n')
 (out/'events.json').write_text(json.dumps(events)); (out/'result.json').write_text(json.dumps(result,indent=2))
 print(json.dumps(result,indent=2))
finally:
 server.terminate()
 try: server.wait(timeout=15)
 except subprocess.TimeoutExpired: server.kill(); server.wait()
 log.close()
