"""Retouch operations. Each effect returns candidate RGB and coverage."""
import cv2 as cv
import numpy as np

from .regions import BROWS, EYES, IRIS, MOUTH, LIPS, blur, ellipse, ramp
from .eye_vessels import retouch_eye_vessels
from .eye_brilliance import retouch_eye_brilliance
from .clean_backdrop import retouch_clean_backdrop
from .fabric import retouch_fabric
from .stray_hairs import retouch_stray_hairs
from .glasses_glare import retouch_glasses_glare


def lab(rgb):
    return cv.cvtColor(rgb, cv.COLOR_RGB2LAB)


def rgb_color(values):
    return cv.cvtColor(values, cv.COLOR_LAB2RGB)


def weighted(values, mask, radius):
    return blur(values * mask, radius) / np.maximum(blur(mask, radius), 0.001)


def luminosity(rgb, delta):
    values = lab(rgb)
    values[..., 0] = np.clip(values[..., 0] + delta, 0, 100)
    return rgb_color(values)


def fill(rgb, mask, radius):
    hard = np.uint8(mask > 0.2) * 255
    if not hard.any():
        return rgb, mask
    # Inpaint the channels as float32 to avoid reducing a 16-bit input to 8-bit.
    fixed = np.stack([cv.inpaint(rgb[..., i].copy(), hard, radius, cv.INPAINT_TELEA)
                      for i in range(3)], axis=-1)
    # OpenCV's float Telea implementation can overshoot on normalized data.
    # Keep the reconstruction in the adjacent source color range.
    kernel = ellipse(max(2, int(radius) * 2))
    return np.clip(fixed, cv.erode(rgb, kernel), cv.dilate(rgb, kernel)), mask


def spots(signal, coverage, threshold, min_area, max_area, radius=1):
    binary = np.uint8((signal > threshold) & (coverage > 0.5))
    count, labels, stats, _ = cv.connectedComponentsWithStats(binary, connectivity=8)
    keep = np.zeros(count, np.uint8)
    for idx, (_, _, width, height, area) in enumerate(stats[1:], start=1):
        if min_area <= area <= max_area and max(width, height) <= 4 * min(width, height):
            keep[idx] = 1
    selected = cv.dilate(keep[labels], ellipse(radius)).astype(np.float32)
    return blur(selected, 0.65) * coverage


def heal(rgb, region, p):
    values = lab(rgb)
    scale = max(1.2, region.scale * 0.012)
    luminance, redness = values[..., 0], values[..., 1]
    dark = blur(luminance, scale * 1.6) - luminance
    support = region.skin
    fixed = rgb.copy()
    mask = np.zeros_like(support)
    if p["pimples"]:
        # Keep detections inside the skin so a red eyelid or lip edge does not
        # turn into a repair. Test at two scales to include wider red marks.
        brows = cv.dilate(region.feature(BROWS), ellipse(max(2, round(scale * 1.5))))
        support = support * (1 - brows)
        interior = cv.erode(support, ellipse(max(2, round(scale * 0.7))))
        red = np.maximum(redness - weighted(redness, support, scale * 1.7),
                         redness - weighted(redness, support, scale * 3.0))
        core = spots(red + 0.15 * dark, interior, 3.2, 3,
                     max(12, scale ** 2 * 36), max(1, round(scale * 0.25)))
        expanded = cv.dilate(core, ellipse(max(2, round(scale * 1.2))))
        mask = blur(expanded, scale * 0.43) * interior * p["pimples"]

        # Rebuild the low-frequency color from skin outside the blemish. Keep
        # the original fine luminance detail to preserve pores.
        neighbors = support * (1 - np.clip(expanded, 0, 1))
        radius = scale * 2.35
        coverage = blur(neighbors, radius)
        mask *= ramp(coverage, 0.02, 0.15)
        normalization = np.maximum(coverage, 0.001)
        cleaned = values.copy()
        for channel in (1, 2):
            cleaned[..., channel] = blur(values[..., channel] * neighbors, radius) / normalization
        base = blur(luminance * neighbors, radius) / normalization
        low_detail = blur(luminance, max(0.75, scale * 0.32))
        # Allow more correction at a strongly red center while retaining
        # broad shadows at the edge of the repair.
        lift = 4.5 + 12 * ramp(red, 4, 13)
        cleaned[..., 0] = np.clip(luminance + np.clip(base - low_detail, -4.5, lift), 0, 100)
        fixed = rgb_color(cleaned)
    if p["moles"]:
        red = redness - blur(redness, scale * 1.6)
        moles = spots(dark, region.skin * (1 - ramp(red, 1, 4)), 8, 2,
                      max(8, scale ** 2 * 13) * 0.55)
        repaired, _ = fill(rgb, moles, max(2, round(scale)))
        mole_mask = moles * p["moles"]
        fixed = np.where((mole_mask > mask)[..., None], repaired, fixed)
        mask = np.maximum(mask, mole_mask)
    return fixed, mask


def dodge_burn(rgb, region, p):
    light = lab(rgb)[..., 0]
    scales = {"auto": 1, "close": 1.5, "half": 0.8, "full": 0.55}
    radius = max(1.3, region.scale * 0.018 * scales[p["scale"]])
    skin = region.skin
    band = weighted(light, skin, radius * 3) - weighted(light, skin, radius * 0.65)
    detail = np.clip(band * p["blend"] * 0.65, -12, 12)
    values = lab(rgb)
    values[..., 0] = np.clip(light + detail, 0, 100)
    values[..., 2] += np.maximum(detail, 0) * p["warmth"] * 0.65
    return rgb_color(values), skin


def portrait_volumes(rgb, region, p):
    field = np.zeros(rgb.shape[:2], np.float32)
    for face in region.faces:
        face_width = np.ptp(face[:, 0])
        for index, weight in [(10, 3), (1, 4), (50, 4), (280, 4), (152, 2), (234, -4), (454, -4)]:
            x, y = np.round(face[index]).astype(int)
            cv.circle(field, (x, y), max(1, round(face_width * 0.07)), weight, -1)
    shape = blur(field, max(1, region.scale * 0.055)) * p["blend"]
    return luminosity(rgb, shape), region.skin


def skin_tone(rgb, region, p):
    values = lab(rgb)
    for channel in (1, 2):
        chroma = values[..., channel]
        center = weighted(chroma, region.skin, max(2, region.scale * 0.19))
        local = weighted(chroma, region.skin, max(1, region.scale * 0.023))
        values[..., channel] += np.clip(center - local, -9, 9) * p["blend"] * 0.58
    return rgb_color(values), region.skin


def mattifier(rgb, region, p):
    light = lab(rgb)[..., 0]
    radius = max(2, region.scale * 0.028)
    diffuse = weighted(light, region.skin, radius * 2.4)
    shine = np.clip(blur(light, radius * 0.30) - diffuse - 2, 0, 22)
    return luminosity(rgb, -shine * p["blend"] * 0.8), region.skin * ramp(light, 51, 78)


def skin_mask(rgb, region, p):
    part = {"face": region.parts[3], "body": region.parts[2], "all": region.skin}[p["region"]]
    if p["refine"]:
        part = blur(part, max(0.5, region.scale * 0.006))
    return np.clip(part * p["sensitivity"], 0, 1)


def eye_vessels(rgb, region, p):
    return retouch_eye_vessels(rgb, region, p["blend"])


def eye_brilliance(rgb, region, p):
    return retouch_eye_brilliance(rgb, region, p["blend"])


def white_teeth(rgb, region, p):
    whiten = float(np.clip(p["whiten"], 0, 1))
    brighten = float(np.clip(p["brighten"], 0, 1))
    if whiten == 0 and brighten == 0:
        return rgb.copy(), np.zeros(rgb.shape[:2], np.float32)
    mouth = region.feature([MOUTH])
    values = lab(rgb)
    light, red, yellow = (values[..., i] for i in range(3))
    # Teeth in shade remain enamel. A high luminance threshold made the
    # correction fade out across a smile, leaving the lateral teeth yellow.
    # Reject red oral tissue relative to yellow, rather than rejecting warm
    # enamel solely for its absolute redness or darkness.
    tooth = ramp(light, 12, 22) * (1 - ramp(red - yellow * 0.55, 5, 12))
    # Protect dark hair strands and interdental detail crossing bright enamel.
    radius = max(1, round(region.scale * 0.002))
    closed = cv.morphologyEx(light, cv.MORPH_CLOSE, ellipse(radius))
    dark_detail = ramp(closed - light, 3, 12)
    mask = tooth * mouth * (1 - dark_detail)
    values[..., 2] -= np.clip(yellow - 4, 0, 45) * whiten * 0.92
    values[..., 0] += (100 - light) * brighten * 0.27
    candidate = rgb_color(values)
    candidate[mask <= 0] = rgb[mask <= 0]
    return candidate, mask


def glasses_glare(rgb, region, p):
    return retouch_glasses_glare(rgb, region, p)


def stray_hairs(rgb, region, p):
    return retouch_stray_hairs(rgb, region, p)


def fabric(rgb, region, p):
    return retouch_fabric(rgb, region, p)


def clean_backdrop(rgb, region, p):
    return retouch_clean_backdrop(rgb, region, p)


def dust(rgb, region, p):
    light = lab(rgb)[..., 0]
    radius = {"fine": 2, "medium": 4, "large": 7}[p["size"]]
    kernel = ellipse(radius)
    particles = np.maximum(cv.morphologyEx(light, cv.MORPH_TOPHAT, kernel),
                           cv.morphologyEx(light, cv.MORPH_BLACKHAT, kernel))
    # Keep portrait details out of the particle detector. The background
    # confidence must remain high across the inpainting neighbourhood.
    background = np.clip(region.parts[0], 0, 1).astype(np.float32)
    background_core = cv.morphologyEx(np.float32(background > 0.85),
                                      cv.MORPH_CLOSE, ellipse(radius * 4))
    coverage = cv.erode(background_core, ellipse(radius + 2))
    mask = spots(particles, coverage, 11, 1, radius ** 2 * 12, 2)
    hard = np.uint8(mask > 0.05) * 255
    if not hard.any():
        return rgb, mask
    # Telea's float path uses an absolute intensity offset. Work on a 0..255
    # float scale, retaining fractional precision, rather than normalized RGB.
    fixed = np.stack([cv.inpaint(rgb[..., i].copy() * 255.0, hard,
                                radius + 1, cv.INPAINT_TELEA) / 255.0
                      for i in range(3)], axis=-1)
    fixed = np.clip(fixed, 0, 1)
    return fixed, np.clip(mask * p["blend"], 0, 1)


def number(label, default, maximum=1):
    return dict(label=label, type="number", min=0, max=maximum, step=0.01, default=default)


def choice(label, default, *values):
    return dict(label=label, type="choice", values=values, default=default)


def toggle(label, default):
    return dict(label=label, type="boolean", default=default)


def entry(label, group, operation, **parameters):
    return dict(label=label, group=group, operation=operation, parameters=parameters)


SIZE = choice("크기", "medium", "fine", "medium", "large")
GLARE_MODE = {**choice("처리 방식", "detail", "ocuflow", "detail"),
              "labels": {"ocuflow": "OcuFlow Original", "detail": "Detail Preserving"}}
TOOLS = {
    "heal": entry("Heal", "피부", heal, pimples=number("트러블 제거", 0.6), moles=number("점 제거", 0)),
    "mattifier": entry("Mattifier", "피부", mattifier, blend=number("강도", 0.5)),
    "dodgeBurn": entry("Dodge & Burn", "피부", dodge_burn, blend=number("강도", 0.55, 2),
                       warmth=number("색온기", 0.1), scale=choice("인물 크기", "auto", "auto", "close", "half", "full")),
    "volumes": entry("Portrait Volumes", "피부", portrait_volumes, blend=number("강도", 0.45, 2)),
    "skinTone": entry("Skin Tone", "피부", skin_tone, blend=number("강도", 0.5, 2)),
    "skinMask": entry("Skin Mask", "피부", skin_mask, sensitivity=number("감도", 1, 2),
                      region=choice("피부 영역", "all", "all", "face", "body"), refine=toggle("경계 정제", True)),
    "eyeVessels": entry("Eye Vessels", "디테일", eye_vessels, blend=number("강도", 0.55)),
    "eyeBrilliance": entry("Eye Brilliance", "디테일", eye_brilliance, blend=number("강도", 0.4, 2)),
    "whiteTeeth": entry("White Teeth", "디테일", white_teeth, whiten=number("미백", 0.5), brighten=number("밝기", 0.3)),
    "glassesGlare": entry("Glasses Glare Removal", "디테일", glasses_glare,
                          mode=GLARE_MODE, blend=number("강도", 0.6)),
    "strayHairs": entry("Stray Hairs", "디테일", stray_hairs, blend=number("강도", 0.6)),
    "fabric": entry("Fabric", "제품과 배경", fabric, blend=number("강도", 0.5, 2)),
    "cleanBackdrop": entry("Clean Backdrop", "제품과 배경", clean_backdrop, blend=number("강도", 0.6),
                           size=SIZE, protectSubject=toggle("피사체 보호", True)),
    "dust": entry("Dust", "제품과 배경", dust, blend=number("강도", 0.7, 2), size=SIZE),
}
