import os
import sys

# Try to import pybind11, but don't fail if it's not available during build setup
try:
    import pybind11
    from pybind11.setup_helpers import Pybind11Extension, build_ext
    PYBIND11_AVAILABLE = True
except ImportError:
    PYBIND11_AVAILABLE = False
    # Define dummy classes for when pybind11 is not available
    class Pybind11Extension:
        def __init__(self, *args, **kwargs):
            pass
    class build_ext:
        pass

from setuptools import setup, Extension

# 获取当前目录
__dir__ = os.path.dirname(os.path.abspath(__file__))

# 获取所有源文件
def get_source_files():
    """获取所有STT源文件"""
    src_files = []
    
    # 添加主源文件
    src_dir = os.path.join(__dir__, 'src')
    for file in os.listdir(src_dir):
        if file.endswith('.cc'):
            src_files.append(os.path.join('src', file))
    
    # 添加绑定文件
    src_files.append('pybind/stt_binding.cpp')
    
    return src_files

# 获取包含目录
def get_include_dirs():
    """获取包含目录"""
    includes = [
        # 当前目录
        __dir__,
        # src目录
        os.path.join(__dir__, 'src'),
        # pybind目录
        os.path.join(__dir__, 'pybind'),
    ]
    
    # 只有在pybind11可用时才添加其包含目录
    if PYBIND11_AVAILABLE:
        includes.extend([
            # pybind11包含目录
            pybind11.get_include(),
            # Python包含目录
            pybind11.get_include(True)
        ])
    
    return includes

# 定义扩展模块
if PYBIND11_AVAILABLE:
    ext_modules = [
        Pybind11Extension(
            "pystt",
            # 源文件列表
            get_source_files(),
            # 包含目录
            include_dirs=get_include_dirs(),
            # 编译选项
            extra_compile_args=[
                '-O3',           # 优化级别
                '-std=c++11',    # C++11标准
                '-fPIC',         # 位置无关代码
                '-DVERSION_INFO="1.4.1"',  # 版本信息
                '-DPYTHON_BINDING'  # Python绑定模式
            ],
            # 链接选项
            extra_link_args=[],
            # 定义宏
            define_macros=[
                ('VERSION_INFO', '"1.4.1"'),
                ('PYTHON_BINDING', '1'),
            ],
            # 语言标准
            cxx_std=11,
        ),
    ]
else:
    # 当pybind11不可用时，使用空列表
    ext_modules = []

# 读取README文件
def read_readme():
    """读取README文件"""
    readme_path = os.path.join(__dir__, 'README.md')
    if os.path.exists(readme_path):
        with open(readme_path, 'r', encoding='utf-8') as f:
            return f.read()
    return "STT Python Binding - Spherical Triangular Tessellation Generator"

# 设置包信息
setup(
    name='pystt',
    version='1.4.1',
    author='STT Development Team',
    author_email='yizhang-geo@zju.edu.cn',
    description='Python binding for Spherical Triangular Tessellation (STT) generator',
    long_description=read_readme(),
    long_description_content_type='text/markdown',
    url='https://github.com/your-repo/stt',
    
    # 扩展模块
    ext_modules=ext_modules,
    
    # 构建命令
    cmdclass={"build_ext": build_ext} if PYBIND11_AVAILABLE else {},
    
    # 依赖
    install_requires=[
        'pybind11>=2.6.0',
        'numpy>=1.19.0',
    ],
    
    # 可选依赖
    extras_require={
        'dev': [
            'pytest>=6.0',
            'pytest-cov',
            'black',
            'flake8',
        ],
        'progress': [
            'tqdm>=4.50.0',
        ],
    },
    
    # Python版本要求
    python_requires='>=3.6',
    
    # 分类
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Science/Research',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
        'Programming Language :: Python :: 3.9',
        'Programming Language :: Python :: 3.10',
        'Programming Language :: Python :: 3.11',
        'Programming Language :: C++',
        'Topic :: Scientific/Engineering :: GIS',
        'Topic :: Scientific/Engineering :: Mathematics',
    ],
    
    # 关键词
    keywords='spherical triangular tessellation mesh generation geography',
    
    # 项目URL
    project_urls={
        'Bug Reports': 'https://github.com/your-repo/stt/issues',
        'Source': 'https://github.com/your-repo/stt',
        'Documentation': 'https://stt.readthedocs.io/',
    },
    
    # 包含包数据
    include_package_data=True,
    
    # 排除文件
    exclude_package_data={
        '': ['*.cpp', '*.cc', '*.h', '*.hpp', 'CMakeLists.txt', 'Makefile'],
    },
    
    # ZIP安全
    zip_safe=False,
)