# loader.py
# Uses importlib.SourcelessFileLoader to load literal .pyc files as modules.
import sys, os, importlib.machinery, importlib.util

class PycImporter:
    def _search_paths(self, fullname, path):
        base_name = fullname.split(".")[-1]
        paths = list(path) if path is not None else list(sys.path)
        for base in paths:
            if not base:
                base = os.getcwd()
            yield os.path.join(base, base_name + ".pyc")
            pycache = os.path.join(base, "__pycache__")
            if os.path.isdir(pycache):
                for fname in os.listdir(pycache):
                    if fname.startswith(base_name) and fname.endswith(".pyc"):
                        yield os.path.join(pycache, fname)

    def find_spec(self, fullname, path, target=None):
        for candidate in self._search_paths(fullname, path):
            if os.path.exists(candidate):
                loader = importlib.machinery.SourcelessFileLoader(fullname, candidate)
                spec = importlib.util.spec_from_loader(fullname, loader, origin=candidate)
                return spec
        return None

_installed = False
def install():
    global _installed
    if _installed:
        return
    sys.meta_path.insert(0, PycImporter())
    _installed = True

# Auto-install when this module is imported
install()
