"""Replay the V13 opening trim in the production checkout. Requires FFmpeg and Pillow."""
import hashlib
import json
import os
import subprocess
import sys
import tempfile
from pathlib import Path

ROOT = Path(__file__).resolve().parent
PARENT = ROOT.parent / 'scene-one-v12'
LANGUAGE_PASS = ROOT.parent / 'scene-one-v9'
SITE = ROOT.parents[2]
SUBTITLES = SITE / 'kit/cinema-subtitles.py'
FPS = 24
KEEP, OLD_END = 68, 80
SAMPLE_RATE = 48000
FADE = 480


def record(path, base):
    with path.open('rb') as source:
        return {'file': os.path.relpath(path, base), 'sha256': hashlib.file_digest(source, 'sha256').hexdigest()}


def write_json(path, value):
    path.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + '\n', encoding='utf-8')


def ffmpeg(*args, data=None, cwd=None):
    return subprocess.run(['ffmpeg', '-nostdin', '-v', 'error', '-y', *args], input=data,
                          stdout=subprocess.PIPE, cwd=cwd, check=True).stdout


def picture(folder):
    # Trim in display order. A packet-copy boundary here would include a later B-frame reference.
    source, output = PARENT / 'chair.mp4', folder / 'chair.mp4'
    trim = f'trim=end_frame={KEEP},setpts=PTS-STARTPTS'
    ffmpeg('-i', source, '-map', '0:v:0', '-an', '-vf', trim, '-c:v', 'libx264', '-profile:v', 'high',
           '-preset', 'medium', '-crf', '8', '-threads', '2', '-pix_fmt', 'yuv420p',
           '-color_primaries', 'bt709', '-color_trc', 'bt709', '-colorspace', 'bt709', '-color_range', 'tv',
           '-video_track_timescale', '12288', '-movflags', '+faststart', output)
    stats = json.loads(subprocess.check_output(['ffprobe', '-v', 'error', '-select_streams', 'v:0',
                       '-count_frames', '-show_entries', 'stream=nb_read_frames', '-of', 'json', output]))
    if int(stats['streams'][0]['nb_read_frames']) != KEEP:
        raise ValueError('Opening duration differs from the selected display range.')
    ffmpeg('-i', source, '-i', output, '-filter_complex',
           f'[0:v]{trim}[ref];[1:v][ref]psnr=stats_file=psnr.txt:shortest=1', '-f', 'null', '-', cwd=folder)
    values = [float(field.split(':')[1]) for row in (folder/'psnr.txt').read_text().splitlines()
              for field in row.split() if field.startswith('psnr_avg:')]
    if len(values) != KEEP or min(values) < 45:
        raise ValueError('Picture comparison failed against the selected source frames.')
    return {'sourceDisplayFrames': [0, KEEP], 'decodedFramesCompared': len(values),
            'minimumFramePsnrDb': min(values),
            'method': 'Decode V12, retain display frames 0–67, encode at native rate in H.264 High, CRF 8. '
                      'Compare each output frame with the source at the same display index.'}


def pcm(path):
    return ffmpeg('-i', path, '-map', '0:a:0', '-f', 's24le', '-')


def sound(folder):
    source = PARENT / 'mix.flac'
    original = pcm(source)
    first, last = (frame * SAMPLE_RATE // FPS for frame in (KEEP, OLD_END))
    stride = 6  # Two signed, little-endian 24-bit samples per stereo sample frame.
    start = first - FADE
    fade = bytearray()
    for i in range(FADE):
        for channel in (0, 1):
            a = (start + i) * stride + channel * 3
            b = (last - FADE + i) * stride + channel * 3
            left = int.from_bytes(original[a:a+3], 'little', signed=True)
            right = int.from_bytes(original[b:b+3], 'little', signed=True)
            value = round((left * (FADE - 1 - i) + right * i) / (FADE - 1))
            fade.extend(value.to_bytes(3, 'little', signed=True))
    joined = original[:start*stride] + fade + original[last*stride:]
    output = folder / 'mix.flac'
    ffmpeg('-f', 's24le', '-ar', str(SAMPLE_RATE), '-ac', '2', '-i', '-', '-c:a', 'flac',
           '-compression_level', '8', output, data=joined)
    decoded = pcm(output)
    if decoded != joined or len(original) - len(decoded) != (last-first)*stride:
        raise ValueError('Lossless audio ripple did not round-trip.')
    return {'sampleRate': SAMPLE_RATE, 'channels': 2, 'bits': 24, 'inputSamplesPerChannel': len(original)//stride,
            'outputSamplesPerChannel': len(decoded)//stride, 'removedStereoSampleFrames': [first, last],
            'crossfadeSourceRanges': [[start, first], [last-FADE, last]], 'crossfadeOutputRange': [start, first],
            'verifiedIdenticalSamplesPerChannelOutsideFade': len(decoded)//stride - FADE,
            'method': 'In the steady apartment bed, linearly blend the 480 stereo sample frames preceding each '
                      'edge at complementary gains. Continue from the far edge. Verify the decoded 24-bit FLAC '
                      'against the assembled PCM, including the unmodified head and rippled tail.'}


def captions(folder):
    sheet = json.loads((LANGUAGE_PASS / 'subtitle-cues.json').read_text())
    language = LANGUAGE_PASS / 'dialogue-language.json'
    dialogue = json.loads(language.read_text())
    cue, = sheet['cues']
    if cue['screenplay'] != dialogue['screenplay'] or cue['spoken'] != dialogue['spoken']:
        raise ValueError('Cue wording differs from the selected language record.')
    sheet['edition'] = 'yesterdays-pnl-v13'
    cue['startFrame'] -= OLD_END - KEEP
    cue['endFrame'] -= OLD_END - KEEP
    cue['source'] = '/' + language.relative_to(SITE).as_posix()
    sheet['spotting'] = ('The cue opens on the first audible Jak at frame 178. The final vowel releases near '
                         'frame 212. Five further frames leave time to read before the cut at frame 217.')
    path = folder / 'subtitle-cues.json'
    write_json(path, sheet)
    subprocess.run([sys.executable, SUBTITLES, path, '--vtt', folder/'scene-one-v13.vtt'], check=True)


def main():
    with tempfile.TemporaryDirectory(dir=ROOT) as temporary:
        folder = Path(temporary)
        receipt = {'parentEdition': 'yesterdays-pnl-v12', 'fps': FPS, 'removedFrames': [KEEP, OLD_END],
                   'rangeConvention': 'Zero-based, end exclusive.', 'credits': 0,
                   'screenAction': 'The professor turns a page. The CRT wakes. His first look leads into the monitor insert.',
                   'reason': 'Cut after the first look, before the second head lift and closing eyes.',
                   'inputs': [record(path, ROOT) for path in (PARENT/'chair.mp4', PARENT/'mix.flac',
                              LANGUAGE_PASS/'subtitle-cues.json', LANGUAGE_PASS/'dialogue-language.json', SUBTITLES)],
                   'pictureAudit': picture(folder), 'soundAudit': sound(folder)}
        captions(folder)
        files = {'picture': 'chair.mp4', 'sound': 'mix.flac', 'cues': 'subtitle-cues.json',
                 'captions': 'scene-one-v13.vtt'}
        receipt['outputs'] = {key: record(folder/name, folder) for key, name in files.items()}
        write_json(folder/'trim-receipt.json', receipt)
        for filename in [*files.values(), 'trim-receipt.json']:
            (folder/filename).replace(ROOT/filename)


if __name__ == '__main__':
    main()
