import os, subprocess, time, pathlib, selectors, json, re, textwrap
from PIL import Image, ImageDraw, ImageFont
ROOT=pathlib.Path(__file__).parent
FONT=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',20)
for side,sha,port in [('base','cad8cd0937',18437),('head','d5208bc6e4',18436)]:
    cwd=os.environ['BASE_CHECKOUT' if side=='base' else 'HEAD_CHECKOUT']
    data=os.environ['BASE_DATA' if side=='base' else 'HEAD_DATA']
    cmd=['node','--require',str(ROOT/'slow-clock.cjs'),'apps/server/src/bin.ts','serve','--base-dir',data,'--port',str(port),'--host','127.0.0.1']
    events=[(0,f'{side.upper()} | commit {sha} | Linux CLI | test relay\nHost Node clock: 10 minutes behind; cloudflared 2026.10.4\n$ t3 serve --port <free> --host 127.0.0.1')]
    start=time.monotonic(); p=subprocess.Popen(cmd,cwd=cwd,env=os.environ,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,bufsize=1)
    (ROOT/(side+'-pid')).write_text(str(p.pid))
    sel=selectors.DefaultSelector();sel.register(p.stdout,selectors.EVENT_READ)
    raw=[]; connections=set(); outcome=False; done_at=None
    try:
        while time.monotonic()-start<100:
            if sel.select(.2):
                line=p.stdout.readline()
                if not line and p.poll() is not None: break
                raw.append(line)
                elapsed=time.monotonic()-start
                if ('T3 Connect' in line and ('reconciled' in line or 'recovery registered' in line or 'no longer accepts' in line or 'reachable from other' in line)) or 'rejection:' in line or 'not_authorized' in line:
                    clean=line.strip().replace(cwd,'<checkout>')
                    events.append((elapsed,clean))
                    if 'recovery registered' in line or 'no longer accepts' in line: outcome=True
                m=re.search(r'connIndex=(\d)',line)
                if m:
                    connections.add(m[1]);events.append((elapsed,f'cloudflared: Registered tunnel connection connIndex={m[1]} protocol=quic'))
                if outcome and len(connections)==4 and done_at is None: done_at=time.monotonic()+12
            if done_at and time.monotonic()>done_at: break
        events.append((time.monotonic()-start,'\n$ t3 connect status'))
        status=subprocess.run(['node','apps/server/src/bin.ts','connect','status','--base-dir',data],cwd=cwd,env=os.environ,capture_output=True,text=True).stdout
        (ROOT/(side+'-status-raw.txt')).write_text(status)
        # Omit account, relay URL, executable path and links from public capture.
        lines=[s for s in status.splitlines() if not any(x in s for x in ['Path:','Relay:','More info:'])]
        clean='\n'.join(lines).replace(data,'<isolated-data>')
        events.append((time.monotonic()-start,clean))
    finally:
        p.send_signal(2)
        try:p.wait(15)
        except subprocess.TimeoutExpired:p.terminate();p.wait(10)
        (ROOT/(side+'-raw.log')).write_text(''.join(raw))
    (ROOT/(side+'-events.json')).write_text(json.dumps(events))
    (ROOT/(side+'-transcript.txt')).write_text('\n'.join(f'[{t:05.1f}s] {s}' for t,s in events))
    duration=events[-1][0]+5
    video=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-pixel_format','rgb24','-video_size','1600x1000','-framerate','2','-i','-','-c:v','libx264','-pix_fmt','yuv420p',str(ROOT/(side+'.mp4'))],stdin=subprocess.PIPE)
    for i in range(int(duration*2)+1):
        now=i/2; rows=[]
        for t,s in events:
            if t<=now:
                for line in s.splitlines():rows.extend(textwrap.wrap(line,122) or [''])
        im=Image.new('RGB',(1600,1000),'#10151d');d=ImageDraw.Draw(im)
        d.text((28,20),f'T3 Connect clock-skew reproduction  |  elapsed {now:05.1f}s',font=FONT,fill='#93b4d8')
        for j,line in enumerate(rows[-34:]):d.text((28,70+j*26),line,font=FONT,fill='#e8edf4')
        video.stdin.write(im.tobytes())
    video.stdin.close();video.wait()
    im.save(ROOT/(side+'.png'))
    print(side,clean,flush=True)
