# CMakeLists.txt

cmake_minimum_required(VERSION 3.10)
project(coffee_crisis_arcade_edition VERSION 2.00)

# Establecer estándar de C++
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED True)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)


# --- GENERACIÓN DE VERSIÓN AUTOMÁTICA ---
find_package(Git QUIET)
if(GIT_FOUND)
    execute_process(
        COMMAND ${GIT_EXECUTABLE} rev-parse --short=7 HEAD
        WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
        OUTPUT_VARIABLE GIT_HASH
        OUTPUT_STRIP_TRAILING_WHITESPACE
        ERROR_QUIET
    )
else()
    set(GIT_HASH "unknown")
endif()

# Configurar archivo de versión
configure_file(${CMAKE_SOURCE_DIR}/source/version.h.in ${CMAKE_BINARY_DIR}/version.h @ONLY)

# --- 1. LISTA EXPLÍCITA DE FUENTES ---
set(APP_SOURCES
    # --- Archivos Principales del Sistema ---
    source/asset.cpp
    source/audio.cpp
    source/director.cpp
    source/global_events.cpp
    source/global_inputs.cpp
    source/input.cpp
    source/lang.cpp
    source/main.cpp
    source/param.cpp
    source/resource.cpp
    source/resource_helper.cpp
    source/resource_loader.cpp
    source/resource_pack.cpp
    source/screen.cpp
    source/text.cpp
    source/writer.cpp
    
    # --- UI (User Interface) ---
    source/ui/menu_option.cpp
    source/ui/menu_renderer.cpp
    source/ui/notifier.cpp
    source/ui/service_menu.cpp
    source/ui/ui_message.cpp
    source/ui/window_message.cpp
    
    # --- Lógica del Juego ---
    source/balloon_formations.cpp
    source/balloon_manager.cpp
    source/balloon.cpp
    source/bullet.cpp
    source/bullet_manager.cpp
    source/enter_name.cpp
    source/explosions.cpp
    source/game_logo.cpp
    source/item.cpp
    source/manage_hiscore_table.cpp
    source/player.cpp
    source/scoreboard.cpp
    source/tabe.cpp
    
    # --- Escenas ---
    source/sections/credits.cpp
    source/sections/game.cpp
    source/sections/hiscore_table.cpp
    source/sections/instructions.cpp
    source/sections/intro.cpp
    source/sections/logo.cpp
    source/sections/title.cpp
    
    # --- Sprites y Gráficos ---
    source/animated_sprite.cpp
    source/background.cpp
    source/card_sprite.cpp
    source/fade.cpp
    source/moving_sprite.cpp
    source/path_sprite.cpp
    source/smart_sprite.cpp
    source/sprite.cpp
    source/texture.cpp
    source/tiled_bg.cpp
    
    # --- Otros ---
    source/color.cpp
    source/demo.cpp
    source/define_buttons.cpp
    source/difficulty.cpp
    source/input_types.cpp
    source/mouse.cpp
    source/options.cpp
    source/shutdown.cpp
    source/stage.cpp
    source/system_utils.cpp
    source/utils.cpp
)

# Fuentes de librerías de terceros
set(EXTERNAL_SOURCES
    source/external/jail_audio.cpp
    source/external/json.hpp
    source/external/gif.cpp
)

# Fuentes del sistema de renderizado
set(RENDERING_SOURCES
    source/rendering/sdl3gpu/sdl3gpu_shader.cpp
)

# Configuración de SDL3
find_package(SDL3 REQUIRED CONFIG REQUIRED COMPONENTS SDL3)
message(STATUS "SDL3 encontrado: ${SDL3_INCLUDE_DIRS}")

# --- SHADER COMPILATION (Linux/Windows only - macOS uses Metal) ---
if(NOT APPLE)
    find_program(GLSLC_EXE NAMES glslc)

    set(SHADER_VERT_SRC     "${CMAKE_SOURCE_DIR}/data/shaders/postfx.vert")
    set(SHADER_FRAG_SRC     "${CMAKE_SOURCE_DIR}/data/shaders/postfx.frag")
    set(SHADER_CRTPI_SRC    "${CMAKE_SOURCE_DIR}/data/shaders/crtpi_frag.glsl")
    set(SHADER_UPSCALE_SRC  "${CMAKE_SOURCE_DIR}/data/shaders/upscale.frag")
    set(SHADER_DOWNSCALE_SRC "${CMAKE_SOURCE_DIR}/data/shaders/downscale.frag")

    set(SHADER_VERT_H       "${CMAKE_SOURCE_DIR}/source/rendering/sdl3gpu/postfx_vert_spv.h")
    set(SHADER_FRAG_H       "${CMAKE_SOURCE_DIR}/source/rendering/sdl3gpu/postfx_frag_spv.h")
    set(SHADER_CRTPI_H      "${CMAKE_SOURCE_DIR}/source/rendering/sdl3gpu/crtpi_frag_spv.h")
    set(SHADER_UPSCALE_H    "${CMAKE_SOURCE_DIR}/source/rendering/sdl3gpu/upscale_frag_spv.h")
    set(SHADER_DOWNSCALE_H  "${CMAKE_SOURCE_DIR}/source/rendering/sdl3gpu/downscale_frag_spv.h")

    set(ALL_SHADER_SOURCES "${SHADER_VERT_SRC}" "${SHADER_FRAG_SRC}" "${SHADER_CRTPI_SRC}" "${SHADER_UPSCALE_SRC}" "${SHADER_DOWNSCALE_SRC}")
    set(ALL_SHADER_HEADERS "${SHADER_VERT_H}" "${SHADER_FRAG_H}" "${SHADER_CRTPI_H}" "${SHADER_UPSCALE_H}" "${SHADER_DOWNSCALE_H}")

    if(GLSLC_EXE)
        add_custom_command(
            OUTPUT  ${ALL_SHADER_HEADERS}
            COMMAND "${CMAKE_SOURCE_DIR}/tools/shaders/compile_spirv.sh"
            DEPENDS ${ALL_SHADER_SOURCES}
            WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
            COMMENT "Compilando shaders SPIR-V..."
        )
        add_custom_target(shaders DEPENDS ${ALL_SHADER_HEADERS})
        message(STATUS "glslc encontrado: shaders se compilarán automáticamente")
    else()
        foreach(_h IN LISTS ALL_SHADER_HEADERS)
            if(NOT EXISTS "${_h}")
                message(FATAL_ERROR
                    "glslc no encontrado y header SPIR-V no existe: ${_h}\n"
                    "  Instala glslc: sudo apt install glslang-tools  (Linux)\n"
                    "                 choco install vulkan-sdk         (Windows)\n"
                    "  O genera los headers manualmente: tools/shaders/compile_spirv.sh"
                )
            endif()
        endforeach()
        message(STATUS "glslc no encontrado - usando headers SPIR-V precompilados")
    endif()
else()
    message(STATUS "macOS: shaders SPIR-V omitidos (usa Metal)")
endif()

# --- 2. AÑADIR EJECUTABLE ---
add_executable(${PROJECT_NAME} ${APP_SOURCES} ${EXTERNAL_SOURCES} ${RENDERING_SOURCES})

if(NOT APPLE AND GLSLC_EXE)
    add_dependencies(${PROJECT_NAME} shaders)
endif()

# --- 3. DIRECTORIOS DE INCLUSIÓN ---
target_include_directories(${PROJECT_NAME} PUBLIC
    "${CMAKE_SOURCE_DIR}/source"
    "${CMAKE_SOURCE_DIR}/source/external"
    "${CMAKE_SOURCE_DIR}/source/rendering"
    "${CMAKE_SOURCE_DIR}/source/rendering/sdl3gpu"
    "${CMAKE_BINARY_DIR}"
)

# Enlazar la librería SDL3
target_link_libraries(${PROJECT_NAME} PRIVATE SDL3::SDL3)


# --- 4. CONFIGURACIÓN PLATAFORMAS Y COMPILADOR  ---
# Configuración de flags de compilación
target_compile_options(${PROJECT_NAME} PRIVATE -Wall)
target_compile_options(${PROJECT_NAME} PRIVATE $<$<CONFIG:RELEASE>:-Os -ffunction-sections -fdata-sections>)

# Definir _DEBUG en modo Debug
target_compile_definitions(${PROJECT_NAME} PRIVATE $<$<CONFIG:DEBUG>:_DEBUG>)

# Descomentar la siguiente línea para activar el modo grabación de demos
# target_compile_definitions(${PROJECT_NAME} PRIVATE RECORDING)


# Configuración específica para cada plataforma
if(WIN32)
    target_compile_definitions(${PROJECT_NAME} PRIVATE WINDOWS_BUILD)
    target_link_libraries(${PROJECT_NAME} PRIVATE ws2_32 mingw32)
elseif(APPLE)
    target_compile_definitions(${PROJECT_NAME} PRIVATE MACOS_BUILD)
    set(CMAKE_OSX_ARCHITECTURES "arm64")
elseif(UNIX AND NOT APPLE)
    target_compile_definitions(${PROJECT_NAME} PRIVATE LINUX_BUILD)
endif()

# Especificar la ubicación del ejecutable
set_target_properties(${PROJECT_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR})

# --- 5. STATIC ANALYSIS TARGETS ---

find_program(CLANG_TIDY_EXE NAMES clang-tidy)
find_program(CLANG_FORMAT_EXE NAMES clang-format)

# Recopilar todos los archivos fuente, excluyendo external/
file(GLOB_RECURSE ALL_SOURCE_FILES
    "${CMAKE_SOURCE_DIR}/source/*.cpp"
    "${CMAKE_SOURCE_DIR}/source/*.hpp"
    "${CMAKE_SOURCE_DIR}/source/*.h"
)
list(FILTER ALL_SOURCE_FILES EXCLUDE REGEX ".*/external/.*")

# Targets de clang-tidy
if(CLANG_TIDY_EXE)
    # En macOS con clang-tidy de Homebrew LLVM, es necesario pasar el sysroot
    # explícitamente para que encuentre los headers del sistema (string, memory, etc.)
    if(APPLE)
        execute_process(
            COMMAND xcrun --show-sdk-path
            OUTPUT_VARIABLE MACOS_SDK_PATH
            OUTPUT_STRIP_TRAILING_WHITESPACE
        )
        set(TIDY_EXTRA_ARGS --extra-arg=-isysroot --extra-arg=${MACOS_SDK_PATH})
    endif()

    add_custom_target(tidy
        COMMAND ${CLANG_TIDY_EXE}
            -p ${CMAKE_BINARY_DIR}
            ${TIDY_EXTRA_ARGS}
            ${ALL_SOURCE_FILES}
        WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
        COMMENT "Running clang-tidy..."
    )

    add_custom_target(tidy-fix
        COMMAND ${CLANG_TIDY_EXE}
            -p ${CMAKE_BINARY_DIR}
            --fix
            ${TIDY_EXTRA_ARGS}
            ${ALL_SOURCE_FILES}
        WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
        COMMENT "Running clang-tidy with fixes..."
    )
else()
    message(STATUS "clang-tidy no encontrado - targets 'tidy' y 'tidy-fix' no disponibles")
endif()

# Targets de clang-format
if(CLANG_FORMAT_EXE)
    add_custom_target(format
        COMMAND ${CLANG_FORMAT_EXE}
            -i
            ${ALL_SOURCE_FILES}
        WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
        COMMENT "Running clang-format..."
    )

    add_custom_target(format-check
        COMMAND ${CLANG_FORMAT_EXE}
            --dry-run
            --Werror
            ${ALL_SOURCE_FILES}
        WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
        COMMENT "Checking clang-format..."
    )
else()
    message(STATUS "clang-format no encontrado - targets 'format' y 'format-check' no disponibles")
endif()
