"""Image processing utilities for Vision AI — resize and base64 encoding."""

from __future__ import annotations

import base64
import io
import logging

from PIL import Image

log = logging.getLogger(__name__)


def resize_image(
    img: Image.Image,
    max_width: int = 1024,
    max_height: int = 768,
    *,
    max_size: int | None = None,
) -> Image.Image:
    """Downscale image if it exceeds the maximum resolution cap.

    New rule (2026-03-13):
      - If screenshot is LARGER than 1920x1080 -> resize to fit within
        1920x1080 while maintaining aspect ratio (cap width at 1920,
        cap height at 1080, scale by whichever limit is hit first).
      - If screenshot is SMALLER or EQUAL to 1920x1080 -> return as-is.

    The ``max_size`` parameter is accepted for backward compatibility but
    ignored — the 1920x1080 cap is always used.

    Args:
        img: PIL Image to resize.
        max_width: Maximum width in pixels (default 1920).
        max_height: Maximum height in pixels (default 1080).
        max_size: **Deprecated / ignored.** Kept for call-site compat.

    Returns:
        Resized (or original) PIL Image.
    """
    width, height = img.size

    # Already within limits — return unchanged
    if width <= max_width and height <= max_height:
        return img

    # Compute scale factor: fit within max_width x max_height box
    scale = min(max_width / width, max_height / height)
    new_width = max(1, int(width * scale))
    new_height = max(1, int(height * scale))

    log.debug(
        "Resizing image %dx%d -> %dx%d (cap %dx%d)",
        width,
        height,
        new_width,
        new_height,
        max_width,
        max_height,
    )
    resample = getattr(Image, "Resampling", Image).BILINEAR
    return img.resize((new_width, new_height), resample)


def preprocess_for_ocr(img: Image.Image) -> Image.Image:
    """Enhance image contrast and sharpness for better OCR accuracy.

    Applies mild contrast boost and sharpening so that text is clearer
    for the vision model — especially on low-DPI or scaled screens.

    Args:
        img: PIL Image to preprocess.

    Returns:
        Enhanced PIL Image.
    """
    try:
        from PIL import ImageEnhance
        img = ImageEnhance.Contrast(img).enhance(1.4)
        img = ImageEnhance.Sharpness(img).enhance(1.6)
    except Exception:
        pass
    return img


def image_to_base64(img: Image.Image, quality: int = 85) -> str:
    """Convert a PIL Image to a base64-encoded JPEG string.

    Args:
        img: PIL Image (any mode — converted to RGB internally).
        quality: JPEG quality 1–95. Default 85 balances size and quality.

    Returns:
        Base64 string (no data URI prefix).
    """
    buf = io.BytesIO()
    img.convert("RGB").save(buf, format="JPEG", quality=quality, optimize=False)
    encoded = base64.b64encode(buf.getvalue()).decode("ascii")
    log.debug(
        "Image encoded to base64: %dx%d → %d bytes (quality=%d)",
        img.size[0],
        img.size[1],
        len(encoded),
        quality,
    )
    return encoded
