#!/usr/bin/env python3
from pathlib import Path
from PIL import Image,ImageDraw
import subprocess,json,sys
for arg in sys.argv[1:]:
    video=Path(arg)
    duration=float(subprocess.check_output(['ffprobe','-v','error','-show_entries','format=duration','-of','json',str(video)],text=True).strip().split('"duration": "')[1].split('"')[0])
    out=video.parent/(video.stem+'-frames')
    out.mkdir(exist_ok=True)
    frames=[]
    for i in range(8):
        t=min(duration-.1,max(.05,duration*i/7))
        p=out/f'frame-{i}.png'
        subprocess.run(['ffmpeg','-v','error','-y','-ss',str(t),'-i',str(video),'-frames:v','1',str(p)],check=True)
        im=Image.open(p).convert('RGB')
        im.thumbnail((720,844))
        frames.append((im,t))
    w=max(im.width for im,t in frames);h=max(im.height for im,t in frames)+30
    sheet=Image.new('RGB',(w*4,h*2),'#dddddd');draw=ImageDraw.Draw(sheet)
    for i,(im,t) in enumerate(frames):
        x=i%4*w;y=i//4*h
        draw.text((x+8,y+8),f'{video.parent.name} | {t:.2f}s',fill='black')
        sheet.paste(im,(x,y+30))
    path=video.parent/(video.stem+'-contact.png');sheet.save(path)
    print(path)
