import os
import sys
import licensing
from importlib.abc import MetaPathFinder, Loader
from importlib.util import spec_from_file_location, resolve_name

class KantreeEncryptedModuleLoader(MetaPathFinder, Loader):
    @classmethod
    def find_spec(cls, name, path=None, target=None):
        fullname = resolve_name(name, path) if name.startswith('.') else name
        if not path or not fullname.startswith('kantree'):
            return None
        if fullname in sys.modules:
            return sys.modules[fullname].__spec__
        basepath = os.path.join(os.path.join(*path), fullname.split('.')[-1])
        filename = basepath + '.pyx'
        if os.path.isfile(filename):
            return spec_from_file_location(fullname, filename, loader=cls())
        filename = os.path.join(basepath, '__init__.pyx')
        if os.path.isfile(filename):
            return spec_from_file_location(fullname, filename, loader=cls(basepath))
        return None

    def __init__(self, basepath=None):
        self._basepath = basepath

    def create_module(self, spec):
        if spec.origin in sys.modules:
            return sys.modules[spec.origin]
        return licensing.load(spec.name, spec.origin, spec.parent, self._basepath)

    def exec_module(self, module):
        pass


sys.meta_path.insert(0, KantreeEncryptedModuleLoader)