from __future__ import annotations

from ._types import parse_aspect_ratio

RESOLUTION_PRESETS: dict[str, tuple[int, int]] = {
    "360p": (640, 360),
    "480p": (854, 480),
    "720p": (1280, 720),
    "1080p": (1920, 1080),
    "2k": (2560, 1440),
    "4k": (3840, 2160),
}


def resolve_resolution(
    resolution: str,
    aspect_ratio: str | None = None,
) -> tuple[int, int]:
    """Compute ``(width, height)`` from a resolution spec.

    *resolution* can be:

    * A preset name like ``"1080p"``
    * An explicit ``"WxH"`` string like ``"1920x1080"``

    When an *aspect_ratio* (e.g. ``"9:16"``) is provided with a preset,
    the short-edge value from the preset determines the smaller dimension
    and the other is computed from the ratio.
    """
    if resolution in RESOLUTION_PRESETS:
        base_w, base_h = RESOLUTION_PRESETS[resolution]
        if aspect_ratio is None:
            return base_w, base_h

        ar_w, ar_h = parse_aspect_ratio(aspect_ratio)
        short_edge = min(base_w, base_h)

        if ar_w >= ar_h:
            h = short_edge
            w = int(round(h * ar_w / ar_h))
        else:
            w = short_edge
            h = int(round(w * ar_h / ar_w))

        w = w if w % 2 == 0 else w + 1
        h = h if h % 2 == 0 else h + 1
        return w, h

    if "x" in resolution:
        parts = resolution.split("x")
        if len(parts) == 2:
            try:
                w, h = int(parts[0]), int(parts[1])
                if w > 0 and h > 0:
                    return w, h
            except ValueError:
                pass

    raise ValueError(
        f"Unknown resolution: {resolution!r}. "
        f"Use a preset ({', '.join(RESOLUTION_PRESETS)}) or 'WxH' format."
    )
