# __init__.py — auto-export public API from _func_*.py modules, hide internals
from __future__ import annotations

import os as _os
import sys as _sys
import importlib as _importlib
from types import ModuleType as _ModuleType
from typing import Iterable as _Iterable

__all__: list[str] = []

# ---------------------------
# version
# ---------------------------
try:
    from ._version import __version__
except Exception:
    __version__ = "unknown"
__all__.append("__version__")

# ---------------------------
# config
# ---------------------------
_SKIP = {
    "annotations",  # from __future__ import annotations
    "__builtins__",
    "__cached__",
    "__doc__",
    "__loader__",
    "__package__",
    "__spec__",
    "__file__",
    "__name__",
    "__path__",
    "__versions__",
}
_PKG = __name__


def _unique(seq: _Iterable[str]) -> list[str]:
    seen, out = set(), []
    for s in seq:
        if s not in seen:
            seen.add(s)
            out.append(s)
    return out


def _debug(msg: str) -> None:
    if _os.environ.get("REPSIM_DEBUG_IMPORT", "").lower() in {"1", "true", "yes"}:
        print(f"[repsim:init] {msg}")


def _iter_func_modules() -> list[str]:
    """Find basenames of _func_*.py under this package."""
    stems: list[str] = []
    for base in getattr(_sys.modules[_PKG].__spec__, "submodule_search_locations", []):
        try:
            for fn in _os.listdir(base):
                if fn.startswith("_func_") and fn.endswith(".py"):
                    stems.append(fn[:-3])  # strip .py
        except FileNotFoundError:
            pass
    return sorted(set(stems))


def _export_from(mod: _ModuleType) -> list[str]:
    """Export exactly names declared in mod.__all__ (minus privates / _SKIP)."""
    if not hasattr(mod, "__all__"):
        _debug(f"{mod.__name__} has no __all__; skipping.")
        return []
    names = [
        n
        for n in mod.__all__
        if isinstance(n, str) and not n.startswith("_") and n not in _SKIP
    ]
    exported: list[str] = []
    for n in names:
        if not hasattr(mod, n):
            raise AttributeError(
                f"{mod.__name__} declares '{n}' in __all__ but does not define it. "
                "Define or import it in that file."
            )
        if n in globals():  # avoid duplicates cleanly
            _debug(f"skip duplicate export: {n}")
            continue
        globals()[n] = getattr(mod, n)
        exported.append(n)
        _debug(f"exported: {n}  (from {mod.__name__})")
    return exported


# discover & export
for stem in _iter_func_modules():
    try:
        m = _importlib.import_module(f".{stem}", _PKG)
    except Exception as e:
        _debug(f"skip {stem}: {e}")
        continue
    __all__.extend(_export_from(m))

# finalize public API
__all__ = _unique(__all__)

# -------- cleanup: remove internals from package namespace --------
for _name in [
    # helper modules / types
    "_os",
    "_sys",
    "_importlib",
    "_ModuleType",
    "_Iterable",
    # helper constants / functions
    "_PKG",
    "_SKIP",
    "_unique",
    "_debug",
    "_iter_func_modules",
    "_export_from",
    # temporary loop vars if any leaked in some shells
    "stem",
    "m",
    # hide the __future__ marker if present
    "annotations",
]:
    globals().pop(_name, None)
del _name  # final tiny cleanup


"""
# __init__.py (manual, explicit, robust)

from __future__ import annotations

# version
try:
    from ._version import __version__
except Exception:
    __version__ = "unknown"

# ---- Public API (explicit re-exports) ----
from ._func_repsim import repsim_hsic, repsim_kernels
from ._func_dot_product import dot_product
from ._func_pwcca import pwcca
from ._func_cka import cka
from ._func_cca import cca
from ._func_svcca import svcca
from ._func_hsic import hsic
from ._func_svcca import svcca

__all__ = [
    "__version__",
    "repsim_hsic",
    "repsim_kernels",
    "dot_product",
    "pwcca",
    "cka",
    "cca",
    "svcca",
    "hsic",
    "svcca",
]
"""
