import builtins
import importlib
from types import ModuleType


def try_import(name: str, alias: str | None = None) -> ModuleType | None:
    try:
        mod = importlib.import_module(alias or name)
        setattr(builtins, name, mod)
    except ImportError:
        msg = (
            f"Could not import '{name}' (attempted import as '{alias}')."
            if alias
            else f"Could not import module '{name}'."
        )
        print(msg)
    return None


setattr(builtins, "try_import", try_import)


def import_ds(  # noqa: C901 - allow 'too complex'
    np: bool = True,
    pd: bool = True,
    pl: bool = False,
    plt: bool = True,
    sns: bool = False,
    px: bool = False,
    scipy: bool = False,
    sklearn: bool = False,
    sm: bool = False,
    torch: bool = False,
    tf: bool = False,
    transformers: bool = False,
) -> None:
    if np:
        try_import("numpy", alias="np")
    if pd:
        try_import("pandas", alias="pd")
    if pl:
        try_import("polars", alias="pl")
    if plt:
        try_import("matplotlib.pyplot", alias="plt")
    if sns:
        try_import("seaborn", alias="sns")
    if px:
        try_import("plotly.express", alias="px")
    if scipy:
        try_import("scipy")
    if sm:
        try_import("statsmodels", alias="sm")
    if sklearn:
        try_import("sklearn")
    if torch:
        try_import("torch")
    if tf:
        try_import("tensorflow", alias="tf")
    if transformers:
        try_import("transformers")
