#!/usr/bin/env python3
"""Render recorded measurements, without rerunning or changing the experiment."""
import pathlib,json,sys,subprocess,textwrap,time,hashlib
from PIL import Image,ImageDraw,ImageFont
run=pathlib.Path(sys.argv[1]);data=json.loads((run/'telemetry.json').read_text());side=data['side'];frames=run/'reviewed-frames';frames.mkdir(exist_ok=True)
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',18);title=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf',29)
def frame(sample):
    im=Image.new('RGB',(1280,720),'#0b1120');d=ImageDraw.Draw(im)
    d.text((40,25),side.upper()+' | Real T3 Code server / npm cache',font=title,fill='white')
    lines=[f"Commit: {data['commit'][:10]} | Linux | Node {data['versions']['node']} | npm {data['versions']['npm']}", 'Codex 0.172.0 (npm global) | Real 19,956,129-byte packument at 400 KiB/s',f"Elapsed: {sample['t']:.1f}s | {sample['phase']}", '',f"Provider refresh RPCs sent: {sample['refreshes']:2d}    replies: {sample['replies']:2d}",f"Registry downloads: {sample['downloads']:2d}   completed: {sample['completed']:2d}   aborted: {sample['aborted']:2d}",f"npm _cacache/tmp: {sample['tmpFiles']:2d} files | {sample['tmpBytes']:12,d} bytes"]
    for i,line in enumerate(lines):d.text((40,90+i*32),line,font=font,fill='#fbbf24' if 'tmp:' in line else '#cbd5e1')
    d.text((40,335),'Recorded event transcript:',font=font,fill='#cbd5e1')
    wrapped=[]
    for e in data['events']:
        if e['t']>sample['t']:continue
        message=e['message']
        if message.startswith('Linux |'):continue
        wrapped.extend(textwrap.wrap(f"{e['t']:6.1f}s {message}",width=104,subsequent_indent='        '))
    for i,line in enumerate(wrapped[-9:]):d.text((40,375+i*29),line,font=font,fill='#a7f3d0')
    d.text((40,678),'Real HTTP / RPC / filesystem measurements | sampled 1 Hz | video playback 5x',font=font,fill='#94a3b8')
    return im
for i,sample in enumerate(data['samples']):frame(sample).save(frames/f'{i:05d}.png')
final=frame(data['samples'][-1]);final.save(run/(side+'.png'));time.sleep(.5);second=frame(data['samples'][-1]);assert final.tobytes()==second.tobytes()
subprocess.run(['ffmpeg','-y','-loglevel','error','-framerate','5','-i',str(frames/'%05d.png'),'-c:v','libx264','-pix_fmt','yuv420p','-crf','22',str(run/(side+'.mp4'))],check=True)
# Contact sheet samples the actual encoded video for visual review.
subprocess.run(['ffmpeg','-y','-loglevel','error','-i',str(run/(side+'.mp4')),'-vf','fps=1/10,scale=640:360,tile=3x3','-frames:v','1',str(run/'video-review.png')],check=True)
print(json.dumps({'side':side,'final':data['samples'][-1],'downloads':data['downloads']},indent=2))
