"""Package version. 作为依赖安装到他人项目时，从该环境已安装包元数据读取；未安装则从仓库 pyproject.toml 读取。"""

from pathlib import Path
import re

# 与 pyproject.toml [project] name 一致，pip/uv 安装后元数据用此名
_DIST_NAME = "mingx-v2"


def _get_version() -> str:
    # 1. 已安装时：从当前环境的包元数据取（他人项目 uv add / pip install mingx-v2 后即走此分支）
    try:
        from importlib.metadata import version, PackageNotFoundError
        return version(_DIST_NAME)
    except PackageNotFoundError:
        pass
    except Exception:
        pass
    # 2. 未安装（如本仓库内 uv run）：从仓库根目录 pyproject.toml 读取
    try:
        root = Path(__file__).resolve().parent.parent.parent
        pyproject = root / "pyproject.toml"
        if pyproject.exists():
            text = pyproject.read_text(encoding="utf-8")
            m = re.search(r'^version\s*=\s*["\']([^"\']+)["\']', text, re.MULTILINE)
            if m:
                return m.group(1)
    except Exception:
        pass
    return "0.0.0"


__version__ = _get_version()
