# CMakeLists.txt

cmake_minimum_required(VERSION 3.10)
project(jaildoctors_dilemma VERSION 1.00)

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

# Exportar comandos de compilación para herramientas de análisis
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
    # Core - Audio
    source/core/audio/audio.cpp

    # Core - Input
    source/core/input/global_inputs.cpp
    source/core/input/input.cpp
    source/core/input/input_types.cpp
    source/core/input/mouse.cpp

    # Core - Rendering
    source/core/rendering/gif.cpp
    source/core/rendering/pixel_reveal.cpp
    source/core/rendering/screen.cpp
    source/core/rendering/surface.cpp
    source/core/rendering/sprite/animated_sprite.cpp
    source/core/rendering/sprite/dissolve_sprite.cpp
    source/core/rendering/sprite/moving_sprite.cpp
    source/core/rendering/sprite/sprite.cpp
    source/core/rendering/text.cpp

    # Core - Locale
    source/core/locale/locale.cpp

    # Core - Resources
    source/core/resources/resource_list.cpp
    source/core/resources/resource_cache.cpp
    source/core/resources/resource_pack.cpp
    source/core/resources/resource_loader.cpp
    source/core/resources/resource_helper.cpp

    # Core - System
    source/core/system/director.cpp
    source/core/system/global_events.cpp

    # Game - Entities
    source/game/entities/enemy.cpp
    source/game/entities/item.cpp
    source/game/entities/player.cpp

    # Game - Configuration
    source/game/options.cpp

    # Game - Gameplay
    source/game/gameplay/cheevos.cpp
    source/game/gameplay/collision_map.cpp
    source/game/gameplay/enemy_manager.cpp
    source/game/gameplay/item_manager.cpp
    source/game/gameplay/item_tracker.cpp
    source/game/gameplay/room.cpp
    source/game/gameplay/room_loader.cpp
    source/game/gameplay/room_tracker.cpp
    source/game/gameplay/scoreboard.cpp
    source/game/gameplay/stats.cpp
    source/game/gameplay/tilemap_renderer.cpp

    # Game - Scenes
    source/game/scenes/credits.cpp
    source/game/scenes/ending.cpp
    source/game/scenes/ending2.cpp
    source/game/scenes/game.cpp
    source/game/scenes/game_over.cpp
    source/game/scenes/loading_screen.cpp
    source/game/scenes/logo.cpp
    source/game/scenes/title.cpp

    # Game - UI
    source/game/ui/console.cpp
    source/game/ui/notifier.cpp

    # Utils
    source/utils/delta_timer.cpp
    source/utils/utils.cpp

    # Main
    source/main.cpp
)

# Fuentes del sistema de renderizado (SDL3 GPU para todas las plataformas)
set(RENDERING_SOURCES
    source/core/rendering/sdl3gpu/sdl3gpu_shader.cpp
)

# Fuentes de debug (solo en modo Debug)
set(DEBUG_SOURCES
    source/core/system/debug.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_VERT_H   "${CMAKE_SOURCE_DIR}/source/core/rendering/sdl3gpu/postfx_vert_spv.h")
    set(SHADER_FRAG_H   "${CMAKE_SOURCE_DIR}/source/core/rendering/sdl3gpu/postfx_frag_spv.h")

    if(GLSLC_EXE)
        add_custom_command(
            OUTPUT  "${SHADER_VERT_H}" "${SHADER_FRAG_H}"
            COMMAND ${CMAKE_COMMAND}
                    -D GLSLC=${GLSLC_EXE}
                    -D SHADERS_DIR=${CMAKE_SOURCE_DIR}/data/shaders
                    -D HEADERS_DIR=${CMAKE_SOURCE_DIR}/source/core/rendering/sdl3gpu
                    -P ${CMAKE_SOURCE_DIR}/tools/shaders/compile_spirv.cmake
            DEPENDS "${SHADER_VERT_SRC}" "${SHADER_FRAG_SRC}"
            WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
            COMMENT "Compilando shaders SPIR-V..."
        )
        add_custom_target(shaders DEPENDS "${SHADER_VERT_H}" "${SHADER_FRAG_H}")
        message(STATUS "glslc encontrado: shaders se compilarán automáticamente")
    else()
        if(NOT EXISTS "${SHADER_VERT_H}" OR NOT EXISTS "${SHADER_FRAG_H}")
            message(FATAL_ERROR
                "glslc no encontrado y headers SPIR-V no existen.\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"
            )
        else()
            message(STATUS "glslc no encontrado - usando headers SPIR-V precompilados")
        endif()
    endif()
else()
    message(STATUS "macOS: shaders SPIR-V omitidos (usa Metal)")
endif()

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

# Shaders deben compilarse antes que el ejecutable (Linux/Windows con glslc)
if(NOT APPLE AND GLSLC_EXE)
    add_dependencies(${PROJECT_NAME} shaders)
endif()

# Añadir fuentes de debug solo en modo Debug
target_sources(${PROJECT_NAME} PRIVATE $<$<CONFIG:Debug>:${DEBUG_SOURCES}>)

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

# Enlazar las librerías 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 y RELEASE_BUILD en modo Release
target_compile_definitions(${PROJECT_NAME} PRIVATE $<$<CONFIG:DEBUG>:_DEBUG>)
target_compile_definitions(${PROJECT_NAME} PRIVATE $<$<CONFIG:RELEASE>:RELEASE_BUILD>)

# 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)
    target_compile_options(${PROJECT_NAME} PRIVATE -Wno-deprecated)
    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 ---

# Buscar herramientas de análisis estático
find_program(CLANG_TIDY_EXE NAMES clang-tidy)
find_program(CLANG_FORMAT_EXE NAMES clang-format)

# Recopilar todos los archivos fuente para formateo
file(GLOB_RECURSE ALL_SOURCE_FILES
    "${CMAKE_SOURCE_DIR}/source/*.cpp"
    "${CMAKE_SOURCE_DIR}/source/*.hpp"
    "${CMAKE_SOURCE_DIR}/source/*.h"
)

# Excluir directorio external del análisis
list(FILTER ALL_SOURCE_FILES EXCLUDE REGEX ".*/external/.*")

# Para clang-tidy, también excluir jail_audio.hpp
set(CLANG_TIDY_SOURCES ${ALL_SOURCE_FILES})
list(FILTER CLANG_TIDY_SOURCES EXCLUDE REGEX ".*jail_audio\\.hpp$")
list(FILTER CLANG_TIDY_SOURCES EXCLUDE REGEX ".*_spv\\.h$")

# Targets de clang-tidy
if(CLANG_TIDY_EXE)
    add_custom_target(tidy
        COMMAND ${CLANG_TIDY_EXE}
            -p ${CMAKE_BINARY_DIR}
            ${CLANG_TIDY_SOURCES}
        WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
        COMMENT "Running clang-tidy..."
    )

    add_custom_target(tidy-fix
        COMMAND ${CLANG_TIDY_EXE}
            -p ${CMAKE_BINARY_DIR}
            --fix
            ${CLANG_TIDY_SOURCES}
        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()

# --- 6. PACK RESOURCES TARGETS ---
set(PACK_TOOL_SOURCES
    ${CMAKE_SOURCE_DIR}/tools/pack_resources/pack_resources.cpp
    ${CMAKE_SOURCE_DIR}/source/core/resources/resource_pack.cpp
)

add_executable(pack_tool ${PACK_TOOL_SOURCES})
target_include_directories(pack_tool PRIVATE ${CMAKE_SOURCE_DIR}/source)
set_target_properties(pack_tool PROPERTIES
    RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/tools/pack_resources
)

file(GLOB_RECURSE DATA_FILES "${CMAKE_SOURCE_DIR}/data/*")

add_custom_command(
    OUTPUT  "${CMAKE_SOURCE_DIR}/resources.pack"
    COMMAND $<TARGET_FILE:pack_tool>
            "${CMAKE_SOURCE_DIR}/data"
            "${CMAKE_SOURCE_DIR}/resources.pack"
    DEPENDS pack_tool ${DATA_FILES}
    WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
    COMMENT "Generando resources.pack desde data/..."
)

add_custom_target(pack DEPENDS "${CMAKE_SOURCE_DIR}/resources.pack")
add_dependencies(${PROJECT_NAME} pack)
