cmake_minimum_required(VERSION 3.15)

# Фикс для Ninja на Windows
if(NOT CMAKE_MAKE_PROGRAM AND WIN32)
    set(POTENTIAL_NINJA "${CMAKE_CURRENT_SOURCE_DIR}/ninja/ninja.exe")
    if(EXISTS "${POTENTIAL_NINJA}")
        set(CMAKE_MAKE_PROGRAM "${POTENTIAL_NINJA}" CACHE FILEPATH "Path to ninja" FORCE)
    endif()
endif()

project(bishkek-witcher LANGUAGES C CXX)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# --- АВТО-ЗАГРУЗКА ЗАВИСИМОСТЕЙ ---
include("${CMAKE_CURRENT_SOURCE_DIR}/../cmake/FetchDependencies.cmake")
# Теперь гарантированно есть папка ../thirdparty со всеми исходниками

# ===========================================
# Lua (5.5.0) - embedded scripting, pure C, compiles with Emscripten
# ===========================================
set(LUA_SRC_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../thirdparty/lua-5.4.8")
file(GLOB LUA_SOURCES "${LUA_SRC_DIR}/*.c")
list(REMOVE_ITEM LUA_SOURCES
    "${LUA_SRC_DIR}/lua.c"
    "${LUA_SRC_DIR}/luac.c"
    "${LUA_SRC_DIR}/onelua.c"
)
add_library(lua_static STATIC ${LUA_SOURCES})
target_include_directories(lua_static PUBLIC "${LUA_SRC_DIR}")

# sol2 (header-only)
set(SOL2_SRC_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../thirdparty/sol2-3.3.0")

# Apply patch for Clang/Emscripten compatibility in optional<T&>::emplace().
set(_sol2_sentinel "${SOL2_SRC_DIR}/.patched")
if(NOT EXISTS "${_sol2_sentinel}")
    find_package(Git QUIET)
    if(GIT_FOUND)
        execute_process(
            COMMAND ${GIT_EXECUTABLE} apply --ignore-whitespace
                "${CMAKE_CURRENT_SOURCE_DIR}/../cmake/patches/sol2-3.3.0-clang-optional.patch"
            WORKING_DIRECTORY "${SOL2_SRC_DIR}"
            RESULT_VARIABLE _sol2_patch_res
        )
        if(_sol2_patch_res EQUAL 0)
            file(WRITE "${_sol2_sentinel}" "patched\n")
            message(STATUS "Applied sol2 Clang optional patch")
        else()
            message(WARNING "sol2 patch failed (exit ${_sol2_patch_res}) — Clang/Emscripten builds may not compile")
        endif()
    else()
        message(WARNING "Git not found — cannot apply sol2 patch automatically. "
                        "Apply cmake/patches/sol2-3.3.0-clang-optional.patch manually.")
    endif()
endif()

# Список исходных файлов (синхронизирован с proj-windows/CMakeLists.txt)
set(SOURCES
    ../src/main.cpp
    ../src/Game.cpp
    ../src/Game.h
    ../src/Character.cpp
    ../src/Character.h
    ../src/Environment.cpp
    ../src/Environment.h
    ../src/render/Renderer.cpp
    ../src/render/Renderer.h
    ../src/render/ShaderManager.cpp
    ../src/render/ShaderManager.h
    ../src/render/TextureManager.cpp
    ../src/render/TextureManager.h
    ../src/TextModel.cpp
    ../src/TextModel.h
    ../src/AudioPlayerAsync.cpp
    ../src/AudioPlayerAsync.h
    ../src/BoneAnimatedModelNew.cpp
    ../src/BoneAnimatedModelNew.h
    ../src/render/OpenGlExtensions.cpp
    ../src/render/OpenGlExtensions.h
    ../src/utils/Utils.cpp
    ../src/utils/Utils.h
    ../src/SparkEmitter.cpp
    ../src/SparkEmitter.h
    ../src/TeleportZone.h
    ../src/TeleportZone.cpp
    ../src/utils/TaskManager.cpp
    ../src/utils/TaskManager.h
    ../src/render/FrameBuffer.cpp
    ../src/render/FrameBuffer.h
    ../src/render/ShadowMap.cpp
    ../src/render/ShadowMap.h
    ../src/UiManager.cpp
    ../src/UiManager.h
    ../src/render/TextRenderer.h
    ../src/render/TextRenderer.cpp
    ../src/MenuManager.h
    ../src/MenuManager.cpp
    ../src/Location.h
    ../src/Location.cpp
    ../src/GameConstants.h
    ../src/GameConstants.cpp
    ../src/ScriptEngine.h
    ../src/ScriptEngine.cpp
    ../src/navigation/PathFinder.h
    ../src/navigation/PathFinder.cpp
    ../src/items/GameObjectLoader.h
    ../src/items/GameObjectLoader.cpp
    ../src/items/Item.h
    ../src/items/Item.cpp
    ../src/items/InteractiveObject.h
    ../src/items/InteractiveObject.cpp
	../src/dialogue/DialogueTypes.h
	../src/dialogue/DialogueDatabase.h
	../src/dialogue/DialogueDatabase.cpp
	../src/dialogue/DialogueRuntime.h
	../src/dialogue/DialogueRuntime.cpp
	../src/dialogue/DialogueOverlay.h
	../src/dialogue/DialogueOverlay.cpp
	../src/dialogue/DialogueSystem.h
	../src/dialogue/DialogueSystem.cpp
	../src/quest/QuestTypes.h
	../src/quest/QuestJournal.h
	../src/quest/QuestJournal.cpp
)

add_executable(bishkek-witcher ${SOURCES})

# Настройка путей к инклудам (используем скачанные исходники)
target_include_directories(bishkek-witcher PRIVATE
    ../src
    ../thirdparty/eigen-5.0.0
    ../thirdparty/boost_1_90_0
    "${SOL2_SRC_DIR}/include"
)

# Сборка libzip через add_subdirectory (Emscripten соберет её из исходников)
set(ENABLE_GNUTLS OFF CACHE BOOL "" FORCE)
set(ENABLE_OPENSSL OFF CACHE BOOL "" FORCE)
set(ENABLE_WINDOWS_CRYPTO OFF CACHE BOOL "" FORCE)
set(ENABLE_COMMONCRYPTO OFF CACHE BOOL "" FORCE)

add_subdirectory("../thirdparty/libzip-1.11.4" libzip-build)

target_link_libraries(bishkek-witcher PRIVATE zip z lua_static websocket.js)

# Эмскриптен-флаги
set(EMSCRIPTEN_FLAGS
    "-sUSE_SDL=2"
    "-sUSE_SDL_IMAGE=2"
    "-sUSE_LIBPNG=1"
    "-sUSE_ZLIB=1"
    "-sUSE_SDL_TTF=2"
    "-sUSE_SDL_MIXER=2"
    "-sSDL2_MIXER_FORMATS=[ogg,mp3]"
    #"-pthread"
    #"-sUSE_PTHREADS=1"
    "-fexceptions"
    "-DNETWORK"
)

target_compile_options(bishkek-witcher PRIVATE ${EMSCRIPTEN_FLAGS} "-O2")

# Only loading.png and the shaders used before resources.zip is ready are preloaded.
# resources.zip is downloaded asynchronously at runtime and served as a separate file.
set(EMSCRIPTEN_LINK_FLAGS
    ${EMSCRIPTEN_FLAGS}
    "-O2"
    #"-sPTHREAD_POOL_SIZE=4"
    "-sALLOW_MEMORY_GROWTH=1"
    "-sFULL_ES3=1"
    "--preload-file ${CMAKE_CURRENT_SOURCE_DIR}/../resources/loading.png@resources/loading.png"
    "--preload-file ${CMAKE_CURRENT_SOURCE_DIR}/../resources/shaders@resources/shaders"
    "--preload-file ${CMAKE_CURRENT_SOURCE_DIR}/../resources/start.lua@resources/start.lua"
    "--preload-file ${CMAKE_CURRENT_SOURCE_DIR}/../resources/start2.lua@resources/start2.lua"
	"--preload-file ${CMAKE_CURRENT_SOURCE_DIR}/../resources/start_dorm.lua@resources/start_dorm.lua"
	"--preload-file ${CMAKE_CURRENT_SOURCE_DIR}/../audio@audio"
)

# Применяем настройки линковки
target_link_options(bishkek-witcher PRIVATE ${EMSCRIPTEN_LINK_FLAGS})

# Для совместимости со старыми версиями CMake, если target_link_options недостаточно
string(REPLACE ";" " " EMSCRIPTEN_LINK_FLAGS_STR "${EMSCRIPTEN_LINK_FLAGS}")
set_target_properties(bishkek-witcher PROPERTIES
    LINK_FLAGS "${EMSCRIPTEN_LINK_FLAGS_STR}"
    SUFFIX ".html"
)

# --- Ресурсы и Деплой (без изменений) ---
set(RESOURCES_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../resources")
set(RESOURCES_ZIP "${CMAKE_CURRENT_BINARY_DIR}/resources.zip")
get_filename_component(RESOURCES_PARENT_DIR "${CMAKE_CURRENT_SOURCE_DIR}/.." ABSOLUTE)

add_custom_command(
    OUTPUT "${RESOURCES_ZIP}"
    COMMAND ${CMAKE_COMMAND} -E tar "cf" "${RESOURCES_ZIP}" --format=zip "resources"
    WORKING_DIRECTORY "${RESOURCES_PARENT_DIR}"
    DEPENDS "${RESOURCES_PARENT_DIR}/resources"
)

add_custom_target(pack_resources DEPENDS "${RESOURCES_ZIP}")
add_dependencies(bishkek-witcher pack_resources)


# Определяем путь к директории установки (относительно папки билда)
set(CMAKE_INSTALL_PREFIX "${CMAKE_BINARY_DIR}/public")

# 1. Устанавливаем основной HTML файл
install(TARGETS bishkek-witcher
        RUNTIME DESTINATION .
)

# 2. Устанавливаем сопутствующие файлы (JS, WASM и сгенерированный архив данных)
install(FILES
        "${CMAKE_CURRENT_BINARY_DIR}/bishkek-witcher.js"
        "${CMAKE_CURRENT_BINARY_DIR}/bishkek-witcher.wasm"
        "${CMAKE_CURRENT_BINARY_DIR}/bishkek-witcher.data"
        DESTINATION .
)

install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/index.html"
        DESTINATION .
)

# resources.zip is served separately and downloaded asynchronously at runtime
install(FILES "${RESOURCES_ZIP}" DESTINATION .)

add_custom_command(TARGET bishkek-witcher POST_BUILD
    COMMAND ${CMAKE_COMMAND} --install .
    WORKING_DIRECTORY "${CMAKE_BINARY_DIR}"
    COMMENT "Automatically deploying to public directory..."
)
