"""
"fashn" engine: realistic try-on with FASHN VTON v1.5 (Apache-2.0), running on YOUR OWN GPU
server (see fashn_server/). Photos never leave your network. Raises on any failure, and the
view then falls back to the quick "warp" engine.
"""
import cv2
import numpy as np
import requests
from django.conf import settings


def render(person_bgr, garment_path, garment_type="one-pieces"):
    """Return the try-on result as a BGR image."""
    ok, buf = cv2.imencode(".jpg", person_bgr, [cv2.IMWRITE_JPEG_QUALITY, 95])
    if not ok:
        raise RuntimeError("Could not encode the photo.")

    headers = {"X-Api-Key": settings.FASHN_API_KEY} if settings.FASHN_API_KEY else {}
    with open(garment_path, "rb") as garment_file:
        resp = requests.post(
            settings.FASHN_SERVER_URL.rstrip("/") + "/tryon",
            files={"person": ("person.jpg", buf.tobytes(), "image/jpeg"),
                   "garment": ("garment", garment_file)},
            data={"category": garment_type},
            headers=headers,
            timeout=settings.FASHN_TIMEOUT,
        )
    if resp.status_code != 200:
        try:
            message = resp.json().get("error", "")
        except ValueError:
            message = ""
        raise RuntimeError(f"AI server answered {resp.status_code}: {message or resp.reason}")
    image = cv2.imdecode(np.frombuffer(resp.content, np.uint8), cv2.IMREAD_COLOR)
    if image is None:
        raise RuntimeError("The GPU server returned no image.")
    return image
