"""Rebuild the two menu strokes and the separate Enter stroke over the existing desk."""
import hashlib
import json
from pathlib import Path
import runpy
import subprocess

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

ROOT = Path(__file__).resolve().parent
V4 = runpy.run_path(str(ROOT.parent / 'scene-one-v4/desk.py'))
TAKE = ROOT.parent / 'scene-one-v6/keyboard.mp4'
OUTPUT = ROOT / 'keyboard.mp4'
SIZE = (1280, 720)
LANCZOS = Image.Resampling.LANCZOS
# The cap faces were spotted in a front-to-back rectification of the desk photograph.
# Each row is in typing order. Coordinates are centres on the actual tops.
ROWS = [
    ('Esc F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12 Prt Scr Ins Del Brk',
     [59,142,203,258,318,375,438,489,534,577,632,675,724,787,845,886,929,973],
     [65,64,63,63,62,61,60,60,60,59,57,56,55,54,53,52,52,51]),
    ('~ 1 2 3 4 5 6 7 8 9 0 - = / * + # Bksp',
     [119,173,225,290,351,404,465,525,582,643,688,736,788,836,888,939,990,1049],
     [133,133,130,129,129,128,126,124,122,120,119,118,116,115,113,112,111,109]),
    ("Tab Q W E R T Y U I O P [ ] \\ 7 8 9",
     [181,289,352,414,476,535,599,650,708,757,798,856,906,959,1003,1060,1112],
     [194,192,191,190,187,185,183,181,179,177,176,175,172,170,169,167,165]),
    ("Caps A S D F G H J K L ; ' 4 5 6 Enter",
     [233,327,397,458,523,581,640,707,766,829,886,940,996,1040,1093,1145],
     [249,248,246,244,242,240,238,235,233,231,228,226,225,223,222,218]),
    ('Shift Z X C V B N M , . / Shift 1 2 3 End UP',
     [292,357,420,477,549,603,657,718,766,819,865,920,966,1020,1059,1106,1183],
     [310,309,307,305,301,300,298,295,292,289,286,285,281,280,276,274,266]),
    ('Ctrl Alt Lock 0 . Home LEFT DOWN RIGHT',
     [328,416,501,1033,1092,1154,1202,1246,1296], [372,370,365,347,344,341,338,335,331])
]
# The slightly sloping type plane converts a spot on a key to the 720p image.
def sensor(x, y):
    u = 270 + x / 1.8
    return u, 665 + y / 3.2 - .20 * (u - 300)


def stamped_plate():
    base = V4['crop'](V4['PLATE'], 341, 137, 612)
    a, b = 1 / 1.8, 1 / 3.2
    flat = base.transform((1400, 420), Image.Transform.AFFINE, (a,0,270,-.2*a,b,671),
                          Image.Resampling.BICUBIC)
    edited = flat.copy()
    mask = Image.new('L', flat.size)
    # This return cap in the plate had a melted lip. Its wide neighbour supplies a
    # matching ivory top and front face in the same lens and light.
    donor = flat.crop((1121,243,1252,311))
    outline = Image.new('L',donor.size)
    points = [(2,13),(12,9),(92,2),(103,3),(128,29),(130,58),(118,66),
              (42,66),(39,41),(7,22)]
    ImageDraw.Draw(outline).polygon(points,fill=255)
    outline = outline.filter(ImageFilter.GaussianBlur(1))
    donor = donor.resize((103,53),LANCZOS)
    outline = outline.resize(donor.size,LANCZOS)
    edited.paste(donor,(1095,200),outline)
    mask.paste(outline,(1095,200))
    textured = edited.copy()
    face = ImageFont.load_default(size=16)
    enter_face = ImageFont.load_default(size=23)
    for names, xs, ys in ROWS:
        for label, x, y in zip(names.split(), xs, ys, strict=True):
            is_arrow = label in ('LEFT','DOWN','RIGHT','UP')
            wide = label in ('Enter','Tab','Caps','Bksp','Shift')
            # Clean the old simulated imprint, using surrounding ivory from the same cap.
            width = 35 if wide else 22
            box = (x-width//2-3, y-9, x+width//2+2, y+8)
            local = np.asarray(textured.crop(box)).copy()
            bright = np.percentile(local.reshape(-1,3), 70, axis=0)
            difference = np.maximum(0, bright-local)
            local = np.uint8(np.clip(local + .90 * difference,0,255))
            area = Image.new('L',(box[2]-box[0],box[3]-box[1]))
            ImageDraw.Draw(area).rounded_rectangle((1,1,area.width-2,area.height-2), radius=3, fill=255)
            area = area.filter(ImageFilter.GaussianBlur(1.1))
            edited.paste(Image.fromarray(local),box,area)
            mask.paste(Image.fromarray(np.maximum(np.asarray(mask.crop(box)),np.asarray(area))),box)

            ink = Image.new('L', (74, 29))
            pen = ImageDraw.Draw(ink)
            if is_arrow:
                direction = {'LEFT':(-1,0),'DOWN':(0,1),'RIGHT':(1,0),'UP':(0,-1)}[label]
                dx,dy = direction
                def point(u,v):
                    return (37+dx*u-dy*v, 14+dy*u+dx*v)
                pen.line([point(-7,0), point(7,0)],fill=245,width=3)
                pen.line([point(1,-5),point(7,0),point(1,5)],fill=245,width=3)
            else:
                pen.text((37,14), label, fill=230, font=enter_face if label=='Enter' else face, anchor='mm', stroke_width=0)
            ink = ink.transform(ink.size, Image.Transform.AFFINE, (1,-.46,6.44,0,1,0),
                                Image.Resampling.BICUBIC)
            left, top = x-37, y-14
            # Printed legends have the warm/soft contrast of the old moulded plastic.
            strength = .88 if label == 'Enter' or is_arrow else .68
            color = tuple(int(c*strength*.45 + c*(1-strength)) for c in bright)
            edited.paste(color,(left,top,left+74,top+29),ink)
            current = np.array(mask.crop((left,top,left+74,top+29)))
            mask.paste(Image.fromarray(np.maximum(current,np.array(ink))),(left,top))
    edited.putalpha(mask)
    # Inverse of sensor(). Only the travelled caps and their legends change.
    overlay = edited.convert('RGBa').transform(SIZE, Image.Transform.AFFINE,
              (1.8,0,-486,.64,3.2,-2320), Image.Resampling.BICUBIC).convert('RGBA')
    base.paste(overlay, (0,0), overlay)
    return base


# Endpoints include the side walls. Pressing one cap compresses it into its own socket.
CAPS = {
    'DOWN': [(1213,325),(1251,319),(1268,341),(1275,394),(1234,400),(1227,355)],
    'Enter': [(1099,210),(1174,202),(1196,223),(1198,247),(1128,251),(1125,232)],
}


def travel(image, key, amount):
    if amount <= 0:
        return
    polygon = [sensor(*p) for p in CAPS[key]]
    mask = Image.new('L', SIZE)
    ImageDraw.Draw(mask).polygon(polygon, fill=255)
    box = mask.getbbox()
    tile = image.crop(box)
    shift = max(1, round(3.4*amount))
    socket = Image.new('RGB',tile.size,(70,63,48))
    socket.paste(tile.resize((tile.width,tile.height-shift), LANCZOS),(0,shift))
    image.paste(socket,box,mask.crop(box).filter(ImageFilter.GaussianBlur(.35)))


def read_take():
    return V4['decode'](TAKE,SIZE)


def actor(index, offset):
    # The provider blended two positions in the two fastest release frames.
    # The same hand has a clean bent position during the descent and at lift.
    index = {20:13, 21:22}.get(index,index)
    source = V4['hand_frame']('keys',index)
    # The archived silhouette carries a thin stripe of the earlier desk above
    # the knuckle and a few cream pixels alongside the moving index finger.
    pixels = np.asarray(source).astype(float)
    red, green, blue = (pixels[:,:,k] for k in range(3))
    chroma = red - green - .82*(green-blue)
    alpha = pixels[:,:,3]
    for x in range(41,295):
        inside = np.flatnonzero(alpha[:,x] > 110)
        if not len(inside):
            continue
        top = inside[0]
        skin = np.flatnonzero((chroma[top:top+24,x] > 12) & (red[top:top+24,x] > 88))
        if len(skin):
            alpha[:max(0,top+skin[0]-1),x] = 0
    edge = np.clip((chroma[88:152,:99]-5)/11,0,1)
    alpha[88:152,:99] *= edge
    new_mask = Image.fromarray(np.uint8(alpha)).filter(ImageFilter.MedianFilter(3))
    source.putalpha(new_mask.filter(ImageFilter.GaussianBlur(.40)))
    source = source.convert('RGBa')
    factor = .55*1280/612
    hand = source.resize((round(source.width*factor),round(source.height*factor)),LANCZOS).convert('RGBA')
    # Keep the generated sleeve reaching the edge of the sensor as the wrist moves across the desk.
    hand_canvas = Image.new('RGBA',(hand.width+32,hand.height))
    hand_canvas.paste(hand)
    hand_canvas.paste(hand.crop((hand.width-1,0,hand.width,hand.height)).resize((32,hand.height)),(hand.width,0))
    down = sensor(1246,335)
    # In source frame 16 the underside of the index pad is at (47,146).
    anchor = round(down[0]-47*factor+offset[0]), round(down[1]+4-146*factor+offset[1])
    return hand_canvas, anchor


def keyboard():
    frames = read_take()
    plate = stamped_plate()
    # The source's later finger becomes translucent. Use the first clean
    # articulation for each stroke, carrying the naturally lifted hand between them.
    curve = [(0,0),(11,5),(17,16),(20,21),(26,27),(32,34),(38,26),(41,23),
             (45,16),(48,20),(52,25),(57,31),(60,26),(63,23),(66,16),
             (68,18),(71,24),(74,27),(77,29)]
    index_frames, indexes = zip(*curve)
    left = sensor(1145,218); right = sensor(1246,335)
    blend = Image.new('L', SIZE)
    # The upper edge is above the highest moving fingertip and below both CRTs at camera right.
    ImageDraw.Draw(blend).polygon([(820,485),(875,472),(1280,470),(1280,720),(0,720),(0,683),
                                  (268,674),(335,650),(808,556)],fill=255)
    blend = blend.filter(ImageFilter.GaussianBlur(1.2))
    for n, old in enumerate(frames):
        canvas = Image.fromarray(old).copy()
        canvas.paste(plate,(0,0),blend)
        # Labels on the left-hand bank also enter at the bottom of the lens.
        idx = round(np.interp(n,index_frames,indexes))
        key = 'Enter' if n>53 else 'DOWN'
        stroke = max((max(0, min((n-(f-3))/3,(f+4-n)/3,1)) for f in (17,45,66)))
        travel(canvas,key,stroke)
        across = np.clip((n-51)/12,0,1)
        across = across*across*(3-2*across)
        hand,origin = actor(idx,((left[0]-right[0])*across, (left[1]-right[1])*across))
        canvas.paste(hand,origin,hand)
        yield canvas


def review():
    images = V4['decode'](OUTPUT,SIZE)
    sheet = Image.new('RGB',(1024,550),(28,29,25))
    pen = ImageDraw.Draw(sheet)
    title = ImageFont.load_default(size=17)
    small = ImageFont.load_default(size=14)
    for r, (name, times) in enumerate([('Two menu strokes', (12,17,41,45)),
                                        ('Enter · approach, contact, release and settle', (60,66,70,76))]):
        y = 12+r*270
        pen.text((12,y),name,font=title,fill='#f6f1e4')
        for c,n in enumerate(times):
            x = c*256
            crop = Image.fromarray(images[n]).crop((836,501,1084,694))
            sheet.paste(crop.resize((256,199), LANCZOS),(x,y+27))
            pen.text((x+12,y+233),f'Frame {488+n} · key frame {n}',font=small,fill='#ddd9cd')
    sheet.save(ROOT/'keyboard-proof.jpg',quality=94,subsampling=0)
    digest = lambda path: hashlib.sha256(path.read_bytes()).hexdigest()
    inputs = ['../scene-one-v6/keyboard.mp4','../scene-one-v4/desk.py','../scene-one-v4/desk.png',
              '../scene-one-v4/keys-matte.png','../scene-one-v2/keys.mp4','../yesterday/render.py']
    record = {
        'sourceShot': {'edition':'yesterdays-pnl-v7','start':488,'endExclusive':566},
        'sources': [{'path':path,'sha256':digest(ROOT/path)} for path in inputs],
        'recipe':'keyboard.py','output':'keyboard.mp4','sha256':digest(OUTPUT),
        'frames':len(images),'fps':24,'contacts':[{'key':k,'localFrame':n,'masterFrame':488+n}
                                               for k,n in [('Down',17),('Down',45),('Enter',66)]],
        'sourcePerformance':'The release uses the clean early finger articulation from the archived hand. Two translucent source exposures are replaced with nearby clear positions from the same performance.',
        'action':'The two Down strokes move the menu to Bath, then Kettle. The same hand crosses to Enter for a third stroke. The last contact and release are both visible before cutting to the water.',
        'legends':'Small warm ink follows the key-top plane. The two struck caps travel independently just over three screen pixels. The secondary CRT is the existing reviewed picture.',
        'check':'keyboard-proof.jpg'
    }
    (ROOT/'keyboard-receipt.json').write_text(json.dumps(record,indent=2,ensure_ascii=False)+'\n')


if __name__=='__main__':
    V4['encode'](OUTPUT,keyboard())
    review()
