# Render the captured terminal events; preserve output verbatim with line wrapping.
# Each request/result is held for 10 seconds for readable playback.
import json,pathlib,textwrap,sys,os
sys.path.insert(0,str(pathlib.Path(__file__).parent/'python'))
from PIL import Image,ImageDraw,ImageFont
root=pathlib.Path(__file__).parent
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',20)
small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',17)
for side in ['base','head']:
 log=(root/f'driver-{side}-private.log').read_text()
 run=pathlib.Path(log.split('OUTPUT_DIRECTORY=')[-1].strip())
 events=[json.loads(l)[2].strip() for l in (run/'session.cast').read_text().splitlines()[1:]]
 intro=events[0].splitlines()
 for i in range(3):
  request=events[2+i*2]; response=events[3+i*2]
  im=Image.new('RGB',(1440,900),'#10151d');d=ImageDraw.Draw(im)
  d.text((36,22),f'{"BEFORE / BASE" if side=="base" else "AFTER / HEAD"} — real server MCP terminal recording',font=font,fill='#f3f6fb')
  d.text((36,58),'Recorded output • decoded JSON • playback paused 10s per step • same 1440×900 dark viewport',font=small,fill='#a7b6c9')
  y=102
  for line in intro:
   for wrapped in textwrap.wrap(line,110):d.text((36,y),wrapped,font=font,fill='#a7b6c9');y+=27
  y+=20
  for text,color in [(request,'#80c8ff'),(response,'#f3f6fb')]:
   for line in text.splitlines():
    lines=textwrap.wrap(line,110,replace_whitespace=False,drop_whitespace=False) or ['']
    for wrapped in lines:d.text((36,y),wrapped,font=font,fill=color);y+=27
   y+=18
  if y>860:raise Exception(f'Clipped: {side} {i} {y}')
  im.save(root/f'{side}-step-{i+1}.png')
 (root/f'{side}-transcript.txt').write_text((run/'transcript.txt').read_text())
 (root/f'{side}-session.cast').write_text((run/'session.cast').read_text())
 (root/f'{side}-responses.json').write_text((run/'responses.json').read_text())
