if(NOT MACE)
  return()
endif()
set(mace_test_python "${MACE_TEST_PYTHON}")
if(NOT mace_test_python AND DEFINED ENV{PIMD_MACE_PYTHON})
  set(mace_test_python "$ENV{PIMD_MACE_PYTHON}")
endif()
if(NOT mace_test_python)
  set(mace_test_python "${Python3_EXECUTABLE}")
endif()
execute_process(COMMAND "${mace_test_python}" -c
  "import importlib.util,sys; sys.exit(0 if all(importlib.util.find_spec(m) for m in ('torch','mace','ase','yaml')) else 1)"
  RESULT_VARIABLE mace_python_ready OUTPUT_QUIET ERROR_QUIET TIMEOUT 30)
if(NOT "${mace_python_ready}" STREQUAL "0")
  message(STATUS "MACE verification omitted: set MACE_TEST_PYTHON to its installed Python runtime")
  return()
endif()
set(mace_test_model "${MACE_TEST_MODEL}")
if(mace_test_model)
  if(NOT EXISTS "${mace_test_model}" OR IS_DIRECTORY "${mace_test_model}")
    message(FATAL_ERROR "MACE_TEST_MODEL must name an existing checkpoint")
  endif()
elseif(MACE_TEST_DOWNLOAD_MODEL)
  set(mace_test_model "${PROJECT_BINARY_DIR}/tests/models/mace_mp_0_small.model")
  set(model_sha "2ddb079cee0e131eaaf6912ba581b394551ead283e95c99cfe78c605d10b5736")
  set(model_ready FALSE)
  if(EXISTS "${mace_test_model}")
    file(SHA256 "${mace_test_model}" current_sha)
    if(current_sha STREQUAL model_sha)
      set(model_ready TRUE)
    endif()
  endif()
  if(NOT model_ready)
    message(STATUS "Downloading the MACE verification checkpoint into the build tree")
    file(MAKE_DIRECTORY "${PROJECT_BINARY_DIR}/tests/models")
    file(DOWNLOAD
      "https://github.com/ACEsuit/mace-foundations/releases/download/mace_mp_0/2023-12-10-mace-128-L0_energy_epoch-249.model"
      "${mace_test_model}.download" EXPECTED_HASH "SHA256=${model_sha}"
      TLS_VERIFY ON TIMEOUT 180 STATUS download_status)
    list(GET download_status 0 download_code)
    if(NOT download_code EQUAL 0)
      file(REMOVE "${mace_test_model}.download")
      message(FATAL_ERROR "MACE checkpoint download failed: ${download_status}. Supply MACE_TEST_MODEL for offline builds.")
    endif()
    file(RENAME "${mace_test_model}.download" "${mace_test_model}")
  endif()
else()
  message(STATUS "MACE verification omitted: supply MACE_TEST_MODEL or enable MACE_TEST_DOWNLOAD_MODEL")
  return()
endif()
set(example "${CMAKE_CURRENT_SOURCE_DIR}/SiO2")
add_example_derivative_tests(MACE SiO2 "${example}"
  MACE_MODEL "${mace_test_model}" FILES "${mace_test_model}")
foreach(name IN ITEMS validation-mace-SiO2-force-1beads validation-mace-SiO2-virial-3beads)
  set_property(TEST ${name} APPEND PROPERTY ENVIRONMENT "PIMD_MACE_PYTHON=${mace_test_python}")
endforeach()
