import importlib
import importlib.abc
import importlib.util
import types
from .hooks_bytecode import patch_bytecode

class NoExitLoader(importlib.abc.Loader):
    def create_module(self, spec):
        return None

    def exec_module(self, module):
        code = module.__spec__.loader_state
        patched = patch_bytecode(code)
        exec(patched, module.__dict__)

class NoExitFinder(importlib.abc.MetaPathFinder):
    def find_spec(self, fullname, path=None, target=None):
        try:
            spec = importlib.util.find_spec(fullname)
            if not spec or not spec.loader:
                return None

            code = spec.loader.get_code(fullname)
            if not isinstance(code, types.CodeType):
                return None

            spec.loader_state = code
            spec.loader = NoExitLoader()
            return spec
        except:
            return None
