"""Version comparison utilities.

Normalizes Gitea-style tags (v0.3.0-alpha.1) to PEP 440 (0.3.0a1)
so that ``packaging.version.Version`` can compare them correctly.
"""

import logging
import re

from packaging.version import InvalidVersion, Version

logger = logging.getLogger(__name__)


_PRE_MAP = {
    "alpha": "a",
    "beta": "b",
    "rc": "rc",
}

_PRE_PATTERN = re.compile(
    r"^(\d+\.\d+\.\d+)[-.]?(alpha|beta|rc)[.-]?(\d+)$", re.IGNORECASE
)


def normalize_version(raw: str) -> Version:
    """Convert a tag like ``v0.3.0-alpha.1`` to a PEP 440 ``Version``.

    Raises ``InvalidVersion`` if the string cannot be parsed.
    """
    cleaned = raw.lstrip("v").strip()
    m = _PRE_PATTERN.match(cleaned)
    if m:
        base, pre_label, pre_num = m.group(1), m.group(2).lower(), m.group(3)
        pep_label = _PRE_MAP.get(pre_label, pre_label)
        cleaned = f"{base}{pep_label}{pre_num}"
    return Version(cleaned)


def is_newer(candidate: str, current: str) -> bool:
    """Return True if *candidate* is strictly newer than *current*.

    Returns False if either version string is unparseable.
    """
    try:
        return normalize_version(candidate) > normalize_version(current)
    except InvalidVersion as e:
        logger.debug("Unparseable version string in comparison: %s", e)
        return False
