import subprocess, os, sys, time, textwrap, pathlib, datetime
root, side, sha = sys.argv[1:]
p = pathlib.Path(__file__).parent
out = p / (side + '-' + datetime.datetime.now().strftime('%Y%m%d-%H%M%S'))
out.mkdir()
panel=out/'terminal.txt'
header = [f'{side.upper()} | {sha}', 'Linux x86_64 | Node v26.12.1 | fresh isolated HOME / T3 home', 'Production fx status check + real NodeServices + synthetic CLI', 'Budget: 10 seconds. Same driver and inputs on both commits.', '']
lines=[]
start=time.monotonic()
def paint(done=False):
    body=[]
    for line in lines:
        body.extend(textwrap.wrap(line, width=110, replace_whitespace=False) or [''])
    text='\n'.join(header+[f'Wall time: {time.monotonic()-start:05.1f}s' if not done else 'Run complete', '']+body[-29:])
    tmp=out/'next.txt'; tmp.write_text(text); tmp.replace(panel)
paint()
video=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-re','-f','lavfi','-i','color=c=0x101820:s=1600x1000:r=2','-vf',f"drawtext=fontfile=/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf:textfile={panel}:reload=1:fontcolor=0xe7edf5:fontsize=21:x=35:y=30:line_spacing=7:expansion=none",'-c:v','libx264','-preset','ultrafast','-crf','20','-pix_fmt','yuv420p',str(out/'recording.mp4')],stdin=subprocess.PIPE)
env=dict(os.environ, REPRO_SCRATCH=str(out)); env.pop('NODE_ENV',None)
proc=subprocess.Popen(['sh',str(p/'repro.sh')],cwd=root,env=env,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
import threading,queue
q=queue.Queue()
def reader():
    for line in proc.stdout:q.put(line.rstrip())
threading.Thread(target=reader,daemon=True).start()
with (out/'transcript.txt').open('w') as log:
    log.write('\n'.join(header)+'\n'); log.flush()
    while proc.poll() is None or not q.empty():
        try:
            line=q.get(timeout=.2)
            lines.append(line); log.write(line+'\n'); log.flush(); print(line,flush=True)
        except queue.Empty:pass
        paint()
    lines.append(f'Command exit: {proc.returncode}')
    log.write(lines[-1]+'\n'); paint(True)
time.sleep(2)
video.communicate(b'q')
subprocess.run(['ffmpeg','-y','-loglevel','error','-sseof','-1','-i',str(out/'recording.mp4'),'-frames:v','1',str(out/'summary.png')],check=True)
print('OUTPUT '+str(out),flush=True)
