"""Image compression utility — resize and compress before GDrive upload."""

import io


def compress_image(file_bytes: bytes, max_px: int = 1280, quality: int = 75) -> bytes:
    """
    Resize image to max_px on longest side (maintain aspect ratio) and
    compress to JPEG at given quality. Returns compressed JPEG bytes.

    Typical result: 100–300 KB vs original 3–8 MB.
    """
    from PIL import Image

    img = Image.open(io.BytesIO(file_bytes))

    # Convert to RGB (handles PNG with alpha, CMYK, etc.)
    if img.mode not in ("RGB", "L"):
        img = img.convert("RGB")

    # Resize only if larger than max_px
    w, h = img.size
    if max(w, h) > max_px:
        ratio = max_px / max(w, h)
        img = img.resize((int(w * ratio), int(h * ratio)), Image.LANCZOS)

    buf = io.BytesIO()
    img.save(buf, format="JPEG", quality=quality, optimize=True)
    return buf.getvalue()
