from __future__ import annotations
from PIL import Image
from PIL.Image import Resampling


MAX_METRIC_PIXELS = 1_000_000


def to_rgb(im: Image.Image) -> Image.Image:
    if im.mode != "RGB":
        rgb = im.convert("RGB")
    else:
        rgb = im
    return rgb


def downscale_for_metrics(im: Image.Image, max_pixels: int = MAX_METRIC_PIXELS) -> Image.Image:
    w, h = im.size
    if w * h <= max_pixels:
        return im
    scale = (max_pixels / (w * h)) ** 0.5
    new_w = max(1, int(w * scale))
    new_h = max(1, int(h * scale))
    return im.resize((new_w, new_h), Resampling.BOX)