from importlib.metadata import PackageNotFoundError, version
from importlib.resources import files
from pathlib import Path


def _checkout_version() -> str | None:
    current = Path(__file__).resolve()
    for parent in current.parents:
        candidate = parent / "VERSION"
        if candidate.is_file():
            value = candidate.read_text(encoding="utf-8").strip()
            if value:
                return value
    return None


def get_version() -> str:
    """Return the checkout VERSION, or installed package metadata as fallback."""
    checkout = _checkout_version()
    if checkout:
        return checkout
    try:
        bundled = files("ccma").joinpath("VERSION").read_text(encoding="utf-8").strip()
        if bundled:
            return bundled
    except (FileNotFoundError, ModuleNotFoundError):
        pass
    try:
        return version("ccma")
    except PackageNotFoundError:
        return "0+unknown"
