cmake_minimum_required(VERSION 3.20)
project(turboxl VERSION 0.3.0 LANGUAGES CXX)

# Set C++ standard
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# Project options
option(BUILD_TESTS "Build tests" ON)
option(BUILD_PYTHON "Build Python module" ON)
option(BUILD_CLI "Build CLI tool" OFF)
option(BUILD_BENCHMARKS "Build benchmarks" OFF)
option(TURBOXL_PORTABLE_BUILD "Disable host-specific CPU tuning for portable binaries" OFF)
option(TURBOXL_CI_FAST_BUILD "Reduce compile-time optimizations for faster CI builds" OFF)
option(TURBOXL_ENABLE_NATIVE_OPTIMIZATION "Enable host-specific CPU optimization flags where safe" ON)
option(TURBOXL_ENABLE_IPO "Enable interprocedural optimization (LTO) for Release builds" ON)
option(TURBOXL_STATIC_WINDOWS_DEPS "Define static-library APIs for Windows dependencies" OFF)

include(CheckIPOSupported)

# --- Windows-specific discovery (minimal guard) ---
if(WIN32)
    # Prefer CMake package configs supplied by vcpkg; keep variable names used below.
    find_package(LibXml2 REQUIRED)
    # The FindLibXml2 module defines LIBXML2_INCLUDE_DIRS/LIBXML2_LIBRARIES

    # zlib: with zlib-ng[compat] in vcpkg, find_package(ZLIB) resolves to the
    # compatibility layer, so consumers still link against ZLIB as usual.
    find_package(ZLIB REQUIRED)
    set(ZLIB_LIBRARY "zlib")
    set(ZLIB_INCLUDE_DIRS ${ZLIB_INCLUDE_DIRS})
    set(ZLIB_LIBRARIES ${ZLIB_LIBRARIES})
    set(ZLIB_LIBRARY_DIRS "")

    # minizip-ng via CMake config (vcpkg installs config under minizip-ng).
    find_package(minizip-ng CONFIG QUIET)
    find_package(minizip CONFIG QUIET)
    find_package(unofficial-minizip-ng CONFIG QUIET)
    find_package(unofficial-minizip CONFIG QUIET)
    if(
        minizip-ng_FOUND OR
        minizip_FOUND OR
        TARGET MINIZIP::minizip-ng OR
        TARGET MINIZIP::minizip OR
        TARGET unofficial::minizip-ng::minizip-ng OR
        TARGET unofficial::minizip::minizip
    )
        # Normalize common exported target names to minizip::minizip.
        if(TARGET minizip::minizip)
            set(ZIP_LIBRARY "minizip-ng")
            set(ZIP_INCLUDE_DIRS "")
            set(ZIP_LIBRARIES minizip::minizip)
        elseif(TARGET MINIZIP::minizip-ng)
            add_library(minizip::minizip ALIAS MINIZIP::minizip-ng)
            set(ZIP_LIBRARY "minizip-ng")
            set(ZIP_INCLUDE_DIRS "")
            set(ZIP_LIBRARIES minizip::minizip)
        elseif(TARGET MINIZIP::minizip)
            add_library(minizip::minizip ALIAS MINIZIP::minizip)
            set(ZIP_LIBRARY "minizip-ng")
            set(ZIP_INCLUDE_DIRS "")
            set(ZIP_LIBRARIES minizip::minizip)
        elseif(TARGET unofficial::minizip-ng::minizip-ng)
            add_library(minizip::minizip ALIAS unofficial::minizip-ng::minizip-ng)
            set(ZIP_LIBRARY "minizip-ng")
            set(ZIP_INCLUDE_DIRS "")
            set(ZIP_LIBRARIES minizip::minizip)
        elseif(TARGET unofficial::minizip::minizip)
            # Normalize vcpkg's commonly exported target name
            add_library(minizip::minizip ALIAS unofficial::minizip::minizip)
            set(ZIP_LIBRARY "minizip-ng")
            set(ZIP_INCLUDE_DIRS "")
            set(ZIP_LIBRARIES minizip::minizip)
        elseif(TARGET minizip)
            # Create expected namespace alias if only plain target exists
            add_library(minizip::minizip ALIAS minizip)
            set(ZIP_LIBRARY "minizip-ng")
            set(ZIP_INCLUDE_DIRS "")
            set(ZIP_LIBRARIES minizip::minizip)
        else()
            # Allow explicit override if a config is present but no expected targets are exported
            if(DEFINED MINIZIP_LIBRARY AND DEFINED MINIZIP_INCLUDE_DIR)
                add_library(minizip::minizip STATIC IMPORTED)
                set_target_properties(minizip::minizip PROPERTIES
                    IMPORTED_LOCATION "${MINIZIP_LIBRARY}"
                    INTERFACE_INCLUDE_DIRECTORIES "${MINIZIP_INCLUDE_DIR}"
                )
                set(ZIP_LIBRARY "minizip-ng")
                set(ZIP_INCLUDE_DIRS "${MINIZIP_INCLUDE_DIR}")
                set(ZIP_LIBRARIES minizip::minizip)
            else()
                message(FATAL_ERROR "minizip package found, but expected target not exported; set MINIZIP_LIBRARY and MINIZIP_INCLUDE_DIR to override.")
            endif()
        endif()
    else()
        # Final fallback: manual override via variables provided by the build system
        if(DEFINED MINIZIP_LIBRARY AND DEFINED MINIZIP_INCLUDE_DIR)
            add_library(minizip::minizip STATIC IMPORTED)
            set_target_properties(minizip::minizip PROPERTIES
                IMPORTED_LOCATION "${MINIZIP_LIBRARY}"
                INTERFACE_INCLUDE_DIRECTORIES "${MINIZIP_INCLUDE_DIR}"
            )
            set(ZIP_LIBRARY "minizip-ng")
            set(ZIP_INCLUDE_DIRS "${MINIZIP_INCLUDE_DIR}")
            set(ZIP_LIBRARIES minizip::minizip)
        else()
            message(FATAL_ERROR "minizip-ng not found (install via vcpkg) and no manual override provided.")
        endif()
    endif()

    # If we have a concrete include dir, also add its parent so includes like <minizip-ng/...> resolve
    if(DEFINED MINIZIP_INCLUDE_DIR)
        get_filename_component(_parent_inc "${MINIZIP_INCLUDE_DIR}" DIRECTORY)
        list(APPEND ZIP_INCLUDE_DIRS "${_parent_inc}")
    endif()

else()
    # --- Non-Windows: keep existing pkg-config based discovery ---
    find_package(PkgConfig REQUIRED)
    # Find libxml2
    pkg_check_modules(LIBXML2 REQUIRED libxml-2.0)
    if(NOT LIBXML2_FOUND)
        message(FATAL_ERROR "libxml2 not found. Please install libxml2-dev")
    endif()

    # Find zlib-ng with compatibility mode (preferred) or fallback to standard zlib
    pkg_check_modules(ZLIB_NG zlib-ng)
    if(ZLIB_NG_FOUND)
        set(ZLIB_LIBRARY "zlib-ng")
        set(ZLIB_INCLUDE_DIRS ${ZLIB_NG_INCLUDE_DIRS})
        set(ZLIB_LIBRARIES ${ZLIB_NG_LIBRARIES})
        set(ZLIB_LIBRARY_DIRS ${ZLIB_NG_LIBRARY_DIRS})
        message(STATUS "Using zlib-ng for optimized compression performance")
    else()
        find_package(ZLIB REQUIRED)
        set(ZLIB_LIBRARY "zlib")
        set(ZLIB_INCLUDE_DIRS ${ZLIB_INCLUDE_DIRS})
        set(ZLIB_LIBRARIES ${ZLIB_LIBRARIES})
        set(ZLIB_LIBRARY_DIRS "")
        message(STATUS "Using standard zlib (consider installing zlib-ng for better performance)")
    endif()

    # Allow explicit Linux override from CI to force deterministic linkage.
    if(DEFINED MINIZIP_LIBRARY AND EXISTS "${MINIZIP_LIBRARY}" AND
       DEFINED MINIZIP_INCLUDE_DIR AND EXISTS "${MINIZIP_INCLUDE_DIR}")
        set(ZIP_LIBRARY "minizip-ng")
        set(ZIP_INCLUDE_DIRS "${MINIZIP_INCLUDE_DIR}")
        get_filename_component(_parent_inc "${MINIZIP_INCLUDE_DIR}" DIRECTORY)
        list(APPEND ZIP_INCLUDE_DIRS "${_parent_inc}")
        set(ZIP_LIBRARIES "${MINIZIP_LIBRARY}")
        set(MZ_WHOLE_ARCHIVE_LIB "${MINIZIP_LIBRARY}")
        set(_ZIP_READY ON)
    endif()

    # Find minizip-ng (prefer a CMake package target), then fall back to
    # either the minizip-ng or distro-provided minizip pkg-config module.
    if(NOT _ZIP_READY)
        find_package(minizip CONFIG QUIET)
        find_package(minizip-ng CONFIG QUIET)
        if(TARGET MINIZIP::minizip)
            set(ZIP_LIBRARY "minizip-ng")
            set(ZIP_INCLUDE_DIRS "")
            set(ZIP_LIBRARIES MINIZIP::minizip)
            set(_ZIP_READY ON)
        else()
            pkg_check_modules(MINIZIP minizip-ng)
            if(NOT MINIZIP_FOUND)
                pkg_check_modules(MINIZIP minizip)
            endif()
            if(MINIZIP_FOUND)
                set(ZIP_LIBRARY "minizip-ng")
                set(ZIP_INCLUDE_DIRS ${MINIZIP_INCLUDE_DIRS})
                # Also add parent include directory so includes like <minizip-ng/...> resolve
                foreach(_inc IN LISTS MINIZIP_INCLUDE_DIRS)
                    get_filename_component(_parent_inc "${_inc}" DIRECTORY)
                    list(APPEND ZIP_INCLUDE_DIRS "${_parent_inc}")
                endforeach()
                # Prefer full link entries produced by pkg-config (can include absolute
                # archive paths), not just bare -l names.
                if(MINIZIP_LINK_LIBRARIES)
                    set(ZIP_LIBRARIES ${MINIZIP_LINK_LIBRARIES})
                else()
                    set(ZIP_LIBRARIES ${MINIZIP_LIBRARIES})
                endif()

                # If pkg-config gave us a static archive path, keep it so we can force
                # full symbol inclusion on Linux module link.
                foreach(_mz_lib IN LISTS ZIP_LIBRARIES)
                    if(_mz_lib MATCHES "libminizip(-ng)?\\.a$")
                        set(MZ_WHOLE_ARCHIVE_LIB "${_mz_lib}")
                        break()
                    endif()
                endforeach()
                set(_ZIP_READY ON)
            endif()
        endif()
    endif()

    if(NOT _ZIP_READY)
        message(FATAL_ERROR "minizip with the unzip compatibility API is required")
    endif()
endif()

# Core library
add_library(turboxl_core
    src/core/zip_reader.cpp
    src/core/opc_package.cpp
    src/core/workbook.cpp
    src/core/styles_registry.cpp
    src/core/shared_strings_provider.cpp
    src/core/cell_data.cpp
    src/core/sheet_stream_reader.cpp
    src/core/data_converter.cpp
    src/csv/csv_encoder.cpp
    src/facade/xlsx_reader.cpp
)

target_include_directories(turboxl_core
    PUBLIC
        $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
        $<INSTALL_INTERFACE:include>
    PRIVATE
        ${CMAKE_CURRENT_SOURCE_DIR}/src
        ${CMAKE_CURRENT_SOURCE_DIR}/include
        ${LIBXML2_INCLUDE_DIRS}
        ${ZIP_INCLUDE_DIRS}
        ${ZLIB_INCLUDE_DIRS}
)

# On Windows, when linking against a static libxml2, headers expect LIBXML_STATIC
if(WIN32)
    set(_LIBXML2_IS_STATIC OFF)
    if(TURBOXL_STATIC_WINDOWS_DEPS)
        set(_LIBXML2_IS_STATIC ON)
    endif()
    foreach(_lib ${LIBXML2_LIBRARIES})
        string(TOLOWER "${_lib}" _lib_lower)
        if(_lib_lower MATCHES "libxml2s\\.lib" OR _lib_lower MATCHES "libxml2\\.a")
            set(_LIBXML2_IS_STATIC ON)
        endif()
    endforeach()
    if(_LIBXML2_IS_STATIC)
        target_compile_definitions(turboxl_core PRIVATE LIBXML_STATIC)
    endif()
endif()

target_link_libraries(turboxl_core
    PUBLIC
        ${LIBXML2_LIBRARIES}
        ${ZIP_LIBRARIES}
        ${ZLIB_LIBRARIES}
)

# Add library search directories for zlib-ng if needed
if(ZLIB_LIBRARY_DIRS)
    target_link_directories(turboxl_core PRIVATE ${ZLIB_LIBRARY_DIRS})
endif()

# Add library search directories for minizip/libzip if provided
if(MINIZIP_FOUND AND MINIZIP_LIBRARY_DIRS)
    target_link_directories(turboxl_core PRIVATE ${MINIZIP_LIBRARY_DIRS})
endif()
if(LIBZIP_FOUND AND LIBZIP_LIBRARY_DIRS)
    target_link_directories(turboxl_core PRIVATE ${LIBZIP_LIBRARY_DIRS})
endif()

target_compile_features(turboxl_core PUBLIC cxx_std_20)

set_target_properties(turboxl_core PROPERTIES POSITION_INDEPENDENT_CODE ON)

# Compiler-specific settings
if(CMAKE_CXX_COMPILER_ID MATCHES "Clang|GNU")
    target_compile_options(turboxl_core PRIVATE
        -Wall -Wextra -Wpedantic
        -fvisibility=hidden
    )

    if(TURBOXL_CI_FAST_BUILD)
        target_compile_options(turboxl_core PRIVATE
            $<$<CONFIG:Release>:-O2>
        )
    else()
        target_compile_options(turboxl_core PRIVATE
            $<$<CONFIG:Release>:-O3>
        )
    endif()

    if(TURBOXL_ENABLE_NATIVE_OPTIMIZATION AND NOT TURBOXL_PORTABLE_BUILD)
        target_compile_options(turboxl_core PRIVATE
            $<$<CONFIG:Release>:-march=native>
        )
    endif()
endif()

if(MSVC)
    target_compile_options(turboxl_core PRIVATE
        /W4 /wd4251 /MP4
        $<$<CONFIG:Release>:/O2>
    )
    target_compile_definitions(turboxl_core PRIVATE
        _CRT_SECURE_NO_WARNINGS
    )

    if(TURBOXL_ENABLE_NATIVE_OPTIMIZATION AND NOT TURBOXL_PORTABLE_BUILD)
        target_compile_options(turboxl_core PRIVATE
            $<$<CONFIG:Release>:/arch:AVX2>
        )
    endif()
endif()

if(TURBOXL_ENABLE_IPO)
    check_ipo_supported(RESULT TURBOXL_IPO_SUPPORTED OUTPUT TURBOXL_IPO_ERROR)
    if(TURBOXL_IPO_SUPPORTED)
        set_property(TARGET turboxl_core PROPERTY INTERPROCEDURAL_OPTIMIZATION_RELEASE ON)
    else()
        message(WARNING "IPO/LTO not enabled: ${TURBOXL_IPO_ERROR}")
    endif()
endif()

# Python bindings
if(BUILD_PYTHON)
    find_package(Python REQUIRED COMPONENTS
        Interpreter
        Development.Module
        ${SKBUILD_SABI_COMPONENT}
    )
    find_package(nanobind CONFIG REQUIRED)

    if(SKBUILD_SABI_COMPONENT)
        nanobind_add_module(turboxl STABLE_ABI src/python/module.cpp)
    else()
        nanobind_add_module(turboxl src/python/module.cpp)
    endif()
    target_link_libraries(turboxl PRIVATE turboxl_core)

    # Propagate LIBXML_STATIC to the Python extension compile if needed
    if(WIN32 AND _LIBXML2_IS_STATIC)
        target_compile_definitions(turboxl PRIVATE LIBXML_STATIC)
    endif()
    
    # Add library search directories for zlib-ng if needed
    if(ZLIB_LIBRARY_DIRS)
        target_link_directories(turboxl PRIVATE ${ZLIB_LIBRARY_DIRS})
    endif()
    # Add library search directories for minizip/libzip if provided
    if(MINIZIP_FOUND AND MINIZIP_LIBRARY_DIRS)
        target_link_directories(turboxl PRIVATE ${MINIZIP_LIBRARY_DIRS})
    endif()
    if(LIBZIP_FOUND AND LIBZIP_LIBRARY_DIRS)
        target_link_directories(turboxl PRIVATE ${LIBZIP_LIBRARY_DIRS})
    endif()
    
    # Ensure hidden visibility for small ABI surface
    set_target_properties(turboxl PROPERTIES
        CXX_VISIBILITY_PRESET hidden
        VISIBILITY_INLINES_HIDDEN ON
    )

    # Install the Python extension into the wheel's platlib root
    install(TARGETS turboxl
        LIBRARY DESTINATION . COMPONENT python
        RUNTIME DESTINATION . COMPONENT python
        ARCHIVE DESTINATION . COMPONENT python
    )
endif()

# Tests
if(BUILD_TESTS)
    enable_testing()
    find_package(Python REQUIRED COMPONENTS Interpreter)
    configure_file(tests/fixture_config.hpp.in fixture_config.hpp @ONLY)
    execute_process(COMMAND "${Python_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tools/wheels/fixtures.py"
        --workbook "${CMAKE_CURRENT_BINARY_DIR}/integration.xlsx"
        COMMAND_ERROR_IS_FATAL ANY)
    
    set(BUILD_GMOCK OFF CACHE BOOL "Only Google Test is needed" FORCE)
    set(gtest_force_shared_crt ON CACHE BOOL "Use CPython-compatible MSVC runtime" FORCE)
    # Find Google Test
    find_package(GTest QUIET)
    if(NOT GTest_FOUND)
        # Fallback: download and build GTest
        include(FetchContent)
        FetchContent_Declare(
            googletest
            GIT_REPOSITORY https://github.com/google/googletest.git
            GIT_TAG 58d77fa8070e8cec2dc1ed015d66b454c8d78850 # release-1.12.1
        )
        FetchContent_MakeAvailable(googletest)
    endif()
    
    add_executable(turboxl_tests
        tests/main.cpp
        tests/test_zip_reader.cpp
        tests/test_opc_package.cpp
        tests/test_workbook.cpp
        tests/test_styles_registry.cpp
        tests/test_shared_strings_provider.cpp
        tests/test_sheet_stream_reader.cpp
        tests/test_sheet_discovery.cpp
        tests/test_phase5_functionality.cpp
        tests/test_csv_encoder.cpp
        tests/test_integration.cpp
    )
    
    target_include_directories(turboxl_tests PRIVATE "${CMAKE_CURRENT_BINARY_DIR}")

    target_link_libraries(turboxl_tests
        PRIVATE
            turboxl_core
            GTest::gtest
    )
    
    # Add library search directories for zlib-ng if needed
    if(ZLIB_LIBRARY_DIRS)
        target_link_directories(turboxl_tests PRIVATE ${ZLIB_LIBRARY_DIRS})
    endif()
    
    add_test(NAME core_tests COMMAND turboxl_tests)
endif()

# CLI tool
if(BUILD_CLI)
    add_executable(turboxl_cli tools/cli.cpp)
    target_link_libraries(turboxl_cli PRIVATE turboxl_core)
endif()

# Benchmarks
if(BUILD_BENCHMARKS)
    set(BENCHMARK_ENABLE_TESTING OFF CACHE BOOL "" FORCE)
    set(BENCHMARK_ENABLE_GTEST_TESTS OFF CACHE BOOL "" FORCE)
    find_package(benchmark QUIET)
    if(NOT benchmark_FOUND)
        include(FetchContent)
        FetchContent_Declare(
            benchmark
            GIT_REPOSITORY https://github.com/google/benchmark.git
            GIT_TAG v1.8.3
        )
        FetchContent_MakeAvailable(benchmark)
    endif()
    
    add_executable(turboxl_benchmarks benchmarks/main.cpp)
    target_link_libraries(turboxl_benchmarks
        PRIVATE
            turboxl_core
            benchmark::benchmark
    )
    if(ZLIB_LIBRARY_DIRS)
        target_link_directories(turboxl_benchmarks PRIVATE ${ZLIB_LIBRARY_DIRS})
    endif()
    if(MINIZIP_FOUND AND MINIZIP_LIBRARY_DIRS)
        target_link_directories(turboxl_benchmarks PRIVATE ${MINIZIP_LIBRARY_DIRS})
    endif()
endif()

# Installation
install(TARGETS turboxl_core
    EXPORT turboxlTargets
    LIBRARY DESTINATION lib
    ARCHIVE DESTINATION lib
    RUNTIME DESTINATION bin
    INCLUDES DESTINATION include
)

install(DIRECTORY include/ DESTINATION include)

install(EXPORT turboxlTargets
    FILE turboxlTargets.cmake
    NAMESPACE turboxl::
    DESTINATION lib/cmake/turboxl
)

# Create config file
include(CMakePackageConfigHelpers)
write_basic_package_version_file(
    "${CMAKE_CURRENT_BINARY_DIR}/turboxlConfigVersion.cmake"
    VERSION ${PROJECT_VERSION}
    COMPATIBILITY AnyNewerVersion
)

configure_file(
    "${CMAKE_CURRENT_SOURCE_DIR}/cmake/turboxlConfig.cmake.in"
    "${CMAKE_CURRENT_BINARY_DIR}/turboxlConfig.cmake"
    @ONLY
)

install(FILES
    "${CMAKE_CURRENT_BINARY_DIR}/turboxlConfig.cmake"
    "${CMAKE_CURRENT_BINARY_DIR}/turboxlConfigVersion.cmake"
    DESTINATION lib/cmake/turboxl
)
