#!/usr/bin/env python3
"""Bridge approved moving cinema plates into the existing bookend manifest."""
import argparse
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile


def main():
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument('--preset', type=Path, required=True)
    ap.add_argument('--project-key', required=True)
    ap.add_argument('--out-dir', type=Path, required=True)
    ap.add_argument('--json-out', type=Path, required=True)
    ap.add_argument('--body', type=Path, required=True)
    args = ap.parse_args()
    preset = json.loads(args.preset.read_text())
    config = preset['projects'][args.project_key]
    source = (args.preset.resolve().parent / config['source']).resolve()
    if not source.is_file():
        raise ValueError(f'Missing source plate: {source}')
    # Refuse implicit stretching/cropping or fps conversion of an accepted body.
    probe = json.loads(subprocess.check_output([
        os.environ.get('FFPROBE_BIN', 'ffprobe'), '-v', 'error', '-select_streams', 'v:0',
        '-show_entries', 'stream=width,height,r_frame_rate', '-of', 'json', str(args.body)]))['streams'][0]
    from fractions import Fraction
    if (probe['width'], probe['height'], Fraction(probe['r_frame_rate'])) != (preset['width'], preset['height'], preset['fps']):
        raise ValueError('Cinema preset must match the body resolution and frame rate.')
    if args.out_dir.resolve() != args.json_out.resolve().parent:
        raise ValueError('Manifest must live directly in --out-dir.')
    config = dict(config, source=str(source))
    preset = dict(preset, projects={'film': config})
    args.out_dir.mkdir(parents=True, exist_ok=True)
    run = Path(tempfile.mkdtemp(prefix='cinema-', dir=args.out_dir))
    config_path = run / 'preset.json'
    config_path.write_text(json.dumps(preset, ensure_ascii=False, indent=2))
    subprocess.run([sys.executable, str(Path(__file__).with_name('cinematic_render.py')),
                    '--preset', str(config_path), '--output', str(run / 'render')], check=True)
    cards, blocks = [], []
    for kind, audio in [('intro', 'riser'), ('outro', 'tail')]:
        seconds = preset[kind + 'Frames'] / preset['fps']
        clip = run / 'render/film' / (kind + '.mp4')
        stream = json.loads(subprocess.check_output([
            os.environ.get('FFPROBE_BIN', 'ffprobe'), '-v', 'error', '-select_streams', 'v:0',
            '-count_frames', '-show_entries', 'stream=nb_read_frames,width,height,r_frame_rate',
            '-of', 'json', str(clip)]))['streams'][0]
        if (int(stream['nb_read_frames']), stream['width'], stream['height'], Fraction(stream['r_frame_rate'])) != (preset[kind+'Frames'], preset['width'], preset['height'], preset['fps']):
            raise ValueError('Rendered cinematic plate failed frame/shape checks.')
        file = clip.relative_to(args.out_dir)
        cards.append(dict(id=kind, seconds=seconds, zoom=1, file=str(file), media='video'))
        blocks.append(dict(id=kind, seconds=seconds, audio=audio, cards=[kind], xfade=0))
    manifest = dict(card=dict(width=preset['width'], height=preset['height']), fps=preset['fps'],
                    renderScale=1, cards=cards, blocks=blocks, order=['intro','BODY','outro'],
                    bookendSeconds=sum(b['seconds'] for b in blocks), treatment='cinematic')
    tmp = args.json_out.with_suffix('.tmp')
    tmp.write_text(json.dumps(manifest, indent=2))
    tmp.replace(args.json_out)


if __name__ == '__main__':
    try:
        main()
    except (ValueError, KeyError, OSError, subprocess.CalledProcessError) as exc:
        print(f'cinematic_cards: {exc}', file=sys.stderr)
        sys.exit(2)
