"""Rebuild two continuous hand gestures from the original high-resolution frame art.

The V9 CRTs, keyboard artwork, contact times and cut lengths supply the set.
Only the arm projection, finger articulation and contact shadow are re-photographed.
"""
from functools import lru_cache
import math
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
HD = runpy.run_path(str(PROD/'scene-one-v9/desk-hd.py'))
KEYS = runpy.run_path(str(PROD/'scene-one-v8/keyboard.py'))
SIZE = (1920, 1080)
START = {'switch':416, 'keyboard':488}
COUNT = {'switch':72, 'keyboard':78}
SOURCE = {'switch':'../scene-one/switch.png', 'keyboard':'../scene-one-v2/keys.png'}
CROP = {'switch':(835,120,1672,845), 'keyboard':(1010,510,1672,941)}
ROI = {'switch':(1070,205,1920,1080), 'keyboard':(1240,675,1920,1080)}
# Splines follow the actual cuff, individual fingertips and paddled underside in each photograph.
# Points are local to CROP, in original source pixels.
EDGES = {
    'switch':[(858,8),(832,14),(806,21),(779,38),(749,56),(720,81),(693,102),
      (674,133),(655,169),(642,215),(634,227),(604,228),(575,230),(552,225),
      (535,226),(513,235),(495,250),(483,262),(455,271),(421,277),(387,286),
      (348,296),(320,300),(298,308),(275,322),(247,328),(221,335),(200,344),
      (176,349),(149,359),(136,365),(131,372),(110,376),(89,382),(69,390),
      (55,400),(51,410),(51,424),(55,437),(65,449),(83,460),(105,465),
      (130,467),(153,465),(179,459),(202,451),(218,444),(240,444),(267,441),
      (292,436),(314,430),(326,425),(311,441),(301,458),(296,476),(297,493),
      (305,515),(315,537),(324,567),(336,603),(348,634),(362,654),(380,666),
      (396,672),(411,682),(430,686),(450,685),(483,680),(508,676),(527,680),
      (555,686),(578,683),(586,671),(590,674),(614,679),(650,682),(672,678),
      (680,664),(682,647),(696,640),(709,640),(732,642),(763,639),(805,632),(858,620)],
    'keyboard':[(678,67),(657,78),(645,81),(627,84),(609,87),(591,91),(576,104),
      (565,120),(556,138),(540,139),(511,139),(491,135),(471,128),(447,117),
      (419,106),(399,96),(376,82),(348,67),(322,52),(307,45),(295,43),
      (276,46),(263,48),(246,42),(222,36),(207,32),(198,32),(190,38),(177,51),
      (167,53),(153,54),(143,59),(130,71),(119,84),(103,99),(91,112),(76,131),
      (65,151),(58,170),(53,190),(45,204),(44,213),(46,218),(52,222),(62,224),
      (72,223),(80,220),(90,214),(99,204),(107,192),(114,177),(124,173),
      (137,163),(141,159),(142,166),(147,182),(150,197),(139,199),(129,201),
      (120,207),(115,216),(115,229),(118,240),(125,249),(138,255),(162,261),
      (193,268),(220,273),(248,277),(271,284),(305,295),(336,304),(366,310),
      (394,312),(421,309),(443,305),(470,304),(497,304),(522,308),(535,311),
      (542,334),(551,347),(564,360),(587,373),(620,387),(652,400),(678,409)]
}
# Open area between the folded second and third finger, from the actual keyboard plate.
KEY_GAP = [(184,161),(192,149),(190,158),(191,172),(198,193),(203,200),(195,199),(190,184)]

def contour(mask, points, color):
    p = np.array(points, dtype=float)
    dense = []
    for i in range(len(p)):
        a,b,c,d = (p[j%len(p)] for j in (i-1,i,i+1,i+2))
        for t in np.arange(0,1,.125):
            pt = .5*(2*b+(-a+c)*t+(2*a-5*b+4*c-d)*t*t+(-a+3*b-3*c+d)*t**3)
            dense.append(tuple(3*pt))
    ImageDraw.Draw(mask).polygon(dense,fill=color)

@lru_cache(maxsize=2)
def hand(shot):
    original = Image.open(ROOT/SOURCE[shot]).crop(CROP[shot]).convert('RGB')
    matte = Image.new('L',(3*original.width,3*original.height))
    edge = EDGES[shot]
    # Carry the open cuff well beyond the crop before closing its silhouette.
    # The closing spline stays clear of the photographed edge.
    side = original.width+210
    contour(matte, edge+[(side,edge[-1][1]),(side+30,edge[-1][1]),
                         (side+30,edge[0][1]),(side,edge[0][1])], 255)
    if shot=='keyboard':
        contour(matte, KEY_GAP, 0)
    matte = matte.resize(original.size,Image.Resampling.LANCZOS).filter(ImageFilter.GaussianBlur(.8))
    original.putalpha(matte)
    return original.convert('RGBa')

def path(t, knots):
    # Shape-preserving cubic Hermite. The wrist decelerates into contact and
    # accelerates as it leaves. A reversal has exactly zero tangent.
    x,y = np.array(knots,dtype=float).T
    slopes = np.diff(y)/np.diff(x)
    m = np.zeros(len(y)); m[[0,-1]]=slopes[[0,-1]]
    for i,(a,b) in enumerate(zip(slopes,slopes[1:]),1):
        if a*b>0: m[i]=2*a*b/(a+b)
    i = max(0,min(len(x)-2,np.searchsorted(x,t)-1))
    h=x[i+1]-x[i];u=np.clip((t-x[i])/h,0,1)
    return (2*u**3-3*u*u+1)*y[i]+(u**3-2*u*u+u)*h*m[i]+(-2*u**3+3*u*u)*y[i+1]+(u**3-u*u)*h*m[i+1]

def contact(t, f):
    return path(t-f,[(-5,0),(-2.5,.10),(-.4,.86),(0,1),(1.4,1),(3,.48),(5,0)])

def geometry(shot,t):
    if shot=='switch':
        # Contact is on global f444. Off-camera working distance is inherited
        # from the preceding wide. A small recoil lets the depressed rocker return.
        travel=path(t,[(-1,997),(0,942),(4,738),(10,405),(18,138),(24,36),(28,0),
                       (30,-2),(32,-1.5),(35,1),(38,9),(41,45),(46,213),(52,610),(57,970)])
        rise=path(t,[(-1,294),(0,275),(4,188),(10,101),(18,42),(24,12),(28,0),
                     (32,1),(35,-1),(38,-7),(44,-24),(54,-38)])
        # The tip marks the actual forward edge of the pad, in the starter.
        # Wrist rotation and pad compression unfold continuously in source space.
        pivot=path(t,[(0,-.032),(12,-.012),(22,.015),(28,.028),(34,.022),(40,-.014),(55,-.072)])
        compress=path(t,[(0,0),(25,0),(28,1),(32,.92),(36,.1),(39,0)])
        loose=path(t,[(0,0),(21,.3),(28,1),(35,.7),(43,-.7),(54,-1)])
        return (1148.6+travel,618.7+rise), (.83,50,418), (pivot,compress,loose)
    # Down, Down, Enter. A continuous wrist transfer starts after the second release.
    across=path(t,[(0,0),(49,0),(53,.04),(58,.47),(63,.98),(65,1)])
    x=1443.33-84.17*across
    y=955.86-38.01*across
    lift=path(t,[(0,17),(6,18),(10,23),(12,22),(15,8),(17,-4.7),(18,-4.3),(20,6),
                 (23,22),(27,27),(34,20),(38,22),(41,18),(43,6),(45,-4.7),(46,-4.1),
                 (49,12),(53,27),(58,36),(61,25),(63,13),(66,-4.7),(67,-3.8),(70,12),
                 (73,22),(77,23)])
    # The wrist turns toward Enter before the thumb follows it. The grip opens
    # again as the arm arrives. The folded digits settle slightly behind the index.
    roll=path(t,[(0,0),(49,0),(54,.35),(58,1),(61,.64),(65,0),(77,0)])
    tuck=path(t,[(0,0),(47,0),(52,.07),(57,.6),(60,1),(63,.91),(66,.38),(70,-.15),(75,0)])
    return (x,y),(.90,56,222),(lift,across,roll,tuck)

@lru_cache(maxsize=2)
def mesh_grid(shot):
    l,t,r,b=ROI[shot]; boxes=[]; nodes=[]
    for y in range(0,b-t,18):
        for x in range(0,r-l,18):
            u,v=min(r-l,x+18),min(b-t,y+18)
            boxes.append((x,y,u,v))
            nodes.append([(l+x,t+y),(l+x,t+v),(l+u,t+v),(l+u,t+y)])
    return boxes,np.array(nodes,dtype=float)

def project_hand(shot,t):
    (px,py),(scale,tip_x,tip_y),motion=geometry(shot,t)
    boxes,grid=mesh_grid(shot)
    x=(grid[:,:,0]-px)/scale + tip_x
    y=(grid[:,:,1]-py)/scale + tip_y
    if shot=='switch':
        angle,compress,loose=motion
        # Back-project to the original hand. Keep the distal pad on the rocker
        # while the palm continues to settle and the curled fingers release.
        dx,dy=x-tip_x,y-tip_y
        sx=tip_x+dx*math.cos(angle)+dy*math.sin(angle)
        sy=tip_y+dy*math.cos(angle)-dx*math.sin(angle)
        pad=np.exp(-((x-60)/90)**2-((y-419)/54)**2)
        sx-=compress*2.3*pad
        sy+=loose*5*np.exp(-((x-400)/120)**2-((y-620)/110)**2)
    else:
        lift,across,roll,tuck=motion
        # Distal finger travel is greatest beyond the first joint. Keep the
        # thumb and folded fingers anatomically attached while the knuckle flexes.
        reach=np.clip((200-x)/90,0,1)
        reach=reach*reach*(3-2*reach)
        near_index=1/(1+np.exp(np.clip((x-131)/6+(y-182)/18,-25,25)))
        flex=.75*reach*near_index
        wrist=.16+.09*np.exp(-((x-191)/155)**2)
        sy=y+lift*(wrist+flex)
        sx=x-.20*lift*flex + .018*lift*np.clip((400-x)/380,0,1)
        sy+=2.5*np.sin(np.pi*across)*np.clip((600-x)/450,0,1)
        sx+=.014*roll*(y-212)
        sy-=.014*roll*(x-535)
        thumb=np.exp(-((x-151)/110)**2-((y-237)/44)**2)
        fingers=np.exp(-((x-196)/72)**2-((y-165)/36)**2)
        sx-=7.8*tuck*thumb + 2.2*roll*fingers
        sy-=5.6*tuck*thumb - 3.2*roll*fingers
    # Continue the cuff towards the camera boundary using the same perspective
    # and the original sleeve weave. This mild projection grows only at the wrist.
    outer=np.maximum(0,sx-(535 if shot=='switch' else 440))
    sx-=outer*(.44 if shot=='switch' else .26)*(1-np.exp(-outer/110))
    coords=np.stack((sx,sy),axis=-1).reshape(-1,8)
    mesh=[(box,tuple(quad)) for box,quad in zip(boxes,coords)]
    l,h,r,b=ROI[shot]
    return hand(shot).transform((r-l,b-h),Image.Transform.MESH,mesh,Image.Resampling.BICUBIC)

@lru_cache(maxsize=1)
def key_scene():
    plate=KEYS['stamped_plate']()
    mask=Image.new('L',SIZE)
    pts=[(0,665),(255,661),(326,630),(800,540),(865,457),(1280,455),(1280,720),(0,720)]
    ImageDraw.Draw(mask).polygon([(round(1.5*x),round(1.5*y)) for x,y in pts],fill=255)
    return plate,mask.filter(ImageFilter.GaussianBlur(5))

def background(shot,n):
    if shot=='switch':return HD['canvas']('switch','-$43' if n<28 else None,None,1,n>=28).copy()
    option='LIGHTS' if n<17 else 'BATH' if n<45 else 'KETTLE'
    base=HD['canvas']('keyboard',None,option,1,True).copy()
    plate,mask=key_scene()
    caps=plate.copy()
    amount=max(contact(n,c) for c in (17,45,66))
    KEYS['travel'](caps,'DOWN' if n<54 else 'Enter',amount)
    base.paste(caps.resize(SIZE,Image.Resampling.LANCZOS),(0,0),mask)
    return base

def exposure(shot,n):
    base=background(shot,n)
    if shot=='switch' and (n<=2 or n>=56):
        return base
    l,t,r,b=ROI[shot]
    # Integrate premultiplied photographic samples across half a frame of
    # exposure. This also prevents a fast fingertip from appearing stroboscopic.
    offsets=np.linspace(-.21,.21,7 if shot=='switch' else 3)
    total=np.zeros((b-t,r-l,4),np.uint16)
    for d in offsets:
        total+=np.asarray(project_hand(shot,n+d))
    sample=Image.fromarray(np.uint8((total+len(offsets)//2)//len(offsets)),'RGBa').convert('RGBA')
    if shot=='keyboard':
        (x,y),_,(lift,*_)=geometry(shot,n)
        shadow=Image.new('L',(r-l,b-t)); draw=ImageDraw.Draw(shadow)
        strength=int(64-1.2*max(0,lift))
        draw.ellipse((x-l-8,y-t-3,x-l+43,y-t+8),fill=strength)
        shadow=shadow.filter(ImageFilter.GaussianBlur(float(4+max(0,lift)*.12)))
        base.paste((51,43,32),(l,t,r,b),shadow)
    base.paste(sample,(l,t),sample.getchannel('A'))
    return base

def encode(shot, dest):
    cmd=['ffmpeg','-nostdin','-v','error','-y','-f','rawvideo','-pixel_format','rgb24',
         '-video_size','1920x1080','-framerate','24','-i','pipe:0','-an','-vf',
         'scale=out_color_matrix=bt709:out_range=tv,format=yuv420p,setparams=range=limited:color_primaries=bt709:color_trc=bt709:colorspace=bt709','-c:v','libx264','-threads','2',
         '-crf','14','-preset','medium','-colorspace','bt709','-color_range','tv','-color_trc',
         'bt709','-color_primaries','bt709','-movflags','+faststart',dest]
    with subprocess.Popen(cmd,stdin=subprocess.PIPE) as proc:
        for n in range(COUNT[shot]): proc.stdin.write(exposure(shot,n).tobytes())
        proc.stdin.close()
        if proc.wait():raise RuntimeError('Could not render '+shot)

def main():
    with tempfile.TemporaryDirectory(dir=ROOT) as scratch:
        for shot in COUNT:
            path=Path(scratch)/(shot+'.mp4')
            encode(shot,path)
            path.replace(ROOT/path.name)

if __name__=='__main__': main()
