"""Geometry + rendering: warp the dress onto the body and alpha-blend it."""
import cv2
import numpy as np

# Tweak these to change how the dress fits.
WIDEN = 1.25            # dress is 25% wider than shoulders/hips
NECK_LIFT = 0.08        # raise the neckline a bit above the shoulder line (fraction of torso)
LENGTH_FACTOR = 2.1     # shoulder-to-hem length as a multiple of shoulder-to-hip length
HEM_FLARE = 1.10        # hem a little wider than the hips


def build_dress_quad(points_px):
    """
    points_px: (4, 2) pixel array [left_shoulder, right_shoulder, left_hip, right_hip].
    Returns a float32 (4, 2) destination quad [top-left, top-right, bottom-right, bottom-left],
    or None if the geometry is degenerate.
    """
    ls, rs, lh, rh = points_px
    sh_mid = (ls + rs) / 2
    hip_mid = (lh + rh) / 2

    torso = hip_mid - sh_mid
    torso_len = float(np.linalg.norm(torso))
    if torso_len < 10:
        return None
    down = torso / torso_len

    sh_half = (rs - ls) / 2 * WIDEN
    hip_half = (rh - lh) / 2 * WIDEN * HEM_FLARE
    lift = down * torso_len * NECK_LIFT
    extra = down * torso_len * (LENGTH_FACTOR - 1.0)  # extend below the hips

    top_l = sh_mid - sh_half - lift
    top_r = sh_mid + sh_half - lift
    bot_l = hip_mid - hip_half + extra
    bot_r = hip_mid + hip_half + extra
    return np.array([top_l, top_r, bot_r, bot_l], dtype=np.float32)


FIT_WIDEN = 1.12        # with anchors: make the garment a bit wider than the body to cover it


def _garment_bottom_extent(dress_bgra):
    """(x_left, x_right, y_bottom) of the garment's lowest visible rows, in garment pixels."""
    alpha = dress_bgra[:, :, 3]
    rows = np.where((alpha > 128).any(axis=1))[0]
    if len(rows) == 0:
        return None
    y_bottom = int(rows.max())
    band = alpha[max(0, y_bottom - max(3, len(rows) // 25)): y_bottom + 1] > 128   # lowest ~4 % of the garment
    cols = np.where(band.any(axis=0))[0]
    return float(cols.min()), float(cols.max()), float(y_bottom)


NECK_RAISE = 0.08    # a jacket's shoulder line sits a little above the shoulder-joint landmarks (x shoulder width)
HEM_FLARE_MIN, HEM_FLARE_MAX = 0.95, 1.35   # hem width vs hip width (stops sarees/gowns from ballooning)


def fit_quads(points_px, dress_shape, anchors=None, dress_bgra=None):
    """
    Decide how the garment image maps onto the body. Returns (src_quad, dst_quad):
      src = 4 points in the garment image, dst = matching 4 points in the camera frame.
    With `anchors` (the model's shoulders/hips found in the dress photo) the garment is mapped
    SHOULDERS -> HEM: the top edge lands on the customer's shoulders and the bottom edge on a hem
    placed at the model's proportions (scaled to the customer's torso), with the hem width limited
    so long garments do not flare out sideways.
    Without anchors (flat-lay / mannequin photos) the whole image is stretched onto the torso.
    """
    ls, rs, lh, rh = points_px
    if anchors is not None and len(anchors) == 4:
        a_ls, a_rs, a_rh, a_lh = (np.array(p, np.float32) for p in anchors)  # model: shoulders, hips
        sh_mid, hip_mid = (ls + rs) / 2, (lh + rh) / 2
        sh_half = (rs - ls) / 2 * FIT_WIDEN
        _t = hip_mid - sh_mid
        _tl = float(np.linalg.norm(_t))
        lift = -(_t / _tl if _tl > 1 else np.array([0.0, 1.0], np.float32)) * NECK_RAISE * float(np.linalg.norm(rs - ls))
        sh_top = sh_mid + lift          # raised neckline / shoulder line

        extent = _garment_bottom_extent(dress_bgra) if dress_bgra is not None else None
        torso = hip_mid - sh_mid
        torso_len = float(np.linalg.norm(torso))
        model_torso = float(np.linalg.norm((a_lh + a_rh) / 2 - (a_ls + a_rs) / 2))
        if extent is not None and torso_len > 1 and model_torso > 1 and extent[2] > (a_ls[1] + a_rs[1]) / 2 + 1:
            x_l, x_r, y_b = extent
            scale = torso_len / model_torso                      # customer torso / model torso
            down = torso / torso_len
            length = (y_b - (a_ls[1] + a_rs[1]) / 2) * scale     # shoulders -> hem on the customer
            hem_center = sh_mid + down * length
            model_hip_w = max(1.0, float(np.linalg.norm(a_rh - a_lh)))
            ratio = float(np.clip((x_r - x_l) / model_hip_w, HEM_FLARE_MIN, HEM_FLARE_MAX))
            hip_vec = rh - lh
            hip_dir = hip_vec / max(float(np.linalg.norm(hip_vec)), 1.0)
            hem_half = hip_dir * float(np.linalg.norm(hip_vec)) * ratio * FIT_WIDEN / 2
            src = np.float32([a_ls, a_rs, [x_r, y_b], [x_l, y_b]])
            dst = np.float32([sh_top - sh_half, sh_top + sh_half, hem_center + hem_half, hem_center - hem_half])
            return src, dst

        # Short garment / no usable extent: plain shoulders -> hips mapping
        hip_half = (rh - lh) / 2 * FIT_WIDEN
        src = np.float32([a_ls, a_rs, a_rh, a_lh])
        dst = np.float32([sh_top - sh_half, sh_top + sh_half, hip_mid + hip_half, hip_mid - hip_half])
        return src, dst

    quad = build_dress_quad(points_px)
    if quad is None:
        return None
    dh, dw = dress_shape[:2]
    src = np.float32([[0, 0], [dw - 1, 0], [dw - 1, dh - 1], [0, dh - 1]])
    return src, quad


def warp_dress(frame_shape, dress_bgra, fit):
    """Perspective-warp the dress using `fit` = (src_quad, dst_quad). Returns a BGRA image the
    size of the frame, or None if the geometry is unusable (bad pose detection)."""
    if fit is None:
        return None
    src, dst = fit
    if not (np.all(np.isfinite(src)) and np.all(np.isfinite(dst))):
        return None
    # Reject twisted / non-convex / tiny shapes
    if not cv2.isContourConvex(dst.astype(np.float32)) or cv2.contourArea(dst) < 400:
        return None
    if cv2.contourArea(src) < 100:
        return None
    h, w = frame_shape[:2]
    matrix = cv2.getPerspectiveTransform(src, dst)
    return cv2.warpPerspective(
        dress_bgra, matrix, (w, h),
        flags=cv2.INTER_LINEAR,
        borderMode=cv2.BORDER_CONSTANT,
        borderValue=(0, 0, 0, 0),
    )


def blend_warped(frame_bgr, warped_bgra):
    """Alpha-blend a warped BGRA dress over the frame."""
    if warped_bgra is None:
        return frame_bgr
    alpha = warped_bgra[:, :, 3:4].astype(np.float32) / 255.0
    alpha = np.clip((alpha - 0.2) / 0.6, 0.0, 1.0)  # crisp edge, no grey fringe
    blended = warped_bgra[:, :, :3].astype(np.float32) * alpha + frame_bgr.astype(np.float32) * (1.0 - alpha)
    return blended.astype(np.uint8)


def overlay_dress(frame_bgr, dress_bgra, fit):
    """Convenience: warp + blend in one call."""
    return blend_warped(frame_bgr, warp_dress(frame_bgr.shape, dress_bgra, fit))


def cover_clothes(frame_bgr, points_px, quad, person_mask, color_bgr, sleeves="wrist", dress_alpha=None):
    """
    Hide the customer's own clothes so the dress looks like it REPLACES them.
    The torso (down to the dress hem) and the sleeves are repainted with the dress's
    average colour, multiplied by the frame's brightness so the natural folds and
    shadows of the body still show through (it reads as fabric, not a flat paint).

    sleeves: "none" (torso only), "elbow" (cover upper arms) or "wrist" (cover whole arms)
    """
    if quad is None or color_bgr is None:
        return frame_bgr
    h, w = frame_bgr.shape[:2]
    ls, rs, lh, rh, le, re, lw, rw = points_px

    zone = np.zeros((h, w), np.uint8)

    # Torso: from the shoulder line down to the dress hem (neck stays untouched)
    mid = (ls + rs) / 2
    half = (rs - ls) / 2 * 1.22
    torso = np.array([mid - half, mid + half, quad[2], quad[3]], dtype=np.int32)
    cv2.fillConvexPoly(zone, torso, 255)

    # Wherever the dress will be drawn (e.g. a long skirt), hide the customer's own clothes too
    if dress_alpha is not None:
        zone = np.maximum(zone, cv2.dilate((dress_alpha > 10).astype(np.uint8) * 255, np.ones((9, 9), np.uint8)))

    # Sleeves: thick lines shoulder -> elbow (-> wrist, stopping before the hand)
    sw = float(np.linalg.norm(rs - ls))
    thick = int(max(8, sw * 0.52))
    if sleeves in ("elbow", "wrist"):
        for sh, el, wr in ((ls, le, lw), (rs, re, rw)):
            sh_i, el_i = tuple(int(v) for v in sh), tuple(int(v) for v in el)
            cv2.line(zone, sh_i, el_i, 255, thick)
            cv2.circle(zone, sh_i, int(thick * 0.3), 255, -1)
            cv2.circle(zone, el_i, thick // 2, 255, -1)
            if sleeves == "wrist":
                end = el + (wr - el) * 0.85
                cv2.line(zone, el_i, tuple(int(v) for v in end), 255, int(thick * 0.85))

    # Trim the "shoulder pads": never repaint above the shoulder line (a jacket is not a hump)
    mid_pt = (ls + rs) / 2
    sv = (rs - ls) / max(sw, 1.0)                      # unit vector along the shoulders
    up = np.array([sv[1], -sv[0]], np.float32)         # perpendicular, pointing up
    yy, xx = np.mgrid[0:h, 0:w].astype(np.float32)
    above = (xx - mid_pt[0]) * up[0] + (yy - mid_pt[1]) * up[1]
    zone[above > 0.06 * sw] = 0

    # Collar wings: cover the customer's own collar on BOTH sides of the neck, but never the
    # neck itself (skin-coloured pixels are left alone) or the chin (centre strip is skipped).
    wings = np.zeros((h, w), np.uint8)
    a, b, height = 0.22 * sw, 0.46 * sw, 0.14 * sw
    for sign in (-1.0, 1.0):
        quad_w = np.array([
            mid_pt + sign * a * sv - 0.02 * sw * up,
            mid_pt + sign * b * sv - 0.02 * sw * up,
            mid_pt + sign * b * sv + height * up,
            mid_pt + sign * a * sv + height * up,
        ], dtype=np.int32)
        cv2.fillConvexPoly(wings, quad_w, 255)
    ycc = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2YCrCb)
    skin = cv2.inRange(ycc, (0, 133, 77), (255, 185, 140)) > 0
    wings[skin] = 0
    zone = np.maximum(zone, wings)

    # Only repaint pixels that belong to the person (never the wall behind)
    if person_mask is not None and person_mask.shape[:2] == (h, w):
        grown = cv2.dilate(person_mask, np.ones((3, 3), np.uint8))  # 1 px: avoids a rim of old clothes
        zone = cv2.bitwise_and(zone, grown)

    region = zone > 127
    if not region.any():
        return frame_bgr

    # Fabric-like fill: dress colour x relative brightness of the original pixels
    gray = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2GRAY).astype(np.float32)
    mean_l = max(float(gray[region].mean()), 1.0)
    factor = np.clip(1.0 + 0.7 * (gray / mean_l - 1.0), 0.55, 1.45)
    fill = np.clip(np.array(color_bgr, np.float32)[None, None, :] * factor[:, :, None], 0, 255)

    alpha = cv2.GaussianBlur(zone, (0, 0), 1.5).astype(np.float32)[:, :, None] / 255.0 * 0.97
    out = fill * alpha + frame_bgr.astype(np.float32) * (1.0 - alpha)
    return out.astype(np.uint8)
