import pathlib, json, sys, textwrap, subprocess
from PIL import Image, ImageDraw, ImageFont
root=pathlib.Path(sys.argv[1]); side=sys.argv[2]
events=json.loads((root/'events.json').read_text())
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',23)
titlefont=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf',30)
small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',21)
frames=root/'frames'; frames.mkdir(exist_ok=True)
def draw(items, filename, playback):
    im=Image.new('RGB',(1920,1080),'#101720'); d=ImageDraw.Draw(im)
    d.text((42,26),'CANCELLATION CLEANUP / UNRELATED WAIT TIMEOUT',font=titlefont,fill='#edf2f7')
    d.text((42,74),side+' | '+events[0]['text'].split('commit ')[1][:10]+' | Linux / Node | fresh database',font=font,fill='#8dc7ff')
    d.text((42,112),'CLI --json fields; UTC timestamps; '+playback,font=small,fill='#b8c5d6')
    lines=[]
    for e in items:
        lines.extend(textwrap.wrap(e['text'],width=128,subsequent_indent='    ',replace_whitespace=False))
    for n,line in enumerate(lines[-29:]):
        color='#e7edf5'
        if 'holding request' in line or 'still held=True' in line: color='#ffcb75'
        if 'completed' in line or 'timedOut' in line and 'true' in line: color='#9ae6b4'
        d.text((42,166+n*29),line,font=font,fill=color)
    d.text((42,1030),'Local cleanup service: first request 503; retry held until explicitly released.',font=small,fill='#b8c5d6')
    im.save(filename)
# Record the output stream in order, preserving elapsed time at 10x playback.
end=events[-1]['seconds']
for sec in range(int(end/10)+3):
    items=[e for e in events if e['seconds']<=sec*10]
    draw(items,frames/f'{sec:04}.png','output recording at 10x speed')
idx=next(i for i,e in enumerate(events) if 'OBSERVATION BEFORE RELEASE' in e['text'])
draw(events[:idx+2],root/'observation.png','observation before releasing cleanup')
subprocess.run(['ffmpeg','-y','-loglevel','error','-framerate','1','-i',str(frames/'%04d.png'),'-c:v','libx264','-r','10','-pix_fmt','yuv420p','-movflags','+faststart',str(root/'recording.mp4')],check=True)
