"""Compute shared masks once at working resolution."""
from functools import cached_property

import cv2 as cv
import mediapipe as mp
import numpy as np

from .models import DIRECTORY

EYES = [
    [33, 160, 158, 133, 153, 144],
    [362, 385, 387, 263, 373, 380],
]
IRIS = [[469, 470, 471, 472], [474, 475, 476, 477]]
BROWS = [
    [70, 63, 105, 66, 107, 55, 65, 52, 53, 46],
    [300, 293, 334, 296, 336, 285, 295, 282, 283, 276],
]
MOUTH = [78, 191, 80, 81, 82, 13, 312, 311, 310, 415, 308, 324, 318, 402, 317, 14, 87, 178, 88, 95]
LIPS = [61, 40, 37, 0, 267, 270, 291, 321, 314, 17, 84, 91]


def blur(values, radius):
    return cv.GaussianBlur(values, (0, 0), max(float(radius), 0.35))


def ramp(values, low, high):
    return np.clip((values - low) / (high - low), 0, 1)


def ellipse(radius):
    side = int(radius) * 2 + 1
    return cv.getStructuringElement(cv.MORPH_ELLIPSE, (side, side))


class Analysis:
    def __init__(self, rgb, vision):
        self.height, self.width = rgb.shape[:2]
        self.rgb = rgb
        self.vision = vision

    @cached_property
    def data(self):
        return self.vision.analyze(self.rgb)

    @property
    def faces(self):
        return self.data[0]

    @property
    def parts(self):
        return self.data[1]

    @cached_property
    def scale(self):
        widths = [np.ptp(face[:, 0]) for face in self.faces]
        return max(12.0, float(np.median(widths)) if widths else min(self.width, self.height) / 3)

    def polygon(self, paths, feather=0.75):
        mask = np.zeros((self.height, self.width), np.uint8)
        for path in paths:
            cv.fillPoly(mask, [np.round(path * 16).astype(np.int32)], 255, shift=4)
        return blur(mask.astype(np.float32) / 255, feather)

    def feature(self, groups):
        return self.polygon([face[group] for face in self.faces for group in groups], max(0.5, self.scale * 0.003))

    @cached_property
    def skin(self):
        protected = cv.dilate(self.feature([*EYES, LIPS]), ellipse(max(1, round(self.scale * 0.009))))
        return np.clip((self.parts[2] + self.parts[3]) * (1 - protected), 0, 1)

    @cached_property
    def subject(self):
        return 1 - self.parts[0]


class Vision:
    def __init__(self):
        tasks = mp.tasks.vision
        self.faces = tasks.FaceLandmarker.create_from_options(tasks.FaceLandmarkerOptions(
            base_options=mp.tasks.BaseOptions(model_asset_path=str(DIRECTORY / "face.task")),
            num_faces=8, min_face_detection_confidence=0.45,
        ))
        self.segmenter = tasks.ImageSegmenter.create_from_options(tasks.ImageSegmenterOptions(
            base_options=mp.tasks.BaseOptions(model_asset_path=str(DIRECTORY / "parts.tflite")),
            output_confidence_masks=True,
        ))

    def close(self):
        self.faces.close()
        self.segmenter.close()

    def analyze(self, rgb):
        height, width = rgb.shape[:2]
        source = mp.Image(image_format=mp.ImageFormat.SRGB, data=np.ascontiguousarray(
            np.rint(rgb * 255), dtype=np.uint8))
        faces = [
            np.array([(point.x * width, point.y * height) for point in face], np.float32)
            for face in self.faces.detect(source).face_landmarks
        ]
        return faces, self.segment(rgb)

    def segment(self, rgb):
        height, width = rgb.shape[:2]
        source = mp.Image(image_format=mp.ImageFormat.SRGB, data=np.ascontiguousarray(
            np.rint(rgb * 255), dtype=np.uint8))
        masks = self.segmenter.segment(source).confidence_masks
        return np.stack([mask.numpy_view().reshape(height, width) for mask in masks]).astype(np.float32)
