"""Image assets (TZ 2.6.7, 2.10.2): validation, normalisation, dedupe, thumbnails."""

from __future__ import annotations

import hashlib
import io
from typing import Any

from django.db import IntegrityError, transaction
from PIL import Image, ImageOps, UnidentifiedImageError

from snapfile.core import ids
from snapfile.core.errors import ApiError
from snapfile.core.storage import store
from snapfile.projects.models import Project
from snapfile_render.svg import SvgError, looks_like_svg, sanitize_svg, svg_thumbnail

from .models import Asset

Image.MAX_IMAGE_PIXELS = 100_000_000
MAX_SIDE = 12_000
THUMB_SIDE = 320
_FORMAT_MIME = {
    "PNG": "image/png",
    "JPEG": "image/jpeg",
    "WEBP": "image/webp",
    "GIF": "image/gif",
    "TIFF": "image/tiff",
    "BMP": "image/bmp",
}


def _inspect(data: bytes) -> Image.Image:
    try:
        with Image.open(io.BytesIO(data)) as probe:
            probe.verify()
        img = Image.open(io.BytesIO(data))
    except (UnidentifiedImageError, OSError, SyntaxError, Image.DecompressionBombError) as exc:
        raise ApiError(415, "UNSUPPORTED_MEDIA_TYPE", "File is not a supported image") from exc
    if img.width > MAX_SIDE or img.height > MAX_SIDE:
        raise ApiError(422, "IMAGE_TOO_LARGE", f"Image exceeds {MAX_SIDE}x{MAX_SIDE} px")
    return img


def _normalise(data: bytes, img: Image.Image) -> tuple[bytes, str, str]:
    """Return (bytes, mime, ext). JPEG/PNG kept as-is unless EXIF rotation is needed; others converted."""
    fmt = (img.format or "").upper()
    orientation = 1
    try:
        orientation = int(img.getexif().get(0x0112, 1))
    except Exception:
        orientation = 1
    if fmt in ("JPEG", "PNG") and orientation in (0, 1):
        return data, _FORMAT_MIME[fmt], "jpg" if fmt == "JPEG" else "png"
    img.load()
    img = ImageOps.exif_transpose(img)
    has_alpha = img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info)
    buf = io.BytesIO()
    if fmt == "JPEG" or (not has_alpha and fmt not in ("PNG", "GIF")):
        img.convert("CMYK" if img.mode == "CMYK" else "RGB").save(buf, "JPEG", quality=90, optimize=True)
        return buf.getvalue(), "image/jpeg", "jpg"
    img.convert("RGBA" if has_alpha else "RGB").save(buf, "PNG", optimize=True)
    return buf.getvalue(), "image/png", "png"


def _thumbnail(data: bytes) -> tuple[bytes, str]:
    with Image.open(io.BytesIO(data)) as img:
        img.thumbnail((THUMB_SIDE, THUMB_SIDE), Image.Resampling.LANCZOS)
        buf = io.BytesIO()
        if img.mode in ("RGBA", "LA", "P"):
            img.convert("RGBA").save(buf, "PNG", optimize=True)
            return buf.getvalue(), "png"
        img.convert("RGB").save(buf, "JPEG", quality=82, optimize=True)
        return buf.getvalue(), "jpg"


def upload_image(
    project: Project,
    name: str,
    data: bytes,
    folder: str | None,
    actor: dict[str, Any] | None,
    max_mb: int = 20,
    source_url: str | None = None,
) -> tuple[Asset, bool]:
    if len(data) > max_mb * 1024 * 1024:
        raise ApiError(413, "FILE_TOO_LARGE", f"Image exceeds {max_mb} MB")
    is_svg = looks_like_svg(data=data)
    sha = hashlib.sha256(data).hexdigest()
    existing = Asset.objects.filter(project=project, sha256=sha).first()
    if existing is not None:
        if existing.deleted_at is not None:
            existing.deleted_at = None
            existing.save(update_fields=["deleted_at", "updated_at"])
        return existing, True
    if is_svg:
        try:
            stored, (width, height) = sanitize_svg(data)
            thumb, thumb_ext = svg_thumbnail(stored, THUMB_SIDE), "png"
        except SvgError as exc:
            raise ApiError(415, "UNSUPPORTED_MEDIA_TYPE", f"Invalid SVG: {exc}") from exc
        mime, ext, has_alpha, mode, dpi_info = "image/svg+xml", "svg", True, "RGBA", None
    else:
        img = _inspect(data)
        stored, mime, ext = _normalise(data, img)
        with Image.open(io.BytesIO(stored)) as final:
            width, height = final.width, final.height
            has_alpha = final.mode in ("RGBA", "LA") or (final.mode == "P" and "transparency" in final.info)
            mode = final.mode
            dpi_info = final.info.get("dpi")
        thumb, thumb_ext = _thumbnail(stored)
    st = store()
    rel = f"projects/{project.id}/assets/{sha[:2]}/{sha}.{ext}"
    st.write(rel, stored)
    thumb_rel = f"projects/{project.id}/assets/variants/{sha}/thumb.{thumb_ext}"
    st.write(thumb_rel, thumb)
    try:
        with transaction.atomic():
            asset = Asset.objects.create(
                project=project,
                folder=folder or None,
                name=(name or f"image.{ext}")[:255],
                kind="image",
                mime=mime,
                sha256=sha,
                size_bytes=len(stored),
                width_px=width,
                height_px=height,
                dpi=int(dpi_info[0]) if dpi_info else None,
                has_alpha=has_alpha,
                color_space={"CMYK": "cmyk", "L": "gray", "LA": "gray"}.get(mode, "rgb"),
                path=rel,
                variants={"thumb": thumb_rel},
                source_url=source_url,
                created_by=actor,
            )
    except IntegrityError:
        return Asset.objects.get(project=project, sha256=sha), True
    return asset, False


def asset_dict(a: Asset, deduplicated: bool | None = None) -> dict[str, Any]:
    aid = ids.encode("ast", a.id)
    out = {
        "id": aid,
        "name": a.name,
        "folder": a.folder,
        "kind": a.kind,
        "mime": a.mime,
        "sha256": a.sha256,
        "size_bytes": a.size_bytes,
        "width_px": a.width_px,
        "height_px": a.height_px,
        "has_alpha": a.has_alpha,
        "color_space": a.color_space,
        "file_url": f"/internal/v1/assets/{aid}/file",
        "thumb_url": f"/internal/v1/assets/{aid}/file?variant=thumb",
        "created_at": a.created_at.isoformat(),
    }
    if deduplicated is not None:
        out["deduplicated"] = deduplicated
    return out
