"""
Setup script for kheavyhash package.

This script is used by setuptools to build the package. It attempts to build
the Cython extension if dependencies are available, otherwise builds pure
Python package only.
"""

from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
from pathlib import Path
import sys


class OptionalBuildExt(build_ext):
    """
    Custom build extension that gracefully handles missing Cython/numpy.

    If Cython or numpy are not available, the extension build is skipped
    and the package installs with pure Python only.
    """

    def run(self):
        """Attempt to build extensions, skip if dependencies are missing."""
        try:
            # Check if we can import required dependencies
            import Cython  # noqa: F401
            # If we get here, try to build
            super().run()
        except ImportError:
            # Cython not available - skip extension build
            print(
                "Warning: Cython not available. "
                "Building pure Python package only. "
                "Install with 'pip install -e \".[cython]\"' to build extension.",
                file=sys.stderr,
            )
            # Don't fail the build, just skip extensions
            return
        except Exception as e:
            # Any other error during build - log and continue
            print(
                f"Warning: Error building Cython extension: {e}. "
                "Building pure Python package only.",
                file=sys.stderr,
            )
            return


def get_extensions():
    """
    Get list of Cython extensions if dependencies are available.

    Returns:
        List of Extension objects, or empty list if dependencies unavailable.
    """
    extensions = []
    try:
        from Cython.Build import cythonize

        # Check if .pyx file exists
        pyx_file = Path("src/kheavyhash/_c_ext.pyx")
        if not pyx_file.exists():
            print(
                f"Warning: {pyx_file} not found. Building pure Python package only.",
                file=sys.stderr,
            )
            return []

        # Define the extension with C source files
        # Include the Cython .pyx file and the C implementation files
        c_source_dir = Path("src/kheavyhash")
        c_sources = [
            str(pyx_file),
            str(c_source_dir / "kheavyhash_core.c"),
            str(c_source_dir / "keccak_nano.c"),
        ]

        # Define the extension
        ext = Extension(
            "kheavyhash._c_ext",
            sources=c_sources,
            include_dirs=[str(c_source_dir)],
            language="c",
            extra_compile_args=["-std=c99", "-O2"],  # C99 standard, optimize
        )

        # Cythonize with appropriate directives
        extensions = cythonize(
            [ext],
            compiler_directives={
                "language_level": "3",
                "boundscheck": False,
                "wraparound": False,
            },
            quiet=False,  # Show warnings during build
        )
    except ImportError:
        # Cython not available - return empty list
        pass
    except Exception as e:
        # Any other error (e.g., .pyx file issues) - log and continue
        print(
            f"Warning: Could not prepare Cython extension: {e}. "
            "Building pure Python package only.",
            file=sys.stderr,
        )

    return extensions


# This setup.py is used by setuptools.build_meta to handle optional Cython extensions
# Most metadata comes from pyproject.toml, but extensions need to be defined here
# The setup() call must be at module level for setuptools to find it

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