from __future__ import annotations


def get_plotnine_all() -> str:
    """
    Generate package level * (star) imports for plotnine
    """
    from importlib import import_module

    modules = (
        "coords",
        "facets",
        "geoms",
        "ggplot",
        "guides",
        "labels",
        "mapping",
        "positions",
        "qplot",
        "scales",
        "stats",
        "themes",
        "themes.elements",
        "watermark",
    )

    def get_all_from_module(name):
        """
        Module level imports
        """
        qname = f"plotnine.{name}"
        m = import_module(qname)

        return sorted(m.__all__)

    imports = []
    all_funcs = []

    for name in modules:
        funcs = get_all_from_module(name)
        import_funcs = "\n    ".join(f"{x}," for x in funcs)
        imports.append(f"from .{name} import (\n    {import_funcs}\n)")
        all_funcs.extend(funcs)

    all_funcs = [f'    "{x}",' for x in sorted(all_funcs)]

    _imports = "\n".join(imports)
    _all = "__all__ = (\n" + "\n".join(all_funcs) + "\n)"

    return f"{_imports}\n\n{_all}"


def get_init_py() -> str:
    """
    Generate plotnine/__init__.py
    """

    preamble: str = """# Do not edit this file by hand.
#
# Generate it using:
#
# $ python -c 'from plotnine._utils import dev; print(dev.get_init_py())'

from importlib.metadata import PackageNotFoundError, version

try:
    __version__ = version("plotnine")
except PackageNotFoundError:
    # package is not installed
    pass
finally:
    del version
    del PackageNotFoundError

"""

    return preamble + get_plotnine_all()
