cmake_minimum_required(VERSION 3.20)
set(PSXRECOMP_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/psxrecomp" CACHE PATH
    "Path to psxrecomp")
if(NOT EXISTS "${PSXRECOMP_ROOT}/runtime/runtime.cmake")
    message(FATAL_ERROR
        "PSXRecomp runtime is missing: ${PSXRECOMP_ROOT}/runtime/runtime.cmake\n"
        "This project expects the psxrecomp framework checkout at ${PSXRECOMP_ROOT}.\n"
        "Run: git submodule update --init --recursive\n"
        "If psxrecomp/ is not a submodule, set -DPSXRECOMP_ROOT=<path-to-psxrecomp>.")
endif()

project(MythologyKombat LANGUAGES C CXX)

# --- Reproducible release build (T3.26) --------------------------------------
# tools/release.ps1 passes -DMK_SOURCE_DATE_EPOCH=<commit time, unix seconds>.
# With it set, two builds of one commit give a byte-identical exe:
#  - __DATE__/__TIME__ (psxrecomp crash_trace.c build id) become the commit time,
#    through a force-included header (only that one source uses them);
#  - the PE COFF timestamp is dropped (lld --no-insert-timestamp);
#  - build/source paths are mapped away (-ffile-prefix-map), so the staging
#    folder name does not leak into the binary.
# Unset (the default), nothing here changes. The psxrecomp submodule is not edited.
set(MK_SOURCE_DATE_EPOCH "" CACHE STRING
    "Unix time to use for __DATE__/__TIME__ and the PE timestamp (empty = normal build)")
set(MK_REPRODUCIBLE FALSE)
if(NOT MK_SOURCE_DATE_EPOCH STREQUAL "")
    if(NOT MK_SOURCE_DATE_EPOCH MATCHES "^[0-9]+$")
        message(FATAL_ERROR "MK_SOURCE_DATE_EPOCH must be unix seconds, got '${MK_SOURCE_DATE_EPOCH}'")
    endif()
    set(MK_REPRODUCIBLE TRUE)
    set(ENV{SOURCE_DATE_EPOCH} "${MK_SOURCE_DATE_EPOCH}")
    string(TIMESTAMP _mk_date "%b %d %Y" UTC)
    string(TIMESTAMP _mk_time "%H:%M:%S" UTC)
    unset(ENV{SOURCE_DATE_EPOCH})
    # C __DATE__ pads the day with a space ("Oct  5 2026"), not a zero.
    string(REGEX REPLACE "^([A-Za-z]+) 0" "\\1  " _mk_date "${_mk_date}")
    file(WRITE "${CMAKE_BINARY_DIR}/mk_reproducible.h"
        "#pragma clang diagnostic ignored \"-Wbuiltin-macro-redefined\"\n"
        "#undef __DATE__\n#define __DATE__ \"${_mk_date}\"\n"
        "#undef __TIME__\n#define __TIME__ \"${_mk_time}\"\n")
    message(STATUS "reproducible build: __DATE__ '${_mk_date}' __TIME__ '${_mk_time}'")
    add_compile_options(
        "-ffile-prefix-map=${CMAKE_SOURCE_DIR}=/src"
        "-ffile-prefix-map=${CMAKE_BINARY_DIR}=/build")
    set_property(SOURCE "${PSXRECOMP_ROOT}/runtime/src/crash_trace.c" APPEND PROPERTY
        COMPILE_OPTIONS "-include" "${CMAKE_BINARY_DIR}/mk_reproducible.h")
endif()

# --- Opt-in product surfaces (OFF by default in the framework) -------------
# Scaffold prompts / flags fill these. Without recomp-ui, PSX_RECOMP_UI is OFF.
# The wizard (WIZARD_CMAKE_BLOCK / ENABLE_SETUP_WIZARD) is the first-run disc
# picker; releases are compiled from the committed generated/ C, so it never
# needs to generate or rebuild anything on a player's machine.
# recomp-ui submodule present (PSX_RECOMP_UI defaults ON).
# Full netplay UI -- enable after adding recomp-ui + testing:
# if(EXISTS "${PSXRECOMP_ROOT}/lib/recomp-net/CMakeLists.txt")
#     set(PSX_NETPLAY ON CACHE BOOL "..." FORCE)
# endif()
set(PSX_SETUP_WIZARD ON CACHE BOOL
    "Advertise first-run setup wizard + Generate & rebuild in recomp-ui" FORCE)
include("${PSXRECOMP_ROOT}/runtime/runtime.cmake")

# This project's own mod catalog. The FRAMEWORK stages it -- together with its
# builtin psx.* packages -- into <exe-dir>/mods/bundled, and refuses to
# configure if a catalog exists here but is not declared. Never copy it by
# hand: five titles did, and framework 4cc04be3's rename of the staged
# directory broke all five silently (bead beads-eio.3.101).
set(PSX_PRELOADED_MODS "${CMAKE_CURRENT_SOURCE_DIR}/mods/preloaded")
if(NOT IS_DIRECTORY "${PSX_PRELOADED_MODS}")
    set(PSX_PRELOADED_MODS "NONE")
endif()

psxrecomp_add_game_runtime(psx-runtime
    PRELOADED_MODS_DIR "${PSX_PRELOADED_MODS}"
    # ENABLE_NETPLAY_IF_PRESENT
    # NETPLAY_LOBBY_URL ws://netplay.retcomm.net:8765
    ENABLE_SETUP_WIZARD
    WINDOW_TITLE "MythologyKombat"
    DEFAULT_GAME_CONFIG_PATH "game.toml"
    MAX_PLAYERS 1
    # LAUNCHER_BOXART "${CMAKE_CURRENT_SOURCE_DIR}/launcher_assets/img/boxart.tga"
    APP_ICON "${CMAKE_CURRENT_SOURCE_DIR}/assets/psxrecomp.ico"
    # Committed game C (psxrecomp_cli.py generate; git add generated). Release
    # CI configures with -DPSXRECOMP_REQUIRE_GAME_C=ON so a checkout without
    # it fails instead of building a setup host.
    GEN_MARKER "generated/SLUS_004.76_dispatch.c"
    # T2.16: statically compiled overlay shard (dispatcher + one unit per
    # overlay image), written by Generate from aot/overlays.json
    # (static_output); must name the same file. Keep it BEFORE the
    # multi-value GEN_FULL_GLOB / CODEGEN_SETUP_SOURCES, which would swallow it
    # as more source files (runtime.cmake multiValueArgs).
    GAME_OVERLAY_STATIC_C "${CMAKE_CURRENT_SOURCE_DIR}/generated/overlays_static.c"
    GEN_FULL_GLOB "generated/SLUS_004.76_full_*.c"
    CODEGEN_SETUP_SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/codegen_setup.c"
)

# T2.19: shared playtest diagnostics (input recorder + input display). Must
# come AFTER psxrecomp_add_game_runtime (it needs the target and the staged
# catalog) and is a separate call, so it cannot be swallowed by the multi-value
# GEN_FULL_GLOB / CODEGEN_SETUP_SOURCES lists above. MOD_ID is the package
# under mods/preloaded/packages. PSX_PUBLIC_RELEASE is NOT set here: it stays
# the framework default (OFF); only a release packager sets it ON.
include("${PSXRECOMP_ROOT}/runtime/playtest_diagnostics.cmake")
psxrecomp_add_playtest_diagnostics(psx-runtime
    GAME_ID "SLUS-00476"
    MOD_ID "mythologykombat.diagnostics")

if(MK_REPRODUCIBLE)
    # lld (MinGW driver): no link-time stamp in the PE header.
    target_link_options(psx-runtime PRIVATE -Wl,--no-insert-timestamp)
endif()

# T2.4 workaround (upstream bug, see docs/OPEN_QUESTIONS.md): recomp-ui's
# _recomp_ui_utf8_manifest() guard misses psxrecomp's manifest, which is added
# as $<TARGET_OBJECTS:psx-runtime_manifest> (no ".manifest"/"manifest.rc"
# suffix), so both link in and lld reports "duplicate resource: MANIFEST".
# Both manifests carry activeCodePage=UTF-8; keep psxrecomp's, drop recomp-ui's.
if(WIN32 AND NOT MSVC)
    get_target_property(_psx_rt_srcs psx-runtime SOURCES)
    list(FILTER _psx_rt_srcs EXCLUDE REGEX "psx-runtime_recomp_utf8_manifest\\.rc$")
    set_property(TARGET psx-runtime PROPERTY SOURCES "${_psx_rt_srcs}")
endif()

# Stage runtime configs next to the exe for direct build/ launches. Only copy
# files that exist — never fail POST_BUILD when game_options.toml is absent.
foreach(_PSX_RUNTIME_CONFIG game.toml game_options.toml)
    if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${_PSX_RUNTIME_CONFIG}")
        add_custom_command(TARGET psx-runtime POST_BUILD
            COMMAND ${CMAKE_COMMAND} -E copy_if_different
                "${CMAKE_CURRENT_SOURCE_DIR}/${_PSX_RUNTIME_CONFIG}"
                "$<TARGET_FILE_DIR:psx-runtime>/${_PSX_RUNTIME_CONFIG}"
            COMMENT "Staging ${_PSX_RUNTIME_CONFIG}"
            VERBATIM)
    endif()
endforeach()
