"""Project the photographed CRT fronts into each camera angle. Requires Pillow and NumPy."""
from functools import lru_cache
from pathlib import Path
import runpy
import subprocess

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

ROOT = Path(__file__).resolve().parent
ORIGINAL = ROOT.parent.parent / 'sources/original'
GLYPHS = runpy.run_path(str(ROOT.parent / 'yesterday/render.py'))['GLYPHS'] | {
    'a':[0,0,14,1,15,17,15], 'm':[0,0,26,21,21,21,21],
    'r':[0,0,22,25,16,16,16], 'e':[0,0,14,17,31,16,14],
    'd':[1,1,15,17,17,17,15], 'y':[0,0,17,17,15,1,14],
    's':[0,0,15,16,14,1,30], 'b':[16,16,30,17,17,17,30],
    'o':[0,0,14,17,17,17,14], 'i':[4,0,12,4,4,4,14],
    'g':[0,0,15,17,15,1,14], 'h':[16,16,22,25,17,17,17],
    't':[8,8,28,8,8,9,6], 'l':[12,4,4,4,4,4,14],
}
# Coordinates are measured at a proxy width of 1000 in the two original daylight photographs.
MAIN_FACE = [(206,42),(695,55),(694,460),(199,481)]
MAIN_GLASS = [(253,98),(625,101),(624,401),(253,410)]
MAIN_EDGE = [(253,132),(257,113),(267,105),(289,101),(349,97),(459,96),
             (558,99),(598,104),(614,111),(621,122),(624,145),(627,213),
             (627,280),(624,354),(621,379),(617,388),(607,394),(582,400),
             (528,404),(443,408),(347,409),(295,406),(268,403),(260,399),
             (257,389),(254,370),(252,312),(251,222)]
AUTO_FACE = [(230,21),(537,16),(609,314),(281,376)]
AUTO_GLASS = [(273,52),(522,43),(556,264),(305,309)]
AUTO_EDGE = [(276,68),(304,58),(358,48),(430,44),(499,45),(518,49),(522,57),
             (535,123),(551,210),(553,253),(550,263),(530,272),(452,290),
             (363,302),(311,306),(306,302),(297,252),(282,122)]
SIZE = (820,700)


def matrix(source, destination):
    """Fit the 3x3 homography taking four ordered points onto four others."""
    a, b = [], []
    for (x,y),(u,v) in zip(source,destination):
        a.extend(([x,y,1,0,0,0,-u*x,-u*y],[0,0,0,x,y,1,-v*x,-v*y]))
        b.extend((u,v))
    return np.append(np.linalg.solve(a,b),1).reshape(3,3)


def transform_points(h, points):
    v = np.array([[x,y,1] for x,y in points]).T
    x,y,w = h @ v
    return list(zip(x/w,y/w))


def to_image(source, size, h):
    # Pillow expects output-to-input coordinates.
    inv = np.linalg.inv(h)
    return source.transform(size,Image.Transform.PERSPECTIVE,
                            (inv/inv[2,2]).ravel()[:8],Image.Resampling.BICUBIC)


def glyph_mask(size, lines):
    # Author at native phosphor resolution. Blur the strokes together just enough
    # to recover the soft focus at the face of the original glass.
    im = Image.new('L',size)
    draw = ImageDraw.Draw(im)
    for x,y,text,pixel in lines:
        for n,char in enumerate(text):
            for row,bits in enumerate(GLYPHS[char]):
                for col in range(5):
                    if bits & (16>>col):
                        l,t = x+(6*n+col)*pixel,y+row*pixel
                        draw.rectangle((round(l),round(t),round(l+pixel-.5),round(t+pixel-.5)),fill=255)
    return im


def clear_lettering(photo,box):
    # Inpaint only emissive strokes and highlight bars. Reflections and the
    # photographed scan texture between letters survive the change of wording.
    l,t,r,b=box
    roi=photo[t:b,l:r]
    height=b-t
    pad=Image.fromarray(np.uint8((roi[:,:,1]-(roi[:,:,0]+roi[:,:,2])*.5>28)*255))
    stamp=np.array(pad.filter(ImageFilter.MaxFilter(13)).filter(ImageFilter.GaussianBlur(1.6)),
                   dtype=np.float32)[:,:,None]/255
    mix=np.linspace(0,1,height+2)[1:-1,None,None]
    base=(1-mix)*np.mean(photo[t-3:t,l:r],axis=0)+mix*np.mean(photo[b:b+3,l:r],axis=0)
    # Borrow fine grain from the adjacent unlettered area of the same tube.
    start=min(b+4,photo.shape[0]-height)
    nearby=photo[start:start+height,l:r]
    smooth=np.array(u8(nearby).filter(ImageFilter.GaussianBlur(2.5)),dtype=np.float32)
    restored=photo.copy()
    restored[t:b,l:r]=roi*(1-stamp)+(base+nearby-smooth)*stamp
    return restored

@lru_cache(maxsize=2)
def photograph(kind):
    main = kind=='primary'
    name = 'monitor-i-am-ready' if main else 'monitor-automation-options-day'
    source = Image.open(ORIGINAL/(name+'.png')).convert('RGB')
    scale = source.width/1000
    quad = MAIN_FACE if main else AUTO_FACE
    edge = MAIN_EDGE if main else AUTO_EDGE
    outside = [(0,0),(SIZE[0],0),SIZE,(0,SIZE[1])]
    normal = matrix(quad,outside)
    h = normal @ np.diag([1/scale,1/scale,1])
    face = to_image(source,SIZE,h)
    def coords(pts):
        return [(round(x),round(y)) for x,y in transform_points(normal,pts)]
    # Work in screen coordinates to remove the original embedded text exactly.
    # A six-pixel margin includes its dim phosphor halo.
    region = [(315,153),(462,153),(462,181),(315,181)] if main else [(310,101),(459,92),(464,182),(317,194)]
    points=coords(region)
    l,t=np.min(points,axis=0)-4
    r,b=np.max(points,axis=0)+4
    photographic=np.array(face).astype(np.float32)
    clean=clear_lettering(photographic,(l,t,r,b))
    mask=Image.new('L',SIZE)
    ImageDraw.Draw(mask).polygon(coords(edge),fill=255)
    mask=mask.filter(ImageFilter.GaussianBlur(1.15))
    alpha=np.array(mask,dtype=np.float32)[:,:,None]/255
    # The power switch changes emission. Window reflections stay on the glass.
    luma=clean @ np.array([.26,.59,.15],dtype=np.float32)
    neutral=np.maximum(5,luma-(24 if main else 9))
    off=np.stack((neutral*.95,neutral*1.01,neutral*.93),axis=2)
    off=photographic*(1-alpha)+off*alpha
    return clean,off,normal


def u8(values):
    return Image.fromarray(np.clip(values,0,255).astype('uint8'))


@lru_cache(maxsize=2)
def rocker(pressed):
    # Both positions are photographs of the same physical lever. Leave the
    # outer socket in the original reference and change only its inner travel.
    cmd=['ffmpeg','-v','error','-ss',str(35/24 if pressed else 0),
         '-i',str(ROOT.parent/'scene-one/switch.mp4'),'-vf','scale=640:360,crop=38:36:272:186',
         '-frames:v','1','-f','rawvideo','-pix_fmt','rgb24','-']
    return Image.frombytes('RGB',(38,36),subprocess.check_output(cmd))


def finish_face(field,main,normal,pressed):
    im=u8(field)
    if main:
        # Register the physical lever to the original daylight socket.
        q=transform_points(normal,[(650,422),(667,421),(667,439),(650,440)])
        sprite=rocker(pressed)
        h=matrix([(0,0),(38,0),(38,36),(0,36)],q)
        patch=to_image(sprite,SIZE,h)
        mask=Image.new('L',SIZE)
        ImageDraw.Draw(mask).polygon(q,fill=255)
        im.paste(patch,(0,0),mask.filter(ImageFilter.GaussianBlur(.6)))
    return im


@lru_cache(maxsize=28)
def face(kind, message=None, opening=1.0, pressed=False):
    main=kind=='primary'
    clean,off,normal=photograph(kind)
    if message is None or opening<=0:
        return finish_face(off,main,normal,pressed)
    on=clean.copy()
    if main:
        if message:
            x,y=transform_points(normal,[(322,159)])[0]
            letters=glyph_mask(SIZE,[(x,y,message,3.3)])
            light=np.array(letters.filter(ImageFilter.GaussianBlur(.68)),dtype=np.float32)/255
            bloom=np.array(letters.filter(ImageFilter.GaussianBlur(4)),dtype=np.float32)/255
            # Match the warm green stroke and broader, low-energy green halo
            # around the actual I am ready line that survives in the source.
            on+=light[:,:,None]*np.array([100,148,103])+bloom[:,:,None]*np.array([24,42,22])
    else:
        # Use the photographed face and its window reflection at right.
        # Recreate the three rows at their original tilt after rectification.
        labels=('Lights','Bath','Kettle')
        idx=[s.upper() for s in labels].index(message)
        base=transform_points(normal,[(324,111),(326,140),(329,168)])
        # Account for the slight slope of the menu inside its sloping case.
        bar=Image.new('L',SIZE)
        barquad = [[(313,108),(454,99),(457,120),(316,131)],
                   [(317,137),(458,126),(461,148),(320,159)],
                   [(320,164),(461,154),(464,175),(323,186)]][idx]
        ImageDraw.Draw(bar).polygon(transform_points(normal,barquad),fill=255)
        fill=np.array(bar.filter(ImageFilter.GaussianBlur(1)),dtype=np.float32)[:,:,None]/255
        on=on*(1-fill) + fill*np.array([70,185,71])
        for i,(word,(x,y)) in enumerate(zip(labels,base)):
            letters=glyph_mask(SIZE,[(x,y,word,4.4)])
            stroke=np.array(letters.filter(ImageFilter.GaussianBlur(.85)),dtype=np.float32)[:,:,None]/255
            if i==idx:
                on=on*(1-stroke)+stroke*np.array([18,34,18])
            else:
                on+=stroke*np.array([84,144,74])
    if opening<1:
        # The field first occupies the centre, already luminous. Its curved
        # border opens out in under half a second without a travelling scan bar.
        y,x=np.mgrid[:SIZE[1],:SIZE[0]]
        rx=(x-SIZE[0]*.50)/(SIZE[0]*.399*(1.23-.23*opening))
        ry=(y-SIZE[1]*.49)/(SIZE[1]*.385)
        spread=np.sqrt(rx*rx+ry*ry)
        feather=np.clip((opening*1.57-spread)/.34+.16,0,1)
        aperture=(feather*feather*(3-2*feather))[:,:,None]
        on=off*(1-aperture)+on*aperture
    return finish_face(on,main,normal,pressed)


def composite(frame,kind,destination,message=None,opening=1,pressed=False):
    """Place the whole photographed bezel, recessed rocker and tube in one plane."""
    sprite=face(kind,message,opening,pressed)
    width,height=SIZE
    h=matrix([(0,0),(width,0),(width,height),(0,height)],destination)
    x0,y0=np.maximum(np.floor(np.min(destination,axis=0)).astype(int)-2,0)
    x1,y1=np.minimum(np.ceil(np.max(destination,axis=0)).astype(int)+3,frame.size)
    if x1<=x0 or y1<=y0: return
    offset=np.array([[1,0,-x0],[0,1,-y0],[0,0,1]])
    w,hout=x1-x0,y1-y0
    # Optical reduction before the final perspective transform prevents hard
    # scanline aliases and keeps a small monitor integrated in a wide angle.
    scale=min(1,max(w/sprite.width,hout/sprite.height)*1.25)
    if scale<.9:
        reduced=(max(2,round(width*scale)),max(2,round(height*scale)))
        sprite=sprite.resize(reduced,Image.Resampling.LANCZOS)
        h=h @ np.diag([width/reduced[0],height/reduced[1],1])
    patch=to_image(sprite,(w,hout),offset@h)
    mask=Image.new('L',(w*2,hout*2))
    ImageDraw.Draw(mask).polygon([((x-x0)*2,(y-y0)*2) for x,y in destination],fill=255)
    mask=mask.resize((w,hout),Image.Resampling.LANCZOS).filter(ImageFilter.GaussianBlur(.55))
    frame.paste(patch,(x0,y0),mask)


def screen(frame,track,tube,n,source_frame,colours=None):
    """Drop-in for the tracked tubes in the fourth workprint's plate renderer."""
    end=next((i for i,(f,_) in enumerate(track) if f>=source_frame),len(track)-1)
    f0,a=track[max(0,end-1)];f1,b=track[end]
    t=np.clip((source_frame-f0)/max(1,f1-f0),0,1)
    corners=np.array(a)*(1-t)+np.array(b)*t
    dark=tube.get('darkFrames',0);ramp=tube.get('lightRamp',0)
    opening=min(1,max(0,(n-dark+1)/ramp)) if ramp else 1
    msg=next((m['text'] for m in reversed(tube['messages']) if n>=m['at']),'')
    if n<dark or n>=tube.get('offAt',float('inf')): msg=None

    # Keep the physical dimensions of the wide's enclosure. The newer flat
    # glass occupied nearly its complete face, unlike the recessed source.
    tl,tr,br,bl=corners
    face_quad=[tl+[-6,-7],tr+[13,-8],br+[14,9],bl+[-6,12]]
    composite(frame,'primary',face_quad,msg,opening)
    auto=np.array([(444,325),(510,317),(528,403),(460,416)])+(tl-[331,305])
    composite(frame,'menu',auto)
