"""Technical badge generation and detection for video properties."""

from PIL import Image, ImageDraw

from .fonts import get_system_font


# Base badge types that can be detected (HFR variants are generated dynamically)
BADGE_TYPES = ["4k", "hdr", "hd"]


def detect_badges(video_properties: dict) -> list[str]:
    """Determine which badges apply based on video properties.

    Returns a list of badge type strings, e.g. ["4k", "hdr"] or ["hd"].
    When the video is HFR (fps >= 48), the resolution badge includes the
    frame rate, e.g. "4k60", "4k48", "hd60".
    Order: resolution first, then HDR.
    """
    badges = []
    fps = video_properties.get("fps", 0.0)
    is_hfr = fps >= 48
    fps_int = round(fps) if is_hfr else 0

    if video_properties.get("is_4k"):
        badges.append(f"4k{fps_int}" if is_hfr else "4k")
    elif video_properties.get("is_hd"):
        badges.append(f"hd{fps_int}" if is_hfr else "hd")
    if video_properties.get("is_hdr"):
        badges.append("hdr")
    return badges


def load_badge_image(badge_type: str) -> Image.Image:
    """Generate a badge image for the given type using Pillow.

    Technical badges are always generated programmatically from text.
    Returns an RGBA PIL Image.
    """
    return _generate_badge(badge_type)


def _generate_badge(badge_type: str) -> Image.Image:
    """Generate a simple, elegant badge programmatically.

    Creates a small rounded-corner rectangle with text, similar to
    Blu-ray cover badges. Semi-transparent background with white text
    and a subtle border.

    Badge text mapping:
    - "4k" → "4K"
    - "hdr" → "HDR"
    - "hd" → "HD"
    - "4k60" → "4K60", "hd48" → "HD48", etc. (HFR variants)
    """
    text_map = {
        "4k": "4K",
        "hdr": "HDR",
        "hd": "HD",
    }
    text = text_map.get(badge_type, badge_type.upper())

    # Badge dimensions
    height = 28
    padding_h = 12  # horizontal padding

    font_size = 14
    font = get_system_font(font_size, bold=True)

    # Measure text to determine badge width
    dummy = Image.new("RGBA", (1, 1))
    draw = ImageDraw.Draw(dummy)
    bbox = draw.textbbox((0, 0), text, font=font)
    text_width = bbox[2] - bbox[0]
    width = text_width + padding_h * 2

    # Create badge image
    badge = Image.new("RGBA", (width, height), (0, 0, 0, 0))
    draw = ImageDraw.Draw(badge)

    # Background: semi-transparent dark
    draw.rounded_rectangle(
        [0, 0, width - 1, height - 1],
        radius=4,
        fill=(40, 40, 40, 200),
        outline=(120, 120, 120, 180),
        width=1,
    )

    # Text: white, centered
    text_x = width // 2
    text_y = height // 2
    draw.text(
        (text_x, text_y),
        text,
        fill=(255, 255, 255, 230),
        font=font,
        anchor="mm",
    )

    return badge


def render_badges_on_image(
    image: Image.Image,
    badges: list[str],
    x_start: int,
    y_center: int,
    max_width: int,
    badge_height: int = 28,
    spacing: int = 6,
) -> int:
    """Render badge images onto the poster at the specified position.

    Badges are placed left-to-right starting at (x_start, y_center - badge_height//2).
    Each badge is scaled to the target badge_height while maintaining aspect ratio.

    Args:
        image: The poster image to draw on (modified in place).
        badges: List of badge type strings, e.g. ["4k", "hdr"].
        x_start: Left edge x coordinate for the first badge.
        y_center: Vertical center line for badges (same as note text baseline area).
        max_width: Maximum total width available for badges.
        badge_height: Target height for each badge in pixels.
        spacing: Horizontal spacing between badges.

    Returns:
        The total width consumed by all badges + spacing (for note text wrapping).
    """
    if not badges:
        return 0

    # Convert to RGBA for alpha compositing
    was_rgb = image.mode == "RGB"
    if was_rgb:
        image_rgba = image.convert("RGBA")
    else:
        image_rgba = image

    total_width = 0
    x = x_start

    for badge_type in badges:
        badge_img = load_badge_image(badge_type)

        # Scale to target height
        orig_w, orig_h = badge_img.size
        scale = badge_height / orig_h
        new_w = int(orig_w * scale)
        badge_img = badge_img.resize((new_w, badge_height), Image.LANCZOS)

        # Check if we exceed max width
        if total_width + new_w > max_width:
            break

        # Paste with alpha
        y = y_center - badge_height // 2
        image_rgba.paste(badge_img, (x, y), mask=badge_img)

        x += new_w + spacing
        total_width = x - x_start

    # Copy back to original image if needed
    if was_rgb:
        rgb_result = image_rgba.convert("RGB")
        image.paste(rgb_result)

    return total_width
