# __init__.py
from __future__ import annotations

from importlib import import_module as _import_module
from pkgutil import iter_modules as _iter_modules
from types import ModuleType as _ModuleType
import inspect as _inspect
from typing import Iterable as _Iterable

__all__: list[str] = []

# Skip internals but *not* the global __version__ defined in _version.py
_SKIP_NAMES = {
    "annotations",
    "__builtins__",
    "__cached__",
    "__doc__",
    "__loader__",
    "__package__",
    "__spec__",
    "__file__",
    "__name__",
    "__path__",
    "__versions__",  # plural only skipped
}


def _unique_sorted(seq: _Iterable[str]) -> list[str]:
    return sorted(set(seq))


def _export_from_module(mod: _ModuleType) -> list[str]:
    """
    Collect exportable names from a module and inject them into package globals.

    Preference:
      1) If module defines __all__, export those names (minus _SKIP_NAMES and privates).
      2) Else, export top-level functions defined in that module (non-private).
    """
    if hasattr(mod, "__all__"):
        candidates = [n for n in mod.__all__ if isinstance(n, str)]
        names = [
            n
            for n in candidates
            if not n.startswith("_") and n not in _SKIP_NAMES and hasattr(mod, n)
        ]
    else:
        names = [
            n
            for n, obj in vars(mod).items()
            if (not n.startswith("_"))
            and (n not in _SKIP_NAMES)
            and _inspect.isfunction(obj)
            and getattr(obj, "__module__", None) == mod.__name__
        ]

    exported: list[str] = []
    for n in names:
        if n in globals():
            raise RuntimeError(
                f"Duplicate export name '{n}' encountered when importing {mod.__name__}. "
                "Rename the symbol or adjust __all__ to resolve the conflict."
            )
        globals()[n] = getattr(mod, n)
        exported.append(n)
    return exported


# 1. Load the version info first
try:
    from ._version import __version__

    __all__.append("__version__")
except ImportError:
    __version__ = "unknown"

# 2. Discover, import, and export from all _func_*.py modules in this package
for _m in _iter_modules(list(__path__)):  # __path__ exists for packages
    if _m.ispkg:
        continue
    if _m.name.startswith("_func_"):
        _mod = _import_module(f".{_m.name}", __name__)
        __all__.extend(_export_from_module(_mod))

# 3. Make __all__ deterministic and unique
__all__ = _unique_sorted(__all__)

# Clean up internals
del (
    _import_module,
    _iter_modules,
    _ModuleType,
    _inspect,
    _export_from_module,
    _unique_sorted,
    _Iterable,
    _m,
)
