"""BanGUI backend application package.

This package exposes the application version based on the project metadata.
"""

from __future__ import annotations

from pathlib import Path
from typing import Final

import importlib.metadata
import tomllib

PACKAGE_NAME: Final[str] = "bangui-backend"


def _read_pyproject_version() -> str:
    """Read the project version from ``pyproject.toml``.

    This is used as a fallback when the package metadata is not available (e.g.
    when running directly from a source checkout without installing the package).
    """

    project_root = Path(__file__).resolve().parents[1]
    pyproject_path = project_root / "pyproject.toml"
    if not pyproject_path.exists():
        raise FileNotFoundError(f"pyproject.toml not found at {pyproject_path}")

    data = tomllib.loads(pyproject_path.read_text(encoding="utf-8"))
    return str(data["project"]["version"])


def _read_docker_version() -> str:
    """Read the project version from ``Docker/VERSION``.

    This file is the single source of truth for release scripts and must not be
    out of sync with the frontend and backend versions.
    """

    repo_root = Path(__file__).resolve().parents[2]
    version_path = repo_root / "Docker" / "VERSION"
    if not version_path.exists():
        raise FileNotFoundError(f"Docker/VERSION not found at {version_path}")

    version = version_path.read_text(encoding="utf-8").strip()
    return version.lstrip("v")


def _read_version() -> str:
    """Return the current package version.

    Prefer the release artifact in ``Docker/VERSION`` when available so the
    backend version always matches what the release tooling publishes.

    If that file is missing (e.g. in a production wheel or a local checkout),
    fall back to ``pyproject.toml`` and finally installed package metadata.
    """

    try:
        return _read_docker_version()
    except FileNotFoundError:
        try:
            return _read_pyproject_version()
        except FileNotFoundError:
            return importlib.metadata.version(PACKAGE_NAME)


__version__ = _read_version()
