"""Real T3 server reproduction. Requires the stage env and two CLI-linked isolated homes.
Usage: python3 driver.py WORKTREE HOME SIDE ARTIFACT_DIRECTORY OLD_BINARY
Each server is a real subprocess; no service mocks, binary stubs, or database edits.
"""
import os, sys, subprocess, time, pathlib, shutil, signal, json, re, selectors
worktree, home, side, artifacts, old_binary = sys.argv[1:]
home, out, old = pathlib.Path(home), pathlib.Path(artifacts), pathlib.Path(old_binary)
out.mkdir(parents=True, exist_ok=True)
pin = home/'tools/cloudflared/2026.10.4/linux-x64/cloudflared'
if pin.exists():
    pin.rename(out/'initial-pin')
for case in ['path', 'override', 'managed']:
    if pin.exists(): pin.rename(out/(case+'-saved-pin'))
    env = dict(os.environ, T3CODE_DEV_SEED='0')
    env.pop('T3CODE_CLOUDFLARED_PATH', None)
    if case == 'path': env['PATH'] = str(old.parent)+os.pathsep+env['PATH']
    if case == 'override': env['T3CODE_CLOUDFLARED_PATH'] = str(old)
    if case == 'managed':
        dest = home/'tools/cloudflared/2026.9.3/linux-x64/cloudflared'
        dest.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(old,dest)
    command = ['node','apps/server/src/bin.ts','serve','--port','18401','--host','127.0.0.1','--base-dir',str(home)]
    proc = subprocess.Popen(command,cwd=worktree,env=env,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,start_new_session=True)
    start = time.monotonic(); events=[]; text=''; completed=None
    print(side,case,'server spawned',flush=True)
    sel=selectors.DefaultSelector();sel.register(proc.stdout,selectors.EVENT_READ)
    try:
        with open(out/(case+'-raw.log'),'wb') as raw:
            while time.monotonic()-start < 160:
                for key,_ in sel.select(timeout=0.5):
                    chunk=os.read(key.fileobj.fileno(),65536)
                    if not chunk: break
                    raw.write(chunk);raw.flush()
                    s=chunk.decode(errors='replace');text+=s;events.append([round(time.monotonic()-start,3),s])
                if 'Relay client tunnel connection registered' in text and completed is None: completed=time.monotonic()
                if case=='override' and side=='head' and 'must point to cloudflared 2026.10.3 or newer' in text and completed is None: completed=time.monotonic()
                if completed and time.monotonic()-completed>5: break
                if proc.poll() is not None: break
    finally:
        os.killpg(proc.pid,signal.SIGINT)
        try: proc.wait(timeout=15)
        except subprocess.TimeoutExpired: os.killpg(proc.pid,signal.SIGKILL);proc.wait()
        sel.close()
    (out/(case+'-events-private.json')).write_text(json.dumps(events))
    print(side,case,'finished', 'connected='+str('Relay client tunnel connection registered' in text),flush=True)
    for match in re.finditer(r'Relay client process started[^\n]*\n\s*\{[^}]*\}',text):
        b=match.group(); print('\n'.join(x for x in b.splitlines() if 'source:' in x or 'version:' in x),flush=True)
