"""
"ai" engine: realistic try-on with an OPEN-SOURCE diffusion model (IDM-VTON by default),
called through a Hugging Face Space with `gradio_client` (pip install gradio_client).

IMPORTANT
- Needs the internet; the customer's photo is sent to that Space (a third-party server).
- Free Spaces are queued and rate-limited; one photo can take 20-90 seconds.
- Model licences differ (IDM-VTON is CC BY-NC-SA 4.0 = non-commercial). Check before selling.
- The Space's API can change. If it breaks, open the Space page -> "Use via API"
  and adjust the predict() call below. If anything fails, the view falls back to the
  "warp" engine automatically.
You can instead host the same model yourself on a GPU machine and point TRYON_AI_SPACE at it.
"""
import logging
import os
import tempfile

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

logger = logging.getLogger(__name__)


def prepare_garment(dress):
    """
    IDM-VTON is built for UPPER-BODY clothes shown on a plain white background. So instead of the
    original upload (a full-length model photo with a head, legs and shoes) we send the cleaned
    garment cut-out, cropped from the collar down to just below the hips, on white.
    Returns (path, is_temporary_file). Falls back to the original upload if that is not possible.
    """
    try:
        if dress.garment_type != "bottoms" and dress.anchors and dress.image:
            img = Image.open(dress.image.path).convert("RGBA")
            (_, lsy), (_, rsy), (_, rhy), (_, lhy) = dress.anchors      # shoulders L,R then hips R,L
            shoulder_y, hip_y = (lsy + rsy) / 2, (rhy + lhy) / 2
            bottom = int(min(img.height, hip_y + 0.25 * max(hip_y - shoulder_y, 1)))
            crop = img.crop((0, 0, img.width, max(bottom, 16)))
            white = Image.new("RGB", crop.size, (255, 255, 255))
            white.paste(crop, mask=crop.getchannel("A"))
            handle, path = tempfile.mkstemp(suffix=".jpg")
            os.close(handle)
            white.save(path, quality=95)
            return path, True
    except Exception:  # noqa: BLE001
        logger.exception("Could not prepare the upper-body garment image")
    return dress.raw_image.path, False


def portrait_crop(photo_bgr):
    """
    The model works on 3:4 portrait pictures. A wide webcam frame is cropped to a portrait window
    centred on the person (found through their shoulders) so the person fills the picture.
    """
    h, w = photo_bgr.shape[:2]
    target_w = int(h * 3 / 4)
    if w <= target_w:
        return photo_bgr
    centre = w / 2
    try:
        from .pose_detector import detect_body

        detection = detect_body(photo_bgr)
        if detection is not None:
            centre = float(detection["points"][:2, 0].mean()) * w
    except Exception:  # noqa: BLE001
        logger.exception("Person detection failed; centring the crop")
    x0 = int(np.clip(centre - target_w / 2, 0, w - target_w))
    return photo_bgr[:, x0:x0 + target_w]


def _make_client(Client, space, token):
    """gradio_client versions name the login-token option differently (token / hf_token / none)."""
    if token:
        for keyword in ("token", "hf_token"):
            try:
                return Client(space, **{keyword: token})
            except TypeError:
                continue
    return Client(space)


def render(person_bgr, garment_path, description="a garment"):
    """Return the try-on result as a BGR image. Raises on any failure."""
    from gradio_client import Client, handle_file  # lazy import (optional dependency)

    client = _make_client(Client, settings.TRYON_AI_SPACE, settings.HF_TOKEN)

    with tempfile.TemporaryDirectory() as tmp:
        person_path = os.path.join(tmp, "person.jpg")
        cv2.imwrite(person_path, person_bgr, [cv2.IMWRITE_JPEG_QUALITY, 95])

        result = client.predict(
            dict={"background": handle_file(person_path), "layers": [], "composite": None},
            garm_img=handle_file(str(garment_path)),
            garment_des=description,
            is_checked=True,        # auto-generate the body mask
            is_checked_crop=False,
            denoise_steps=30,
            seed=42,
            api_name="/tryon",
        )
        out_path = result[0] if isinstance(result, (list, tuple)) else result
        image = cv2.imread(str(out_path))
        if image is None:
            raise RuntimeError("The AI service returned no image.")
        return image
