#!/usr/bin/env python3
"""Render the real server/CLI transcript and 10 Hz filesystem samples as evidence.
This is a measurement replay, not an app screenshot. Never fabricates file activity.
Usage: record.py RUN_DIRECTORY OUTPUT_DIRECTORY
"""
import json,sys,subprocess,math,textwrap
from pathlib import Path
from PIL import Image,ImageDraw,ImageFont
run=Path(sys.argv[1]); out=Path(sys.argv[2]); out.mkdir(exist_ok=True)
samples=json.loads((run/'samples.json').read_text()); events=json.loads((run/'events.json').read_text()); summary=json.loads((run/'summary.json').read_text()); side=summary['side']
font='/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf'; mono='/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf'
def F(n,m=False): return ImageFont.truetype(mono if m else font,n)
BG='#10151f'; FG='#ebeff8'; MUT='#a7b2c8'; GRID='#303b50'; SHARED='#f47d87'; PRIVATE='#f2c268'; BLUE='#80c8fa'; GREEN='#91dab4'
W,H=1600,1000; total=samples[-1]['t']; mib=1024**2

def metrics(s,key='timeout'):
 r=s[key]; return sum(x['bytes'] for x in r['sharedTmp'])/mib,sum(x['bytes'] for d in r['private'] for x in d['tmp'])/mib,len(r['sharedTmp']),sum(len(d['tmp']) for d in r['private']),len(r['private']),sum(x['bytes'] for x in r['sharedObjects'])/mib
peak=1536  # Identical 0–1536 MiB scale for the matched before/after captures.

def draw_frame(idx,final=False):
 s=samples[idx]; t=s['t']; m=metrics(s); im=Image.new('RGB',(W,H),BG); d=ImageDraw.Draw(im)
 def txt(x,y,text,size=22,color=FG,mon=False):d.text((x,y),str(text),font=F(size,mon),fill=color)
 txt(45,23,f"{'BEFORE' if side=='before' else 'AFTER'}  |  Checkpoint timeout / Git LFS",34)
 txt(45,72,f"Commit {summary['sha'][:10]}  |  Linux / Git 2.43.0 / official Git LFS 3.4.1",20,MUT)
 txt(45,105,'Real server + CLI measurement replay  •  10 Hz filesystem sampling  •  same corpus and steps',19,MUT)
 txt(45,136,'Timeout repo: 6 × 1 GiB random .npz; add 2 × 1 GiB on turn two; LFS duty limit 5% on both commits',18,MUT)
 txt(1280,24,f'{t:05.1f} s',34,BLUE,True)
 txt(1280,73,'server RUNNING' if s['serverAlive'] else 'server stopped',20,GREEN)
 # Gauges
 for x,label,value,color in [(45,'Shared .git/lfs/tmp',f'{m[0]:.1f} MiB / {m[2]} files',SHARED),(555,'Private capture LFS tmp',f'{m[1]:.1f} MiB / {m[3]} files',PRIVATE),(1065,'Private capture directories',str(m[4]),BLUE)]:
  d.rounded_rectangle((x,180,x+475,284),radius=12,fill='#1b2433');txt(x+18,195,label,20,MUT);txt(x+18,230,value,28,color)
 # Time series
 x0,y0,x1,y1=90,375,1515,585
 for frac in [0,.25,.5,.75,1]:
  yy=y1-(y1-y0)*frac;d.line((x0,yy,x1,yy),fill=GRID);txt(10,yy-10,f'{peak*frac:.0f}',17,MUT)
 txt(45,345,'LFS temporary data (MiB)',20,MUT)
 for sec in range(0,math.ceil(total/10)*10+1,10):
  xx=x0+(x1-x0)*sec/total
  if xx<=x1:d.line((xx,y0,xx,y1),fill=GRID);txt(xx-10,y1+5,f'{sec}s',15,MUT)
 for j,color in [(0,SHARED),(1,PRIVATE)]:
  points=[(x0+(x1-x0)*q['t']/total,y1-(y1-y0)*metrics(q)[j]/peak) for q in samples[:idx+1]]
  if len(points)>1:d.line(points,fill=color,width=4)
 # Exact timeout events from the running server
 for e in events:
  msg=e['message']
  if e['t']>t:continue
  if msg.startswith('SERVER:') and ('baseline capture failed;' in msg or 'WARN' in msg and 'orchestration V2 checkpoint capture failed' in msg):
   xx=x0+(x1-x0)*e['t']/total;d.line((xx,y0,xx,y1),fill=FG,width=1);txt(xx+4,y0+6,'5 s limit' if 'baseline' in msg else '30 s limit',16)
 txt(1040,345,'shared tmp',18,SHARED);txt(1240,345,'private LFS tmp',18,PRIVATE)
 active=[(f'.git/lfs/tmp/{f["path"]}',f['bytes']) for f in s['timeout']['sharedTmp']]
 active += [(f'.git/objects/{v["directory"]}/lfs/tmp/{f["path"]}',f['bytes']) for v in s['timeout']['private'] for f in v['tmp']]
 if active:
  for row,(name,size) in enumerate(active[:2]):txt(45,294+22*row,f'{name}  {size/mib:.1f} MiB',16,MUT,True)
 else:txt(45,302,'No partial LFS files in shared or private capture storage at this sample.',18,GREEN)
 # Success lane
 good=s['success'];published=sum(x['bytes'] for x in good['sharedObjects']); gpriv=len(good['private'])
 txt(45,625,f'Success repo: shared LFS objects = {published/mib:.2f} MiB / {len(good["sharedObjects"])} objects; private dirs = {gpriv}',21,BLUE)
 restored=any(e['t']<=t and 'APP CHECKPOINT ROLLBACK:' in e['message'] and '"match": true' in e['message'] for e in events)
 txt(45,658,'App checkpoint rollback: SHA-256 MATCH; network disabled' if restored else 'Success capture / app rollback: pending',21,GREEN if restored else MUT)
 txt(45,704,'Observed CLI and server events',21)
 visible=[]
 for e in events:
  if e['t']>t:break
  msg=e['message']
  if 'TURN ' in msg or msg.startswith('observed') or msg.startswith('SUCCESS PATH') or msg.startswith('APP CHECKPOINT ROLLBACK') or msg.startswith('RESTORE via') or msg.startswith('SERVER:') and ('checkpoint' in msg and 'WARN' in msg or 'after 30000ms' in msg):
   if 'APP CHECKPOINT ROLLBACK' in msg:msg='App checkpoint.rollback completed; restored SHA-256 matches original payload'
   if 'RESTORE via' in msg:msg='Offline Git restore from saved app checkpoint also restored identical payload bytes'
   visible.append(f"{e['t']:6.1f}s  "+msg.replace('SERVER: ','').split('WARN',1)[-1].strip())
 yy=744
 for line in visible[-7:]:
  for part in textwrap.wrap(line,118)[:2]:txt(45,yy,part,18,FG,True);yy+=25
 txt(45,966,'Private path: .git/objects/tmp_objdir-t3-checkpoint-*/lfs/tmp  |  Every frame uses recorded filesystem sizes.',16,MUT)
 return im

# Final chart and a frame immediately before each timeout for visual inspection.
draw_frame(len(samples)-1,True).save(out/f'{side}.png')
active_idx=max(range(len(samples)),key=lambda j:metrics(samples[j])[1] if side=='after' else metrics(samples[j])[0])
draw_frame(active_idx).save(out/f'{side}-active.png')
for target in [10,25,40,60,75]:
 i=min(range(len(samples)),key=lambda j:abs(samples[j]['t']-target))
 draw_frame(i).save(out/f'{side}-inspect-{target}.png')
p=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-pix_fmt','rgb24','-s',f'{W}x{H}','-r','2','-i','-','-c:v','libx264','-preset','fast','-crf','22','-pix_fmt','yuv420p',str(out/f'{side}.mp4')],stdin=subprocess.PIPE)
for n in range(math.ceil(total*2)+1):
 target=min(total,n/2);i=min(range(len(samples)),key=lambda j:abs(samples[j]['t']-target));p.stdin.write(draw_frame(i).tobytes())
p.stdin.close()
if p.wait():raise RuntimeError('ffmpeg failed')
print(out/f'{side}.png');print(out/f'{side}.mp4')
