
import sys
import atexit
import readline
import rlcompleter
import os

if "PYTHONHISTFILE" in os.environ:
    history = os.path.expanduser(os.environ["PYTHONHISTFILE"])

elif "XDG_STATE_HOME" in os.environ:
    history = os.path.join(
        os.path.expanduser(os.environ["XDG_STATE_HOME"]), "python_history"
    )

else:
    history = os.path.join(os.path.expanduser("~"), ".python_history")

history = os.path.abspath(history)
_dir, _ = os.path.split(history)
os.makedirs(_dir, exist_ok=True)

if "PYTHON_HISTORY" in os.environ:
    history = os.path.expanduser(os.environ["PYTHON_HISTORY"])
elif "XDG_STATE_HOME" in os.environ:
    history = os.path.join(
        os.path.expanduser(os.environ["XDG_STATE_HOME"]), "python", "python_history"
    )
else:
    history = os.path.join(os.path.expanduser("~"), ".python_history")


def install_tab_completion():
    readline.parse_and_bind("tab: complete")


def install_history():
    if os.path.exists(history):
        readline.read_history_file(history)
    atexit.register(save_history)


def save_history():
    import readline

    readline.write_history_file(history)


def python2():
    install_tab_completion()
    install_history()


def python3():
    pass


if sys.version_info <= (3,):
    python2()
else:
    python3()

    def import_path(path):
        import os
        import importlib

        name = os.path.basename(path).replace("-", "_")
        spec = importlib.util.spec_from_loader(
            name, importlib.machinery.SourceFileLoader(name, path)
        )
        module = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(module)
        return module

    del history
    del save_history

del sys
del atexit
del os
del readline
del rlcompleter
del install_tab_completion
del install_history
del python2
del python3
