"""Module for asteex generators to create instances from Python modules and packages."""

import importlib
import pkgutil
import logging

from asteex.core.generator.group.abstract import GroupGenerator, GroupError


class ModuleGenerator(GroupGenerator):
    """Class for a generator that creates instances from Python modules and packages."""

    def get_subgroups(self, group):
        """Get subgroups of a group.

        :param group: string full name of the module or package.
        :returns: tuple with string names of the children of the group.
        :raises: :class:`GroupError` if a module is not a subpackage of the root or
            can't be imported.
        """
        group = str(group)

        logger = logging.getLogger(__name__)

        if (group != self.root) and (not group.startswith(f"{self.root}.")):
            logger.error("Module '%s' does not belong to the hierarchy.", group)
            raise GroupError(f"Module '{group}' does not belong to the hierarchy")

        try:
            module = importlib.import_module(group)
        except Exception as error:
            logger.exception("Failed to import the module '%s'.", group)
            raise GroupError(f"Failed to import the module '{group}'") from error

        module_path = getattr(module, "__path__", None)

        if module_path is None:
            submodules = ()
        else:
            submodules = tuple(
                f"{group}.{module_info.name}"
                for module_info in pkgutil.iter_modules(module_path)
            )

        return submodules
