cmake_minimum_required(VERSION 3.16)
project(RISCB C)

set(CMAKE_C_STANDARD 23)

find_package(PkgConfig REQUIRED)

# Allow setting the target platform manually
if (NOT DEFINED TARGET_PLATFORM)
    if (WIN32)
        set(TARGET_PLATFORM windows)
    elseif (UNIX)
        set(TARGET_PLATFORM linux)
    else ()
        message(FATAL_ERROR "Unsupported platform. Please set TARGET_PLATFORM manually.")
    endif ()
endif ()

message(STATUS "Target platform: ${TARGET_PLATFORM}")

# Detect build type and configure SDL2 paths accordingly
if (TARGET_PLATFORM STREQUAL "windows")
    include_directories(${SDL2_INCLUDE_DIR})
elseif (TARGET_PLATFORM STREQUAL "mingw")
    set(CMAKE_C_COMPILER x86_64-w64-mingw32-gcc)
    set(CMAKE_RC_COMPILER x86_64-w64-mingw32-windres)
    find_package(SDL2 REQUIRED)
    find_package(SDL2_ttf REQUIRED)
    include_directories(${SDL2_INCLUDE_DIRS})
    link_directories(${SDL2_LIBRARY_DIRS})
    add_definitions(${SDL2_CFLAGS_OTHER})
elseif (TARGET_PLATFORM STREQUAL "linux")
    pkg_check_modules(SDL2 REQUIRED sdl2)
    pkg_check_modules(SDL2_TTF REQUIRED SDL2_ttf)
    include_directories(${SDL2_INCLUDE_DIRS})
    add_definitions(${SDL2_CFLAGS_OTHER})
else ()
    message(FATAL_ERROR "Unsupported TARGET_PLATFORM: ${TARGET_PLATFORM}")
endif ()

# Define source files
set(SOURCE_FILES
        main.c
        util/font.c util/font.h
        assembler/assembler.c assembler/assembler.h
        cpu/memory.c cpu/memory.h
        cpu/core.c cpu/core.h
        util/texteditor.c util/texteditor.h
        util/hexdump.c util/hexdump.h
        util/cpustatusui.c util/cpustatusui.h
        peripherals/audio.c
        peripherals/audio.h
        peripherals/peripheraldata.c
        peripherals/peripheraldata.h
)

# Build the target executable
add_executable(RISCB ${SOURCE_FILES})
target_link_libraries(RISCB SDL2 SDL2_ttf m)

# Cross-compile Windows executable on Unix
if (UNIX AND TARGET_PLATFORM STREQUAL "mingw")
    add_executable(RISCB_WIN32 ${SOURCE_FILES})
    set_target_properties(RISCB_WIN32 PROPERTIES COMPILE_FLAGS "-mwindows")
    set(CMAKE_C_COMPILER x86_64-w64-mingw32-gcc)
    set(CMAKE_RC_COMPILER x86_64-w64-mingw32-windres)
    add_definitions(-DSDL_MAIN_HANDLED)
    target_link_libraries(RISCB_WIN32 mingw32 SDL2main SDL2 SDL2_ttf -static-libgcc -static-libstdc++)
endif ()
