Smart import function

import pkg_resources

import importlib

import subprocess

from pip._internal.operations.freeze import freeze

from pip._internal.exceptions import InstallationError


def installed(package):

    installed_packages = [pkg.key.lower() for pkg in pkg_resources.working_set]

    return package.lower() in installed_packages


def imported(package):

    try:

        importlib.import_module(package)

        print(f'Package {package} is already imported.\n')

        return True

    except ImportError:

        print(f'Package {package} is not imported yet.\n')

        return False


def can_install(package):

    try:

        subprocess.run(['pip', 'install', '--dry-run', package], check=True)

        return True

    except InstallationError as e:

        print(f'Cannot install package {package}. Error: {e}\n')

        return False


def install(package):

    print(f'Package {package} is going to be installed.\n')

    try:

        subprocess.run(['pip', 'install', package], check=True)

    except subprocess.CalledProcessError as e:

        print(f'Error installing package {package}. Error: {e}\n')


def resolve_package_name(package):

    new_name = input(f'There are some issues related to package name: {package}. Enter an alternate package name to try: ')

    return new_name


def want_to_retry():

    retry = input('Retry from the beginning? (y/n) ')

    return retry.lower() == 'y'


def smart_import(package):

    if not imported(package):

        if not installed(package):

            if not can_install(package):

                new_package = resolve_package_name(package)

                if want_to_retry():

                    smart_import(new_package)

                else:

                    exit()

            else:

                install(package)

        else:

            importlib.import_module(package)


# Example usage:

smart_import('pyautogui')