# generate_swig_version.cmake
execute_process(
    COMMAND ${SWIG_EXECUTABLE} -version
    OUTPUT_VARIABLE SWIG_OUTPUT
    ERROR_VARIABLE SWIG_ERROR
    OUTPUT_STRIP_TRAILING_WHITESPACE
    ERROR_STRIP_TRAILING_WHITESPACE
)

set(FULL_OUTPUT "${SWIG_OUTPUT}\n${SWIG_ERROR}")

string(REGEX MATCH "SWIG Version ([0-9]+)\\.([0-9]+)\\.([0-9]+)" MATCH_FOUND "${FULL_OUTPUT}")

if(MATCH_FOUND)
    # Extract capture groups
    set(SWIG_VERSION_MAJOR ${CMAKE_MATCH_1})
    set(SWIG_VERSION_MINOR ${CMAKE_MATCH_2})
    set(SWIG_VERSION_PATCH ${CMAKE_MATCH_3})

    message(STATUS "Found SWIG Version: ${SWIG_VERSION_MAJOR}.${SWIG_VERSION_MINOR}.${SWIG_VERSION_PATCH}")

    # Format: 0x<MAJ><MIN><PATCH> (assuming 8 bits per component)
    # Calculation: (Major << 16) | (Minor << 8) | Patch

    math(EXPR VERSION_NUM
        "(${SWIG_VERSION_MAJOR} << 16) + (${SWIG_VERSION_MINOR} << 8) + ${SWIG_VERSION_PATCH}"
        OUTPUT_FORMAT HEXADECIMAL
    )

    set(HEADER_FILE "swig_version.h")

    file(WRITE ${SWIG_VERSION_HEADER}
"// Auto-generated by CMake
#ifndef SWIG_VERSION_META_H
#define SWIG_VERSION_META_H

#define SWIG_VERSION_MAJOR ${SWIG_VERSION_MAJOR}
#define SWIG_VERSION_MINOR ${SWIG_VERSION_MINOR}
#define SWIG_VERSION_PATCH ${SWIG_VERSION_PATCH}

// Hex format 0xMAJMINPAT (e.g. 4.1.0 -> 0x40100)
#define SWIG_VERSION  ${VERSION_NUM}

#endif // SWIG_VERSION_META_H
"
    )

    message(STATUS "Generated ${HEADER_FILE} with version ${VERSION_NUM}")

else()
    message(WARNING "Could not parse SWIG version from output:\n${FULL_OUTPUT}")
endif()

