cmake_minimum_required(VERSION 3.16)

# Require project name to be passed from command line
if(NOT DEFINED PROJECT_NAME)
    message(FATAL_ERROR 
        "PROJECT_NAME is not defined!\n"
        "Please pass -DPROJECT_NAME=your_project_name when configuring CMake.\n"
        "Example: cmake -DPROJECT_NAME=hello-rpi ..."
    )
endif()

# Validate project name (no spaces, special characters, etc.)
if(PROJECT_NAME MATCHES "[ /\\]")
    message(FATAL_ERROR 
        "PROJECT_NAME contains invalid characters: ${PROJECT_NAME}\n"
        "Project name should not contain spaces or path separators."
    )
endif()

# Project name and version
project(${PROJECT_NAME} VERSION 1.0 LANGUAGES C CXX)

# Display configuration info
message(STATUS "Building project: ${PROJECT_NAME}")
message(STATUS "Buildroot path: ${BUILDROOT_PATH}")

# Generate compile_commands.json for IntelliSense
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

# Set C standard
set(CMAKE_C_STANDARD 23)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_EXTENSIONS ON)

# Set C++ standard
set(CMAKE_CXX_STANDARD 23)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS ON)  # This enables GNU extensions (gnu++23 instead of c++23)

# Add compile options
add_compile_options(-fno-exceptions -fno-rtti -Wall -Wextra -Wpedantic)

# Build with debug symbols by default
if(NOT CMAKE_BUILD_TYPE)
    set(CMAKE_BUILD_TYPE Debug)
endif()

# --------------------------------------------------------------------------
# Graphics library (platform-independent core)
# --------------------------------------------------------------------------
add_library(gfx_core STATIC
    gfx_canvas.cpp
)
target_include_directories(gfx_core PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})

# --------------------------------------------------------------------------
# Linux framebuffer HAL
# --------------------------------------------------------------------------
add_library(gfx_linux_fb STATIC
    linux_fb_display.cpp
)
target_link_libraries(gfx_linux_fb PUBLIC gfx_core)

# Use project name for executable
add_executable(${PROJECT_NAME}
    main.cpp
)

# If you have additional source files, add them here:
# add_executable(${PROJECT_NAME}
#     main.cpp
#     other_file.cpp
#     another_file.cpp
# )

find_package(PkgConfig REQUIRED)
set(ENV{PKG_CONFIG_SYSROOT_DIR} "${CMAKE_SYSROOT}")
set(ENV{PKG_CONFIG_LIBDIR}      "${CMAKE_SYSROOT}/usr/lib/pkgconfig:${CMAKE_SYSROOT}/usr/share/pkgconfig")
pkg_check_modules(LIBNL_GENL REQUIRED libnl-genl-3.0)

target_include_directories(${PROJECT_NAME} PRIVATE ${LIBNL_GENL_INCLUDE_DIRS})
target_link_libraries(${PROJECT_NAME} PRIVATE gfx_linux_fb ${LIBNL_GENL_LIBRARIES})

# Install rule (optional)
install(TARGETS ${PROJECT_NAME} DESTINATION bin)