# CMake script to embed binary files as C arrays

function(embed_resource RESOURCE_FILE OUTPUT_FILE VAR_NAME)
    file(READ "${RESOURCE_FILE}" HEX_CONTENT HEX)
    
    # Convert hex to C array format
    string(LENGTH "${HEX_CONTENT}" HEX_LENGTH)
    math(EXPR BYTE_COUNT "${HEX_LENGTH} / 2")
    
    set(ARRAY_CONTENT "")
    set(INDEX 0)
    while(INDEX LESS HEX_LENGTH)
        string(SUBSTRING "${HEX_CONTENT}" ${INDEX} 2 BYTE)
        string(APPEND ARRAY_CONTENT "0x${BYTE},")
        math(EXPR INDEX "${INDEX} + 2")
        math(EXPR BYTE_NUM "${INDEX} / 2")
        math(EXPR MOD "${BYTE_NUM} % 16")
        if(MOD EQUAL 0)
            string(APPEND ARRAY_CONTENT "\n    ")
        endif()
    endwhile()
    
    # Generate header file
    set(HEADER_CONTENT "// Auto-generated embedded resource - DO NOT EDIT
#pragma once
#include <cstddef>
#include <cstdint>

namespace embedded {

inline constexpr unsigned char ${VAR_NAME}_data[] = {
    ${ARRAY_CONTENT}
};

inline constexpr size_t ${VAR_NAME}_size = ${BYTE_COUNT};

} // namespace embedded
")
    
    file(WRITE "${OUTPUT_FILE}" "${HEADER_CONTENT}")
    message(STATUS "Embedded ${RESOURCE_FILE} -> ${OUTPUT_FILE} (${BYTE_COUNT} bytes)")
endfunction()
