"""Extract timestamped whole-viewport frames from each final evidence recording."""
from pathlib import Path
import json,subprocess
from PIL import Image,ImageDraw,ImageFont
root=Path('/tmp/lead-25709-r1b/evidence-capture');out=root/'storyboards';out.mkdir(exist_ok=True)
font=ImageFont.truetype('/usr/share/fonts/truetype/noto/NotoSans-Regular.ttf',17)
records=json.loads((root/'videos/timelines.json').read_text())
for v in records:
 dur=float(subprocess.check_output(['ffprobe','-v','error','-show_entries','format=duration','-of','csv=p=0',v['file']]))
 ts=[min(.25,dur/2)]+[min(dur-.1,max(0,s['t']+.4))for s in v['steps'][1:]]+[max(0,dur-.25)]
 sheet=Image.new('RGB',(1480,520*((len(ts)+1)//2)),'#ddd');d=ImageDraw.Draw(sheet)
 for i,t in enumerate(ts):
  frame=out/(v['name']+f'-{i}.png');subprocess.run(['ffmpeg','-v','error','-y','-ss',str(t),'-i',v['file'],'-frames:v','1',str(frame)],check=True)
  im=Image.open(frame);im.thumbnail((720,475));x=i%2*740;y=i//2*520;d.text((x+8,y+6),v['name']+f' · {t:.1f}s',font=font,fill='black');sheet.paste(im,(x+8+(720-im.width)//2,y+35))
 sheet.save(out/(v['name']+'-storyboard.png'))
print('Storyboards',len(records))
