# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals

import os
import sys
import importlib.util

MODULE_NAME = __name__.rsplit(".", 1)[-1]


def _pick_py_folder():
    v = sys.version_info
    if v[:2] >= (3, 11):
        return "py311"
    if v[:2] >= (3, 10):
        return "py310"
    if v[:2] >= (3, 9):
        return "py39"
    return "py37"


def _compiled_filename():
    return MODULE_NAME + ".pyc"


def _load_pyc():
    here = os.path.dirname(__file__)
    py_folder = _pick_py_folder()
    pyc_path = os.path.join(here, "bin_translations", py_folder, _compiled_filename())

    if not os.path.isfile(pyc_path):
        raise ImportError("Missing compiled module: %s" % pyc_path)

    try:
        spec = importlib.util.spec_from_file_location(__name__, pyc_path)
        if spec is None or spec.loader is None:
            raise ImportError("Failed to create spec for: %s" % pyc_path)

        mod = importlib.util.module_from_spec(spec)

        # Avoid duplicate module instances during nested imports / reload paths
        sys.modules[__name__] = mod

        spec.loader.exec_module(mod)
        return mod

    except Exception as exc:
        raise ImportError(
            "Failed to load compiled module '%s' from '%s': %s"
            % (__name__, pyc_path, exc)
        )


_load_pyc()