from __future__ import annotations

import importlib.metadata as metadata
import sys
from pathlib import Path


_FALLBACK_VERSIONS = {
    "paramiko": "5.0.0",
    "bcrypt": "5.0.0",
    "cryptography": "48.0.0",
    "pynacl": "1.6.2",
    "pyNaCl".lower(): "1.6.2",
}


def _append_runtime_metadata_paths() -> None:
    """补充 PyInstaller 运行目录，避免第三方库查询版本元数据时找不到 dist-info。"""
    candidates: list[Path] = []
    meipass = getattr(sys, "_MEIPASS", "")
    if meipass:
        candidates.append(Path(meipass))
    if getattr(sys, "frozen", False):
        exe_dir = Path(sys.executable).resolve().parent
        candidates.append(exe_dir / "_internal")
        candidates.append(exe_dir)

    for candidate in candidates:
        try:
            path = str(candidate.resolve())
        except OSError:
            continue
        if path not in sys.path:
            sys.path.append(path)


def ensure_package_metadata_fallbacks() -> None:
    """为打包环境增加第三方库版本兜底，防止缺少元数据时启动崩溃。"""
    _append_runtime_metadata_paths()
    if getattr(metadata.version, "_wawacloud_patched", False):
        return

    original_version = metadata.version

    def safe_version(distribution_name: str) -> str:
        try:
            return original_version(distribution_name)
        except metadata.PackageNotFoundError:
            fallback = _FALLBACK_VERSIONS.get(str(distribution_name).lower())
            if fallback:
                return fallback
            raise

    setattr(safe_version, "_wawacloud_patched", True)
    metadata.version = safe_version
