# setup.py
from __future__ import annotations

import os
from pathlib import Path

import sys

from setuptools import Extension, setup
from setuptools.command.build_ext import build_ext


class BuildExt(build_ext):
    """Подкладывает numpy include dirs после установки numpy в build env."""

    def finalize_options(self) -> None:
        super().finalize_options()
        import numpy as np

        self.include_dirs.append(np.get_include())


def _get_ext_modules():
    common_macros = [("NPY_NO_DEPRECATED_API", "NPY_1_7_API_VERSION")]
    if sys.platform.startswith("win"):
        extra_compile_args = ["/O2"]
    else:
        extra_compile_args = ["-O3"]

    pareto_pyx = Path("src/zen_fronts/pareto_core/_pareto_rating_cy.pyx")
    pareto_c = pareto_pyx.with_suffix(".c")
    pareto_ext = Extension(
        name="zen_fronts.pareto_core._pareto_rating_cy",
        sources=[str(pareto_pyx)],
        language="c",
        define_macros=common_macros,
        extra_compile_args=extra_compile_args,
    )

    mc_pyx = Path("src/zen_fronts/selection_core/_mc_rank.pyx")
    mc_c = mc_pyx.with_suffix(".c")
    mc_ext = Extension(
        name="zen_fronts.selection_core._mc_rank",
        sources=[str(mc_pyx)],
        language="c",
        define_macros=common_macros,
        extra_compile_args=extra_compile_args,
    )

    try:
        from Cython.Build import cythonize

        ANNOTATE = os.environ.get("CYTHON_ANNOTATE", "0") == "1"
        return cythonize(
            [pareto_ext, mc_ext],
            annotate=ANNOTATE,
            force=ANNOTATE,
            compiler_directives={
                "language_level": "3",
                "boundscheck": False,
                "wraparound": False,
                "cdivision": True,
                "nonecheck": False,
            },
        )
    except Exception:
        # если захотите поддержать сборку без Cython из sdist:
        # нужно заранее сгенерировать и закоммитить _pareto_rating_cy.c
        pareto_ext.sources = [str(pareto_c)]
        mc_ext.sources = [str(mc_c)]
        return [pareto_ext, mc_ext]


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


# python setup.py build_ext --inplace
# CYTHON_ANNOTATE=1 python setup.py build_ext --inplace
