"""Supplementary full-surface contact sheets and recording review frames."""
import json
import subprocess
import sys
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont

root = Path(sys.argv[1])
font = ImageFont.load_default(size=20)
for fixture in ['F1', 'F2']:
    sheet = Image.new('RGB', (2560, 1680), '#252525')
    draw = ImageDraw.Draw(sheet)
    for i, suffix in enumerate(['before', 'after', 'diff0', 'diffT']):
        x, y = (i % 2) * 1280, (i // 2) * 840
        label = {'before':'Before 37fbefd147', 'after':'After c6784ac1e9',
                 'diff0':'Diff0: absolute RGB difference x32',
                 'diffT':'DiffT: any RGB channel >16/255 (magenta)'}[suffix]
        draw.text((x+12, y+8), f'{fixture} 1280x800 dark | {label}', font=font, fill='white')
        sheet.paste(Image.open(root / f'{fixture}-1280x800-dark-{suffix}.png').convert('RGB'), (x, y+40))
    sheet.save(root / f'{fixture}-sheet.png')

video_manifest = []
for video in sorted(root.glob('*.mp4')):
    probe = json.loads(subprocess.check_output(['ffprobe', '-v', 'error', '-show_streams', '-show_format', '-of', 'json', str(video)]))
    duration = float(probe['format']['duration'])
    times = [0, 2, 4, max(0,duration-.3)]
    sheet = Image.new('RGB', (1280, 880), '#252525')
    draw = ImageDraw.Draw(sheet)
    for i, time in enumerate(times):
        output = root / f'{video.stem}-review-{i}.png'
        subprocess.run(['ffmpeg','-hide_banner','-loglevel','error','-ss',str(time),'-i',str(video),'-frames:v','1','-y',str(output)],check=True)
        im = Image.open(output).convert('RGB')
        im.thumbnail((640,400))
        x,y=(i%2)*640,(i//2)*440
        draw.text((x+8,y+8), f'{video.stem}: {time:.2f}s', font=font, fill='white')
        sheet.paste(im,(x+(640-im.width)//2,y+40))
    sheet.save(root / f'{video.stem}-filmstrip.png')
    stream=next(s for s in probe['streams'] if s['codec_type']=='video')
    video_manifest.append(dict(file=video.name,duration=duration,width=stream['width'],height=stream['height'],codec=stream['codec_name']))
(root/'video-manifest.json').write_text(json.dumps(video_manifest,indent=2))
print(json.dumps(video_manifest,indent=2))
