# Source-owned Linux build of the corrected N64Recomp (condition bits, reference call names), driven by
# tools/baseline/prepare_codegen_fp.py.
#
# This driver adds the clean pinned checkout named by the dependencies.lock.json n64recomp_codegen entry
# EXCLUDE_FROM_ALL and keeps every upstream target and setting. It replaces exactly two N64Recomp sources and one
# LiveRecomp source, matched by resolved identity, with the materialized seven-file corrected view. Every involved
# consumer selects the view's four recompiler headers first; generator.h includes the local operations.h, so all
# four travel together. The pinned checkout and its original build are never written. The owner builds only
# N64RecompCLI; the focused condition-test targets are ordinary build/test targets.
#
# Scope: the accepted MIPS c.cond.fmt condition bits plus canonical names for regular original function reference
# C calls; not FCSR flags, traps or full FP emulation.
cmake_minimum_required(VERSION 3.20)
project(CodegenFpCondition LANGUAGES C CXX)

if(NOT CMAKE_SYSTEM_NAME STREQUAL "Linux")
    message(FATAL_ERROR "The corrected codegen is a Linux tool build; configure it under Linux/WSL")
endif()
if(NOT CMAKE_GENERATOR STREQUAL "Unix Makefiles" OR NOT CMAKE_BUILD_TYPE STREQUAL "RelWithDebInfo")
    message(FATAL_ERROR "Configure with the Unix Makefiles generator and CMAKE_BUILD_TYPE=RelWithDebInfo, as the qualified probe")
endif()

set(CMAKE_C_STANDARD 17)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

foreach(codegen_fp_flags IN ITEMS CMAKE_C_FLAGS CMAKE_CXX_FLAGS CMAKE_C_FLAGS_RELWITHDEBINFO CMAKE_CXX_FLAGS_RELWITHDEBINFO)
    if("${${codegen_fp_flags}}" MATCHES "-ffast-math|-ffinite-math-only|-Ofast")
        message(FATAL_ERROR "${codegen_fp_flags} must not enable fast or finite-math-only math: ${${codegen_fp_flags}}")
    endif()
endforeach()

set(CODEGEN_ROOT "" CACHE PATH "Clean pinned N64Recomp-codegen checkout (dependencies.lock.json n64recomp_codegen)")
set(CODEGEN_FP_OVERLAY "" CACHE PATH "Materialized seven-file corrected source view (prepare_codegen_fp.py)")
set(CODEGEN_FP_CONDITION_TEST "" CACHE FILEPATH "Immutable focused condition-bit test utility")
if(NOT IS_DIRECTORY "${CODEGEN_ROOT}" OR NOT IS_DIRECTORY "${CODEGEN_FP_OVERLAY}" OR NOT EXISTS "${CODEGEN_FP_CONDITION_TEST}")
    message(FATAL_ERROR "Supply CODEGEN_ROOT, CODEGEN_FP_OVERLAY and CODEGEN_FP_CONDITION_TEST; tools/baseline/prepare_codegen_fp.py supplies all three")
endif()
file(REAL_PATH "${CODEGEN_ROOT}" codegen_fp_base)
file(REAL_PATH "${CODEGEN_FP_OVERLAY}" codegen_fp_overlay)
cmake_path(IS_PREFIX codegen_fp_base "${codegen_fp_overlay}" NORMALIZE codegen_fp_overlay_in_base)
cmake_path(IS_PREFIX codegen_fp_overlay "${codegen_fp_base}" NORMALIZE codegen_fp_base_in_overlay)
if(codegen_fp_overlay_in_base OR codegen_fp_base_in_overlay)
    message(FATAL_ERROR "The corrected view ${codegen_fp_overlay} must be disjoint from the pinned source ${codegen_fp_base}")
endif()

set(codegen_fp_files
    include/recompiler/context.h
    include/recompiler/generator.h
    include/recompiler/live_recompiler.h
    include/recompiler/operations.h
    src/operations.cpp
    src/cgenerator.cpp
    LiveRecomp/live_generator.cpp)
foreach(relative_path IN LISTS codegen_fp_files)
    if(NOT EXISTS "${codegen_fp_base}/${relative_path}")
        message(FATAL_ERROR "Missing pinned original ${codegen_fp_base}/${relative_path}")
    endif()
    if(NOT EXISTS "${codegen_fp_overlay}/${relative_path}")
        message(FATAL_ERROR "Missing corrected view file ${codegen_fp_overlay}/${relative_path}")
    endif()
endforeach()
# The view holds exactly the seven files, so it cannot shadow recomp.h or any other pinned header.
file(GLOB_RECURSE codegen_fp_present LIST_DIRECTORIES false RELATIVE "${codegen_fp_overlay}" "${codegen_fp_overlay}/*")
list(SORT codegen_fp_present)
set(codegen_fp_expected ${codegen_fp_files})
list(SORT codegen_fp_expected)
if(NOT "${codegen_fp_present}" STREQUAL "${codegen_fp_expected}")
    message(FATAL_ERROR "Corrected view must hold exactly the seven files; found ${codegen_fp_present}")
endif()

add_subdirectory("${codegen_fp_base}" "${CMAKE_CURRENT_BINARY_DIR}/upstream" EXCLUDE_FROM_ALL)

foreach(target IN ITEMS N64Recomp N64RecompCLI LiveRecomp LiveRecompTest)
    if(NOT TARGET ${target})
        message(FATAL_ERROR "The pinned codegen no longer defines target ${target}")
    endif()
endforeach()
get_target_property(codegen_fp_cli_name N64RecompCLI OUTPUT_NAME)
if(NOT codegen_fp_cli_name STREQUAL "N64Recomp")
    message(FATAL_ERROR "N64RecompCLI must keep OUTPUT_NAME N64Recomp; found ${codegen_fp_cli_name}")
endif()

function(codegen_fp_replace_source target relative_path)
    get_target_property(target_sources ${target} SOURCES)
    get_target_property(target_source_dir ${target} SOURCE_DIR)
    file(REAL_PATH "${codegen_fp_base}/${relative_path}" expected_original)
    set(replacement "${codegen_fp_overlay}/${relative_path}")
    set(updated_sources)
    set(replaced 0)
    foreach(source IN LISTS target_sources)
        get_filename_component(absolute_source "${source}" ABSOLUTE BASE_DIR "${target_source_dir}")
        file(REAL_PATH "${absolute_source}" actual_source)
        if(actual_source STREQUAL expected_original)
            list(APPEND updated_sources "${replacement}")
            math(EXPR replaced "${replaced} + 1")
        else()
            list(APPEND updated_sources "${source}")
        endif()
    endforeach()
    if(NOT replaced EQUAL 1)
        message(FATAL_ERROR "Expected exactly one ${target}:${relative_path}, found ${replaced}")
    endif()
    set_property(TARGET ${target} PROPERTY SOURCES "${updated_sources}")
    message(STATUS "Corrected codegen source: ${target} ${expected_original} -> ${replacement}")
endfunction()

codegen_fp_replace_source(N64Recomp src/operations.cpp)
codegen_fp_replace_source(N64Recomp src/cgenerator.cpp)
codegen_fp_replace_source(LiveRecomp LiveRecomp/live_generator.cpp)
target_include_directories(N64Recomp BEFORE PUBLIC "${codegen_fp_overlay}/include")
foreach(target IN ITEMS N64RecompCLI LiveRecomp LiveRecompTest)
    target_include_directories(${target} BEFORE PRIVATE "${codegen_fp_overlay}/include")
endforeach()

# Focused actual-generator test utility (immutable) and its emitted C program. Explicit checks stay active under
# NDEBUG; no fast or finite-math-only flags. The upstream LiveRecompTest data-file harness is not registered.
add_executable(CodegenFpConditionTest "${CODEGEN_FP_CONDITION_TEST}")
target_link_libraries(CodegenFpConditionTest PRIVATE LiveRecomp)
target_include_directories(CodegenFpConditionTest BEFORE PRIVATE "${codegen_fp_overlay}/include")
target_compile_definitions(CodegenFpConditionTest PRIVATE NDEBUG)
target_compile_options(CodegenFpConditionTest PRIVATE -fno-fast-math -fno-strict-aliasing)
set_target_properties(CodegenFpConditionTest PROPERTIES CXX_STANDARD 20 CXX_STANDARD_REQUIRED ON CXX_EXTENSIONS OFF)

set(codegen_fp_emitted "${CMAKE_CURRENT_BINARY_DIR}/fp-condition-emitted.c")
add_custom_command(
    OUTPUT "${codegen_fp_emitted}"
    COMMAND "$<TARGET_FILE:CodegenFpConditionTest>" --emit-c "${codegen_fp_emitted}"
    DEPENDS CodegenFpConditionTest "${CODEGEN_FP_CONDITION_TEST}"
    COMMENT "Emitting synthetic C predicates through the actual mapped corrected CGenerator"
    VERBATIM)
add_executable(CodegenFpConditionCOutput "${codegen_fp_emitted}")
target_include_directories(CodegenFpConditionCOutput PRIVATE "${codegen_fp_base}/include")
target_compile_definitions(CodegenFpConditionCOutput PRIVATE NDEBUG)
target_compile_options(CodegenFpConditionCOutput PRIVATE -fno-fast-math -fno-strict-aliasing)
set_target_properties(CodegenFpConditionCOutput PROPERTIES C_STANDARD 17 C_STANDARD_REQUIRED ON)

enable_testing()
add_test(NAME codegen_fp_condition_c COMMAND CodegenFpConditionCOutput)
add_test(NAME codegen_fp_condition_live COMMAND CodegenFpConditionTest --live)
add_test(NAME codegen_reference_call_names COMMAND CodegenFpConditionTest --reference-call-names)
