"""Package module autoloading utilities."""

import importlib
from pathlib import Path
from typing import Any


def _validate_package(package: Any) -> None:
    if not hasattr(package, "__name__") or not hasattr(package, "__path__"):
        raise TypeError("autoload requires an imported package object with __name__ and __path__")


def _iter_modules(package: Any) -> list[str]:
    module_names: list[str] = []
    for base_path in sorted(str(path) for path in package.__path__):
        base = Path(base_path)
        for path in sorted(base.rglob("*.py")):
            if path.name == "__init__.py":
                continue
            relative_parts = path.relative_to(base).with_suffix("").parts
            module_name = ".".join((package.__name__, *relative_parts))
            module_names.append(module_name)
    return module_names


def autoload(package: Any) -> None:
    """Recursively import all modules in a package."""

    _validate_package(package)
    for module_name in _iter_modules(package):
        importlib.import_module(module_name)


__all__ = ["autoload"]

