import logging
import os

from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.files.base import ContentFile
from django.core.validators import FileExtensionValidator
from django.db import models

from .services import image_utils

logger = logging.getLogger(__name__)


def validate_dress_size(file):
    """Reject oversized uploads. (ImageField itself verifies it is a real image.)"""
    limit = settings.MAX_DRESS_UPLOAD_MB * 1024 * 1024
    if file.size > limit:
        raise ValidationError(f"Image too large (max {settings.MAX_DRESS_UPLOAD_MB} MB).")


class Dress(models.Model):
    CATEGORY_CHOICES = [
        ("casual", "Casual"),
        ("party", "Party"),
        ("formal", "Formal"),
        ("traditional", "Traditional"),
    ]

    name = models.CharField(max_length=120)
    category = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default="casual")
    GARMENT_TYPES = [
        ("tops", "Top / jacket / suit jacket / shirt"),
        ("bottoms", "Bottoms (trousers, skirt)"),
        ("one-pieces", "Full-body (dress, gown, saree, jumpsuit)"),
    ]
    garment_type = models.CharField(
        max_length=12, choices=GARMENT_TYPES, default="one-pieces",
        help_text="Used by the AI try-on engine to know which part of the body to dress.",
    )
    price = models.DecimalField(max_digits=8, decimal_places=2, default=0)

    remove_model = models.BooleanField(
        "Remove model's face & skin",
        default=True,
        help_text="Keep ticked for photos of a person wearing the dress. "
                  "Untick for flat-lay / mannequin photos or dresses with skin-like colours.",
    )

    SLEEVE_CHOICES = [
        ("none", "Torso only (customer's own sleeves stay visible)"),
        ("elbow", "Cover the upper arms (short sleeves)"),
        ("wrist", "Cover the whole arms (full sleeves)"),
    ]
    sleeves = models.CharField(
        max_length=10, choices=SLEEVE_CHOICES, default="wrist",
        help_text="How much of the customer's own clothing to hide around the dress.",
    )

    # What the admin uploads (any photo of the dress on a plain-ish background)
    raw_image = models.ImageField(
        upload_to="dresses_raw/",
        validators=[FileExtensionValidator(["jpg", "jpeg", "png", "webp"]), validate_dress_size],
        help_text="Photo of the dress, front view. The background is removed automatically.",
    )
    # Generated automatically on save
    image = models.ImageField(upload_to="dresses/", blank=True, editable=False)
    thumbnail = models.ImageField(upload_to="thumbnails/", blank=True, editable=False)

    # Shoulder/hip positions found in the dress photo (used for a natural fit)
    anchors = models.JSONField(null=True, blank=True, editable=False)

    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-created_at"]

    def __str__(self):
        return self.name

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Remember which raw file we started with, to detect re-uploads.
        self._orig_raw = self.raw_image.name if self.pk else None
        self._orig_remove_model = self.remove_model if self.pk else None

    def save(self, *args, **kwargs):
        needs_processing = bool(self.raw_image) and (
            self._state.adding
            or self.raw_image.name != self._orig_raw
            or self.remove_model != self._orig_remove_model
            or not self.image
        )
        super().save(*args, **kwargs)  # first save writes raw_image to disk
        if needs_processing:
            self._process_images()
            self._orig_raw = self.raw_image.name
            self._orig_remove_model = self.remove_model

    def _process_images(self):
        """Remove background with rembg, store transparent PNG + 200px thumbnail."""
        try:
            self.raw_image.open("rb")
            try:
                raw_bytes = self.raw_image.read()
            finally:
                self.raw_image.close()

            dress_img, self.anchors = image_utils.extract_garment(raw_bytes, self.remove_model)
            thumb_img = image_utils.make_thumbnail(dress_img, 200)

            # Delete previously generated files so they don't pile up on disk
            if self.image:
                self.image.delete(save=False)
            if self.thumbnail:
                self.thumbnail.delete(save=False)

            base = os.path.splitext(os.path.basename(self.raw_image.name))[0]
            self.image.save(f"{base}.png", ContentFile(image_utils.to_png_bytes(dress_img)), save=False)
            self.thumbnail.save(f"{base}_thumb.png", ContentFile(image_utils.to_png_bytes(thumb_img)), save=False)
            # Save only the two generated fields (avoids re-triggering processing)
            models.Model.save(self, update_fields=["image", "thumbnail", "anchors"])
        except Exception:  # noqa: BLE001 - never lose the admin's upload because of a CV error
            logger.exception("Background removal failed for dress %s", self.pk)
