"""
"openai" engine: edits the customer photo with an OpenAI image model (paid, per image).

- The customer photo and the cleaned garment image are sent to OpenAI (a third party): get consent.
- Needs an API key with billing (OPENAI_API_KEY in .env). The key is never logged.
- Unlike FASHN (a dedicated try-on model) this is a general image editor: it may change small details
  of the face, background or garment. Test it on your own photos before relying on it.
"""
import base64
import io

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

PROMPT = (
    "Image 1 is a photo of a customer. Image 2 shows a garment on a plain white background. "
    "Edit image 1 so the customer is wearing the garment from image 2. "
    "Keep the customer's face, identity, skin tone, hair, body shape, pose and the background exactly as they are; "
    "change only the clothing. The garment must look realistic with natural folds and a correct fit, and keep its "
    "colour, pattern and details. Do not add text, logos or extra people."
)


def garment_on_white(dress):
    """The cleaned garment (no model, no background) on white; falls back to the original upload."""
    try:
        if dress.image:
            img = Image.open(dress.image.path).convert("RGBA")
            white = Image.new("RGB", img.size, (255, 255, 255))
            white.paste(img, mask=img.getchannel("A"))
            buf = io.BytesIO()
            white.save(buf, format="PNG")
            return buf.getvalue(), "garment.png", "image/png"
    except Exception:  # noqa: BLE001
        pass
    with open(dress.raw_image.path, "rb") as handle:
        return handle.read(), "garment.jpg", "image/jpeg"


def _size_for(photo_bgr):
    h, w = photo_bgr.shape[:2]
    if abs(w - h) < 0.1 * max(w, h):
        return "1024x1024"
    return "1024x1536" if h > w else "1536x1024"


def render(person_bgr, dress):
    """Return the edited photo as a BGR image. Raises RuntimeError with a readable message on failure."""
    key = settings.OPENAI_API_KEY
    if not key:
        raise RuntimeError("OPENAI_API_KEY is not set in .env")

    ok, buf = cv2.imencode(".jpg", person_bgr, [cv2.IMWRITE_JPEG_QUALITY, 95])
    if not ok:
        raise RuntimeError("Could not encode the photo.")
    garment_bytes, garment_name, garment_type = garment_on_white(dress)

    resp = requests.post(
        settings.OPENAI_BASE_URL.rstrip("/") + "/images/edits",
        headers={"Authorization": f"Bearer {key}"},
        files=[
            ("image[]", ("customer.jpg", buf.tobytes(), "image/jpeg")),
            ("image[]", (garment_name, garment_bytes, garment_type)),
        ],
        data={
            "model": settings.OPENAI_IMAGE_MODEL,
            "prompt": PROMPT,
            "size": _size_for(person_bgr),
            "quality": settings.OPENAI_IMAGE_QUALITY,
        },
        timeout=settings.OPENAI_TIMEOUT,
    )
    if resp.status_code != 200:
        try:
            message = resp.json().get("error", {}).get("message", "")
        except ValueError:
            message = ""
        raise RuntimeError(f"OpenAI answered {resp.status_code}: {(message or resp.reason)[:150]}")

    data = resp.json().get("data") or []
    if not data or not data[0].get("b64_json"):
        raise RuntimeError("OpenAI returned no image.")
    image = cv2.imdecode(np.frombuffer(base64.b64decode(data[0]["b64_json"]), np.uint8), cv2.IMREAD_COLOR)
    if image is None:
        raise RuntimeError("OpenAI returned an unreadable image.")
    return image
