cmake_minimum_required(VERSION 3.16)
project(aee_2026 VERSION 0.1.0 LANGUAGES CXX)

if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
    set(CMAKE_BUILD_TYPE Debug CACHE STRING "" FORCE)
endif()

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

# --- GENERACIÓ DEL VERSION.H AMB GIT HASH ---
# Si GIT_HASH ve passat des de fora (Makefile), l'usem; si no, el resolem amb git.
if(NOT DEFINED GIT_HASH OR GIT_HASH STREQUAL "")
    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
        )
    endif()
    if(NOT DEFINED GIT_HASH OR GIT_HASH STREQUAL "")
        set(GIT_HASH "unknown")
    endif()
endif()

configure_file(${CMAKE_SOURCE_DIR}/source/version.h.in ${CMAKE_BINARY_DIR}/version.h @ONLY)

# Sources comuns del sistema d'entitats: s'afegeixen tant a l'executable
# principal com al smoke test. Mantenir-los en variable separada evita
# duplicació entre els dos targets.
set(ENTITY_SOURCES
    source/game/entities/entity.cpp
    source/game/entities/animation_component.cpp
    source/game/entities/event_bus.cpp
    source/game/entities/entity_factory.cpp
    source/game/entities/entity_loader.cpp
    source/game/entities/entity_manager.cpp
    source/game/entities/concrete/torch.cpp
    source/game/entities/concrete/sarcophagus.cpp
    source/game/entities/concrete/door.cpp
    source/game/entities/concrete/mummy.cpp
    source/game/entities/concrete/rolling_rock.cpp
    source/game/entities/concrete/wall_trap.cpp
    source/game/entities/concrete/floor_trap.cpp
)

set(APP_SOURCES
    source/main.cpp
    source/core/system/director.cpp
    source/core/audio/audio.cpp
    source/core/audio/audio_adapter.cpp
    source/core/audio/jail_audio.cpp
    source/core/locale/locale.cpp
    source/core/input/key_config.cpp
    source/core/input/global_inputs.cpp
    source/core/input/input_state.cpp
    source/core/input/gamepad_manager.cpp
    source/core/rendering/screen.cpp
    source/core/rendering/canvas.cpp
    source/core/rendering/notifier.cpp
    source/core/rendering/render_info.cpp
    source/core/rendering/gif.cpp
    source/core/rendering/surface.cpp
    source/core/rendering/text.cpp
    source/core/rendering/sprite/sprite.cpp
    source/core/rendering/sprite/moving_sprite.cpp
    source/core/rendering/sprite/animated_sprite.cpp
    source/core/rendering/sdl3gpu/sdl3gpu_shader.cpp
    source/core/rendering/sdl3gpu/viewport.cpp
    source/core/rendering/sdl3gpu/pipelines/crtpi_pipeline.cpp
    source/core/resources/resource_helper.cpp
    source/core/resources/resource_cache.cpp
    source/core/resources/palette_loader.cpp
    source/utils/easing.cpp
    source/utils/utils.cpp
    source/game/debug_config.cpp
    source/game/options.cpp
    source/game/options_apply.cpp
    source/game/ui/service_menu.cpp
    source/game/scenes/placeholder_input.cpp
    source/game/scenes/logo_scene.cpp
    source/game/scenes/title_scene.cpp
    source/game/scenes/intro_scene.cpp
    source/game/scenes/game_scene.cpp
    source/game/entities/player.cpp
    source/game/map/map.cpp
    source/game/map/tilemap.cpp
    ${ENTITY_SOURCES}
    # Fitxer només del binari principal: `loadFromLevel` depèn de
    # Resource::Cache (→ Surface → GIF → àudio). Separat per no arrossegar
    # les seues dependències al smoke test stand-alone.
    source/game/entities/entity_manager_loadlevel.cpp
)

find_package(SDL3 REQUIRED CONFIG REQUIRED COMPONENTS SDL3)

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

    set(SHADERS_DIR "${CMAKE_SOURCE_DIR}/data/shaders")
    set(HEADERS_DIR "${CMAKE_SOURCE_DIR}/source/core/rendering/sdl3gpu/spv")

    set(ALL_SHADER_SOURCES
        "${SHADERS_DIR}/postfx.vert"
        "${SHADERS_DIR}/postfx.frag"
        "${SHADERS_DIR}/crtpi_frag.glsl"
    )
    set(ALL_SHADER_HEADERS
        "${HEADERS_DIR}/postfx_vert_spv.h"
        "${HEADERS_DIR}/postfx_frag_spv.h"
        "${HEADERS_DIR}/crtpi_frag_spv.h"
    )

    if(GLSLC_EXE)
        add_custom_command(
            OUTPUT  ${ALL_SHADER_HEADERS}
            COMMAND ${CMAKE_COMMAND}
                    -D GLSLC=${GLSLC_EXE}
                    -D SHADERS_DIR=${SHADERS_DIR}
                    -D HEADERS_DIR=${HEADERS_DIR}
                    -P ${CMAKE_SOURCE_DIR}/tools/shaders/compile_spirv.cmake
            DEPENDS ${ALL_SHADER_SOURCES}
            WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
            COMMENT "Compilant shaders SPIR-V..."
        )
        add_custom_target(shaders DEPENDS ${ALL_SHADER_HEADERS})
        message(STATUS "glslc trobat: els shaders es compilaran automaticament")
    else()
        # Dummy guards: sense glslc obligem que els headers pre-compilats existisquen.
        foreach(HDR ${ALL_SHADER_HEADERS})
            if(NOT EXISTS "${HDR}")
                message(FATAL_ERROR
                    "glslc no trobat i el header SPIR-V no existeix: ${HDR}\n"
                    "  Instal·la glslc (Linux: sudo apt install glslang-tools) o\n"
                    "  comprova que el fitxer pre-compilat existeix al repositori."
                )
            endif()
        endforeach()
        message(STATUS "glslc no trobat - usant headers SPIR-V pre-compilats")
    endif()
endif()

add_executable(${PROJECT_NAME} ${APP_SOURCES})

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

target_include_directories(${PROJECT_NAME} PRIVATE
    "${CMAKE_SOURCE_DIR}/source"
    "${CMAKE_BINARY_DIR}"
)

target_link_libraries(${PROJECT_NAME} PRIVATE SDL3::SDL3)

# Còpia recursiva de data/ al costat del binari perquè les rutes relatives
# ("data/player/player.gif") funcionin sense desplegament. Es defineix com
# a custom target amb `ALL` — s'executa a cada `cmake --build` encara que
# el binari no hagi canviat, de manera que editar YAML/GIF sense tocar codi
# igualment sincronitza el build. Abans era un POST_BUILD, i si només es
# modificava una dada la còpia no es disparava.
add_custom_target(sync_data ALL
    COMMAND ${CMAKE_COMMAND} -E copy_directory
        "${CMAKE_SOURCE_DIR}/data"
        "${CMAKE_BINARY_DIR}/data"
    COMMENT "Copying data/ next to the binary"
)
add_dependencies(${PROJECT_NAME} sync_data)

target_compile_options(${PROJECT_NAME} PRIVATE -Wall -Wextra -Wpedantic)
target_compile_definitions(${PROJECT_NAME} PRIVATE
    $<$<CONFIG:Debug>:_DEBUG>
    $<$<CONFIG:Release>:RELEASE_BUILD>
)

# --- STATIC ANALYSIS / FORMAT TARGETS ---
find_program(CLANG_TIDY_EXE NAMES clang-tidy)
find_program(CLANG_FORMAT_EXE NAMES clang-format)
find_program(CPPCHECK_EXE NAMES cppcheck)

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/.*")

set(CPPCHECK_SOURCES ${ALL_SOURCE_FILES})
list(FILTER CPPCHECK_SOURCES INCLUDE REGEX ".*\\.cpp$")

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

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

if(CPPCHECK_EXE)
    add_custom_target(cppcheck
        COMMAND ${CPPCHECK_EXE}
            --enable=warning,style,performance,portability
            --std=c++20
            --language=c++
            --inline-suppr
            --suppress=missingIncludeSystem
            --suppress=toomanyconfigs
            --suppress=*:*source/external/*
            --suppress=*:*source/core/rendering/sdl3gpu/spv/*
            --suppress=*:*source/core/rendering/sdl3gpu/msl/*
            --suppress=normalCheckLevelMaxBranches
            -D_DEBUG
            -DLINUX_BUILD
            --quiet
            -I ${CMAKE_SOURCE_DIR}/source
            ${CPPCHECK_SOURCES}
        WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
        COMMENT "Running cppcheck..."
    )
else()
    message(STATUS "cppcheck no encontrado - target 'cppcheck' no disponible")
endif()

# --- SMOKE TESTS ---
# Executable stand-alone que cobreix el sistema d'entitats. No obri finestra
# ni GPU: pot córrer en qualsevol entorn. `ctest --output-on-failure` el
# dispara des de `build/`.
option(BUILD_TESTS "Build smoke tests" ON)
if(BUILD_TESTS)
    add_executable(test_entities_smoke
        tests/test_entities_smoke.cpp
        source/core/resources/resource_helper.cpp
        source/game/map/map.cpp
        ${ENTITY_SOURCES}
    )
    target_include_directories(test_entities_smoke PRIVATE
        "${CMAKE_SOURCE_DIR}/source"
        "${CMAKE_BINARY_DIR}"
    )
    target_link_libraries(test_entities_smoke PRIVATE SDL3::SDL3)
    target_compile_options(test_entities_smoke PRIVATE -Wall -Wextra -Wpedantic)
    enable_testing()
    add_test(NAME entities_smoke
             COMMAND test_entities_smoke
             WORKING_DIRECTORY ${CMAKE_SOURCE_DIR})

    # Smoke del flux d'escenes i del parser de debug.yaml. Stand-alone:
    # només enllaça els helpers purs (debug_config, placeholder_input,
    # key_config) perquè la integració completa dels placeholders arrossegaria
    # tot l'stack SDL (Screen/Notifier/RenderInfo), coberta pel smoke xvfb.
    add_executable(test_scene_flow
        tests/test_scene_flow.cpp
        source/game/debug_config.cpp
        source/game/scenes/placeholder_input.cpp
        source/core/input/key_config.cpp
        source/core/resources/resource_helper.cpp
    )
    target_include_directories(test_scene_flow PRIVATE
        "${CMAKE_SOURCE_DIR}/source"
        "${CMAKE_BINARY_DIR}"
    )
    target_link_libraries(test_scene_flow PRIVATE SDL3::SDL3)
    target_compile_options(test_scene_flow PRIVATE -Wall -Wextra -Wpedantic)
    add_test(NAME scene_flow
             COMMAND test_scene_flow
             WORKING_DIRECTORY ${CMAKE_SOURCE_DIR})
endif()
