"""Bring the professor's approaching shadow into the existing kettle shot. Requires NumPy, Pillow and FFmpeg."""
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
WIDTH, HEIGHT, FPS = 1280, 720, 24


def smooth(value):
    value = np.clip(value, 0, 1)
    return value * value * (3 - 2 * value)


def recipe():
    edit = json.loads((ROOT / 'edit.json').read_text())
    shot = next(s for s in edit['shots'] if s['id'] == 'pour')
    master = ROOT / shot['shadow']['source']
    if hashlib.sha256(master.read_bytes()).hexdigest() != edit['previousMasterSha256']:
        raise ValueError('The light pass requires the exact marked master.')
    return shot, master


def finish(shot, master, target):
    light = shot['shadow']
    count = shot['frames']
    x = np.arange(WIDTH, dtype=np.float32)
    y = np.arange(HEIGHT, dtype=np.float32)[:, None]
    # The sink faces the professor as he approaches from camera-right. Daylight
    # through the high window stays constant. The shadow deepens down the porcelain
    # and steel towards the front of the counter, where he blocks the room's fill.
    near = smooth((y - 365) / 190)
    sink_depth = 0.32 * (HEIGHT - y)
    stride = WIDTH * HEIGHT * 3 // 2
    read = ['ffmpeg','-v','error','-ss',f"{light['sourceIn']/FPS:.6f}",'-i',str(master),
            '-vframes',str(count),'-an','-pix_fmt','yuv420p','-f','rawvideo','-']
    write = ['ffmpeg','-v','error','-y','-f','rawvideo','-s',f'{WIDTH}x{HEIGHT}',
             '-pix_fmt','yuv420p','-r',str(FPS),'-i','-','-an','-c:v','libx264',
             '-crf','13','-preset','medium','-threads','2','-video_track_timescale','12288',str(target)]
    with subprocess.Popen(read,stdout=subprocess.PIPE) as source, subprocess.Popen(write,stdin=subprocess.PIPE) as dest:
        for frame in range(count):
            data = source.stdout.read(stride)
            if len(data) != stride:
                raise ValueError(f'Partial source frame {frame}')
            if frame > light['start']:
                t = smooth((frame - light['start']) / (light['settle'] - light['start']))
                leading_edge = 1430 - 816 * t + sink_depth
                shade = light['maximum'] * near * smooth((x - leading_edge + 135) / 265)
                luma = np.frombuffer(data, np.uint8, WIDTH*HEIGHT).reshape(HEIGHT, WIDTH)
                corrected = luma - np.maximum(luma.astype(np.float32) - 16, 0) * shade
                dest.stdin.write(np.rint(corrected).astype(np.uint8).tobytes())
                dest.stdin.write(data[WIDTH*HEIGHT:])
            else:
                dest.stdin.write(data)
        dest.stdin.close()
        if source.wait() or dest.wait():
            raise RuntimeError('Could not finish the kettle shadow.')


def samples(path, frames):
    select = '+'.join(f'eq(n\\,{n})' for n in frames)
    data = subprocess.check_output(['ffmpeg','-v','error','-i',str(path),'-vf',f'select={select}',
                                    '-an','-fps_mode','passthrough','-f','rawvideo','-pix_fmt','rgb24','-'])
    stride = WIDTH * HEIGHT * 3
    if len(data) != stride * len(frames):
        raise ValueError('Missing a comparison frame.')
    return [Image.frombytes('RGB',(WIDTH,HEIGHT),data[i*stride:(i+1)*stride]) for i in range(len(frames))]


def review(shot, parent, finished, folder):
    start = shot['shadow']['sourceIn']
    frames = [88, 113, 128, 140]
    old = samples(parent,[start+n for n in frames])
    new = samples(finished,frames)
    # A crop of the front sink lip includes its direct specular reflection.
    zones = {'sinkLip':[912,663,1164,691], 'cup':[788,479,849,527], 'window':[870,36,1005,73]}
    levels = []
    for n, a, b in zip(frames,old,new):
        regions = {}
        for name, box in zones.items():
            first, second = [np.asarray(image.crop(box).convert('L'),float).mean() for image in (a,b)]
            regions[name] = {'old':round(first,2),'new':round(second,2),'difference':round(second-first,2)}
        levels.append({'frame':start+n,'shotFrame':n,'levels':regions})
    if levels[2]['levels']['sinkLip']['difference'] > -8 or abs(levels[2]['levels']['window']['difference']) > 1:
        raise ValueError('Expected light loss on the sink, with steady daylight above it.')
    sheet = Image.new('RGB',(4*314+8,2*209+8),'#171814')
    draw = ImageDraw.Draw(sheet)
    font = ImageFont.load_default(size=16)
    for row, (label, images) in enumerate([('V7',old),('V8',new)]):
        for col, (n, img) in enumerate(zip(frames,images)):
            x,y = 8+col*314,8+row*209
            sheet.paste(img.resize((306,172),Image.Resampling.LANCZOS),(x,y))
            draw.text((x,y+177),f'{label}   frame {start+n}',font=font,fill='#f3efdf')
    sheet.save(folder/'shadow-proof.jpg',quality=93,subsampling=0)
    result = {'source':shot['shadow']['source'],'sourceSha256':hashlib.sha256(parent.read_bytes()).hexdigest(),
              'selected':'pour.mp4','selectedSha256':hashlib.sha256(finished.read_bytes()).hexdigest(),
              'target':'A soft loss of room fill enters the steel draining board from camera right, reaches the near face of the mug and rests at the cut to his hand. The window keeps its daylight.',
              'frames':shot['frames'],'fps':FPS,'recipe':shot['shadow'],'zones':zones,'measure':'Mean full-range 8-bit image luma in each box, decoded from each movie.','samples':levels}
    (folder/'shadow-check.json').write_text(json.dumps(result,indent=2,ensure_ascii=False)+'\n')


def main():
    shot, parent = recipe()
    with tempfile.TemporaryDirectory(dir=ROOT) as tmp:
        folder = Path(tmp)
        finish(shot,parent,folder/'pour.mp4')
        review(shot,parent,folder/'pour.mp4',folder)
        for name in ('pour.mp4','shadow-proof.jpg','shadow-check.json'):
            (folder/name).replace(ROOT/name)


if __name__ == '__main__':
    main()
