import os,sys,subprocess,socket,tempfile,time,signal,re,json,pathlib
if '--inside' not in sys.argv:
    os.execvp('unshare',['unshare','-Urn',sys.executable,__file__,'--inside',*sys.argv[1:]])
_,_,checkout,out,side,sha=sys.argv
out=pathlib.Path(out); out.mkdir(parents=True,exist_ok=True)
subprocess.run(['ip','link','set','lo','up'],check=True)
start=time.monotonic(); events=[]
def say(s):
    events.append({'seconds':round(time.monotonic()-start,2),'text':s}); print(s,flush=True)
def listeners():
    text=subprocess.check_output(['ss','-H','-ltn'],text=True)
    return '\n'.join(line for line in text.splitlines() if '127.0.0.' in line or '[::1]' in line) or '(none)'
say(f'{side.upper()} | Linux | isolated network namespace | commit {sha[:10]}')
say('Fresh data directory; no --port, T3CODE_PORT, or saved bootstrap port.')
say('Initial TCP listeners: '+listeners())
holder=socket.socket(); holder.bind(('127.0.0.2',3773)); holder.listen()
say('Python holder bound only to 127.0.0.2:3773')
say(listeners())
for host,family in [('127.0.0.1',socket.AF_INET),('::1',socket.AF_INET6)]:
    with socket.socket(family) as probe:
        probe.bind((host,3773)); say(f'Confirmed {host}:3773 free')
env={k:v for k,v in os.environ.items() if not k.startswith('T3CODE_') and k not in ('PORT','VITE_HTTP_URL','VITE_WS_URL')}; env['T3CODE_DEV_SEED']='0'
with tempfile.TemporaryDirectory(dir=out) as data:
    logfile=open(out/'raw.log','w+')
    say('$ t3 serve --host 127.0.0.2 --base-dir <fresh> --no-browser <empty cwd>')
    cwd=pathlib.Path(data)/'project'; cwd.mkdir()
    p=subprocess.Popen(['node',str(pathlib.Path(checkout)/'apps/server/dist/bin.mjs'),'serve','--host','127.0.0.2','--base-dir',str(pathlib.Path(data)/'data'),'--no-browser',str(cwd)],cwd=checkout,env=env,stdout=logfile,stderr=subprocess.STDOUT,start_new_session=True)
    try:
        deadline=time.monotonic()+60; found=None
        while time.monotonic()<deadline:
            if p.poll() is not None: break
            state=listeners()
            ports=re.findall(r'127\.0\.0\.2:(\d+)',state)
            found=next((int(x) for x in ports if int(x)!=3773),None)
            if found:
                import http.client
                try:
                    c=http.client.HTTPConnection('127.0.0.2',found,timeout=2); c.request('GET','/'); r=c.getresponse(); body=r.read(); c.close()
                    
                    if r.status:
                        say(f'HTTP GET 127.0.0.2:{found}/ -> {r.status}'); break
                except OSError: pass
            time.sleep(.1)
        logfile.flush(); raw=(out/'raw.log').read_text()
        for line in raw.splitlines():
            if 'EADDRINUSE' in line or 'ServeError' in line:
                clean=re.sub(r'/[^\s:]+(?:/[^\s:]*)?', '<path>',line)
                say(clean)
        say('TCP listeners after startup:\n'+listeners())
        if p.poll() is not None: say(f'T3 exited with code {p.returncode}')
        else:
            say(f'T3 remains running; selected alias port {found}')
            time.sleep(3); say('Three seconds later: '+('still running' if p.poll() is None else f'exited {p.returncode}'))
        (out/'events.json').write_text(json.dumps(events,indent=2))
        (out/'transcript.txt').write_text('\n'.join(f'[{e["seconds"]:05.2f}s] {e["text"]}' for e in events)+'\n')
    finally:
        if p.poll() is None:
            os.killpg(p.pid,signal.SIGTERM)
            try:p.wait(timeout=10)
            except subprocess.TimeoutExpired:os.killpg(p.pid,signal.SIGKILL);p.wait()
        logfile.close(); holder.close()
