"""
setup.py — build-time helper for the SPARTpy PyPI package.

The C sources generated by MATLAB Coder live in codegen/dll/SPART_C/ inside
the SPART source tree.  This file copies them into SPARTpy/_c_src/SPART_C/
so that they are treated as regular package data and end up inside the
installed wheel alongside the Python source.

The compiled SPART_C.so is included if it is already present.  Users who
install from a source distribution (sdist) on a different architecture can
rebuild it automatically on first import — the lazy-build logic in SPARTpy.py
calls gcc transparently when the .so is absent or stale.

Usage
-----
  pip install .                 # build + install
  pip install -e .              # editable / development install
  python -m build               # produce sdist + wheel in dist/
"""

import os
import shutil
from setuptools import setup
from setuptools.command.build_py import build_py


# ---------------------------------------------------------------------------
# Paths
# ---------------------------------------------------------------------------
_HERE = os.path.dirname(os.path.abspath(__file__))
_C_SOURCE_DIR = os.path.join(_HERE, "codegen", "dll", "SPART_C")
_C_DEST_DIR   = os.path.join(_HERE, "SPARTpy", "_c_src", "SPART_C")

# File extensions to include
_C_EXTENSIONS = {".c", ".h", ".so", ".def"}


class _BuildPyWithCSrc(build_py):
    """Copy SPART C sources into SPARTpy/_c_src/SPART_C before building."""

    def run(self):
        self._copy_c_sources()
        super().run()

    def _copy_c_sources(self):
        if not os.path.isdir(_C_SOURCE_DIR):
            print(
                f"[setup.py] WARNING: C source directory not found:\n"
                f"  {_C_SOURCE_DIR}\n"
                "  The compiled C back-end will be unavailable.  "
                "Only the pure-Python URDF loader will work after install."
            )
            return

        os.makedirs(_C_DEST_DIR, exist_ok=True)

        copied = 0
        for fname in os.listdir(_C_SOURCE_DIR):
            ext = os.path.splitext(fname)[1].lower()
            if ext in _C_EXTENSIONS:
                src  = os.path.join(_C_SOURCE_DIR, fname)
                dest = os.path.join(_C_DEST_DIR, fname)
                shutil.copy2(src, dest)
                copied += 1

        print(f"[setup.py] Copied {copied} C-source/header/library files "
              f"→ SPARTpy/_c_src/SPART_C/")


setup(
    cmdclass={"build_py": _BuildPyWithCSrc},
)
