#!/usr/bin/env python3
"""Prepare MP4 media using the V3 Rev.3 manual's H.264/AAC/1080p30 guidance.

Requires Python 3, ffmpeg and ffprobe on PATH. No packages, network access,
input-file changes or output overwrites. Validate on your player before a show.
"""
import argparse
import json
import math
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile


def probe(path):
    p = subprocess.run(['ffprobe', '-v', 'error', '-protocol_whitelist', 'file,pipe,crypto,data', '-show_streams', '-show_format',
                        '-of', 'json', str(path)], capture_output=True, text=True,
                       timeout=30)
    if p.returncode:
        raise ValueError('ffprobe could not read the input/output media: ' + p.stderr.strip())
    return json.loads(p.stdout)


def number(value):
    try:
        result = float(value)
        return result if math.isfinite(result) and result > 0 else None
    except (TypeError, ValueError):
        return None


def prepare(source, output):
    if not shutil.which('ffmpeg') or not shutil.which('ffprobe'):
        raise ValueError('Install FFmpeg with ffprobe first, then rerun this command.')
    source = Path(source).expanduser().resolve(strict=True)
    output = Path(output).expanduser().absolute()
    if not source.is_file() or output.suffix.lower() != '.mp4':
        raise ValueError('Choose a media input and a new .mp4 output filename.')
    if output.exists() or output.is_symlink():
        raise ValueError('Output already exists; choose a new filename. Nothing was overwritten.')
    if not output.parent.is_dir():
        raise ValueError('Choose an existing output directory.')
    data = probe(source)
    video = next((s for s in data['streams'] if s['codec_type'] == 'video'
                  and not s.get('disposition', {}).get('attached_pic', 0)), None)
    audio = next((s for s in data['streams'] if s['codec_type'] == 'audio'), None)
    if not video and not audio:
        raise ValueError('No usable video or audio stream was found.')
    audio_only = video is None
    duration = None
    if audio_only:
        duration = number(audio.get('duration')) or number(data.get('format', {}).get('duration'))
        if not duration:
            raise ValueError('Audio duration is unavailable; do not encode an unbounded background.')
    fd, temporary_name = tempfile.mkstemp(prefix='.v3-prepare-', suffix='.mp4', dir=output.parent)
    os.close(fd)
    temporary = Path(temporary_name)
    try:
        command = ['ffmpeg', '-hide_banner', '-nostdin', '-protocol_whitelist', 'file,pipe,crypto,data', '-y']
        if audio_only:
            command += ['-f', 'lavfi', '-i', 'color=c=black:s=1920x1080:r=30',
                        '-protocol_whitelist', 'file,pipe,crypto,data', '-i', str(source), '-map', '0:v:0', '-map', '1:' + str(audio['index']),
                        '-t', format(duration, '.9f')]
        else:
            command += ['-i', str(source), '-map', '0:' + str(video['index'])]
            if audio:
                command += ['-map', '0:' + str(audio['index'])]
            command += ['-vf', 'scale=1920:1080:force_original_aspect_ratio=decrease,'
                        'pad=1920:1080:(ow-iw)/2:(oh-ih)/2,setsar=1,fps=30']
        command += ['-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-crf', '18']
        if audio_only:
            command += ['-tune', 'stillimage']
        if audio:
            command += ['-c:a', 'aac', '-b:a', '192k', '-ar', '48000', '-ac', '2']
        else:
            command += ['-an']
        command += ['-movflags', '+faststart', str(temporary)]
        result = subprocess.run(command)
        if result.returncode:
            raise ValueError('FFmpeg failed; no final output was created. Review the error above.')
        encoded = probe(temporary)
        encoded_video = next(s for s in encoded['streams'] if s['codec_type'] == 'video')
        encoded_audio = next((s for s in encoded['streams'] if s['codec_type'] == 'audio'), None)
        if (encoded_video.get('codec_name'), encoded_video.get('width'), encoded_video.get('height'),
                encoded_video.get('pix_fmt'), encoded_video.get('r_frame_rate')) != ('h264', 1920, 1080, 'yuv420p', '30/1'):
            raise ValueError('Output did not match the requested media properties.')
        if audio and (not encoded_audio or encoded_audio.get('codec_name') != 'aac'):
            raise ValueError('Output did not contain the requested AAC audio.')
        actual_duration = number(encoded.get('format', {}).get('duration'))
        if duration and (not actual_duration or abs(actual_duration - duration) > 0.1):
            raise ValueError('Output duration differed from the audio input; no final output was created.')
        # Same-directory hard link publishes without ever replacing an existing filename.
        # If another process creates the target meanwhile, this raises FileExistsError.
        try:
            os.link(temporary, output)
        except OSError as error:
            raise ValueError('Could not safely create the new output. Use a local disk folder and '
                             'a new filename; no existing file was overwritten.') from error
        return {'output': str(output), 'audio_only': audio_only,
                'input_audio_duration_seconds': duration,
                'output_duration_seconds': actual_duration,
                'video': {k: encoded_video.get(k) for k in ['codec_name', 'width', 'height', 'pix_fmt', 'r_frame_rate']},
                'audio': {k: encoded_audio.get(k) for k in ['codec_name', 'sample_rate', 'channels']} if encoded_audio else None,
                'hardware_playback_verified': False}
    finally:
        temporary.unlink(missing_ok=True)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('input', help='Original video or audio file; it is never changed.')
    parser.add_argument('output', help='New MP4 output, for example 1_intro.mp4.')
    args = parser.parse_args()
    try:
        print(json.dumps(prepare(args.input, args.output), indent=2))
    except (OSError, ValueError, subprocess.TimeoutExpired, json.JSONDecodeError) as error:
        print(str(error), file=sys.stderr)
        return 1
    return 0


if __name__ == '__main__':
    sys.exit(main())
