import os,sys,time,json,subprocess,pathlib,datetime,socket,signal,shutil
ROOT=pathlib.Path(__file__).resolve().parent
side=sys.argv[1]; checkout=pathlib.Path(sys.argv[2]).resolve()
run=ROOT/(side+'-'+datetime.datetime.now().strftime('%Y%m%d-%H%M%S')); run.mkdir()
repo=run/'repo'; repo.mkdir(); data=run/'data'; events=[]; start=time.monotonic()
def emit(s):
    print(s,flush=True); events.append({'seconds':round(time.monotonic()-start,3),'text':s}); (run/'recording.json').write_text(json.dumps(events,indent=2))
def git(*args): return subprocess.run(['git','-C',str(repo),*args],check=True,capture_output=True,text=True).stdout
emit('Linux x86_64 | real T3 Code server + Replay (dev) | fresh database')
emit('Commit '+subprocess.check_output(['git','-C',str(checkout),'rev-parse','HEAD'],text=True).strip())
git('init'); git('config','user.name','Evidence'); git('config','user.email','evidence@example.com'); (repo/'README.md').write_text('Synthetic checkpoint timing reproduction\n'); git('add','README.md'); git('commit','-m','seed')
emit('Generating 40 x 100 MB untracked random files (4 GB).')
for i in range(40):
    if len(sys.argv)>3:
        shutil.copyfile(pathlib.Path(sys.argv[3])/f'random-{i:02}.bin',repo/f'random-{i:02}.bin'); continue
    with (repo/f'random-{i:02}.bin').open('wb') as f:
        for j in range(10): f.write(os.urandom(10_000_000))
emit('Starting server; no seed copied; dev URL registers recorded Replay agent.')
sock=socket.socket(); sock.bind(('127.0.0.1',0)); port=sock.getsockname()[1]; sock.close()
env={**os.environ,'T3CODE_DEV_SEED':'0','T3CODE_TELEMETRY_ENABLED':'false'}
log=(run/'server-private.log').open('w')
server=subprocess.Popen(['node',str(checkout/'apps/server/src/bin.ts'),'serve','--base-dir',str(data),'--port',str(port),'--host','127.0.0.1','--dev-url',f'http://127.0.0.1:{port+1}','--no-browser'],cwd=checkout,env=env,stdout=log,stderr=log)
results=[]
def cli(*args):
    t=time.monotonic(); p=subprocess.run(['node',str(checkout/'apps/server/src/bin.ts'),*args,'--base-dir',str(data)],cwd=repo,env=env,capture_output=True,text=True,timeout=180)
    if p.returncode: raise RuntimeError(p.stdout+p.stderr)
    return p.stdout,round(time.monotonic()-t,3)
try:
    for _ in range(120):
        if (data/'userdata/server-runtime.json').exists(): break
        if server.poll() is not None: raise RuntimeError('server exited: '+(run/'server-private.log').read_text()[-3000:])
        time.sleep(.5)
    emit('Wait 20 s for Replay model discovery.'); time.sleep(20)
    emit('t3 project add <synthetic repo>'); out,_=cli('project','add',str(repo))
    emit('Warmup: t3 thread start --provider devReplay --model showcase --wait --json <repo> "go A"')
    out,duration=cli('thread','start','--provider','devReplay','--model','showcase','--wait','--json',str(repo),'go A')
    (run/'warmup.json').write_text(out); obj=json.loads(out); emit('Warmup completed in '+str(duration)+' s; result saved.')
    # --wait returns threadId either directly or under thread.
    aid=obj.get('threadId') or obj.get('id') or obj.get('thread',{}).get('id')
    if not aid: raise RuntimeError('Cannot find thread id: '+out[:1000])
    emit('Wait 34 s for warmup post-turn capture to time out (streak becomes 2).'); time.sleep(34)
    for n in range(1,4):
        emit(f'Round {n}: t3 thread send --wait A "round {n}"')
        a,ad=cli('thread','send','--wait','--json',aid,f'round {n}'); (run/f'A-{n}.json').write_text(a)
        emit(f'Round {n}: A reply returned after {ad} s. Wait 1 s; A post-turn capture holds folder lock.'); time.sleep(1)
        emit(f'Round {n}: t3 thread start --provider devReplay --model showcase --wait --json <repo> "go B {n}"')
        b,bd=cli('thread','start','--provider','devReplay','--model','showcase','--wait','--json',str(repo),f'go B {n}'); (run/f'B-{n}.json').write_text(b)
        results.append({'round':n,'A_wait_seconds':ad,'B_wait_seconds':bd,'B_result':json.loads(b)})
        emit(f'Round {n}: B completed in {bd} s; same Replay reply; checkpoint baseline skipped.'); time.sleep(65)
    (run/'results.json').write_text(json.dumps(results,indent=2)); emit('Three rounds complete. Trace contains baseline and provider turn-start spans.')
finally:
    server.terminate()
    try: server.wait(timeout=15)
    except subprocess.TimeoutExpired: server.kill(); server.wait()
    log.close()
    emit('Server stopped.')
    print('RUN_DIRECTORY='+str(run),flush=True)
