import argparse, subprocess, os, time, threading, pathlib, socket, shutil, json, signal
p=argparse.ArgumentParser(); p.add_argument('checkout'); p.add_argument('node'); p.add_argument('output'); p.add_argument('side'); a=p.parse_args()
out=pathlib.Path(a.output)/time.strftime('%Y%m%d-%H%M%S'); out.mkdir(parents=True)
root=pathlib.Path(a.checkout); cwd=root/'apps/server'
sha=subprocess.check_output(['git','rev-parse','HEAD'],cwd=root,text=True).strip()
version=subprocess.check_output([a.node,'--version'],text=True).strip()
events=[]; lock=threading.Lock(); started=time.monotonic(); counts={'restart':0,'ready':0}; rows=[]
def emit(s):
    with lock:
        t=round(time.monotonic()-started,2); events.append([t,s]); print(f'{t:6.2f}s {s}',flush=True)
def reader():
    for line in proc.stdout:
        line=line.strip()
        if '[dev]' in line or 'Listening on http://' in line or 'Running database migrations' in line or 'Migrations ran successfully' in line:
            if 'Listening on' in line:
                counts['ready']+=1; line='SERVER: Listening on loopback (HTTP request checked below)'
            if '[dev] Restarting' in line: counts['restart']+=1
            emit(line)
        elif 'Error:' in line or 'ERROR' == line: emit('SERVER ERROR: '+line.replace(str(root),'<checkout>').replace(str(out),'<isolated-state>'))
def wait_ready(n,timeout=45):
    end=time.monotonic()+timeout
    while counts['ready']<n:
        if time.monotonic()>end: raise RuntimeError('server readiness timed out')
        time.sleep(.1)
    import urllib.request, urllib.error
    try:
        r=urllib.request.urlopen(f'http://127.0.0.1:{port}/api/health',timeout=3); status=r.status
    except urllib.error.HTTPError as e: status=e.code
    emit(f'HTTP probe answered: status {status}')
def step(label,action):
    emit('ACTION: '+label); before=counts['restart']; ready=counts['ready']; action(); time.sleep(6)
    delta=counts['restart']-before
    emit(f'OBSERVED over 6 seconds: {delta} restart(s)'); rows.append([label,delta])
    if delta: wait_ready(ready+delta)
def append(path):
    with open(cwd/path,'a') as f: f.write('\n// directory-swap runtime proof\n')
s=socket.socket(); s.bind(('127.0.0.1',0)); port=s.getsockname()[1]; s.close()
emit(f'{a.side.upper()} | commit {sha}'); emit(f'Linux x86_64 | Node {version} | real apps/server/scripts/dev.ts'); emit('Fresh isolated database; T3CODE_DEV_SEED=0; no provider or seeded data')
env=os.environ.copy(); env['T3CODE_DEV_SEED']='0'
proc=subprocess.Popen([a.node,'scripts/dev.ts','--port',str(port),'--host','127.0.0.1','--no-browser','--base-dir',str(out/'state')],cwd=cwd,env=env,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
t=threading.Thread(target=reader,daemon=True); t.start()
try:
    wait_ready(1)
    step('Control: append src/bin.ts',lambda:append(pathlib.Path('src/bin.ts')))
    emit('PREPARE: cp -r src/guest guest-replacement (outside src, same filesystem)')
    shutil.copytree(cwd/'src/guest',cwd/'guest-replacement',copy_function=shutil.copy2)
    def swap():
        os.rename(cwd/'src/guest',cwd/'guest-original'); os.rename(cwd/'guest-replacement',cwd/'src/guest')
    step('Swap: rename src/guest away, rename replacement into src/guest',swap)
    step('Append replacement src/guest/http.ts',lambda:append(pathlib.Path('src/guest/http.ts')))
    step('Append replacement src/guest/guestView.ts',lambda:append(pathlib.Path('src/guest/guestView.ts')))
    step('Append moved-away guest-original/http.ts (outside src)',lambda:append(pathlib.Path('guest-original/http.ts')))
    step('Control: append src/bin.ts again',lambda:append(pathlib.Path('src/bin.ts')))
    step('Control: append untouched src/git/detachStackFrame.ts',lambda:append(pathlib.Path('src/git/detachStackFrame.ts')))
    emit('COMPLETE: '+json.dumps(rows))
finally:
    proc.send_signal(signal.SIGTERM)
    try: proc.wait(timeout=20)
    except subprocess.TimeoutExpired: proc.kill(); proc.wait()
    t.join(timeout=2)
    (out/'events.json').write_text(json.dumps(events,indent=2))
    (out/'transcript.txt').write_text('\n'.join(f'{t:6.2f}s {s}' for t,s in events)+'\n')
    (out/'result.json').write_text(json.dumps({'sha':sha,'rows':rows,'events':events},indent=2))
    print('OUTPUT '+str(out),flush=True)
