#!/usr/bin/env python3
"""Render the timestamped, captured server observations as a terminal replay.
This is a transcript recording of server/CLI behavior, not a web UI recording.
"""
from PIL import Image,ImageDraw,ImageFont
import pathlib,sys,json,textwrap,re,subprocess
root=pathlib.Path(sys.argv[1]); obs=(root/'observations.txt').read_text().splitlines(); data=json.loads((root/'result.json').read_text())
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',21); small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',18); titlefont=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf',30)
def frame(lines,footer):
 im=Image.new('RGB',(1600,1000),'#111820'); d=ImageDraw.Draw(im)
 d.text((36,24),'Storage cleanup • slow merge-check fetch',font=titlefont,fill='#eef4fa')
 d.text((36,76),f'{data["side"].upper()}  {data["sha"][:10]}   |   Linux · real T3 server · fresh synthetic data',font=small,fill='#a8c4d8')
 d.line((36,113,1564,113),fill='#3a5267',width=2)
 wrapped=[]
 for l in lines:
  wrapped+=textwrap.wrap(l,116,replace_whitespace=False) or ['']
 for n,l in enumerate(wrapped[-31:]):
  color='#ebd084' if 'RESULT:' in l else '#d5e1eb'
  if 'timed out' in l.lower(): color='#ff9a9a'
  d.text((36,140+n*25),l,font=font,fill=color)
 d.text((36,955),footer,font=small,fill='#9fb6c8')
 return im
# Frames retain the captured order. Playback is condensed; source timestamps remain visible.
frames=root/'frames'; frames.mkdir(exist_ok=True)
for i in range(1,len(obs)+1): frame(obs[:i],'Recorded CLI/server observations • condensed replay • source timestamps shown').save(frames/f'{i:04d}.png')
last=[l for l in obs if any(t in l for t in ['BEFORE |','AFTER |','Upstream advanced','fetch.unpackLimit','SWEEP','RESULT:','garbage:','size-garbage:'])]
last+=['','Actual fetch argv (Git trace2):']
for c in data['commands']:
 if 'fetch' in c: last.append(' '.join(c))
last+=['',f'FINAL: origin/main {"advanced to upstream" if data["final"]==data["target"] else "never advanced"}; '+f'{len(data["partialPacks"])} partial pack(s) remain; {data["cleanupFailures"]} cleanup failure(s).']
if data['cleanupFailures']: last+=['Server diagnostic: GitVcsDriver.fetchRemoteTrackingBranch — Git command timed out.']
frame(last,'Summary rendered from captured real-server output • synthetic repository • no production data').save(root/'summary.png')
subprocess.run(['ffmpeg','-y','-loglevel','error','-framerate','2','-i',str(frames/'%04d.png'),'-vf','pad=ceil(iw/2)*2:ceil(ih/2)*2','-c:v','libx264','-pix_fmt','yuv420p','-movflags','+faststart',str(root/'recording.mp4')],check=True)
