cmake_minimum_required(VERSION 3.10)

option(BUILD_PYTHON_BINDINGS "Build Python bindings via pybind11" OFF)

# Python extensions require /MD (dynamic CRT); static library uses /MT
if(BUILD_PYTHON_BINDINGS)
    set(CMAKE_POSITION_INDEPENDENT_CODE ON)
endif()

file(READ "${CMAKE_CURRENT_SOURCE_DIR}/VERSION.txt" LIB_VERSION)
string(STRIP "${LIB_VERSION}" LIB_VERSION)
project(LibraryFEMTHERM VERSION ${LIB_VERSION} LANGUAGES CXX)
set(target_name LibraryFEMTHERM)

include(cmake/LibraryFEMTHERMProjectMacros.cmake)
include(cmake/LibraryFEMTHERMinternal_utils.cmake)
include(cmake/LibraryFEMTHERMCompilerFlags.cmake)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED True)

# Enable MSVC parallel (multi-processor) compilation for all targets and
# dependencies defined below. Placed before add_subdirectory/FetchContent so
# every later target inherits it (add_compile_options only affects later targets).
if(MSVC)
    add_compile_options(/MP)
endif()

set(GLOBAL_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)

# Sets global output directory for single configuration
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${GLOBAL_OUTPUT_PATH})
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${GLOBAL_OUTPUT_PATH})
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${GLOBAL_OUTPUT_PATH})

# google test will not be created by this project if this is not the main project. Main project is expected to handle google test.
get_directory_property(hasParent PARENT_DIRECTORY)

if(hasParent)
    set(BUILD_LibraryFEMTHERM_TESTING OFF)
    set(DOWNLOAD_GTEST OFF)
    if(BUILD_TESTING STREQUAL ON) # Parent testing is ON
        set(BUILD_KeffC_TESTING ON)
    endif()
else()
    option(BUILD_LibraryFEMTHERM_TESTING "Build testing targets" ON)
    # Only the tests need google test; without them it would be installed into the wheel.
    set(DOWNLOAD_GTEST ${BUILD_LibraryFEMTHERM_TESTING})
endif()

# Download external projects automatically
option(BUILD_FileParse_tests "Build the FileParse tests" OFF)

include(FetchContent)

# Local development mode. The `local` preset sets LBNL_LOCAL_SIBLINGS=ON (a cache
# variable, so it cascades into FetchContent sub-builds). When it is on, prefer a
# sibling working copy (../<Name>) of each of THIS project's direct dependencies,
# so the whole dependency graph can be built from local disk during development.
# A dependency whose sibling is not checked out falls back to its declared remote,
# independently. Propagation: a sibling dependency that also honors this flag wires
# up its own siblings in turn. When the flag is off (e.g. the `default` preset),
# nothing here runs and every dependency comes from its remote.
if(LBNL_LOCAL_SIBLINGS)
    foreach(_sibling "LBNLCPPCommon=LBNLCPPCOMMON" "FileParse=FILEPARSE" "miniz=MINIZ" "googletest=GOOGLETEST")
        string(REPLACE "=" ";" _sibling "${_sibling}")
        list(GET _sibling 0 _sibling_dir)
        list(GET _sibling 1 _sibling_var)
        if(NOT FETCHCONTENT_SOURCE_DIR_${_sibling_var}
           AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/../${_sibling_dir}/CMakeLists.txt")
            set(FETCHCONTENT_SOURCE_DIR_${_sibling_var}
                "${CMAKE_CURRENT_SOURCE_DIR}/../${_sibling_dir}")
            message(STATUS "[local] ${_sibling_dir} -> ${FETCHCONTENT_SOURCE_DIR_${_sibling_var}}")
        endif()
    endforeach()
endif()

set(LBNLCPPCommon_Branch "v0.19")

if(NOT TARGET LBNLCPPCommon)
    FetchContent_Declare(
            LBNLCPPCommon
            GIT_REPOSITORY https://github.com/LBNL-ETA/LBNLCPPCommon.git
            GIT_TAG ${LBNLCPPCommon_Branch}
    )
    FetchContent_MakeAvailable(LBNLCPPCommon)
endif()
FetchContent_GetProperties(LBNLCPPCommon)

set(FileParse_Branch "Version_1.1.7")

if(NOT TARGET FileParse)
    FetchContent_Declare(
        FileParse
        GIT_REPOSITORY https://github.com/LBNL-ETA/FileParse.git
        GIT_TAG ${FileParse_Branch}
    )
    FetchContent_MakeAvailable(FileParse)
endif()
FetchContent_GetProperties(FileParse)

set(miniz_Branch "89d7a5f6c3ce8893ea042b0a9d2a2d9975589ac9")

if(NOT TARGET miniz)
    FetchContent_Declare(
        miniz
        GIT_REPOSITORY https://github.com/richgel999/miniz
        GIT_TAG ${miniz_Branch}
    )
    FetchContent_MakeAvailable(miniz)
endif()

# Dependency targets compile with their upstream warning baggage (miniz static helpers,
# XMLParser legacy code); their sources are not this project's to fix. On GCC/Clang their
# warnings are silenced outright with -w. On MSVC only miniz is noisy (C4505), and a
# targeted /wd avoids the D9025 override noise a blanket /w would trigger against the
# /W levels those targets already carry. Headers become system includes for consumers.
foreach(_dep_target miniz xmlParser FileParse)
    if(TARGET ${_dep_target})
        get_target_property(_dep_type ${_dep_target} TYPE)
        if(NOT _dep_type STREQUAL "INTERFACE_LIBRARY" AND NOT MSVC)
            set_property(TARGET ${_dep_target} APPEND PROPERTY COMPILE_OPTIONS -w)
        endif()
        if(CMAKE_VERSION VERSION_GREATER_EQUAL "3.25")
            set_property(TARGET ${_dep_target} PROPERTY SYSTEM ON)
        endif()
    endif()
endforeach()
if(MSVC AND TARGET miniz)
    set_property(TARGET miniz APPEND PROPERTY COMPILE_OPTIONS /wd4505)
endif()

if(BUILD_PYTHON_BINDINGS)
    find_package(Python3 REQUIRED COMPONENTS Interpreter Development.Module)
    FetchContent_Declare(pybind11
        GIT_REPOSITORY https://github.com/pybind/pybind11.git
        GIT_TAG v3.1.0)
    FetchContent_MakeAvailable(pybind11)
endif()

if(DOWNLOAD_GTEST)
    if(MSVC)
        set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
    endif()
    if(NOT TARGET gtest)
        FetchContent_Declare(
            googletest
            GIT_REPOSITORY https://github.com/google/googletest.git
            GIT_TAG v1.17.0
        )
        FetchContent_MakeAvailable(googletest)

        include_directories(${gtest_SOURCE_DIR}/include)
    endif()
endif()

# Generate dependency diagram from template; indirect versions come from the pins
# FileParse exports
get_property(xmlParser_Branch TARGET FileParse PROPERTY xmlParser_Branch)
get_property(nlohmann_json_Branch TARGET FileParse PROPERTY nlohmann_json_Branch)
# This project's own box in the dependency chart: the checked-out branch while work is
# in flight, the version when the checkout sits exactly on a release tag.
set(Chart_Self "Version_${PROJECT_VERSION}")
execute_process(COMMAND git describe --tags --exact-match
    WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
    RESULT_VARIABLE Chart_NotOnTag OUTPUT_QUIET ERROR_QUIET)
execute_process(COMMAND git rev-parse --abbrev-ref HEAD
    WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
    OUTPUT_VARIABLE Chart_Branch OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET)
if(Chart_Branch STREQUAL "HEAD" AND DEFINED ENV{GITHUB_REF_NAME})
    set(Chart_Branch "$ENV{GITHUB_REF_NAME}")
endif()
if(Chart_NotOnTag AND Chart_Branch AND NOT Chart_Branch STREQUAL "HEAD")
    set(Chart_Self "${Chart_Branch}")
endif()
configure_file(
    ${CMAKE_CURRENT_SOURCE_DIR}/doc/LibraryFEMTHERM.md.in
    ${CMAKE_CURRENT_SOURCE_DIR}/doc/DependencyChart.md
)

file(GLOB_RECURSE SOURCES_HXX "src/*.hxx")
file(GLOB_RECURSE SOURCES_CXX "src/*.cxx")
LIST(APPEND SOURCES ${SOURCES_HXX} ${SOURCES_CXX})

source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${SOURCES})

add_library(${target_name} STATIC ${SOURCES})

set_target_properties(${target_name} PROPERTIES LINKER_LANGUAGE CXX)

target_include_directories(${target_name}
        PUBLIC
        ${CMAKE_CURRENT_SOURCE_DIR}/src
)

# Dependency headers are third-party from this project's point of view: bring them in
# as system includes so warnings inside them never surface in this project's builds.
target_include_directories(${target_name}
        SYSTEM PUBLIC
        ${fileparse_SOURCE_DIR}/include
        ${LBNLCPPCommon_SOURCE_DIR}/include
)

target_link_libraries(${target_name} PRIVATE FileParse LBNLCPPCommon miniz)

set_property(TARGET ${target_name} PROPERTY FileParse_Branch ${FileParse_Branch})
set_property(TARGET ${target_name} PROPERTY miniz_Branch ${miniz_Branch})
set_property(TARGET ${target_name} PROPERTY LBNLCPPCommon_Branch ${LBNLCPPCommon_Branch})

enable_testing()

if(BUILD_LibraryFEMTHERM_TESTING)
    add_subdirectory(tst)
    # Add include directories for tests if necessary
    set(TEST_DATA_DIR "${CMAKE_CURRENT_SOURCE_DIR}/tst")
    target_compile_definitions(LibraryFEMTHERM_tests PRIVATE TEST_DATA_DIR="${TEST_DATA_DIR}")
endif()

if(BUILD_PYTHON_BINDINGS)
    add_subdirectory(python)
endif()

config_compiler_and_linker_LibraryFEMTHERM()

if (MSVC)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /EHsc /utf-8")
    set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /utf-8")
    set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /utf-8")
endif()

# Warning levels
if (MSVC)
    add_compile_options(/W4)
else()
    add_compile_options(-Wall -Wextra -Wpedantic)
endif()