"""The fifth cut's CRT geometry with clean subpixel casing edges on optical reduction."""
from pathlib import Path
import runpy

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

ROOT=Path(__file__).resolve().parent
V5=runpy.run_path(str(ROOT.parent/'scene-one-v5/crt.py'))
ORIGINAL, MAIN_FACE = V5['ORIGINAL'], V5['MAIN_FACE']
matrix, transform_points = V5['matrix'], V5['transform_points']


def composite(frame,kind,destination,message=None,opening=1,pressed=False):
    sprite=V5['face'](kind,message,opening,pressed)
    width,height=sprite.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
    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])
    # Black pixels outside the source polygon darkened the edge in v5. Give
    # the spline and antialiasing filter real edge colour on both sides.
    sprite=Image.fromarray(np.pad(np.asarray(sprite),((3,3),(3,3),(0,0)),mode='edge'))
    h=h @ np.array([[1,0,-3],[0,1,-3],[0,0,1]])
    patch=V5['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)


# run_path creates a private module namespace. Retain v5's track interpolation,
# typography, light timing and contact states, substituting the optical projection.
screen=V5['screen']
screen.__globals__['composite']=composite
