"""Photograph the two CRT fronts into the locked desk angles at 1920 × 1080.

Render the English monitor states from the archived glass and cabinet art. The
keyboard insert retains the director's approved V8 hand and key travel.
"""
from functools import lru_cache
import hashlib
import json
from pathlib import Path
import runpy
import subprocess
import tempfile

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

ROOT = Path(__file__).resolve().parent
PROD = ROOT.parent
DESK = runpy.run_path(str(PROD/'scene-one-v5/desk.py'))
PLATE = DESK['V4']['PLATE']
CRT = runpy.run_path(str(PROD/'scene-one-v6/crt.py'))
SIZE = 1920, 1080
CAMERA = {'ready':(179,11,549), 'answer':(179,11,549), 'switch':(183,68,541),
          'keyboard':(341,137,612), 'question':(203,21,452)}
COUNTS = {'ready':72,'answer':108,'switch':72,'keyboard':78,'question':100}
SOURCES = ['../scene-one-v8/keyboard.mp4','../scene-one-v6/crt.py','../scene-one-v5/crt.py',
           '../scene-one-v5/desk.py','../scene-one-v4/desk.py','../scene-one-v4/desk.png',
           '../scene-one-v4/switch-matte.png','../scene-one/switch.mp4','../yesterday/render.py',
           '../../sources/original/monitor-i-am-ready.png','../../sources/original/monitor-automation-options-day.png']


def project(shot, point):
    left, top, width = CAMERA[shot]
    return (point[0] - left)*SIZE[0]/width, (point[1] - top)*SIZE[0]/width


@lru_cache(maxsize=20)
def canvas(shot, word, option, opening, pressed):
    left, top, width = CAMERA[shot]
    scale = PLATE.width/1000
    box = (left*scale,top*scale,(left+width)*scale,(top+width*9/16)*scale)
    image = PLATE.resize(SIZE, Image.Resampling.LANCZOS, box=box)
    CRT['composite'](image, 'primary', [project(shot,p) for p in DESK['FRONT']], word, opening,
                     pressed or option is not None)
    CRT['composite'](image, 'menu', [project(shot,p) for p in DESK['TERMINAL']], option)
    return image


def keyboard():
    # Only the lower hand and keyboard are taken from V8. Both monitor faces,
    # including the English menu, have been projected directly at delivery size.
    path = PROD/'scene-one-v8/keyboard.mp4'
    command = ['ffmpeg','-v','error','-i',path,'-f','rawvideo','-pix_fmt','rgb24','-an','pipe:1']
    matte = Image.new('L', SIZE)
    polygon = [(0,665),(255,661),(326,630),(800,540),(865,457),(1280,455),(1280,720),(0,720)]
    ImageDraw.Draw(matte).polygon([(round(1.5*x), round(1.5*y)) for x,y in polygon], fill=255)
    matte = matte.filter(ImageFilter.GaussianBlur(5))
    stride = 1280*720*3
    with subprocess.Popen(command,stdout=subprocess.PIPE) as decoder:
        for n in range(COUNTS['keyboard']):
            raw = decoder.stdout.read(stride)
            if len(raw) != stride:
                raise ValueError('The approved Enter sequence ended early.')
            original = Image.frombytes('RGB',(1280,720),raw).resize(SIZE,Image.Resampling.LANCZOS)
            state = 'LIGHTS' if n<17 else 'BATH' if n<45 else 'KETTLE'
            image = canvas('keyboard', None, state, 1, True).copy()
            image.paste(original,(0,0),matte)
            yield image
        if decoder.stdout.read(1) or decoder.wait():
            raise ValueError('Unexpected keyboard source duration.')


def switch(n):
    # Replay the V5 wrist path and source indices, projecting the matte directly
    # into the HD window; the rocker and switch contact retain their frame.
    image = canvas('switch', '-$43' if n<28 else None, None, 1, n>=28).copy()
    if n>=62:
        return image
    src=round(np.interp(n,[0,13,22,28,34,39,45,54],[0,2,9,16,23,28,35,43]))
    hand=DESK['V4']['hand_frame']('switch',src)
    s=.61
    rocker_x,rocker_y=DESK['SWITCH']
    if n<=28:
        dx,dy=DESK['reach'](n)
        x=rocker_x+dx-s*np.interp(src,[0,12,16],[74,45,24])
        y=rocker_y+dy-s*np.interp(src,[0,12,16],[146,136,137])
    else:
        x=rocker_x-s*24 + min(330,max(0,n-38)**1.65*2.8)
        y=rocker_y-s*137
    factor=s*SIZE[0]/CAMERA['switch'][2]
    hand = hand.convert('RGBa').resize((round(hand.width*factor),round(hand.height*factor)),
                                        Image.Resampling.LANCZOS).convert('RGBA')
    image.paste(hand,tuple(round(v) for v in project('switch',(x,y))),hand)
    return image


def frames(shot):
    if shot=='keyboard':
        yield from keyboard()
        return
    for n in range(COUNTS[shot]):
        if shot=='switch':
            yield switch(n)
        elif shot=='question':
            word = None if n<12 else 'IS MY BODY READY' if n>=29 else ''
            opening = min(1.,max(0.,(n-11)/9))
            yield canvas(shot,word,'KETTLE',opening,True)
        else:
            yield canvas(shot,'-$43' if shot=='answer' and n>=42 else 'I AM READY_',None,1,False)


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


def main():
    with tempfile.TemporaryDirectory(dir=ROOT) as temp:
        folder = Path(temp)
        result = folder/'desk-hd.mp4'
        rows, cursor = [], 0
        for shot, count in COUNTS.items():
            rows.append({'shot':shot,'reelFrames':[cursor,cursor+count]})
            cursor += count
        cut_times=','.join(str(row['reelFrames'][0]/24) for row in rows)
        encode=['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','-force_key_frames',cut_times,'-movflags','+faststart',result]
        with subprocess.Popen(encode,stdin=subprocess.PIPE) as encoder:
            for shot in COUNTS:
                for image in frames(shot):
                    encoder.stdin.write(image.tobytes())
            encoder.stdin.close()
            if encoder.wait():
                raise RuntimeError('Could not encode the HD desk reel.')
        probe=json.loads(subprocess.check_output(['ffprobe','-v','error','-select_streams','v:0',
                '-show_streams','-of','json',result]))['streams'][0]
        assert (int(probe['nb_frames']),probe['avg_frame_rate'],probe['width'],probe['height'])==(cursor,'24/1',*SIZE)
        report={'file':result.name,'sha256':digest(result),'size':SIZE,'frames':cursor,'fps':24,
                'shots':rows,'sources':[{'file':s,'sha256':digest(ROOT/s)} for s in SOURCES],
                'method':'The camera crop samples the archived 1672 × 941 desk image, then projects each source tube directly into the 1920 × 1080 image. Both displays retain their English text and exact state frames. The original V5 hand matte follows its reviewed rocker trajectory. The lower portion of the keyboard shot preserves V8’s selected localized Enter correction.'}
        (folder/'desk-hd.json').write_text(json.dumps(report,indent=2,ensure_ascii=False)+'\n')
        result.replace(ROOT/result.name)
        (folder/'desk-hd.json').replace(ROOT/'desk-hd.json')

if __name__=='__main__':
    main()
