from setuptools import setup, Extension
import platform
import os
import shutil

base_dir = os.path.dirname(__file__)
c_lib_root = os.path.normpath(os.path.join(base_dir, '..', '..', 'oosxl'))
pkg_source_dir = os.path.join(base_dir, 'pyoosxl')
libs_target_dir = os.path.join(pkg_source_dir, 'libs')

os.makedirs(pkg_source_dir, exist_ok=True)
os.makedirs(libs_target_dir, exist_ok=True)

lib_name = 'oosxl'

system = platform.system()
machine = platform.machine().lower()

if system == 'Windows':
    arch_map = {
        'amd64': 'x64',
        'x86': 'x86',
        'arm64': 'arm64',
    }
    lib_subdir = arch_map.get(machine)
    if lib_subdir is None:
        raise RuntimeError(f"Unsupported Windows architecture: {machine}")
    lib_arch_dir = os.path.join(c_lib_root, 'lib', lib_subdir)
    lib_ext = '.dll'
    lib_filename = f'{lib_name}{lib_ext}'

elif system == 'Linux':
    arch_map = {
        'x86_64': 'x86_64',
        'aarch64': 'aarch64',
        'i386': 'i386',
        'i686': 'i386',
        'armv7l': 'armhf',
    }
    lib_subdir = arch_map.get(machine)
    if lib_subdir is None:
        raise RuntimeError(f"Unsupported Linux architecture: {machine}")
    lib_arch_dir = os.path.join(c_lib_root, 'lib', lib_subdir)
    lib_ext = '.so'
    lib_filename = f'lib{lib_name}{lib_ext}'       # Linux 下为 liboosxl.so

elif system == 'Darwin':
    arch_map = {
        'x86_64': 'x86_64',
        'arm64': 'arm64',
    }
    lib_subdir = arch_map.get(machine)
    universal_dir = os.path.join(c_lib_root, 'lib', 'universal')
    if lib_subdir and os.path.isdir(os.path.join(c_lib_root, 'lib', lib_subdir)):
        lib_arch_dir = os.path.join(c_lib_root, 'lib', lib_subdir)
    elif os.path.isdir(universal_dir):
        lib_arch_dir = universal_dir
    else:
        raise RuntimeError(f"No suitable library directory found for macOS {machine}")
    lib_ext = '.dylib'
    lib_filename = f'lib{lib_name}{lib_ext}'

else:
    raise RuntimeError(f"Unsupported operating system: {system}")

lib_src = os.path.join(lib_arch_dir, lib_filename)
if not os.path.isfile(lib_src):
    raise RuntimeError(f"Required library not found: {lib_src}")

lib_target = os.path.join(libs_target_dir, lib_filename)
if not os.path.isfile(lib_target) or os.path.getmtime(lib_src) > os.path.getmtime(lib_target):
    shutil.copy2(lib_src, lib_target)
    print(f"Copied {lib_src} -> {lib_target}")

include_dirs = [
    os.path.join(c_lib_root, 'include', 'c'),
    os.path.join(base_dir, 'src')
]
library_dirs = [lib_arch_dir]
libraries = [lib_name]

extra_compile_args = []
if system == 'Windows':
    extra_compile_args.append('/O2')
elif system in ('Linux', 'Darwin'):
    extra_compile_args.append('-O2')

extra_link_args = []
if system == 'Windows':
    pass
elif system == 'Linux':
    extra_link_args.append('-Wl,-rpath,$ORIGIN/libs')
elif system == 'Darwin':
    extra_link_args.append('-Wl,-rpath,@loader_path/libs')

oosxl_module = Extension(
    'oosxl._oosxl',
    sources=[
        'src/oosxl_module.c',
        'src/utils.c',
        'src/document.c',
        'src/workbook.c',
        'src/worksheet.c',
        'src/style.c',
        'src/richtext.c',
        'src/tabledef.c'
    ],
    include_dirs=include_dirs,
    libraries=libraries,
    library_dirs=library_dirs,
    define_macros=[('PY_SSIZE_T_CLEAN', None)],
    extra_compile_args=extra_compile_args,
    extra_link_args=extra_link_args,
    language='c'
)

setup(
    name='pyoosxl',
    version='0.1.0',
    description='Python binding for OOSXL library',
    packages=['oosxl'],
    package_dir={'oosxl': 'pyoosxl'},
    package_data={
        'oosxl': ['libs/*.dll', 'libs/*.so', 'libs/*.dylib']
    },
    ext_modules=[oosxl_module],
    zip_safe=False,
    classifiers=[
        'Programming Language :: Python :: 3',
        'Operating System :: Microsoft :: Windows',
        'Operating System :: POSIX :: Linux',
        'Operating System :: MacOS :: MacOS X',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ],
)
