from setuptools import setup, find_packages
from setuptools.command.build_ext import build_ext
import os
import subprocess
import sys

def check_lapacke():
    """Check if LAPACKE is installed on the system."""
    try:
        # Run ldconfig to check if liblapacke.so is available
        output = subprocess.check_output(["ldconfig", "-p"], stderr=subprocess.DEVNULL).decode()
        if "liblapacke.so" not in output:
            raise FileNotFoundError
    except (FileNotFoundError, subprocess.CalledProcessError):
        print("\n⚠️  LAPACKE is not installed! Please install it before proceeding:\n")
        print("    sudo apt-get install liblapacke liblapacke-dev\n")
        sys.exit(1)

class BuildExt(build_ext):
    """Custom build extension to compile C shared library"""
    def run(self):
        # First, check if LAPACKE is installed
        check_lapacke()

        # Ensure the target directory exists
        build_path = os.path.join(os.path.dirname(__file__), "gsvd")
        os.makedirs(build_path, exist_ok=True)

        # Compile the C code into a shared library
        subprocess.check_call([
            "gcc", "-shared", "-o", os.path.join(build_path, "libgsvd.so"),
            "gsvd/gsvd_wrapper.c", "-fPIC", "-llapacke", "-llapack", "-lblas"
        ])
        build_ext.run(self)

setup(
    name='gsvd',
    version='0.1.2',
    packages=find_packages(),
    include_package_data=True,
    package_data={'gsvd': ['libgsvd.so']},  # Include compiled shared library
    install_requires=['numpy'],
    author="Harsha Narayana P",
    description="A minimal Python wrapper for GSVD using LAPACKE_dggsvd3",
    cmdclass={'build_ext': BuildExt},  # Use custom build command
)
