"""Image pipeline: every uploaded photo becomes small, fast WebP files sized for the web.

For each photo we save three widths (400, 800, 1200 px) named <base>-400.webp, <base>-800.webp, <base>-1200.webp.
The product stores the 800 px URL; the storefront derives srcset from the naming pattern, so phones download the
400 px file (typically 15–35 KB) and desktops the 800/1200 px file. EXIF data (GPS, camera info) is stripped,
orientation is fixed, and images are never upscaled.
"""
import io
import os
import re
import uuid

from django.conf import settings
from PIL import Image, ImageOps

WIDTHS = (400, 800, 1200)
QUALITY = 72          # visually clean for product photos at a fraction of JPEG size
MAX_SOURCE_PX = 6000  # reject absurdly large images
FOLDER = "products"


def _safe_base(name, hint=""):
    base = re.sub(r"[^a-z0-9]+", "-", (hint or os.path.splitext(name)[0]).lower()).strip("-")[:60] or "image"
    return f"{base}-{uuid.uuid4().hex[:6]}"


def process(fileobj, filename, hint=""):
    """Compress an uploaded image. Returns {"url": <800w url>, "sizes": {w: bytes}}. Raises ValueError on bad input."""
    try:
        im = Image.open(fileobj)
        im.load()
    except Exception as e:  # noqa: BLE001 - any decode error means it's not a usable image
        raise ValueError("That file isn't a readable image.") from e
    if max(im.size) > MAX_SOURCE_PX:
        raise ValueError("Image is too large; please upload under 6000 px.")
    im = ImageOps.exif_transpose(im)           # respect phone rotation, then drop EXIF
    if im.mode in ("P", "LA"):
        im = im.convert("RGBA")
    if im.mode == "RGBA":
        # Product photos on white: flatten transparency onto white so every browser shows the same thing
        bg = Image.new("RGB", im.size, (255, 255, 255))
        bg.paste(im, mask=im.split()[-1])
        im = bg
    elif im.mode != "RGB":
        im = im.convert("RGB")

    folder = os.path.join(settings.MEDIA_ROOT, FOLDER)
    os.makedirs(folder, exist_ok=True)
    base = _safe_base(filename, hint)
    sizes = {}
    for w in WIDTHS:
        target = im if im.width <= w else im.resize((w, round(im.height * w / im.width)), Image.LANCZOS)
        buf = io.BytesIO()
        target.save(buf, "WEBP", quality=QUALITY, method=6)
        with open(os.path.join(folder, f"{base}-{w}.webp"), "wb") as out:
            out.write(buf.getvalue())
        sizes[w] = buf.tell()
    return {"url": f"{settings.MEDIA_URL}{FOLDER}/{base}-800.webp", "sizes": sizes}
