"""LED Grab - Ambient lighting based on screen content."""

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

# Fallback version — patched at build time by build/build-dist.ps1 so the
# bundled Windows distribution reports the release version (the installer
# strips ledgrab-*.dist-info, so importlib.metadata fails there).
# In dev (running from source without `pip install -e .`) and on Android
# (Chaquopy embeds the source directly with no dist-info), we additionally
# read pyproject.toml so the version is always correct without manual sync.
_FALLBACK_VERSION = "0.4.2"


def _read_pyproject_version() -> str | None:
    """Read version from pyproject.toml (server/pyproject.toml relative to this file).

    Returns None if the file is absent (typical for installed/bundled distributions
    where pyproject.toml isn't shipped) or unreadable.
    """
    try:
        # __init__.py -> ledgrab/ -> src/ -> server/
        pyproject = Path(__file__).resolve().parents[2] / "pyproject.toml"
        if not pyproject.is_file():
            return None
        try:
            import tomllib  # Python 3.11+
        except ImportError:
            return None
        with pyproject.open("rb") as f:
            data = tomllib.load(f)
        v = data.get("project", {}).get("version")
        return v if isinstance(v, str) else None
    except Exception:
        return None


# Prefer pyproject.toml when it sits next to the source (dev checkout). This
# avoids stale `pip install -e .` dist-info pinning an older version after a
# bump. When pyproject.toml isn't shipped (installed packages, Windows bundle,
# Android), fall back to importlib.metadata, then the patched literal.
_live = _read_pyproject_version()
if _live:
    __version__ = _live
else:
    try:
        __version__ = version("ledgrab")
    except PackageNotFoundError:
        __version__ = _FALLBACK_VERSION

__author__ = "Alexei Dolgolyov"
__email__ = "dolgolyov.alexei@gmail.com"

# ─── Project links ───────────────────────────────────────────
GITEA_BASE_URL = "https://git.dolgolyov-family.by"
GITEA_REPO = "alexei.dolgolyov/ledgrab"
REPO_URL = f"{GITEA_BASE_URL}/{GITEA_REPO}"
DONATE_URL = ""  # TODO: set once donation platform is chosen
