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.
# Entitats sense dependència directa amb Player.cpp: les enllacen tant
# l'executable principal com el test_entities_smoke (que evita arrossegar
# l'stack del jugador i les seues dependències pesades).
set(ENTITY_SOURCES_BASE
    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
    source/game/entities/concrete/hole.cpp
    source/game/entities/concrete/dust.cpp
)

# Entitats que criden directament símbols de Player (com WhipAttack via
# `enterHurt`/`getBaseBox`): només van a l'executable principal.
set(ENTITY_SOURCES
    ${ENTITY_SOURCES_BASE}
    source/game/entities/concrete/whip_attack.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/audio_effects.cpp
    source/core/audio/jail_audio.cpp
    source/core/audio/sound_effects_config.cpp
    source/core/locale/locale.cpp
    source/core/ui/ui_config.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/input/gamepad_bindings.cpp
    source/core/input/define_buttons.cpp
    source/core/input/mouse.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/screenshot.cpp
    source/external/stb_image_write_impl.cpp
    source/external/stb_vorbis_impl.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/sprite/animated_sprite_parser.cpp
    source/core/rendering/effects/heat_haze.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/resource_pack.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/ui/hud.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/scenes/room_fsm.cpp
    source/game/entities/player.cpp
    source/game/map/map.cpp
    source/game/map/tilemap.cpp
    source/game/map/tilemap_writer.cpp
    # Writer surgical de claus dins de `geometry:` (door_col), paral·lel
    # al TilemapWriter. Només Debug.
    source/game/map/map_writer.cpp
    source/game/map/paint_layer.cpp
    source/game/levels/level_manager.cpp
    # Mòdul editor (només activa contingut en Debug via `#ifdef _DEBUG`).
    # En Release els fitxers compilen a object buit i l'enllaçador no
    # arrossega cap símbol del joc final.
    source/game/editor/editor.cpp
    source/game/editor/editor_config.cpp
    # Writer del bloc `entities:` del YAML del nivell, paral·lel al
    # TilemapWriter pero per a la persistència de l'editor d'entitats.
    source/game/entities/entity_writer.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})

# Silencia warnings de codi de tercers (mateixa filosofia que el
# .clang-tidy de source/external/). Només afecta aquests TUs concrets;
# la resta del codi continua compilant amb -Wall -Wextra -Wpedantic.
set_source_files_properties(
    source/external/stb_image_write_impl.cpp
    source/external/stb_vorbis_impl.cpp
    PROPERTIES COMPILE_OPTIONS "-Wno-missing-field-initializers;-Wno-deprecated-declarations"
)

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)

# --- EINA STANDALONE: pack_resources ---
# Executable auxiliar que empaqueta `data/` a `build/resources.pack`.
# EXCLUDE_FROM_ALL: només es compila quan algun target en depèn (ho fa
# `resource_pack`). Build manual: `cmake --build build --target pack_resources`.
add_executable(pack_resources EXCLUDE_FROM_ALL
    tools/pack_resources/pack_resources.cpp
    source/core/resources/resource_pack.cpp
)
target_include_directories(pack_resources PRIVATE "${CMAKE_SOURCE_DIR}/source")
target_compile_options(pack_resources PRIVATE -Wall -Wextra -Wpedantic)

# --- REGENERACIÓ AUTOMÀTICA DE build/resources.pack ---
# A cada build re-empaquetem data/ si algun fitxer dins ha canviat. Evita
# debugar amb un pack obsolet. CONFIGURE_DEPENDS força CMake a re-globbar
# a la pròxima invocació (recull fitxers nous afegits a data/).
file(GLOB_RECURSE DATA_FILES CONFIGURE_DEPENDS "${CMAKE_SOURCE_DIR}/data/*")
set(RESOURCE_PACK "${CMAKE_BINARY_DIR}/resources.pack")

add_custom_command(
    OUTPUT ${RESOURCE_PACK}
    COMMAND $<TARGET_FILE:pack_resources>
        "${CMAKE_SOURCE_DIR}/data"
        "${RESOURCE_PACK}"
    DEPENDS pack_resources ${DATA_FILES}
    WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
    COMMENT "Empaquetant data/ → build/resources.pack"
    VERBATIM
)
add_custom_target(resource_pack ALL DEPENDS ${RESOURCE_PACK})
add_dependencies(${PROJECT_NAME} resource_pack)

# --- CÒPIA DE gamecontrollerdb.txt AL COSTAT DEL BINARI ---
# SDL_AddGamepadMappingsFromFile només llegeix del filesystem real (no del
# pack), així que el fitxer ha de viure al directori del binari. Es copia
# només si existeix per no fallar la build d'algú que encara no ha fet
# `make controllerdb`.
if(EXISTS "${CMAKE_SOURCE_DIR}/gamecontrollerdb.txt")
    set(CONTROLLER_DB "${CMAKE_BINARY_DIR}/gamecontrollerdb.txt")
    add_custom_command(
        OUTPUT ${CONTROLLER_DB}
        COMMAND ${CMAKE_COMMAND} -E copy_if_different
            "${CMAKE_SOURCE_DIR}/gamecontrollerdb.txt"
            "${CONTROLLER_DB}"
        DEPENDS "${CMAKE_SOURCE_DIR}/gamecontrollerdb.txt"
        COMMENT "Copiant gamecontrollerdb.txt → build/"
        VERBATIM
    )
    add_custom_target(controller_db ALL DEPENDS ${CONTROLLER_DB})
    add_dependencies(${PROJECT_NAME} controller_db)
endif()

target_compile_options(${PROJECT_NAME} PRIVATE -Wall -Wextra -Wpedantic)
target_compile_definitions(${PROJECT_NAME} PRIVATE
    $<$<CONFIG:Debug>:_DEBUG>
    $<$<CONFIG:Release>:RELEASE_BUILD>
    # En Debug el fallback a disc apunta al source tree (sense re-packejar).
    AEE_SOURCE_DIR="${CMAKE_SOURCE_DIR}/"
)

# --- 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
        tests/hole_player_stubs.cpp
        source/core/resources/resource_helper.cpp
        source/core/resources/resource_pack.cpp
        source/game/map/map.cpp
        ${ENTITY_SOURCES_BASE}
    )
    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)
    # GCC 14 + -O3 + fkyaml header-only inlinia profundament std::map::clear i
    # dispara fals positius -Warray-bounds dins <bits/stl_tree.h>. El warning és
    # del codi de tercers (libstdc++ vist a través de fkyaml), no del test.
    target_compile_options(test_entities_smoke PRIVATE -Wno-array-bounds)
    enable_testing()
    add_test(NAME entities_smoke
             COMMAND test_entities_smoke
             WORKING_DIRECTORY ${CMAKE_SOURCE_DIR})

    # Smoke del WhipAttack. Inclou tot l'stack d'entitats + whip_attack.cpp.
    # `whip_attack_player_stubs.cpp` proveeix símbols mínims de Player per
    # satisfer el linker sense arrossegar audio/gamepad/screen — els tests
    # del whip s'enfoquen a hitbox + Mummy, no a friendly fire.
    add_executable(test_whip_attack
        tests/test_whip_attack.cpp
        tests/whip_attack_player_stubs.cpp
        tests/hole_player_stubs.cpp
        source/core/resources/resource_helper.cpp
        source/core/resources/resource_pack.cpp
        source/game/map/map.cpp
        ${ENTITY_SOURCES_BASE}
        source/game/entities/concrete/whip_attack.cpp
    )
    target_include_directories(test_whip_attack PRIVATE
        "${CMAKE_SOURCE_DIR}/source"
        "${CMAKE_BINARY_DIR}"
    )
    target_link_libraries(test_whip_attack PRIVATE SDL3::SDL3)
    target_compile_options(test_whip_attack PRIVATE -Wall -Wextra -Wpedantic)
    add_test(NAME whip_attack
             COMMAND test_whip_attack
             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
        source/core/resources/resource_pack.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})

    # Smoke del writer surgical del tilemap (escriu el bloc `data:` sense
    # tocar la resta del fitxer). Pura manipulació de text, zero
    # dependències: no cal ni SDL ni el Resource::Cache.
    add_executable(test_tilemap_writer
        tests/test_tilemap_writer.cpp
        source/game/map/tilemap_writer.cpp
    )
    target_include_directories(test_tilemap_writer PRIVATE
        "${CMAKE_SOURCE_DIR}/source"
    )
    target_compile_options(test_tilemap_writer PRIVATE -Wall -Wextra -Wpedantic)
    add_test(NAME tilemap_writer
             COMMAND test_tilemap_writer
             WORKING_DIRECTORY ${CMAKE_SOURCE_DIR})

    # Smoke de la FSM de sala (RoomFsm). Cobreix loadConfig (timings i
    # corbes des de YAML), advance (transicions entre estats), i
    # formatRoomTitle (locale + substitució `{n}`). Stand-alone: no
    # arrossega Audio/Screen/Player/EntityManager — només els helpers
    # purs de la FSM, Locale i UiConfig.
    add_executable(test_game_fsm
        tests/test_game_fsm.cpp
        source/game/scenes/room_fsm.cpp
        source/core/locale/locale.cpp
        source/core/ui/ui_config.cpp
        source/core/resources/resource_helper.cpp
        source/core/resources/resource_pack.cpp
        source/utils/easing.cpp
    )
    target_include_directories(test_game_fsm PRIVATE
        "${CMAKE_SOURCE_DIR}/source"
        "${CMAKE_BINARY_DIR}"
    )
    target_link_libraries(test_game_fsm PRIVATE SDL3::SDL3)
    target_compile_options(test_game_fsm PRIVATE -Wall -Wextra -Wpedantic)
    add_test(NAME game_fsm
             COMMAND test_game_fsm
             WORKING_DIRECTORY ${CMAKE_SOURCE_DIR})

    # Smoke del parser d'animacions amb suport de flip H/V. Stand-alone:
    # només enllaça `animated_sprite_parser.cpp`, que és la part del motor
    # que NO depèn de Resource::Cache ni de Surface — el parser és pure
    # YAML-in / dades-out, així que no cal arrossegar tot l'stack.
    add_executable(test_animated_sprite_flip
        tests/test_animated_sprite_flip.cpp
        source/core/rendering/sprite/animated_sprite_parser.cpp
    )
    target_include_directories(test_animated_sprite_flip PRIVATE
        "${CMAKE_SOURCE_DIR}/source"
    )
    target_link_libraries(test_animated_sprite_flip PRIVATE SDL3::SDL3)
    target_compile_options(test_animated_sprite_flip PRIVATE -Wall -Wextra -Wpedantic)
    add_test(NAME animated_sprite_flip
             COMMAND test_animated_sprite_flip
             WORKING_DIRECTORY ${CMAKE_SOURCE_DIR})
endif()
