import glob
import os
from setuptools import setup, Extension
from setuptools.command.build_py import build_py as _build_py
from setuptools.command.build_ext import build_ext as _build_ext

_COMPILE_MODULES = [
    "overflow",
    "agent",
    "cli",
    "errors",
    "client",
]

try:
    from Cython.Build import cythonize

    ext_modules = cythonize(
        [
            Extension(f"verlex.{mod}", [f"verlex/{mod}.py"])
            for mod in _COMPILE_MODULES
        ],
        compiler_directives={"language_level": "3", "emit_code_comments": False},
    )
    _HAS_CYTHON = True
except ImportError:
    ext_modules = []
    _HAS_CYTHON = False

_COMPILED_SET = {("verlex", mod) for mod in _COMPILE_MODULES}


class build_py(_build_py):
    def find_all_modules(self):
        modules = super().find_all_modules()
        if _HAS_CYTHON:
            modules = [
                (pkg, mod, path)
                for pkg, mod, path in modules
                if (pkg, mod) not in _COMPILED_SET
            ]
        return modules

    def find_package_modules(self, package, package_dir):
        modules = super().find_package_modules(package, package_dir)
        if _HAS_CYTHON:
            modules = [
                (pkg, mod, path)
                for pkg, mod, path in modules
                if (pkg, mod) not in _COMPILED_SET
            ]
        return modules


class build_ext(_build_ext):
    def run(self):
        super().run()
        if _HAS_CYTHON:
            for mod in _COMPILE_MODULES:
                for pattern in (f"verlex/{mod}.c", f"verlex\\{mod}.c"):
                    for f in glob.glob(pattern):
                        os.remove(f)
                if self.build_lib:
                    c_in_lib = os.path.join(self.build_lib, "verlex", f"{mod}.c")
                    if os.path.exists(c_in_lib):
                        os.remove(c_in_lib)


setup(
    cmdclass={"build_py": build_py, "build_ext": build_ext},
    ext_modules=ext_modules,
)
