import os,pty,select,time,json,re,sys,fcntl,termios,struct,subprocess
from pathlib import Path
from PIL import Image,ImageDraw,ImageFont
root=Path(__file__).parent
run=root/time.strftime('%Y%m%d-%H%M%S');run.mkdir()
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',18)
ansi=re.compile(r'\x1b\[[0-?]*[ -/]*[@-~]')
for side,suffix,sha in [('before','-base','51a721da44'),('after','','9a78cd64b1')]:
 checkout=Path.home()/('wt/factory-pr-42303-evidence-1'+suffix)
 events=[]; summary=[]
 def clean(s):
  return ansi.sub('',s).replace(str(checkout),'<checkout>').replace(str(root),'<evidence>').replace(str(Path.home()),'<home>').replace('\r','')
 def add(s): events.append((time.monotonic()-start,clean(s)))
 start=time.monotonic()
 add(f'{side.upper()} | commit {sha}\nLinux x86_64 | Node v26.13.1 | PTY 120x36\nBuilt CLI; real installed agents; fresh empty data per run\n\n')
 for key,byte in [('Ctrl+C',b'\x03'),('Ctrl+D',b'\x04')]:
  data=run/(side+'-'+key[-1]+'-data');data.mkdir()
  add(f'$ t3 triage --base-dir <fresh-empty-dir>\n')
  pid,fd=pty.fork()
  if pid==0:
   os.chdir(checkout)
   os.environ['T3CODE_DEV_SEED']='0';os.environ['NO_COLOR']='1';os.environ['TERM']='xterm-256color'
   os.execvp('node',['node',str(checkout/'apps/server/dist/bin.mjs'),'triage','--base-dir',str(data)])
  fcntl.ioctl(fd,termios.TIOCSWINSZ,struct.pack('HHHH',36,120,0,0))
  output='';sent=False;deadline=time.monotonic()+40
  while time.monotonic()<deadline:
   ready,_,_=select.select([fd],[],[],0.1)
   if ready:
    try: b=os.read(fd,65536)
    except OSError: break
    if not b:break
    s=b.decode(errors='replace');output+=s;add(s)
    if '> ' in output and not sent:
     time.sleep(1);add(f'\n[send {key}]\n');os.write(fd,byte);sent=True
  else:
   os.kill(pid,9);raise RuntimeError('CLI timed out')
  _,status=os.waitpid(pid,0);os.close(fd);code=os.waitstatus_to_exitcode(status)
  add(f'\n[process exit status: {code}]\n\n');time.sleep(1)
  summary.append({'key':key,'sent':sent,'exitCode':code,'output':clean(output)})
 (run/(side+'.json')).write_text(json.dumps(summary,indent=2))
 (run/(side+'.txt')).write_text(''.join(s for _,s in events))
 # Render the recorded output timeline, without inventing terminal output.
 duration=events[-1][0]+3
 proc=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-pix_fmt','rgb24','-s','1440x900','-r','5','-i','-','-an','-c:v','libx264','-pix_fmt','yuv420p',str(run/(side+'.mp4'))],stdin=subprocess.PIPE)
 for n in range(int(duration*5)+1):
  t=n/5;txt=''.join(s for at,s in events if at<=t)
  lines=[]
  for line in txt.split('\n'):
   lines.extend([line[i:i+125] for i in range(0,len(line),125)] or [''])
  im=Image.new('RGB',(1440,900),'#10141c');d=ImageDraw.Draw(im)
  d.text((30,20),f'T3 TRIAGE — {side.upper()} — {sha}',font=font,fill='#8ac7ff')
  d.multiline_text((30,65),'\n'.join(lines[-35:]),font=font,fill='#e1e7ef',spacing=4)
  proc.stdin.write(im.tobytes())
 proc.stdin.close();proc.wait()
 im.save(run/(side+'.png'))
print(run)
