# CMakeLists.txt

cmake_minimum_required(VERSION 3.10)
project(pollo VERSION 0.1)

# Info del proyecto para version.h
set(PROJECT_LONG_NAME "Los pollos hermanos")
set(PROJECT_COPYRIGHT "@2025 JailDesigner")

# 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)

# Establece la política CMP0072 para indicar cómo se debe seleccionar la implementación de OpenGL.
# En este caso, se elige la opción "GLVND", que utiliza bibliotecas modernas y modulares (libOpenGL, libGLX),
# en lugar de la biblioteca OpenGL clásica (libGL). Esto mejora la compatibilidad con drivers recientes
# y evita ambigüedades cuando se encuentran múltiples implementaciones de OpenGL en el sistema.
cmake_policy(SET CMP0072 NEW)
set(OpenGL_GL_PREFERENCE GLVND)

# --- 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/project.h.in ${CMAKE_SOURCE_DIR}/source/project.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/screen.cpp
    source/core/rendering/surface.cpp
    source/core/rendering/surface_animated_sprite.cpp
    source/core/rendering/surface_moving_sprite.cpp
    source/core/rendering/surface_sprite.cpp
    source/core/rendering/text.cpp
    source/core/rendering/texture.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/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/tilemap_renderer.cpp

    # Game - Scenes
    source/game/scenes/game.cpp
    source/game/scenes/logo.cpp
    source/game/scenes/title.cpp

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

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

    # Main
    source/main.cpp
)

# Fuentes del sistema de renderizado
set(RENDERING_SOURCES
    source/core/rendering/opengl/opengl_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}")

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

# 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 opengl32)
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()

# Configuración común para OpenGL
if(NOT WIN32)
    find_package(OpenGL REQUIRED)
    if(OPENGL_FOUND)
        message(STATUS "OpenGL encontrado: ${OPENGL_LIBRARIES}")
        target_link_libraries(${PROJECT_NAME} PRIVATE ${OPENGL_LIBRARIES})
    else()
        message(FATAL_ERROR "OpenGL no encontrado")
    endif()
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$")

# 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()
