#include "core/project_editor.hpp"
#include <fstream>
namespace smartcut::core {
void ProjectEditor::add_segment(KeptSegment segment) {
  undo_stack_.push_back(project_); redo_stack_.clear(); project_.add_segment(std::move(segment));
}
bool ProjectEditor::undo() { if (undo_stack_.empty()) return false; redo_stack_.push_back(project_); project_ = undo_stack_.back(); undo_stack_.pop_back(); return true; }
bool ProjectEditor::redo() { if (redo_stack_.empty()) return false; undo_stack_.push_back(project_); project_ = redo_stack_.back(); redo_stack_.pop_back(); return true; }
bool ProjectEditor::save_atomic(const std::filesystem::path& path) const {
  const auto temporary = path.string() + ".tmp";
  { std::ofstream output(temporary, std::ios::binary | std::ios::trunc); if (!output) return false; output << project_.to_json() << '\n'; if (!output) return false; }
  const auto backup = path.string() + ".bak"; std::error_code error; std::filesystem::remove(backup, error); error.clear(); const bool replacing = std::filesystem::exists(path); if (replacing) { std::filesystem::rename(path, backup, error); if (error) { std::filesystem::remove(temporary); return false; } }
  std::filesystem::rename(temporary, path, error);
  if (error) { std::filesystem::remove(temporary); if (replacing) { std::error_code restore_error; std::filesystem::rename(backup, path, restore_error); } return false; }
  if (replacing) std::filesystem::remove(backup, error);
  return true;
}
}  // namespace smartcut::core
