import sys,json,pathlib,math,subprocess,textwrap
from PIL import Image,ImageDraw,ImageFont
run=pathlib.Path(sys.argv[1]); data=json.loads((run/'result.json').read_text()); events=data['events']; side='BEFORE' if data['sha'].startswith('c764') else 'AFTER'
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',19); small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',16); title=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',28)
labels=['Control: src/bin.ts','Swap existing src/guest directory','Replacement: src/guest/http.ts','Replacement: src/guest/guestView.ts','Moved-away: guest-original/http.ts','Control: src/bin.ts again','Control: src/git/detachStackFrame.ts']
def frame(now):
    im=Image.new('RGB',(1440,1000),'#10151e'); d=ImageDraw.Draw(im)
    d.text((34,24),f'{side} | Nested source directory swap',font=title,fill='white')
    d.text((34,70),f"Commit {data['sha']} | Linux x86_64 | Node v24.15.0",font=small,fill='#a9b9cd')
    d.text((34,101),'Real development server | Fresh isolated state | Same scripted filesystem operations',font=small,fill='#a9b9cd')
    d.text((34,142),f'Timed runtime transcript replay: {now:05.1f}s (1x speed)',font=font,fill='#7ec7ff')
    visible=[]; results=[]
    for t,s in events:
        if t>now: break
        if s.startswith('OBSERVED'): results.append(s.split(': ',1)[1])
        if s.startswith(('ACTION:','PREPARE:','OBSERVED')) or '[dev] Restarting' in s or s.startswith('SERVER: Listening'):
            for i,line in enumerate(textwrap.wrap(s,110)):
                visible.append((f'{t:5.1f}s '+line if i==0 else '       '+line,s))
    y=190
    for line,s in visible[-17:]:
        color='#e7edf5'
        if s.startswith('ACTION'): color='#7ec7ff'
        if '[dev] Restarting' in s: color='#f1ca75'
        if s.startswith('OBSERVED'): color='#c9a6ee'
        d.text((34,y),line,font=font,fill=color); y+=28
    d.line((34,691,1406,691),fill='#3e4c60',width=2)
    d.text((34,710),'Observed restart count per action (6-second observation windows)',font=font,fill='white')
    for i,label in enumerate(labels):
        y=752+i*29; result=results[i] if i<len(results) else 'pending'
        d.text((34,y),label,font=font,fill='#bac9da'); d.text((1000,y),result,font=font,fill='#e7edf5')
    d.text((34,970),'Filtered live stdout; raw timestamped transcript and driver supplied alongside this recording.',font=small,fill='#8e9cb0')
    return im
end=math.ceil(events[-1][0])+2
proc=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-pixel_format','rgb24','-video_size','1440x1000','-framerate','2','-i','-','-c:v','libx264','-preset','fast','-crf','24','-pix_fmt','yuv420p',str(run/(side.lower()+'.mp4'))],stdin=subprocess.PIPE)
for i in range(end*2): proc.stdin.write(frame(i/2).tobytes())
proc.stdin.close(); assert proc.wait()==0
frame(end).save(run/(side.lower()+'.png'))
# Inspect representative swap / replacement / moved-away moments as a contact sheet.
ims=[frame(t).resize((720,500)) for t in (14,25,37,50)]
sheet=Image.new('RGB',(1440,1000));
for im,xy in zip(ims,[(0,0),(720,0),(0,500),(720,500)]): sheet.paste(im,xy)
sheet.save(run/'contact-sheet.png')
