"""
MediaPipe Pose wrapper + landmark smoothing.

THREAD SAFETY
-------------
A MediaPipe Pose object is NOT safe to share between threads. We therefore keep
one instance per thread (threading.local), created lazily on first use. Each
gunicorn worker process / thread ends up with its own detector.
"""
import threading
import time

import cv2
import numpy as np
from django.conf import settings

# MediaPipe landmark indices
L_SHOULDER, R_SHOULDER, L_HIP, R_HIP = 11, 12, 23, 24
MIN_VISIBILITY = 0.5

_local = threading.local()


def _get_pose():
    pose = getattr(_local, "pose", None)
    if pose is None:
        import mediapipe as mp  # lazy import: heavy

        pose = mp.solutions.pose.Pose(
            # static_image_mode=True: every frame is processed independently,
            # so frames from different customers can never mix tracking state.
            static_image_mode=True,
            model_complexity=settings.POSE_MODEL_COMPLEXITY,
            enable_segmentation=True,  # person mask, used to hide the customer's own clothes
            min_detection_confidence=0.5,
        )
        _local.pose = pose
    return pose


def detect_body(frame_bgr):
    """
    Return a dict or None if no person is found:
      points : (8, 2) NORMALISED coords, order
               [L shoulder, R shoulder, L hip, R hip, L elbow, R elbow, L wrist, R wrist]
               ("L" = left side OF THE IMAGE, so mirroring never matters)
      mask   : uint8 person mask (0/255) same size as the frame, or None
    Missing hips / elbows / wrists (person too close) are estimated from the shoulders.
    """
    rgb = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB)
    results = _get_pose().process(rgb)
    if not results.pose_landmarks:
        return None
    lm = results.pose_landmarks.landmark
    h, w = frame_bgr.shape[:2]

    def pt(i):
        return np.array([lm[i].x, lm[i].y], dtype=np.float32), lm[i].visibility

    # (shoulder, elbow, wrist, hip) landmark ids for each body side
    sides = []
    for sh_i, el_i, wr_i, hp_i in ((11, 13, 15, 23), (12, 14, 16, 24)):
        sides.append((pt(sh_i), pt(el_i), pt(wr_i), pt(hp_i)))
    if min(sides[0][0][1], sides[1][0][1]) < MIN_VISIBILITY:
        return None  # need both shoulders to place a dress
    sides.sort(key=lambda t: t[0][0][0])  # left-of-image first
    (ls, _), (rs, _) = sides[0][0], sides[1][0]

    # Geometry in pixels for the estimates
    scale = np.array([w, h], dtype=np.float32)
    vec = (rs - ls) * scale
    sw = float(np.linalg.norm(vec))
    down = np.array([-vec[1], vec[0]], dtype=np.float32) / max(sw, 1.0)  # perpendicular, points down

    def est(s_norm, k):
        return (s_norm * scale + down * sw * k) / scale

    hips_ok = min(sides[0][3][1], sides[1][3][1]) >= MIN_VISIBILITY and max(sides[0][3][0][1], sides[1][3][0][1]) <= 1.5
    out = [ls, rs]
    # hips
    if hips_ok:
        hips = sorted([sides[0][3][0], sides[1][3][0]], key=lambda p: p[0])
    else:
        hips = _estimate_hips(ls, rs, frame_bgr.shape)
    out += hips
    # elbows, wrists (fall back to estimates when not visible)
    for idx, side in enumerate(sides):
        s_norm = side[0][0]
        side_sign = -1.0 if idx == 0 else 1.0  # arms hang slightly outward
        out_vec = (vec / max(sw, 1.0)) * side_sign
        elbow = side[1][0] if side[1][1] >= 0.4 else (s_norm * scale + down * sw * 0.9 + out_vec * sw * 0.1) / scale
        out.append(elbow)
    for idx, side in enumerate(sides):
        s_norm = side[0][0]
        side_sign = -1.0 if idx == 0 else 1.0
        out_vec = (vec / max(sw, 1.0)) * side_sign
        wrist = side[2][0] if side[2][1] >= 0.4 else (s_norm * scale + down * sw * 1.7 + out_vec * sw * 0.15) / scale
        out.append(wrist)

    mask = None
    seg = getattr(results, "segmentation_mask", None)
    if seg is not None:
        mask = ((seg > 0.5).astype(np.uint8)) * 255

    # Are both ankles really in the picture? (needed to show a full-length outfit)
    ank = [pt(27), pt(28)]
    legs_ok = min(ank[0][1], ank[1][1]) >= MIN_VISIBILITY and max(ank[0][0][1], ank[1][0][1]) <= 1.0

    return {"points": np.array(out, dtype=np.float32), "mask": mask,
            "hips_ok": bool(hips_ok), "legs_ok": bool(legs_ok)}


def _estimate_hips(left_s, right_s, shape):
    """Guess hip positions ~1.6 shoulder-widths below the shoulders (normalised coords)."""
    h, w = shape[:2]
    # Work in pixels so the "down" direction is geometrically correct.
    ls = left_s * [w, h]
    rs = right_s * [w, h]
    vec = rs - ls
    width = np.linalg.norm(vec)
    if width < 1:
        return [left_s, right_s]
    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) / [w, h], (mid + half) / [w, h]]


class LandmarkSmoother:
    """
    Exponential moving average per browser session:
        smoothed = alpha * new + (1 - alpha) * previous
    State is kept in memory, guarded by a lock, and expires automatically.
    NOTE: with several gunicorn *processes*, each process has its own state;
    that is fine because the smoothing only affects visual jitter.
    """

    def __init__(self, alpha=0.5, ttl_seconds=120, max_sessions=1000):
        self.alpha = alpha
        self.ttl = ttl_seconds
        self.max_sessions = max_sessions
        self._state = {}  # key -> (timestamp, points)
        self._lock = threading.Lock()

    def smooth(self, key, points):
        now = time.monotonic()
        with self._lock:
            self._evict(now)
            prev = self._state.get(key)
            if prev is not None and now - prev[0] < self.ttl:
                points = self.alpha * points + (1.0 - self.alpha) * prev[1]
            self._state[key] = (now, points)
        return points

    def reset(self, key):
        with self._lock:
            self._state.pop(key, None)

    def _evict(self, now):
        if len(self._state) < self.max_sessions:
            return
        for k in [k for k, (t, _) in self._state.items() if now - t > self.ttl]:
            del self._state[k]
        if len(self._state) >= self.max_sessions:  # still full: drop the oldest
            oldest = min(self._state, key=lambda k: self._state[k][0])
            del self._state[oldest]


smoother = LandmarkSmoother(alpha=settings.SMOOTHING_ALPHA)
