import logging
import os
import re

import cv2
import numpy as np
import requests
from django.conf import settings
from django.http import HttpResponse, JsonResponse
from django.views.decorators.http import require_POST

from catalog.models import Dress

from .services import camera, dress_cache
from .services.overlay import blend_warped, cover_clothes, fit_quads, warp_dress
from .services.pose_detector import detect_body, smoother

logger = logging.getLogger(__name__)


def _error(message, status):
    return JsonResponse({"error": message}, status=status)


def _jpeg_response(img_bgr, person_detected):
    ok, buf = cv2.imencode(".jpg", img_bgr, [cv2.IMWRITE_JPEG_QUALITY, 85])
    if not ok:
        return _error("Could not encode the result image.", 500)
    resp = HttpResponse(buf.tobytes(), content_type="image/jpeg")
    resp["X-Person-Detected"] = "1" if person_detected else "0"
    resp["Cache-Control"] = "no-store"
    return resp


@require_POST  # CSRF is enforced by CsrfViewMiddleware (JS sends X-CSRFToken)
def tryon_api(request):
    # ---- 1. Validate inputs -------------------------------------------------
    upload = request.FILES.get("frame")
    if upload is None:
        return _error("Missing 'frame' file.", 400)
    if upload.size > settings.MAX_UPLOAD_MB * 1024 * 1024:
        return _error(f"Frame too large (max {settings.MAX_UPLOAD_MB} MB).", 413)
    if upload.content_type not in ("image/jpeg", "image/png"):
        return _error("Frame must be a JPEG or PNG image.", 415)

    try:
        dress_id = int(request.POST.get("dress_id", ""))
    except ValueError:
        return _error("dress_id must be an integer.", 400)

    row = (
        Dress.objects.filter(pk=dress_id, is_active=True)
        .exclude(image="")
        .values_list("image", "anchors", "sleeves")
        .first()
    )
    if not row:
        return _error("Dress not found.", 404)
    image_name, anchors, sleeves = row

    # ---- 2. Decode the frame (this also proves it really is an image) -------
    data = np.frombuffer(upload.read(), dtype=np.uint8)
    frame = cv2.imdecode(data, cv2.IMREAD_COLOR)
    if frame is None:
        return _error("Could not decode the image.", 400)

    # Downscale for speed
    h, w = frame.shape[:2]
    if w > settings.MAX_FRAME_WIDTH:
        scale = settings.MAX_FRAME_WIDTH / w
        frame = cv2.resize(frame, (settings.MAX_FRAME_WIDTH, int(h * scale)), interpolation=cv2.INTER_AREA)
        h, w = frame.shape[:2]

    dress_path = str(settings.MEDIA_ROOT / image_name)
    dress, dress_color = dress_cache.get_dress_image(dress_id, dress_path)
    if dress is None:
        return _error("Dress image file is missing on the server.", 500)

    # ---- 3. Pose detection --------------------------------------------------
    if not request.session.session_key:
        request.session.create()
    session_key = request.session.session_key

    try:
        detection = detect_body(frame)
    except Exception:  # noqa: BLE001
        logger.exception("Pose detection failed")
        return _error("Pose detection failed.", 500)

    if detection is None:
        smoother.reset(session_key)
        return _jpeg_response(frame, person_detected=False)

    points_norm = smoother.smooth(session_key, detection["points"])  # reduce jitter

    # ---- 4. Hide the customer's clothes, then warp + blend the dress ---------
    points_px = points_norm * np.array([w, h], dtype=np.float32)
    fit = fit_quads(points_px[:4], dress.shape, anchors, dress)  # shoulders + hips -> (src, dst) quads
    warped = warp_dress(frame.shape, dress, fit)
    result = frame
    if warped is not None:
        result = cover_clothes(
            frame, points_px, fit[1], detection["mask"], dress_color, sleeves,
            dress_alpha=warped[:, :, 3],
        )
        result = blend_warped(result, warped)
    return _jpeg_response(result, person_detected=True)


# =====================================================================
#  PHOTO MODE:  POST /api/tryon/photo/   (photo + dress_id) -> JPEG
# =====================================================================
@require_POST
def tryon_photo(request):
    from .services import engine_ai, engine_claude, engine_fashn, engine_gemini, engine_grok, engine_openai, engine_warp

    upload = request.FILES.get("photo")
    if upload is None:
        return _error("Missing 'photo' file.", 400)
    if upload.size > settings.MAX_PHOTO_MB * 1024 * 1024:
        return _error(f"Photo too large (max {settings.MAX_PHOTO_MB} MB).", 413)
    if upload.content_type not in ("image/jpeg", "image/png"):
        return _error("Photo must be a JPEG or PNG image.", 415)

    try:
        dress_id = int(request.POST.get("dress_id", ""))
    except ValueError:
        return _error("dress_id must be an integer.", 400)

    dress_obj = Dress.objects.filter(pk=dress_id, is_active=True).exclude(image="").first()
    if dress_obj is None:
        return _error("Dress not found.", 404)

    photo = cv2.imdecode(np.frombuffer(upload.read(), dtype=np.uint8), cv2.IMREAD_COLOR)
    if photo is None:
        return _error("Could not decode the photo.", 400)
    h, w = photo.shape[:2]
    if w > settings.MAX_PHOTO_WIDTH:
        photo = cv2.resize(photo, (settings.MAX_PHOTO_WIDTH, int(h * settings.MAX_PHOTO_WIDTH / w)),
                           interpolation=cv2.INTER_AREA)

    result, used, info = None, "warp", None
    ai_failed = False  # True when the chosen AI engine could not be used
    ai_reason = ""     # short, readable reason shown on the page

    # Optional: realistic AI engines. Any failure -> fall back to the warp engine.
    if settings.TRYON_ENGINE == "fashn":
        try:
            result = engine_fashn.render(photo, dress_obj.raw_image.path, dress_obj.garment_type)
            used = "fashn"
        except requests.exceptions.ConnectionError:
            logger.warning("FASHN server is not reachable at %s - is it running? Using the quick preview.",
                           settings.FASHN_SERVER_URL)
            result, ai_failed = None, True
            ai_reason = "the AI server is not reachable (is it running?)"
        except requests.exceptions.Timeout:
            logger.warning("FASHN server timed out after %s s", settings.FASHN_TIMEOUT)
            result, ai_failed = None, True
            ai_reason = f"the AI server took longer than {settings.FASHN_TIMEOUT} s (raise FASHN_TIMEOUT)"
        except Exception as exc:  # noqa: BLE001
            logger.exception("FASHN engine failed, falling back to warp")
            result, ai_failed = None, True
            ai_reason = str(exc)
    elif settings.TRYON_ENGINE == "openai":
        try:
            result = engine_openai.render(photo, dress_obj)
            used = "openai"
        except requests.exceptions.ConnectionError:
            logger.warning("Could not reach the OpenAI API. Using the quick preview.")
            result, ai_failed = None, True
            ai_reason = "OpenAI could not be reached (check the internet connection)"
        except requests.exceptions.Timeout:
            logger.warning("OpenAI took longer than %s s", settings.OPENAI_TIMEOUT)
            result, ai_failed = None, True
            ai_reason = f"OpenAI took longer than {settings.OPENAI_TIMEOUT} s (use OPENAI_IMAGE_QUALITY=low or medium)"
        except Exception as exc:  # noqa: BLE001  (the message never contains the key)
            logger.warning("OpenAI engine failed: %s", exc)
            result, ai_failed = None, True
            ai_reason = str(exc)
    elif settings.TRYON_ENGINE == "gemini":
        try:
            result = engine_gemini.render(photo, dress_obj)
            used = "gemini"
        except requests.exceptions.ConnectionError:
            logger.warning("Could not reach the Gemini API. Using the quick preview.")
            result, ai_failed = None, True
            ai_reason = "Gemini could not be reached (check the internet connection)"
        except requests.exceptions.Timeout:
            logger.warning("Gemini timed out after %s s", settings.GEMINI_TIMEOUT)
            result, ai_failed = None, True
            ai_reason = f"Gemini took longer than {settings.GEMINI_TIMEOUT} s"
        except Exception as exc:  # noqa: BLE001
            logger.warning("Gemini engine failed: %s", exc)
            result, ai_failed = None, True
            ai_reason = str(exc)
    elif settings.TRYON_ENGINE == "grok":
        try:
            result = engine_grok.render(photo, dress_obj)
            used = "grok"
        except requests.exceptions.ConnectionError:
            logger.warning("Could not reach the xAI API. Using the quick preview.")
            result, ai_failed = None, True
            ai_reason = "Grok could not be reached (check the internet connection)"
        except requests.exceptions.Timeout:
            logger.warning("Grok timed out after %s s", settings.XAI_TIMEOUT)
            result, ai_failed = None, True
            ai_reason = f"Grok took longer than {settings.XAI_TIMEOUT} s"
        except Exception as exc:  # noqa: BLE001
            logger.warning("Grok engine failed: %s", exc)
            result, ai_failed = None, True
            ai_reason = str(exc)
    elif settings.TRYON_ENGINE == "claude_grok":
        try:
            garment_guidance = engine_claude.analyze_garment(photo, dress_obj)
        except requests.exceptions.ConnectionError:
            logger.warning("Could not reach the Anthropic API. Using the quick preview.")
            result, ai_failed = None, True
            ai_reason = "Claude could not be reached (check the internet connection)"
        except requests.exceptions.Timeout:
            logger.warning("Claude timed out after %s s", settings.CLAUDE_TIMEOUT)
            result, ai_failed = None, True
            ai_reason = f"Claude took longer than {settings.CLAUDE_TIMEOUT} s"
        except Exception as exc:  # noqa: BLE001
            logger.warning("Claude analysis failed: %s", exc)
            result, ai_failed = None, True
            ai_reason = str(exc)

        if not ai_failed:
            try:
                result = engine_grok.render(photo, dress_obj, garment_guidance=garment_guidance)
                used = "claude_grok"
            except requests.exceptions.ConnectionError:
                logger.warning("Could not reach the xAI API. Using the quick preview.")
                result, ai_failed = None, True
                ai_reason = "Grok could not be reached (check the internet connection)"
            except requests.exceptions.Timeout:
                logger.warning("Grok timed out after %s s", settings.XAI_TIMEOUT)
                result, ai_failed = None, True
                ai_reason = f"Grok took longer than {settings.XAI_TIMEOUT} s"
            except Exception as exc:  # noqa: BLE001
                logger.warning("Grok engine failed after Claude analysis: %s", exc)
                result, ai_failed = None, True
                ai_reason = str(exc)
    elif settings.TRYON_ENGINE == "ai":
        garment, is_temp = None, False
        try:
            garment, is_temp = engine_ai.prepare_garment(dress_obj)   # upper-body garment on white
            person = engine_ai.portrait_crop(photo)                   # 3:4 portrait around the customer
            result = engine_ai.render(person, garment, dress_obj.name)
            used = "ai"
        except Exception:  # noqa: BLE001
            logger.exception("AI engine failed, falling back to warp")
            result, ai_failed = None, True
            ai_reason = "the AI Space call failed (see the server window)"
        finally:
            if is_temp and garment and os.path.exists(garment):
                os.remove(garment)

    if result is None:
        dress, dress_color = dress_cache.get_dress_image(dress_id, dress_obj.image.path)
        if dress is None:
            return _error("Dress image file is missing on the server.", 500)
        try:
            result, info = engine_warp.render(photo, dress, dress_color, dress_obj.anchors, dress_obj.sleeves)
        except Exception:  # noqa: BLE001
            logger.exception("Warp engine failed")
            return _error("Could not process the photo.", 500)
        used = "warp"

    if result is None:
        if ai_failed:
            return _error("The AI server is not available, and the quick preview could not find a person in the "
                          "photo either. Start the AI server, or stand back so your head, shoulders and hips are visible.", 422)
        return _error("No person detected. Please stand back so your head, shoulders and hips are visible.", 422)

    resp = _jpeg_response(result, person_detected=True)
    resp["X-Engine"] = used
    if ai_failed and ai_reason:  # header text must be plain ASCII on one line
        resp["X-AI-Error"] = re.sub(r"[^\x20-\x7E]", " ", ai_reason)[:200]
    if info is not None:
        resp["X-Hips-Visible"] = "1" if info["hips_ok"] else "0"  # 0 = person too close
        needs_legs = dress_obj.garment_type in ("one-pieces", "bottoms")
        resp["X-Full-Body"] = "0" if (needs_legs and not info["legs_ok"]) else "1"
    return resp


# =====================================================================
#  OPENCV CAPTURE:  POST /api/capture/  -> one JPEG from THIS computer's camera
# =====================================================================
@require_POST
def capture_photo(request):
    if settings.CAPTURE_MODE != "opencv":
        return _error("OpenCV capture is switched off (CAPTURE_MODE=browser).", 400)
    # The camera is on THIS machine. Only the machine itself may use it, so another device on the
    # network cannot take a picture of whoever stands at the kiosk.
    if not settings.CAPTURE_ALLOW_REMOTE and request.META.get("REMOTE_ADDR") not in ("127.0.0.1", "::1"):
        return _error("Camera capture is only allowed from this computer.", 403)
    try:
        frame = camera.capture_frame()
    except camera.CameraError as exc:
        logger.warning("Camera capture failed: %s", exc)
        return _error(str(exc), 503)
    ok, buf = cv2.imencode(".jpg", frame, [cv2.IMWRITE_JPEG_QUALITY, 92])
    if not ok:
        return _error("Could not encode the camera picture.", 500)
    resp = HttpResponse(buf.tobytes(), content_type="image/jpeg")
    resp["Cache-Control"] = "no-store"
    return resp
