import os, sys, pathlib, subprocess, time, re, json, pexpect, shutil, socket
# Usage: python3 reproduce.py <base-checkout> <head-checkout> <output-directory>
ROOT=pathlib.Path(sys.argv[3]); ROOT.mkdir(parents=True,exist_ok=True)
run=ROOT / ('run-'+time.strftime('%Y%m%d-%H%M%S')); run.mkdir()
node=subprocess.check_output([shutil.which('node'),'-p','process.execPath']).decode().strip()
# All executables are real system binaries. Only the missing browser opener is excluded.
bindir=run/'bin'; bindir.mkdir()
for p in pathlib.Path('/usr/bin').iterdir():
    if p.name != 'xdg-open' and p.is_file() and os.access(p,os.X_OK):
        (bindir/p.name).symlink_to(p)
file=run/'notadir'; file.touch()
env=os.environ.copy()
env.update(dict(x.split('=',1) for x in subprocess.check_output(['/bin/bash','-c','set -a; . "$HOME/.config/t3-connect-test.env"; env -0']).decode().split('\0') if '=' in x))
for k in ['DISPLAY','WAYLAND_DISPLAY','SSH_CONNECTION','SSH_TTY','BROWSER','VITE_HTTP_URL','VITE_WS_URL']:
    env.pop(k,None)
env.update(PATH=str(bindir)+':'+str(file), SHELL='/bin/bash',T3CODE_DEV_SEED='0',TERM='xterm-256color',NO_COLOR='1')
for side,checkout in [('before',sys.argv[1]),('after',sys.argv[2])]:
    home=run/(side+'-home'); home.mkdir()
    (home/'.bash_profile').write_text('export PATH="'+str(bindir)+':'+str(file)+'"\n')
    e=env|{'HOME':str(home)}
    # Inspect the same real login profile consumed by T3's PATH hydration.
    effective=subprocess.check_output(['/bin/bash','-ilc','printf "%s" "$PATH"'],env=e,stderr=subprocess.DEVNULL).decode()
    print(side,'effective PATH ends in file:',effective.endswith(str(file)),'xdg-open absent:',not (bindir/'xdg-open').exists(),flush=True)
    for mode in ['login','startup']:
        data=run/(side+'-'+mode+'-data')
        sock=socket.socket(); sock.bind(('127.0.0.1',0)); port=sock.getsockname()[1]; sock.close()
        args=['apps/server/src/bin.ts']+(['connect','login'] if mode=='login' else ['--port',str(port),'--host','127.0.0.1'])+['--base-dir',str(data)]
        events=[]; start=time.monotonic(); raw=''
        def add(s):
            global raw
            raw+=s; events.append([round(time.monotonic()-start,3),s])
        child=pexpect.spawn(node,args,cwd=checkout,env=e,encoding='utf-8',dimensions=(40,140),timeout=1)
        sent=False; reached=None; deadline=start+45
        while time.monotonic()<deadline:
            try:
                chunk=child.read_nonblocking(8192,timeout=.2); add(chunk)
            except pexpect.TIMEOUT: pass
            except pexpect.EOF: break
            plain=re.sub(r'\x1b\[[0-?]*[ -/]*[@-~]','',raw)
            if mode=='login' and not sent and 'to open it in your browser.' in plain:
                time.sleep(1); add('\r\n[driver] Press Enter\r\n'); child.send('\r'); sent=True; reached=time.monotonic()
            if mode=='login' and reached and time.monotonic()-reached>5: break
            if mode=='startup' and ('http://' in plain or 'https://' in plain) and reached is None: reached=time.monotonic()
            if mode=='startup' and reached and time.monotonic()-reached>8: break
        alive=child.isalive()
        if mode=='startup':
            try:
                with socket.create_connection(('127.0.0.1',port),timeout=1): add('\r\n[driver] TCP check: server is listening.\r\n')
            except OSError: add('\r\n[driver] TCP check: server is not listening.\r\n')
        add('\r\n[driver] '+('CLI still running; canceling with Ctrl+C.' if mode=='login' and alive else 'Server still running; stopping with Ctrl+C.' if alive else 'Process exited.')+'\r\n')
        if alive: child.sendcontrol('c')
        try:
            while True: add(child.read_nonblocking(8192,timeout=2))
        except (pexpect.TIMEOUT,pexpect.EOF): pass
        child.close(force=True)
        add(f'\r\n[driver] Exit status: {child.exitstatus}; signal: {child.signalstatus}\r\n')
        (run/(side+'-'+mode+'.raw')).write_text(raw)
        (run/(side+'-'+mode+'.json')).write_text(json.dumps(events))
        print(side,mode,'alive after interaction:',alive,'ENOTDIR:', 'ENOTDIR' in raw,'fallback:', 'Could not open a browser' in raw or 'browser auto-open unavailable' in raw,flush=True)
print(run,flush=True)
