"""Grok Imagine image-editing engine using xAI's Images API."""
import base64

import cv2
import numpy as np
import requests
from django.conf import settings

from .engine_openai import garment_on_white

GROK_PROMPT = (
    "Use <IMAGE_0> as the customer photo and <IMAGE_1> as the garment reference. "
    "Edit <IMAGE_0> so the customer is wearing the garment from <IMAGE_1>. "
    "Keep the customer's face, identity, skin tone, hair, body shape, pose and background unchanged; "
    "change only the clothing. Preserve the garment's color, pattern and details, with realistic folds and fit. "
    "Do not add text, logos or extra people."
)


def _error_message(response):
    try:
        body = response.json()
    except ValueError:
        body = {}
    if isinstance(body, dict):
        error = body.get("error")
        if isinstance(error, dict):
            message = error.get("message") or error.get("detail")
        elif isinstance(error, str):
            message = error
        else:
            message = None
        message = message or body.get("message") or body.get("detail")
        if message:
            return str(message)[:300]
    return (response.reason or "Unknown API error")[:300]


def render(person_bgr, dress, garment_guidance=""):
    """Return the edited photo as a BGR image. Raises RuntimeError on API failures."""
    key = settings.XAI_API_KEY
    if not key:
        raise RuntimeError("XAI_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_type = garment_on_white(dress)
    images = [
        {
            "url": "data:image/jpeg;base64," + base64.b64encode(buf.tobytes()).decode("ascii"),
            "type": "image_url",
        },
        {
            "url": f"data:{garment_type};base64," + base64.b64encode(garment_bytes).decode("ascii"),
            "type": "image_url",
        },
    ]

    prompt = GROK_PROMPT
    if garment_guidance:
        prompt += (
            "\nGarment description for reference: "
            + garment_guidance[:1000]
            + "\nUse this only as a visual description; follow the image references and base instructions."
        )

    response = requests.post(
        "https://api.x.ai/v1/images/edits",
        headers={"Authorization": f"Bearer {key}"},
        json={
            "model": settings.XAI_IMAGE_MODEL,
            "prompt": prompt,
            "images": images,
            "response_format": "b64_json",
            "n": 1,
        },
        timeout=settings.XAI_TIMEOUT,
    )
    if response.status_code != 200:
        raise RuntimeError(f"xAI answered {response.status_code}: {_error_message(response)}")

    try:
        data = response.json().get("data") or []
        image_data = data[0].get("b64_json") if data else None
    except (ValueError, AttributeError, IndexError):
        image_data = None
    if not image_data:
        raise RuntimeError("Grok returned no image.")

    try:
        image_bytes = base64.b64decode(image_data, validate=True)
    except (ValueError, base64.binascii.Error) as exc:
        raise RuntimeError("Grok returned invalid image data.") from exc
    image = cv2.imdecode(np.frombuffer(image_bytes, np.uint8), cv2.IMREAD_COLOR)
    if image is None:
        raise RuntimeError("Grok returned an unreadable image.")
    return image
