"""
Rakam Systems — modular AI framework.

Sub-packages are accessible directly as attributes:

    import rakam_systems
    rakam_systems.vectorstore.ConfigurablePgVectorStore
    rakam_systems.agents.BaseAgent

    from rakam_systems import vectorstore, agents, core, tools

    import rakam_systems.vectorstore
"""

import sys
import importlib
from importlib.abc import MetaPathFinder, Loader
from importlib.machinery import ModuleSpec

_ALIASES: dict[str, str] = {
    "core": "rakam_systems_core",
    "agents": "rakam_systems_agent",
    "vectorstore": "rakam_systems_vectorstore",
    "tools": "rakam_systems_tools",
}

# Full dotted names that the finder handles.
_FULL_ALIASES = {f"rakam_systems.{k}": v for k, v in _ALIASES.items()}


class _AliasLoader(Loader):
    def __init__(self, real_name: str) -> None:
        self._real_name = real_name

    def create_module(self, spec):  # noqa: ANN001
        return importlib.import_module(self._real_name)

    def exec_module(self, module) -> None:  # noqa: ANN001
        pass  # module was fully initialised by importlib.import_module above


class _AliasFinder(MetaPathFinder):
    def find_spec(self, fullname, path, target=None):  # noqa: ANN001
        if fullname in _FULL_ALIASES:
            real_name = _FULL_ALIASES[fullname]
            return ModuleSpec(fullname, _AliasLoader(real_name))
        return None


# Register once — guard against re-registration on module reload.
if not any(isinstance(f, _AliasFinder) for f in sys.meta_path):
    sys.meta_path.append(_AliasFinder())


def __getattr__(name: str):
    """Handles `rakam_systems.vectorstore` attribute access."""
    if name in _ALIASES:
        real_pkg = _ALIASES[name]
        try:
            module = importlib.import_module(real_pkg)
        except ImportError as exc:
            raise ImportError(
                f"'rakam_systems.{name}' requires '{real_pkg}' to be installed."
            ) from exc
        sys.modules[f"rakam_systems.{name}"] = module
        globals()[name] = module
        return module
    raise AttributeError(f"module 'rakam_systems' has no attribute {name!r}")


__all__ = list(_ALIASES.keys())
