"""Retain the studio performance and fit the generated Polish picture to its articulation."""
import hashlib
import json
from pathlib import Path
import subprocess
import tempfile

import numpy as np
from PIL import Image, ImageDraw, ImageFont

ROOT = Path(__file__).resolve().parent
FPS = 24
SUBFRAMES = 5
LIP_BOX = (1030, 365, 270, 160)


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


def mouth(path):
    x, y, w, h = LIP_BOX
    filt = f'crop={w}:{h}:{x}:{y}'
    data = subprocess.check_output(['ffmpeg','-nostdin','-v','error','-i',path,'-map','0:v:0',
                                    '-an','-vf',filt,'-pix_fmt','rgb24','-f','rawvideo','pipe:1'])
    return np.frombuffer(data,'uint8').reshape(-1,h,w,3)


def proof(raw, take, ticks, folder):
    originals, finished = mouth(raw), mouth(take)
    if len(finished) != len(ticks):
        raise RuntimeError('The returned speaking shot has the wrong number of frames.')
    chosen = [38, 42, 47, 52, 58, 64, 68, 72]
    size = (184,109)
    sheet = Image.new('RGB',(4*193+12,2*374),'#1e1e1c')
    draw = ImageDraw.Draw(sheet)
    font = ImageFont.load_default(size=14)
    for j, idx in enumerate(chosen):
        phase = ticks[idx]/SUBFRAMES
        lo = int(np.floor(phase))
        x, y = 8+193*(j%4), 7+374*(j//4)
        draw.text((x,y), f'Shot {idx} · source {phase:.1f}', font=font, fill='#f3f2e8')
        for k, (pic, tag) in enumerate([(originals[lo],f'Original {lo}'),(finished[idx],'Finished'),
                                         (originals[lo+1],f'Original {lo+1}')]):
            image = Image.fromarray(pic).resize(size,Image.Resampling.LANCZOS)
            sheet.paste(image,(x,y+23+k*115))
            draw.text((x+4,y+26+k*115),tag,font=font,fill='white',stroke_width=2,stroke_fill='black')
    sheet.save(folder/'speaker-retime.jpg',quality=94,subsampling=0)
    field = finished[:].astype(np.int16)
    numerical = []
    for j,tick in enumerate(ticks):
        if tick % SUBFRAMES == 0:
            frame = originals[tick//SUBFRAMES].astype(np.int16)
            numerical.append(float(np.abs(field[j]-frame).mean()))
    motion = np.abs(np.diff(field,axis=0)).mean(axis=(1,2,3))
    return {'nativeLipCrop':LIP_BOX,'inspectionShotFrames':chosen,
            'integerSourceFramesCompared':len(numerical),
            'worstIntegerFrameMouthErrorRgb':round(max(numerical),3),
            'minimumAdjacentMouthFrameChange':round(float(min(motion)),3),
            'exactlyRepeatedMouthFrames':int((motion==0).sum()),'file':'speaker-retime.jpg'}


def main():
    raw=ROOT/'speaker-hd-raw.mp4'
    align=json.loads((ROOT/'audio-alignment.json').read_text())
    if digest(raw)!=align['sourceSha256']:
        raise ValueError('The generation and its verified time map do not match.')
    anchors=align['pictureMap']
    count=int(anchors['shotFrames'][-1])
    desired=np.interp(np.arange(count),anchors['shotFrames'],anchors['sourceFrames'])
    ticks=np.rint(desired*SUBFRAMES).astype(int)
    if np.any(np.diff(ticks)<=0):
        raise ValueError('Two outputs requested the same source subframe.')
    first=int(anchors['sourceFrames'][0])
    # Decode the normal-speed opening directly. Only the portion which needs
    # fractional source times goes through overlapped bidirectional estimation.
    boundary=next(i for i,t in enumerate(ticks) if t!=(first+i)*SUBFRAMES)
    pad=int(np.floor(desired[boundary]))-2
    last=int(np.ceil(desired[-1]))+4
    chosen='+'.join(f'eq(n,{t-pad*SUBFRAMES})' for t in ticks[boundary:])
    filt=(f'[0:v]split[a][b];[a]trim=start_frame={first}:end_frame={first+boundary},setpts=PTS-STARTPTS[head];'
          f'[b]trim=start_frame={pad}:end_frame={last},setpts=PTS-STARTPTS,'
          f'minterpolate=fps={FPS*SUBFRAMES}:mi_mode=mci:mc_mode=aobmc:me_mode=bidir:'
          f'me=epzs:mb_size=16:search_param=12:vsbmc=1,select=\'{chosen}\','
          f'settb=1/{FPS},setpts=N[ending];[head][ending]concat=n=2:v=1:a=0,'
          f'settb=1/{FPS},setpts=N[out]')
    with tempfile.TemporaryDirectory(dir=ROOT) as temp:
        folder=Path(temp)
        result=folder/'speaker-hd.mp4'
        cmd=['ffmpeg','-nostdin','-v','error','-filter_complex_threads','2','-i',raw,'-filter_complex',filt,
             '-map','[out]','-an','-r','24','-c:v','libx264','-crf','13','-preset','medium','-threads','2',
             '-pix_fmt','yuv420p','-colorspace','bt709','-color_primaries','bt709','-color_trc','bt709',
             '-color_range','tv','-movflags','+faststart',result]
        subprocess.run(cmd,check=True)
        check=proof(raw,result,ticks,folder)
        if check['exactlyRepeatedMouthFrames'] or check['worstIntegerFrameMouthErrorRgb']>3:
            raise RuntimeError('An original mouth landmark or unique motion frame failed the conform check.')
        report={'file':result.name,'sha256':digest(result),'source':raw.name,'sourceSha256':align['sourceSha256'],
                'alignment':'audio-alignment.json','shotFrames':count,'fps':FPS,'nativeSize':[1920,1080],
                'sourceFrameAnchors':anchors['sourceFrames'],'shotFrameAnchors':anchors['shotFrames'],
                'method':'Integer opening frames come directly from the 24 fps source. Bidirectional block-motion estimation at 120 fps supplies fractional source positions during articulation and settle. Each finished frame samples the closest fifth-frame to the measured studio timing. The master uses the original selected studio audio.',
                'sourceFrameForEachOutput':[float(t/SUBFRAMES) for t in ticks],
                'worstSamplingErrorIn24FpsFrames':round(float(np.abs(ticks/SUBFRAMES-desired).max()),4),
                'verification':check}
        (folder/'speaker-retime.json').write_text(json.dumps(report,indent=2,ensure_ascii=False)+'\n')
        for name in [result.name,'speaker-retime.json','speaker-retime.jpg']:
            (folder/name).replace(ROOT/name)


if __name__=='__main__':
    main()
