# Archived first Heal (2026-11-08 release work). Shared regions helpers are imported from the checkpoint.
import cv2 as cv
import numpy as np
from service.regions import blur, ellipse, ramp

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]
    red = redness - blur(redness, scale * 1.6)
    dark = blur(luminance, scale * 1.6) - luminance
    support = region.skin
    area = max(8, scale ** 2 * 13)
    pimples = spots(red + 0.14 * dark, support * ramp(red, 2, 5), 4, 2, area)
    moles = spots(dark, support * (1 - ramp(red, 1, 4)), 8, 2, area * 0.55)
    mask = np.maximum(pimples * p["pimples"], moles * p["moles"])
    fixed, _ = fill(rgb, np.maximum(pimples if p["pimples"] else 0,
                                    moles if p["moles"] else 0), max(2, round(scale)))
    return fixed, mask
