"""
Image helpers: turn an uploaded dress photo into a clean, transparent GARMENT image.

Pipeline
--------
1. rembg (u2net) removes the background (skipped when the photo is already a transparent PNG).
2. If the photo shows a model, we also remove the model's head, neck, arms and
   skin so ONLY the clothing remains:
     a) clothing-segmentation model (USE_CLOTH_SEG, on by default), else
     b) MediaPipe Pose finds the shoulders -> everything above is cut off, then
        skin-coloured pixels are removed and the largest piece is kept.
   Photos with no person in them (flat-lay / mannequin) are left untouched.
rembg and mediapipe are imported lazily (they are heavy).
"""
import gc
import logging

import cv2
import numpy as np
from django.conf import settings
from PIL import Image, ImageChops, ImageOps

logger = logging.getLogger(__name__)

_sessions = {}  # rembg sessions are expensive: build each model once


def _get_session(name):
    if name not in _sessions:
        from rembg import new_session

        _sessions[name] = new_session(name)  # downloads the model on first use
    return _sessions[name]


def _release(name):
    """Free a model's memory once it is no longer needed (dress uploads are rare, RAM is not)."""
    if _sessions.pop(name, None) is not None:
        gc.collect()


def _estimate_hips(ls, rs):
    """Guess hip positions (pixels) ~1.6 shoulder-widths below the shoulders."""
    vec = rs - ls
    width = float(np.linalg.norm(vec))
    if width < 1:
        return [ls, rs]
    down = np.array([-vec[1], vec[0]]) / width  # perpendicular to the shoulder line
    mid = (ls + rs) / 2 + down * width * 1.6
    half = vec / 2 * 0.9
    return [mid - half, mid + half]


def _pose_points(img_rgb):
    """
    Shoulders and hips of the person in the photo, in PIXELS, as
    {"shoulders": [left, right], "hips": [left, right]} (left = smaller x), or None.
    """
    import mediapipe as mp

    w, h = img_rgb.size
    with mp.solutions.pose.Pose(static_image_mode=True, model_complexity=1) as pose:
        res = pose.process(np.array(img_rgb))
    if not res.pose_landmarks:
        return None
    lm = res.pose_landmarks.landmark
    if min(lm[11].visibility, lm[12].visibility) < 0.5:
        return None

    def pt(i):
        return np.array([lm[i].x * w, lm[i].y * h], dtype=np.float64)

    shoulders = sorted([pt(11), pt(12)], key=lambda p: p[0])
    hips_visible = min(lm[23].visibility, lm[24].visibility) >= 0.5 and max(lm[23].y, lm[24].y) <= 1.0
    hips = sorted([pt(23), pt(24)], key=lambda p: p[0]) if hips_visible else _estimate_hips(*shoulders)
    return {"shoulders": shoulders, "hips": hips}


def _cloth_mask(img_rgb):
    """Merge the 3 masks (upper / lower / full body) of the clothing model."""
    masks = _get_session("u2net_cloth_seg").predict(img_rgb)
    _release("u2net_cloth_seg")
    merged = masks[0]
    for m in masks[1:]:
        merged = ImageChops.lighter(merged, m)
    return np.array(merged.resize(img_rgb.size))


def _tidy_mask(mask):
    """Clean a clothing mask: fill pinholes (sheer fabric), drop specks, keep the main pieces."""
    binary = (mask > 128).astype(np.uint8)
    binary = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7)))
    n, labels, stats, _ = cv2.connectedComponentsWithStats(binary)
    if n > 1:
        areas = stats[1:, cv2.CC_STAT_AREA]
        keep = [1 + i for i, a in enumerate(areas) if a >= 0.05 * areas.max()]  # e.g. a separate pallu piece
        binary = np.isin(labels, keep).astype(np.uint8)
    # fill small holes (< 1.5 % of the garment) but keep big gaps (between pallu and skirt)
    contours, hierarchy = cv2.findContours(binary, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
    total = max(1, int(binary.sum()))
    if hierarchy is not None:
        for cnt, hier in zip(contours, hierarchy[0]):
            if hier[3] != -1 and cv2.contourArea(cnt) < 0.015 * total:  # hole inside a piece
                cv2.drawContours(binary, [cnt], -1, 1, -1)
    return cv2.GaussianBlur(binary * 255, (3, 3), 0)


def _add_torso_fill(mask, alpha, rgb, pts):
    """Ties, scarves, belts and shirt fronts are often not "clothing" for the segmentation model
    and leave holes. Add back every non-skin foreground pixel inside the model's torso."""
    ls, rs = pts["shoulders"]
    lh, rh = pts["hips"]
    torso = np.zeros(mask.shape, np.uint8)
    cv2.fillConvexPoly(torso, np.array([ls, rs, rh, lh], dtype=np.int32), 255)
    ycc = cv2.cvtColor(cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR), cv2.COLOR_BGR2YCrCb)
    skin = cv2.inRange(ycc, (0, 133, 77), (255, 185, 140)) > 0
    out = mask.copy()
    out[(alpha > 128) & (torso > 0) & ~skin] = 255
    return out


def _strip_model(img_rgb, rgb, alpha, pts):
    """Return a new alpha channel with the model's head / skin removed."""
    fg_area = max(1, int((alpha > 128).sum()))

    if pts is None:
        # Nobody in the photo: a mannequin or a flat-lay. Keep the WHOLE cut-out (the clothing model
        # tends to drop sheer / net fabric), and only cut off a mannequin's head / neck stand above
        # the top of the garment.
        if getattr(settings, "USE_CLOTH_SEG", True):
            try:
                cloth = _tidy_mask(_cloth_mask(img_rgb))
                rows = np.where((cloth > 128).any(axis=1))[0]
                if len(rows) and (cloth > 128).sum() / fg_area > 0.15:
                    cut = max(0, int(rows.min() - 0.01 * img_rgb.height))
                    alpha = alpha.copy()
                    alpha[:cut] = 0
            except Exception:  # noqa: BLE001
                logger.exception("Cloth segmentation failed; keeping the plain cut-out")
        return alpha

    if getattr(settings, "USE_CLOTH_SEG", True):
        try:
            cloth = _cloth_mask(img_rgb)
            if (cloth > 128).sum() / fg_area > 0.30:  # the model found a sensible amount of clothing
                tidy = _add_torso_fill(_tidy_mask(cloth), alpha, rgb, pts)
                return np.minimum(alpha, tidy)
        except Exception:  # noqa: BLE001
            logger.exception("Cloth segmentation failed, using pose + skin fallback")

    # cut a hair above the shoulder line so the neckline of the garment stays
    cut = max(0, int(min(p[1] for p in pts["shoulders"]) - 0.02 * img_rgb.height))
    alpha = alpha.copy()
    alpha[:cut] = 0  # head and neck

    # Remove skin-coloured pixels (arms, chest, face remains)
    ycc = cv2.cvtColor(cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR), cv2.COLOR_BGR2YCrCb)
    skin = cv2.inRange(ycc, (0, 135, 85), (255, 180, 135)) > 0
    alpha[skin] = 0

    # Clean specks, keep the biggest connected piece (the garment)
    alpha = cv2.morphologyEx(alpha, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)))
    n, labels, stats, _ = cv2.connectedComponentsWithStats((alpha > 20).astype(np.uint8))
    if n > 1:
        biggest = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA]))
        alpha[labels != biggest] = 0
    return cv2.GaussianBlur(alpha, (3, 3), 0)


def _remove_fringe(rgb, alpha):
    """Cut-outs keep a thin light halo of the old background along their edge (it shows up as
    white dotted lines on the customer). Trim ~2 px and repaint the edge from the fabric inside."""
    inner = cv2.erode((alpha > 128).astype(np.uint8), np.ones((3, 3), np.uint8), iterations=3)
    weight = inner.astype(np.float32)
    rgb_f = rgb.astype(np.float32)
    for _ in range(2):  # grow the interior colours outward, twice
        num = cv2.blur(rgb_f * weight[..., None], (7, 7))
        den = cv2.blur(weight, (7, 7))
        fill = num / np.maximum(den[..., None], 1e-3)
        edge = (inner == 0) & (den > 0.05)
        rgb_f[edge] = fill[edge]
        weight = np.maximum(weight, edge.astype(np.float32))
    new_alpha = cv2.GaussianBlur(cv2.erode(alpha, np.ones((3, 3), np.uint8), iterations=2), (3, 3), 0)
    return np.clip(rgb_f, 0, 255).astype(np.uint8), new_alpha


def extract_garment(raw_bytes: bytes, remove_model: bool = True):
    """
    Return (garment_rgba_image, anchors).
    anchors = [[x, y] x4] = model's left shoulder, right shoulder, right hip, left hip
    in the coordinates of the returned image (or None if no person was found).
    The try-on maps these 4 points onto the customer's body for a natural fit.
    """
    import io

    from rembg import remove

    src = ImageOps.exif_transpose(Image.open(io.BytesIO(raw_bytes)))
    src.thumbnail((1200, 1200), Image.LANCZOS)

    own_alpha = None  # the photo may already be a transparent PNG (e.g. made with remove.bg)
    if src.mode in ("RGBA", "LA", "PA") or "transparency" in src.info:
        rgba = src.convert("RGBA")
        a = np.array(rgba.getchannel("A"))
        if (a < 250).mean() > 0.05:
            own_alpha = a

    if own_alpha is not None:
        flat = Image.new("RGB", rgba.size, (255, 255, 255))   # white background for the AI models
        flat.paste(rgba, mask=rgba.getchannel("A"))
        img = flat
        rgb, alpha = np.array(rgba)[:, :, :3], own_alpha       # keep the supplied cut-out
    else:
        img = src.convert("RGB")
        fg = remove(img, session=_get_session("u2net")).convert("RGBA")
        _release("u2net")
        arr = np.array(fg)
        rgb, alpha = arr[:, :, :3], arr[:, :, 3]

    pts = _pose_points(img)

    if remove_model:
        stripped = _strip_model(img, rgb, alpha, pts)
        # Safety net: if almost nothing is left, keep the plain cut-out instead
        if (stripped > 128).sum() >= 0.02 * stripped.size:
            alpha = stripped
        else:
            logger.warning("Model removal left almost nothing; keeping the plain cut-out.")

    rgb, alpha = _remove_fringe(rgb, alpha)

    out = Image.fromarray(np.dstack([rgb, alpha]), "RGBA")
    bbox = out.getchannel("A").getbbox()
    ox, oy = (bbox[0], bbox[1]) if bbox else (0, 0)
    if bbox:
        out = out.crop(bbox)  # tight crop
    width_before = out.width
    out.thumbnail((1000, 1000), Image.LANCZOS)
    scale = out.width / width_before

    anchors = None
    if pts:
        order = [pts["shoulders"][0], pts["shoulders"][1], pts["hips"][1], pts["hips"][0]]
        anchors = [[round(float((p[0] - ox) * scale), 1), round(float((p[1] - oy) * scale), 1)] for p in order]
    return out, anchors


def make_thumbnail(img: Image.Image, size: int = 200) -> Image.Image:
    thumb = img.copy()
    thumb.thumbnail((size, size), Image.LANCZOS)
    return thumb


def to_png_bytes(img: Image.Image) -> bytes:
    import io

    buf = io.BytesIO()
    img.save(buf, format="PNG", optimize=True)
    return buf.getvalue()
