"""Conform the twelve selected shots into the silent HD picture master.

Use --rise to rebuild the promoted apartment shot. With no arguments the
verified selections in picture-plan.json are conformed at their original pace.
"""
import argparse
import hashlib
import json
from pathlib import Path
import runpy
import subprocess
import tempfile

ROOT = Path(__file__).resolve().parent
SIZE = (1920,1080)
FPS = 24


def ffmpeg(*args):
    subprocess.run(['ffmpeg','-nostdin','-v','error','-y',*args],check=True)


def probe(path):
    return json.loads(subprocess.check_output(['ffprobe','-v','error','-select_streams','v:0',
                      '-show_streams','-of','json',path]))['streams'][0]


def digest(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


def rise():
    source=ROOT/'rise-hd-raw.mp4'
    ref=runpy.run_path(str(ROOT/'restore-motion.py'))
    folder=ROOT
    with tempfile.TemporaryDirectory(dir=folder) as temp:
        output=Path(temp)/'rise-hd.mp4'
        cmd=['ffmpeg','-v','error','-f','rawvideo','-pixel_format','rgb24','-video_size','1920x1080',
             '-framerate','24','-i','pipe:0','-an','-c:v','libx264','-crf','13','-preset','medium',
             '-threads','2','-pix_fmt','yuv420p','-movflags','+faststart',output]
        with subprocess.Popen(cmd,stdin=subprocess.PIPE) as proc:
            for frame in ref['wide_frames']('rise',source,26,79,False):
                proc.stdin.write(frame.tobytes())
            proc.stdin.close()
            if proc.wait():
                raise RuntimeError('The promoted rise did not encode.')
        output.replace(folder/output.name)


def conform():
    plan=json.loads((ROOT/'picture-plan.json').read_text())
    baseline=ROOT/plan['previous']['file']
    if digest(baseline)!=plan['previous']['sha256']:
        raise ValueError('The reference is not the marked workprint.')
    timeline=json.loads((baseline.parent/'edit.json').read_text())['shots']
    if [(s['id'],s['frames']) for s in timeline] != [(s['id'],s['frames']) for s in plan['shots']]:
        raise ValueError('One of the locked shot boundaries changed.')
    verified={}
    cursor=0
    cuts=[]
    with tempfile.TemporaryDirectory(dir=ROOT) as temp:
        folder=Path(temp)
        for shot in plan['shots']:
            first,count=shot['in'],shot['frames']
            source=ROOT/shot['file']
            if source not in verified:
                verified[source]=(digest(source),probe(source))
            expected,info=verified[source]
            if shot['sha256']!=expected or info['avg_frame_rate']!='24/1' or first<0 or first+count>int(info['nb_frames']):
                raise ValueError(f"Selected source or range differs for {shot['id']}")
            output=folder/(shot['id']+'.mp4')
            # The archived RGB-to-YUV encodes used swscale's default 601
            # matrix. Runway tagged its HD photographs 709. Normalize every
            # cut so the H.264 decoder never inherits the prior shot's matrix.
            matrix=info.get('color_space','bt601')
            signal=info.get('color_range','tv')
            vf=(f'trim=start_frame={first}:end_frame={first+count},setpts=PTS-STARTPTS,'
                f'scale=1920:1080:flags=lanczos+accurate_rnd:in_color_matrix={matrix}:'
                f'in_range={signal}:out_color_matrix=bt709:out_range=tv,setsar=1,format=yuv420p,'
                'setparams=range=limited:color_primaries=bt709:color_trc=bt709:colorspace=bt709')
            ffmpeg('-i',source,'-map','0:v:0','-an','-vf',vf,'-frames:v',str(count),'-c:v','libx264',
                   '-crf','14','-preset','medium','-threads','2','-color_range','tv','-colorspace','bt709',
                   '-color_primaries','bt709','-color_trc','bt709','-video_track_timescale','12288',output)
            cuts.append(f"file '{output.name}'\n")
            cursor+=count
        if cursor!=1215:
            raise ValueError('The scene must contain 1,215 frames.')
        (folder/'list.txt').write_text(''.join(cuts))
        result=folder/'picture-hd.mp4'
        ffmpeg('-f','concat','-safe','0','-i',folder/'list.txt','-an','-c:v','copy','-bsf:v',
               'setts=pts=round(PTS*TB*24)/(TB*24):dts=round(DTS*TB*24)/(TB*24):duration=1/(24*TB)',
               '-movflags','+faststart',result)
        info=probe(result)
        if (info['width'],info['height'],info['avg_frame_rate'],int(info['nb_frames']))!=(*SIZE,'24/1',cursor):
            raise RuntimeError('The encoded master does not match the locked timeline.')
        if info.get('color_space')!='bt709' or info.get('color_range')!='tv':
            raise RuntimeError('The master does not carry its delivery color specification.')
        result.replace(ROOT/result.name)


if __name__=='__main__':
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument('--rise',action='store_true',help='Rebuild the promoted rise and its original monitor composite.')
    args=p.parse_args()
    if args.rise:
        rise()
    else:
        conform()
