cmake_minimum_required(VERSION 3.15)
project(cutysoup)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# Find Python and pybind11
find_package(Python REQUIRED COMPONENTS Interpreter Development.Module)
find_package(pybind11 CONFIG REQUIRED)

# Build gumbo-parser as a static library
set(GUMBO_SOURCES
    third_party/gumbo-parser/src/attribute.c
    third_party/gumbo-parser/src/char_ref.c
    third_party/gumbo-parser/src/error.c
    third_party/gumbo-parser/src/parser.c
    third_party/gumbo-parser/src/string_buffer.c
    third_party/gumbo-parser/src/string_piece.c
    third_party/gumbo-parser/src/tag.c
    third_party/gumbo-parser/src/tokenizer.c
    third_party/gumbo-parser/src/utf8.c
    third_party/gumbo-parser/src/util.c
    third_party/gumbo-parser/src/vector.c
)

add_library(gumbo STATIC ${GUMBO_SOURCES})
target_include_directories(gumbo PUBLIC third_party/gumbo-parser/src)
set_target_properties(gumbo PROPERTIES POSITION_INDEPENDENT_CODE ON)

# Windows-specific configuration for gumbo
if(WIN32)
    target_include_directories(gumbo PRIVATE third_party/gumbo-parser/visualc/include)
    target_compile_definitions(gumbo PRIVATE _CRT_SECURE_NO_WARNINGS)
endif()

# Include directories
include_directories(src/cpp)
include_directories(third_party/gumbo-parser/src)

# Source files for the canonical Python extension API.
# These bindings match the methods expected by the Python package.
set(SOURCES
    src/cpp/tree.cpp
    src/cpp/node.cpp
    src/cpp/bindings.cpp
    src/cpp/bulk_operations.cpp
    src/cpp/zero_context_batch.cpp
    src/cpp/simple_parallel_walker.cpp
    src/cpp/optimized_parallel_walker.cpp
    src/cpp/ultra_fast_walker.cpp
    src/cpp/lightning_walker.cpp
)

# Create the Python module
pybind11_add_module(_cutysoup ${SOURCES})

# Link with gumbo
target_link_libraries(_cutysoup PRIVATE gumbo)

# Compiler-specific optimizations. Keep them portable by default so wheels
# built on one machine still run on other machines with the same architecture.
if(MSVC)
    target_compile_options(_cutysoup PRIVATE /O2)
elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|X86_64|amd64|AMD64|i[3-6]86)$")
    target_compile_options(_cutysoup PRIVATE -O3 -msse4.2)
else()
    target_compile_options(_cutysoup PRIVATE -O3)
endif()

# Compiler-specific options
target_compile_definitions(_cutysoup PRIVATE VERSION_INFO=${CUTYSOUP_VERSION_INFO})

# Set properties
set_target_properties(_cutysoup PROPERTIES
    CXX_VISIBILITY_PRESET "hidden"
    VISIBILITY_INLINES_HIDDEN YES
)

# Install the compiled extension into the cutysoup package directory
install(TARGETS _cutysoup DESTINATION cutysoup)
