from __future__ import annotations

from importlib.metadata import PackageNotFoundError, packages_distributions, version as _dist_version
from pathlib import Path

__all__ = ["__version__"]

_FALLBACK_VERSION = "0.2.0b1099"


def _resolve_local_pyproject_version() -> str | None:
    module_path = Path(__file__).resolve()
    for parent in module_path.parents:
        candidate = parent / "pyproject.toml"
        if not candidate.is_file():
            continue
        for line in candidate.read_text(encoding="utf-8").splitlines():
            stripped = line.strip()
            if stripped.startswith("version = "):
                return stripped.split("=", 1)[1].strip().strip('"')
        break
    return None


def _resolve_runtime_version() -> str:
    local_version = _resolve_local_pyproject_version()
    if local_version:
        return local_version
    for dist_name in packages_distributions().get("qingflow_mcp", []):
        try:
            return _dist_version(dist_name)
        except PackageNotFoundError:
            continue
    return _FALLBACK_VERSION


__version__ = _resolve_runtime_version()
