"""Media Server - REST API for controlling system media playback."""

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

_VERSION_RE = re.compile(r'^version\s*=\s*"([^"]+)"', re.MULTILINE)


def _detect_version() -> str:
    # 1. Live pyproject.toml — only present in dev checkouts. Prefer this
    # over installed package metadata so `pip install -e .` users don't
    # see stale versions after editing pyproject.toml without reinstalling.
    pyproject = Path(__file__).resolve().parent.parent / "pyproject.toml"
    if pyproject.is_file():
        try:
            match = _VERSION_RE.search(pyproject.read_text(encoding="utf-8"))
            if match:
                return match.group(1)
        except OSError:
            pass

    # 2. Package metadata (works for any pip-installed copy).
    try:
        return version("media-server")
    except PackageNotFoundError:
        pass

    # 3. VERSION file written by build scripts (production builds).
    version_file = Path(__file__).resolve().parent.parent.parent / "VERSION"
    if version_file.is_file():
        return version_file.read_text().strip()

    return "0.0.0-dev"


__version__ = _detect_version()
