"""Compose a clean 16:9 fanart image for media servers (Infuse, Emby)."""

import os

from PIL import Image, ImageFilter

FANART_SUFFIX = "-fanart"
FANART_WIDTH_4K = 3840
FANART_HEIGHT_4K = 2160
FANART_WIDTH_HD = 1920
FANART_HEIGHT_HD = 1080

_ASPECT_16_9 = 16.0 / 9.0
_ASPECT_TOLERANCE = 0.02


def compose_fanart(
    frame_path: str,
    output_path: str,
    is_4k: bool = False,
) -> str:
    """Compose a clean 16:9 fanart image for Infuse/Emby.

    Uses blurred background fill for non-16:9 sources.
    Returns the absolute path of the created fanart image.

    Parameters
    ----------
    frame_path:
        Path to the source JPEG frame (already converted to sRGB by the pipeline).
    output_path:
        Destination path for the fanart JPEG.
    is_4k:
        When ``True`` the output is 3840×2160; otherwise 1920×1080.

    Returns
    -------
    The absolute path of the created fanart image.
    """
    target_w = FANART_WIDTH_4K if is_4k else FANART_WIDTH_HD
    target_h = FANART_HEIGHT_4K if is_4k else FANART_HEIGHT_HD

    with Image.open(frame_path) as src:
        src = src.convert("RGB")
        src_w, src_h = src.size

        src_ratio = src_w / src_h
        target_ratio = target_w / target_h

        if abs(src_ratio - target_ratio) <= _ASPECT_TOLERANCE:
            # Already 16:9 – simple resize
            result = src.resize((target_w, target_h), Image.LANCZOS)
        else:
            # ── Blurred background approach ───────────────────────────────────
            # Background: scale to *fill* target (may exceed bounds), crop, blur
            scale_fill = max(target_w / src_w, target_h / src_h)
            fill_w = int(src_w * scale_fill)
            fill_h = int(src_h * scale_fill)
            bg = src.resize((fill_w, fill_h), Image.LANCZOS)
            # Centre-crop to exact target size
            left = (fill_w - target_w) // 2
            top = (fill_h - target_h) // 2
            bg = bg.crop((left, top, left + target_w, top + target_h))
            bg = bg.filter(ImageFilter.GaussianBlur(radius=20))

            # Foreground: scale to *fit* within target (no cropping)
            scale_fit = min(target_w / src_w, target_h / src_h)
            fg_w = int(src_w * scale_fit)
            fg_h = int(src_h * scale_fit)
            fg = src.resize((fg_w, fg_h), Image.LANCZOS)

            # Composite centred foreground over blurred background
            result = bg.copy()
            paste_x = (target_w - fg_w) // 2
            paste_y = (target_h - fg_h) // 2
            result.paste(fg, (paste_x, paste_y))

        result.save(output_path, "JPEG", quality=92)

    return os.path.abspath(output_path)
