// Hesela probe: execute the unmodified RocksDB v9.7.3 fragmenter in memory.
#include <iomanip>
#include <iostream>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
#include "db/range_tombstone_fragmenter.h"
#include "util/vector_iterator.h"
using namespace ROCKSDB_NAMESPACE;
static std::string key(unsigned value) {
  std::ostringstream out;
  out << std::hex << std::setw(8) << std::setfill('0') << value;
  return out.str();
}
int main(int argc, char** argv) {
  if (argc != 4) return 2;
  const std::string shape = argv[1], mode = argv[3];
  const unsigned n = std::stoul(argv[2]);
  if (n == 0 || n > 256) return 2;
  InternalKeyComparator comparator(BytewiseComparator());
  std::vector<std::string> keys, values;
  std::vector<SequenceNumber> snapshots;
  if (mode == "middle") snapshots.push_back(n / 2);
  else if (mode == "all") for (unsigned i = 1; i <= n; ++i) snapshots.push_back(i);
  else if (mode != "read" && mode != "none") return 2;
  for (unsigned i = 0; i < n; ++i) {
    unsigned start, end;
    if (shape == "nested") { start = i; end = 2 * n - i; }
    else if (shape == "disjoint") { start = 2 * i; end = 2 * i + 1; }
    else if (shape == "coincident") { start = 0; end = 1; }
    else return 2;
    const std::string a = key(start), b = key(end);
    RangeTombstone tombstone(a, b, i + 1);
    auto serialized = tombstone.Serialize();
    keys.push_back(serialized.first.Encode().ToString());
    values.push_back(serialized.second.ToString());
  }
  auto input = std::make_unique<VectorIterator>(keys, values, &comparator);
  FragmentedRangeTombstoneList list(std::move(input), comparator, mode != "read", snapshots);
  std::cout << "[";
  bool first = true;
  for (const auto& stack : list) {
    if (!first) std::cout << ",";
    first = false;
    std::cout << "[" << std::stoul(stack.start_key.ToString(), nullptr, 16) << ","
              << std::stoul(stack.end_key.ToString(), nullptr, 16) << ",[";
    bool first_seq = true;
    for (auto it = list.seq_iter(stack.seq_start_idx); it != list.seq_iter(stack.seq_end_idx); ++it) {
      if (!first_seq) std::cout << ",";
      first_seq = false;
      std::cout << *it;
    }
    std::cout << "]]";
  }
  std::cout << "]\n";
}
