"""
Setup script for building Cython extensions with GSL.
This is called by the build backend specified in pyproject.toml.
"""

from setuptools import setup, Extension
from Cython.Build import cythonize
import numpy as np
import subprocess
import sys
import os


def get_gsl_config(flag):
    """Get GSL compiler/linker flags"""
    try:
        result = subprocess.run(
            ["gsl-config", flag], capture_output=True, text=True, check=True
        )
        return result.stdout.strip().split()
    except (subprocess.CalledProcessError, FileNotFoundError):
        print("Error: gsl-config not found. Please install GSL:", file=sys.stderr)
        print("  macOS:  brew install gsl", file=sys.stderr)
        print("  Ubuntu: sudo apt-get install libgsl-dev", file=sys.stderr)
        sys.exit(1)


# GSL configuration
gsl_include_dirs = [d[2:] for d in get_gsl_config("--cflags") if d.startswith("-I")]
gsl_library_dirs = [d[2:] for d in get_gsl_config("--libs") if d.startswith("-L")]
gsl_libraries = [d[2:] for d in get_gsl_config("--libs") if d.startswith("-l")]

# Compile flags
# -march=native optimizes for current CPU but makes binaries non-portable
# Set GP4C_NATIVE_ARCH=1 to enable (disabled by default for portability)
compile_flags = ["-O3", "-std=c99"]
if os.environ.get("GP4C_NATIVE_ARCH", "0") == "1":
    compile_flags.append("-march=native")

# Define extension
extensions = [
    Extension(
        name="gp4c._core",
        sources=["gp4c/_core.pyx", "gp4c/gp4c.c"],
        include_dirs=[np.get_include(), "gp4c"] + gsl_include_dirs,
        library_dirs=gsl_library_dirs,
        libraries=gsl_libraries,
        extra_compile_args=compile_flags,
        extra_link_args=[],
    )
]

setup(
    packages=["gp4c"],
    ext_modules=cythonize(
        extensions,
        compiler_directives={
            "language_level": "3",
            "boundscheck": False,
            "wraparound": False,
            "cdivision": True,
        },
    ),
)
