from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
import io, subprocess, json

p = Path(__file__).parent
samples = {'M1-M3-dark':[2,13,23,28,52,86,105,114,124], 'M2-M3-supplement':[1,5,13,18,20,24,26], 'O3':[1,3,32,35,37,39,41], 'O3-supplement':[1,3,14,19,24,27,28]}
metadata = {}
font = ImageFont.load_default(size=18)
for row, times in samples.items():
    for side in ['after']:
        name = f'{side}-{row}'
        path = p / f'{name}.mp4'
        if not path.exists(): continue
        probe = json.loads(subprocess.check_output(['ffprobe', '-v', 'quiet', '-show_format', '-show_streams', '-of', 'json', str(path)]))
        stream = next(s for s in probe['streams'] if s['codec_type'] == 'video')
        duration = float(probe['format']['duration'])
        metadata[name] = {'duration': duration, 'width': stream['width'], 'height': stream['height'], 'samples': times}
        sheet = Image.new('RGB', (1920, ((len(times) + 2) // 3) * 430), '#151518')
        draw = ImageDraw.Draw(sheet)
        for i, t in enumerate(times):
            t = min(t, max(0, duration - 0.2))
            raw = subprocess.check_output(['ffmpeg', '-v', 'error', '-ss', str(t), '-i', str(path), '-frames:v', '1', '-vf', 'scale=640:400:force_original_aspect_ratio=decrease,pad=640:400:(ow-iw)/2:(oh-ih)/2', '-f', 'image2pipe', '-vcodec', 'png', '-threads', '1', '-'])
            x, y = (i % 3) * 640, (i // 3) * 430
            draw.text((x + 8, y + 5), f'{name}  {t:.1f}s', fill='white', font=font)
            sheet.paste(Image.open(io.BytesIO(raw)).convert('RGB'), (x, y + 30))
        sheet.save(p / f'{name}-contact.png')
(p / 'recording-metadata.json').write_text(json.dumps(metadata, indent=2))
print(json.dumps(metadata, indent=2))
