from PIL import Image,ImageDraw,ImageFont
import pathlib,json,textwrap,subprocess,sys
root=pathlib.Path(sys.argv[1]); 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 ['before','after']:
 events=json.loads((root/(side+'.events.json')).read_text()); lines=[]; frames=[]
 def draw(lines,title):
    im=Image.new('RGB',(1440,1300),'#101820'); d=ImageDraw.Draw(im)
    d.text((24,18),side.upper()+' | '+events[1][1][7:17]+' | Real CLI | Linux, fresh DB, loopback',font=font,fill='#73d5f5')
    d.text((24,51),'Terminal transcript replay; long pauses compressed. No clock changes.',font=small,fill='#abb9c6')
    d.text((24,80),title,font=small,fill='#abb9c6')
    for i,line in enumerate(lines[-44:]):
        color='#9ce6ad' if ('scopes:' in line or 'lifetime:' in line or 'listed as active:' in line) else '#e1e8ef'
        d.text((24,115+i*26),line,font=font,fill=color)
    return im
 for index,(elapsed,event) in enumerate(events):
    lines.extend(textwrap.wrap(event,112,replace_whitespace=False) or [''])
    im=draw(lines,f'Elapsed wall clock: {elapsed:.3f} seconds')
    path=root/f'{side}-frame-{index:03}.png'; im.save(path); frames.append(path)
 # Fixed summary includes all essential transitions; full output accompanies the recording.
 summary=[]
 for elapsed,event in events:
    if event.startswith(('REAL','commit','$','exit','scopes:','lifetime:','revoked:','Session observed','Killed session','After head','Observed at')):
        summary.extend(textwrap.wrap(event,112))
 draw(summary,'Final observation (scrollback shown in recording)').save(root/(side+'.png'))
 concat=root/(side+'-frames.txt')
 concat.write_text(''.join("file '"+str(p)+"'\nduration "+('4' if i==len(frames)-1 else '1.2')+'\n' for i,p in enumerate(frames))+"file '"+str(frames[-1])+"'\n")
 subprocess.run(['ffmpeg','-y','-v','error','-f','concat','-safe','0','-i',str(concat),'-vf','fps=10','-c:v','libx264','-pix_fmt','yuv420p','-crf','20',str(root/(side+'.mp4'))],check=True)
