"""Version helpers for the backend service."""

from __future__ import annotations

import os
from importlib.metadata import PackageNotFoundError
from importlib.metadata import version as package_version

PACKAGE_NAME = "media-library-viewer-backend"
DEFAULT_VERSION = "0.1.0"


def get_backend_version() -> str:
    """Return the packaged backend version or a stable fallback."""
    env_version = os.getenv("APP_VERSION", "").strip()
    if env_version:
        return env_version
    try:
        return package_version(PACKAGE_NAME)
    except PackageNotFoundError:
        return DEFAULT_VERSION


def get_backend_build_info() -> str:
    """Return a short build marker such as a git SHA or dev marker."""
    return (
        os.getenv("APP_BUILD_INFO", "").strip()
        or os.getenv("GIT_COMMIT", "").strip()
        or os.getenv("BUILD_COMMIT", "").strip()
        or "dev"
    )


def format_version_label(version: str, build_info: str) -> str:
    """Format a user-facing version label."""
    label = version.strip() or DEFAULT_VERSION
    build = build_info.strip()
    if build and build != "dev":
        return f"{label}+{build}"
    return label


def get_version_info() -> dict[str, str]:
    version = get_backend_version()
    build_info = get_backend_build_info()
    return {
        "app": "Manage",
        "backend_version": version,
        "backend_build": build_info,
        "backend_label": format_version_label(version, build_info),
    }
