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

class CMakeExtension(Extension):
    def __init__(self, name, sourcedir=''):
        Extension.__init__(self, name, sources=[])
        self.sourcedir = os.path.abspath(sourcedir)

class CMakeBuild(build_ext):
    def run(self):
        try:
            out = subprocess.check_output(['cmake', '--version'])
        except OSError:
            raise RuntimeError("CMake must be installed to build the following extensions: " +
                               ", ".join(e.name for e in self.extensions))

        for ext in self.extensions:
            self.build_extension(ext)

    def build_extension(self, ext):
        extdir = os.path.abspath(os.path.dirname(self.get_ext_fullpath(ext.name)))
        
        if not os.path.exists(extdir):
            os.makedirs(extdir)

        cmake_args = [
            '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=' + extdir,
            '-DPYTHON_EXECUTABLE=' + sys.executable,
        ]

        cfg = 'Debug' if self.debug else 'Release'
        build_args = ['--config', cfg]

        if sys.platform.startswith("win"):
            cmake_args += ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_{}={}'.format(cfg.upper(), extdir)]
            cmake_args += ['-A', 'x64']
            build_args += ['--', '/m']
        else:
            cmake_args += ['-DCMAKE_BUILD_TYPE=' + cfg]
            build_args += ['--', '-j2']

        env = os.environ.copy()
        
        if not os.path.exists(self.build_temp):
            os.makedirs(self.build_temp)

        source_dir = os.path.join(os.getcwd(), "oxs")
        
        subprocess.check_call(['cmake', source_dir] + cmake_args, cwd=self.build_temp, env=env)
        subprocess.check_call(['cmake', '--build', '.'] + build_args, cwd=self.build_temp)

        # MANUAL COPY FIX: Find the generated .pyd and copy it to extdir
        # Because MSVC CMake generators are tricky with output paths
        print(f"--- Searching for .pyd files in {self.build_temp}")
        found = False
        for root, dirs, files in os.walk(self.build_temp):
            for file in files:
                if file.endswith(".pyd"):
                    src_file = os.path.join(root, file)
                    dst_file = os.path.join(extdir, file)
                    print(f"--- Found: {src_file} -> Copying to {dst_file}")
                    shutil.copyfile(src_file, dst_file)
                    found = True
        
        if not found:
            print("--- WARNING: No .pyd file found after build!")

setup(
    name='oxs',
    version='0.1.0',
    author='Vitor Gabriel',
    author_email='vitor@pantheon.ai',
    description='OXS: Optimized X-Scale SOTA Engine',
    long_description=open('README.md').read() if os.path.exists('README.md') else '',
    long_description_content_type='text/markdown',
    ext_modules=[CMakeExtension('oxs.maxwell_core')],
    cmdclass=dict(build_ext=CMakeBuild),
    packages=find_packages(exclude=['src', 'tests']),
    zip_safe=False,
    install_requires=['numpy'],
    python_requires='>=3.8',
    include_package_data=True,
    package_data={'oxs': ['*.pyd']},
)
