#include <utils/checkpointing/SetResumeFrom.hpp>

#include <utils/pugs_config.hpp>

#ifdef PUGS_HAS_HDF5

#include <optional>
#include <rang.hpp>
#include <utils/Exceptions.hpp>
#include <utils/HighFivePugsUtils.hpp>

void
setResumeFrom(const std::string& filename, const uint64_t& checkpoint_number)
{
  try {
    HighFive::File file(filename, HighFive::File::ReadWrite);
    const std::string checkpoint_name = "checkpoint_" + std::to_string(checkpoint_number);

    if (not file.exist(checkpoint_name)) {
      std::ostringstream error_msg;
      error_msg << "cannot find checkpoint " << rang::fgB::magenta << checkpoint_number << rang::fg::reset << " in "
                << rang::fgB::yellow << filename << rang::fg::reset;
      throw NormalError(error_msg.str());
    }

    HighFive::Group checkpoint = file.getGroup(checkpoint_name);
    if (file.exist("resuming_checkpoint")) {
      file.unlink("resuming_checkpoint");
    }
    file.createHardLink("resuming_checkpoint", checkpoint);
    std::cout << "Resuming checkpoint " << rang::style::bold << "successfully" << rang::style::reset << " set to "
              << rang::fgB::yellow << checkpoint_number << rang::fg::reset << '\n';
  }
  catch (HighFive::Exception& e) {
    throw NormalError(e.what());
  }
}

#else   // PUGS_HAS_HDF5

void
setResumeFrom(const std::string&, const uint64_t&)
{
  std::cerr << rang::fgB::red << "error: " << rang::fg::reset << "setting resuming checkpoint requires HDF5\n";
}

#endif   // PUGS_HAS_HDF5