#include "store.h"

#include "git.h"

#include <algorithm>
#include <atomic>
#include <cstring>
#include <iostream>
#include <thread>
#include <unordered_set>

#include <zstd.h>

namespace vn {

namespace {
PromisorFetcher promisor_fetcher;
} // namespace

void set_promisor_fetcher(PromisorFetcher fetcher) {
  promisor_fetcher = std::move(fetcher);
}

// ---------------------------------------------------------------------------
// Layout
// ---------------------------------------------------------------------------

fs::path veins_dir(const fs::path &root) { return root / ".veins"; }
fs::path packs_dir(const fs::path &root) {
  return veins_dir(root) / "store" / "packs";
}
fs::path tmp_dir(const fs::path &root) {
  return veins_dir(root) / "store" / "tmp";
}
fs::path op_heads_dir(const fs::path &root) {
  return veins_dir(root) / "op-heads";
}
fs::path git_dir(const fs::path &root) { return veins_dir(root) / "git"; }
fs::path git_map_dir(const fs::path &root) {
  return veins_dir(root) / "git-map";
}
fs::path working_copy_dir(const fs::path &root) {
  return veins_dir(root) / "working-copy";
}
fs::path resolutions_dir(const fs::path &root) {
  return veins_dir(root) / "resolutions";
}
fs::path config_path(const fs::path &root) {
  return veins_dir(root) / "config";
}
fs::path format_path(const fs::path &root) {
  return veins_dir(root) / "format";
}

static std::uint64_t repo_storage_usage(const fs::path &root) {
  std::uint64_t total = 0;
  for (const auto &name : list_directory(packs_dir(root))) {
    const auto info = stat_path(packs_dir(root) / path_from_bytes(name));
    if (info && info->kind == 1)
      total += info->size;
  }
  return total;
}

std::uint64_t storage_usage(const fs::path &dir) {
  if (!stat_path(dir)) {
    return 0;
  }
  if (stat_path(format_path(dir))) {
    return repo_storage_usage(dir);
  }
  std::uint64_t total = 0;
  for (const auto &name : list_directory(dir)) {
    const fs::path child = dir / path_from_bytes(name);
    const auto info = stat_path(child);
    if (info && info->kind == 2)
      total += repo_storage_usage(child);
  }
  return total;
}

std::optional<fs::path> discover_repo(const fs::path &start) {
  std::error_code ec;
  fs::path current = fs::absolute(start, ec);
  if (ec)
    return std::nullopt;
  current = fs::weakly_canonical(current, ec);
  if (ec)
    return std::nullopt;
  for (;;) {
    if (path_is_file(current / ".veins" / "format"))
      return current;
    const fs::path parent = current.parent_path();
    if (parent == current || parent.empty())
      return std::nullopt;
    current = parent;
  }
}

static bool migrate_dir(const fs::path &from, const fs::path &to) {
  if (path_is_dir(from) && !path_is_dir(to)) {
    std::error_code ec;
    fs::rename(from, to, ec);
    return !ec;
  }
  return true;
}

static bool ensure_layout(const fs::path &root) {
  if (!migrate_dir(veins_dir(root) / "op_heads", op_heads_dir(root)))
    return false;
  if (!migrate_dir(veins_dir(root) / "working_copy", working_copy_dir(root)))
    return false;
  const fs::path dirs[] = {
      veins_dir(root),           veins_dir(root) / "store",
      packs_dir(root),           tmp_dir(root),
      op_heads_dir(root),        git_map_dir(root),
      git_map_dir(root) / "raw", working_copy_dir(root),
      resolutions_dir(root),
  };
  for (const auto &dir : dirs) {
    if (!ensure_directory(dir))
      return false;
  }
  return true;
}

Result<fs::path> init_repo(const fs::path &path) {
  fs::path root = path.lexically_normal();
  if (root.empty())
    root = ".";
  if (!path_is_dir(root)) {
    if (!ensure_directory(root))
      return unexpected(Error{ErrorKind::Io, 4, "init failed"});
  }
  const fs::path format = format_path(root);
  const std::string_view expected = "veins-store 1";
  if (path_exists(format)) {
    auto data = read_file(format);
    if (!data)
      return unexpected(Error{ErrorKind::Io, 3, "init failed"});
    if (!equals(bytes_of(*data), bytes_of(expected)))
      return unexpected(Error{ErrorKind::InvalidValue, 2, "init failed"});
  }
  if (!ensure_layout(root))
    return unexpected(Error{ErrorKind::Io, 4, "init failed"});
  if (!path_exists(format)) {
    if (!write_file(format, bytes_of(expected)))
      return unexpected(Error{ErrorKind::Io, 11, "init failed"});
  }
  if (!path_exists(config_path(root))) {
    (void)write_file(config_path(root), Bytes{});
  }
  return root;
}

// ---------------------------------------------------------------------------
// Pack decoding
// ---------------------------------------------------------------------------

std::optional<std::size_t> Pack::find_by_offset(std::uint64_t offset) const {
  std::size_t lo = 0;
  std::size_t hi = records.size();
  while (lo < hi) {
    const std::size_t mid = lo + (hi - lo) / 2;
    const std::uint64_t cur = records[mid].record_off;
    if (cur == offset)
      return mid;
    if (cur < offset)
      lo = mid + 1;
    else
      hi = mid;
  }
  return std::nullopt;
}

Result<std::vector<std::uint8_t>> Pack::get(std::size_t record_index) const {
  if (record_index >= records.size())
    return fail(ErrorKind::Corrupt, 0);
  const PackRecord &rec = records[record_index];
  const auto raw_len = static_cast<std::size_t>(rec.raw_len);
  if (raw_len == 0)
    return std::vector<std::uint8_t>{};
  const auto off = static_cast<std::size_t>(rec.data_off);
  const auto stored_len = static_cast<std::size_t>(rec.stored_len);
  if (off > data.size() || stored_len > data.size() - off)
    return fail(ErrorKind::Corrupt, off);
  if (rec.compression == 0) {
    return std::vector<std::uint8_t>(
        data.begin() + static_cast<std::ptrdiff_t>(off),
        data.begin() + static_cast<std::ptrdiff_t>(off + stored_len));
  }
  std::vector<std::uint8_t> out(raw_len);
  const std::size_t n =
      ZSTD_decompress(out.data(), raw_len, data.data() + off, stored_len);
  if (ZSTD_isError(n) || n != raw_len)
    return fail(ErrorKind::Corrupt, off);
  return out;
}

static std::size_t pack_type_limit(std::uint8_t type) {
  return type == TYPE_CHUNK ? MAX_CHUNK_LEN : MAX_OBJECT_BODY;
}

Result<Pack> decode_pack(std::vector<std::uint8_t> data) {
  constexpr std::size_t header_len = 16;
  constexpr std::size_t record_min = 36;
  if (data.size() < header_len + 32)
    return fail(ErrorKind::UnexpectedEnd, 0);
  if (std::memcmp(data.data(), "VPK1", 4) != 0)
    return fail(ErrorKind::InvalidMagic, 0);
  Reader header(Bytes(data.data(), header_len));
  (void)header.raw(4);
  const auto version = header.u32le();
  if (!version)
    return unexpected(version.error());
  if (*version != 1)
    return fail(ErrorKind::UnsupportedVersion, 4);
  const auto count_u64 = header.u64le();
  if (!count_u64)
    return unexpected(count_u64.error());

  const std::size_t body_end = data.size() - 32;
  const auto digest = blake3_hash(Bytes(data.data(), body_end));
  if (!equals(Bytes(digest.data(), digest.size()),
              Bytes(data.data() + body_end, 32)))
    return fail(ErrorKind::HashMismatch, body_end);

  if (*count_u64 > body_end / record_min)
    return fail(ErrorKind::LimitExceeded, 8);
  const std::size_t count = static_cast<std::size_t>(*count_u64);

  Reader r(Bytes(data.data(), body_end));
  (void)r.raw(header_len);
  Pack pack;
  pack.records.reserve(count);
  for (std::size_t i = 0; i < count; ++i) {
    PackRecord rec;
    rec.record_off = r.offset();
    const auto id = r.id();
    if (!id)
      return unexpected(id.error());
    rec.id = *id;
    const auto kind = r.u8();
    if (!kind)
      return unexpected(kind.error());
    if (!type_valid(*kind))
      return fail(ErrorKind::InvalidValue, r.offset() - 1);
    rec.type = *kind;
    const auto comp = r.u8();
    if (!comp)
      return unexpected(comp.error());
    if (*comp > 1)
      return fail(ErrorKind::InvalidValue, r.offset() - 1);
    rec.compression = *comp;
    const std::size_t at = r.offset();
    const auto raw_len = r.varint();
    if (!raw_len)
      return unexpected(raw_len.error());
    const auto stored_len = r.varint();
    if (!stored_len)
      return unexpected(stored_len.error());
    if (*raw_len == 0)
      return fail(ErrorKind::InvalidValue, at);
    if (*raw_len > pack_type_limit(rec.type))
      return fail(ErrorKind::LimitExceeded, at);
    if (rec.compression == 0 && *raw_len != *stored_len)
      return fail(ErrorKind::InvalidValue, at);
    if (*stored_len > r.remaining())
      return fail(ErrorKind::UnexpectedEnd, at);
    rec.raw_len = *raw_len;
    rec.stored_len = *stored_len;
    rec.data_off = r.offset();
    const auto body = r.raw(static_cast<std::size_t>(*stored_len));
    if (!body)
      return unexpected(body.error());
    pack.records.push_back(rec);
  }
  if (r.offset() != body_end)
    return fail(ErrorKind::TrailingBytes, r.offset());
  std::memcpy(pack.trailer.data(), data.data() + body_end, 32);
  pack.data = std::move(data);
  return pack;
}

// ---------------------------------------------------------------------------
// Index
// ---------------------------------------------------------------------------

std::optional<std::size_t> Index::find(const Id &id) const {
  std::size_t lo = 0;
  std::size_t hi = ids.size();
  while (lo < hi) {
    const std::size_t mid = lo + (hi - lo) / 2;
    const int c = std::memcmp(ids[mid].data(), id.data(), ID_LEN);
    if (c == 0)
      return mid;
    if (c < 0)
      lo = mid + 1;
    else
      hi = mid;
  }
  return std::nullopt;
}

Result<Index> decode_index(
    std::vector<std::uint8_t> data,
    const std::optional<std::array<std::uint8_t, 32>> &expected_pack_trailer) {
  constexpr std::size_t base = 1032 + 64;
  if (data.size() < base)
    return fail(ErrorKind::UnexpectedEnd, 0);
  if (std::memcmp(data.data(), "VIX1", 4) != 0)
    return fail(ErrorKind::InvalidMagic, 0);
  Reader r(Bytes(data.data(), data.size()));
  (void)r.raw(4);
  const auto version = r.u32le();
  if (!version)
    return unexpected(version.error());
  if (*version != 1)
    return fail(ErrorKind::UnsupportedVersion, 4);
  std::array<std::uint32_t, 256> fanout{};
  std::uint32_t prev = 0;
  for (std::size_t i = 0; i < 256; ++i) {
    const auto v = r.u32le();
    if (!v)
      return unexpected(v.error());
    if (*v < prev)
      return fail(ErrorKind::Unsorted, r.offset() - 4);
    prev = *v;
    fanout[i] = *v;
  }
  const std::size_t body = data.size() - base;
  if (body % 40 != 0)
    return fail(ErrorKind::TrailingBytes, base);
  const std::size_t count = body / 40;
  if (count != fanout[255])
    return fail(ErrorKind::Corrupt, 1032);

  Index index;
  index.ids.resize(count);
  index.offsets.resize(count);
  std::memcpy(index.ids.data(), data.data() + 1032, count * 32);
  std::memcpy(index.offsets.data(), data.data() + 1032 + count * 32, count * 8);
  std::memcpy(index.pack_trailer.data(),
              data.data() + 1032 + count * 32 + count * 8, 32);
  const std::size_t index_trailer_off = data.size() - 32;
  const auto digest = blake3_hash(Bytes(data.data(), index_trailer_off));
  if (!equals(Bytes(digest.data(), digest.size()),
              Bytes(data.data() + index_trailer_off, 32)))
    return fail(ErrorKind::HashMismatch, index_trailer_off);
  if (expected_pack_trailer &&
      !equals(Bytes(index.pack_trailer.data(), 32),
              Bytes(expected_pack_trailer->data(), 32)))
    return fail(ErrorKind::Corrupt, index_trailer_off);

  std::array<std::uint32_t, 256> counts{};
  for (std::size_t i = 0; i < count; ++i) {
    if (i > 0) {
      const int c =
          std::memcmp(index.ids[i - 1].data(), index.ids[i].data(), ID_LEN);
      if (c == 0)
        return fail(ErrorKind::Duplicate, 1032 + i * 32);
      if (c > 0)
        return fail(ErrorKind::Unsorted, 1032 + i * 32);
    }
    counts[index.ids[i][0]]++;
  }
  std::uint32_t running = 0;
  for (std::size_t i = 0; i < 256; ++i) {
    running += counts[i];
    if (fanout[i] != running)
      return fail(ErrorKind::Corrupt, 8 + i * 4);
  }
  return Result<Index>(std::move(index));
}

static void write_u64le(std::vector<std::uint8_t> &out, std::size_t off,
                        std::uint64_t value) {
  for (int i = 0; i < 8; ++i)
    out[off + static_cast<std::size_t>(i)] =
        static_cast<std::uint8_t>((value >> (i * 8)) & 255u);
}

std::vector<std::uint8_t>
encode_index(const std::vector<RecordMeta> &records,
             const std::array<std::uint8_t, 32> &trailer) {
  std::array<std::uint32_t, 256> counts{};
  for (const auto &rec : records)
    counts[rec.id[0]]++;
  ByteWriter w(records.size() * 40 + 128);
  w.raw("VIX1");
  w.u32le(1);
  std::uint32_t running = 0;
  for (std::size_t i = 0; i < 256; ++i) {
    running += counts[i];
    w.u32le(running);
  }
  for (const auto &rec : records)
    w.id(rec.id);
  for (const auto &rec : records)
    w.u64le(rec.offset);
  w.raw(Bytes(trailer.data(), trailer.size()));
  auto bytes = w.take();
  const auto digest = blake3_hash(bytes_of(bytes));
  bytes.insert(bytes.end(), digest.begin(), digest.end());
  return bytes;
}

// ---------------------------------------------------------------------------
// Pack encoding
// ---------------------------------------------------------------------------

static std::vector<std::uint8_t> zstd_compress(Bytes data) {
  if (data.empty())
    return {};
  const std::size_t bound = ZSTD_compressBound(data.size());
  std::vector<std::uint8_t> out(bound);
  const std::size_t n =
      ZSTD_compress(out.data(), bound, data.data(), data.size(), 1);
  if (ZSTD_isError(n) || n >= data.size())
    return {};
  out.resize(n);
  return out;
}

PackOutput encode_pack(const std::vector<RawObject> &objects) {
  PackOutput output;
  std::set<Id> seen;
  struct Pending {
    const RawObject *object = nullptr;
    Id id{};
    std::uint8_t compression = 0;
    std::vector<std::uint8_t> compressed;
  };
  std::vector<Pending> pending;
  pending.reserve(objects.size());
  for (const auto &object : objects) {
    if (!type_valid(object.type))
      continue;
    const Id id =
        object.id ? *object.id : object_id(object.type, bytes_of(object.body));
    if (!seen.insert(id).second)
      continue;
    pending.push_back(Pending{&object, id, 0, {}});
  }

  auto compress_one = [](Pending &item) {
    if (item.object->body.size() < 64)
      return;
    item.compressed = zstd_compress(bytes_of(item.object->body));
    item.compression = item.compressed.empty() ? 0 : 1;
  };
  if (pending.size() > 1) {
    std::size_t workers = available_cpu_count();
    if (workers == 0)
      workers = 1;
    workers = std::min<std::size_t>(workers, pending.size());
    workers = std::min<std::size_t>(workers, 16);
    if (workers > 1) {
      std::atomic<std::size_t> next{0};
      std::vector<std::thread> threads;
      threads.reserve(workers);
      for (std::size_t w = 0; w < workers; ++w) {
        threads.emplace_back([&]() {
          for (;;) {
            const std::size_t index = next.fetch_add(1);
            if (index >= pending.size())
              return;
            compress_one(pending[index]);
          }
        });
      }
      for (auto &thread : threads)
        thread.join();
    } else {
      for (auto &item : pending)
        compress_one(item);
    }
  } else {
    for (auto &item : pending)
      compress_one(item);
  }

  std::vector<RecordMeta> metas;
  metas.reserve(pending.size());
  std::size_t estimate = 16;
  for (const auto &item : pending) {
    estimate += 32 + 2 + 20 +
                (item.compression == 1 ? item.compressed.size()
                                       : item.object->body.size());
  }
  ByteWriter w(estimate);
  w.raw("VPK1");
  w.u32le(1);
  w.u64le(0);
  for (const auto &item : pending) {
    const auto &object = *item.object;
    const std::uint64_t offset = w.size();
    const Bytes stored = item.compression == 1 ? bytes_of(item.compressed)
                                               : bytes_of(object.body);
    ByteWriter rec(64);
    rec.id(item.id);
    rec.u8(object.type);
    rec.u8(item.compression);
    rec.varint(object.body.size());
    rec.varint(stored.size());
    rec.raw(stored);
    w.raw(rec.view());
    metas.push_back(
        RecordMeta{item.id, offset, object.type, object.body.size()});
  }

  auto pack = w.take();
  write_u64le(pack, 8, static_cast<std::uint64_t>(metas.size()));
  const auto digest = blake3_hash(bytes_of(pack));
  pack.insert(pack.end(), digest.begin(), digest.end());
  std::array<std::uint8_t, 32> trailer{};
  std::memcpy(trailer.data(), digest.data(), 32);

  std::stable_sort(metas.begin(), metas.end(),
                   [](const RecordMeta &a, const RecordMeta &b) {
                     return std::memcmp(a.id.data(), b.id.data(), ID_LEN) < 0;
                   });
  output.index = encode_index(metas, trailer);
  output.name = hex_encode(Bytes(trailer.data(), trailer.size()));
  output.count = metas.size();
  output.pack = std::move(pack);
  return output;
}

int write_pack(const fs::path &root, const std::vector<RawObject> &objects,
               std::uint64_t limit) {
  PackOutput output = encode_pack(objects);
  if (output.count == 0)
    return 0;
  if (limit > 0 && output.pack.size() + output.index.size() > limit)
    return 2;
  const fs::path pfinal = packs_dir(root) / (output.name + ".vpack");
  const fs::path ifinal = packs_dir(root) / (output.name + ".vidx");
  const fs::path ptmp = tmp_dir(root) / (output.name + ".vpack.tmp");
  const fs::path itmp = tmp_dir(root) / (output.name + ".vidx.tmp");
  if (!write_atomic(ptmp, pfinal, bytes_of(output.pack)))
    return 1;
  if (!write_atomic(itmp, ifinal, bytes_of(output.index))) {
    (void)remove_file(pfinal);
    return 1;
  }
  return 0;
}

// ---------------------------------------------------------------------------
// Store
// ---------------------------------------------------------------------------

static bool handle_index(StoreHandle &handle) {
  if (handle.index)
    return true;
  std::string name = basename_string(handle.path);
  if (name.size() <= 6)
    return false;
  name.resize(name.size() - 6);
  const fs::path idx_path = handle.path.parent_path() / (name + ".vidx");
  auto data = read_file_opt(idx_path);
  if (!data)
    return false;
  auto decoded = decode_index(std::move(*data));
  if (!decoded)
    return false;
  if (name != hex_encode(Bytes(decoded->pack_trailer.data(), 32)))
    return false;
  handle.index = std::move(*decoded);
  return true;
}

bool Store::ensure_index(StoreHandle &handle) { return handle_index(handle); }

bool Store::ensure_pack(StoreHandle &handle) {
  if (handle.pack)
    return true;
  if (!ensure_index(handle))
    return false;
  auto data = read_file_opt(handle.path);
  if (!data)
    return false;
  auto decoded = decode_pack(std::move(*data));
  if (!decoded)
    return false;
  if (!equals(Bytes(decoded->trailer.data(), 32),
              Bytes(handle.index->pack_trailer.data(), 32)))
    return false;
  handle.pack = std::move(*decoded);
  return true;
}

static std::uint64_t handle_mtime(const fs::path &path) {
  const auto info = stat_path(path);
  return info ? info->mtime_ns : 0;
}

Store Store::open_all(const fs::path &root) {
  Store store;
  store.root_ = root;
  for (const auto &name : list_directory(packs_dir(root))) {
    if (name.size() <= 6)
      continue;
    if (name.compare(name.size() - 6, 6, ".vpack") != 0)
      continue;
    StoreHandle handle;
    handle.path = packs_dir(root) / path_from_bytes(name);
    handle.mtime_ns = handle_mtime(handle.path);
    store.handles_.push_back(std::move(handle));
  }
  std::stable_sort(store.handles_.begin(), store.handles_.end(),
                   [](const StoreHandle &a, const StoreHandle &b) {
                     return a.mtime_ns >= b.mtime_ns;
                   });
  return store;
}

void Store::preload() {
  for (auto &handle : handles_) {
    (void)ensure_index(handle);
    (void)ensure_pack(handle);
  }
}

void Store::refresh(const fs::path &root) {
  for (const auto &name : list_directory(packs_dir(root))) {
    if (name.size() <= 6)
      continue;
    if (name.compare(name.size() - 6, 6, ".vpack") != 0)
      continue;
    const fs::path path = packs_dir(root) / path_from_bytes(name);
    bool found = false;
    for (const auto &handle : handles_) {
      if (handle.path == path) {
        found = true;
        break;
      }
    }
    if (!found) {
      StoreHandle handle;
      handle.path = path;
      handle.mtime_ns = handle_mtime(path);
      handles_.push_back(std::move(handle));
    }
  }
  std::stable_sort(handles_.begin(), handles_.end(),
                   [](const StoreHandle &a, const StoreHandle &b) {
                     return a.mtime_ns >= b.mtime_ns;
                   });
}

std::optional<Loc> Store::find(const Id &id) {
  for (std::size_t i = 0; i < handles_.size(); ++i) {
    auto &handle = handles_[i];
    if (!ensure_index(handle))
      continue;
    const auto pos = handle.index->find(id);
    if (!pos)
      continue;
    const std::uint64_t offset = handle.index->offsets[*pos];
    if (!ensure_pack(handle))
      continue;
    const auto rec = handle.pack->find_by_offset(offset);
    if (!rec)
      continue;
    return Loc{i, *rec, handle.pack->records[*rec].type};
  }
  return std::nullopt;
}

Result<std::vector<std::uint8_t>> Store::get(const Loc &loc) {
  if (loc.pack_index >= handles_.size())
    return fail(ErrorKind::Corrupt, 0);
  auto &handle = handles_[loc.pack_index];
  if (!ensure_pack(handle))
    return fail(ErrorKind::Corrupt, 0);
  return handle.pack->get(loc.record_index);
}

std::optional<std::vector<std::uint8_t>>
Store::read_body(const Id &id, std::uint8_t expected) {
  auto loc = find(id);
  if (!loc && expected == TYPE_CHUNK && promisor_fetcher && !root_.empty()) {
    if (promisor_fetcher(root_, id)) {
      refresh(root_);
      loc = find(id);
    }
  }
  if (!loc || loc->kind != expected)
    return std::nullopt;
  auto body = get(*loc);
  if (!body)
    return std::nullopt;
  const Id computed = object_id(expected, bytes_of(*body));
  if (std::memcmp(computed.data(), id.data(), ID_LEN) != 0)
    return std::nullopt;
  return std::move(*body);
}

std::optional<View> Store::read_view(const Id &id) {
  auto body = read_body(id, TYPE_VIEW);
  if (!body)
    return std::nullopt;
  auto view = decode_view(bytes_of(*body));
  if (!view)
    return std::nullopt;
  return std::move(*view);
}

std::optional<Operation> Store::read_operation(const Id &id) {
  auto body = read_body(id, TYPE_OPERATION);
  if (!body)
    return std::nullopt;
  auto op = decode_operation(bytes_of(*body));
  if (!op)
    return std::nullopt;
  return std::move(*op);
}

bool Store::has_promisor(const fs::path &root) const {
  auto data = read_file_opt(config_path(root));
  if (!data)
    return false;
  const std::string_view text(reinterpret_cast<const char *>(data->data()),
                              data->size());
  return text.find("promisor") != std::string_view::npos;
}

// ---------------------------------------------------------------------------
// Writer
// ---------------------------------------------------------------------------

Id Writer::add(std::uint8_t type, const std::vector<std::uint8_t> &body) {
  const Id id = object_id(type, bytes_of(body));
  if (quota_hit_ || !seen_.insert(id).second)
    return id;
  if (limit_ > 0 && raw_bytes_ + body.size() > limit_) {
    quota_hit_ = true;
    return id;
  }
  raw_bytes_ += body.size();
  objects_.push_back(RawObject{type, body, id});
  if (type != TYPE_CHUNK || cache_chunks_)
    cache_.push_back(RawObject{type, body, id});
  return id;
}

Id Writer::add(std::uint8_t type, std::vector<std::uint8_t> &&body) {
  const Id id = object_id(type, bytes_of(body));
  if (quota_hit_ || !seen_.insert(id).second)
    return id;
  if (limit_ > 0 && raw_bytes_ + body.size() > limit_) {
    quota_hit_ = true;
    return id;
  }
  raw_bytes_ += body.size();
  if (type != TYPE_CHUNK || cache_chunks_)
    cache_.push_back(RawObject{type, body, id});
  objects_.push_back(RawObject{type, std::move(body), id});
  return id;
}

Id Writer::add_known(std::uint8_t type, const Id &id,
                     const std::vector<std::uint8_t> &body) {
  if (quota_hit_ || !seen_.insert(id).second)
    return id;
  if (limit_ > 0 && raw_bytes_ + body.size() > limit_) {
    quota_hit_ = true;
    return id;
  }
  raw_bytes_ += body.size();
  objects_.push_back(RawObject{type, body, id});
  if (type != TYPE_CHUNK || cache_chunks_)
    cache_.push_back(RawObject{type, body, id});
  return id;
}

Id Writer::add_known(std::uint8_t type, const Id &id,
                     std::vector<std::uint8_t> &&body) {
  if (quota_hit_ || !seen_.insert(id).second)
    return id;
  if (limit_ > 0 && raw_bytes_ + body.size() > limit_) {
    quota_hit_ = true;
    return id;
  }
  raw_bytes_ += body.size();
  if (type != TYPE_CHUNK || cache_chunks_)
    cache_.push_back(RawObject{type, body, id});
  objects_.push_back(RawObject{type, std::move(body), id});
  return id;
}

std::optional<std::vector<std::uint8_t>>
Writer::find_cached(std::uint8_t type, const Id &id) const {
  for (const auto &object : cache_) {
    const Id candidate =
        object.id ? *object.id : object_id(type, bytes_of(object.body));
    if (object.type == type &&
        std::memcmp(candidate.data(), id.data(), ID_LEN) == 0)
      return object.body;
  }
  return std::nullopt;
}

int Writer::finish(const fs::path &root) {
  if (quota_hit_)
    return 2;
  return write_pack(root, objects_, limit_);
}

// ---------------------------------------------------------------------------
// View helpers
// ---------------------------------------------------------------------------

static bool id_less(const Id &a, const Id &b) {
  return std::memcmp(a.data(), b.data(), ID_LEN) < 0;
}

static bool id_equal(const Id &a, const Id &b) {
  return std::memcmp(a.data(), b.data(), ID_LEN) == 0;
}

namespace {
struct IdHash {
  std::size_t operator()(const Id &id) const noexcept {
    std::size_t h = 1469598103934665603ull;
    for (auto b : id) {
      h ^= b;
      h *= 1099511628211ull;
    }
    return h;
  }
};
struct IdEq {
  bool operator()(const Id &a, const Id &b) const noexcept {
    return id_equal(a, b);
  }
};
} // namespace

bool contains_id(const std::vector<Id> &ids, const Id &id) {
  return std::find_if(ids.begin(), ids.end(), [&](const Id &x) {
           return id_equal(x, id);
         }) != ids.end();
}

bool target_contains(const std::vector<std::optional<Id>> &ids, const Id &id) {
  for (const auto &x : ids) {
    if (x && id_equal(*x, id))
      return true;
  }
  return false;
}

std::optional<Id> working_copy_id(const View &view) {
  for (const auto &workspace : view.working_copies) {
    if (workspace.workspace == "default")
      return workspace.target;
  }
  return std::nullopt;
}

void sort_ids(std::vector<Id> &ids) {
  std::stable_sort(ids.begin(), ids.end(), id_less);
}

void sort_view(View &view) {
  sort_ids(view.heads);
  std::stable_sort(view.bookmarks.begin(), view.bookmarks.end(),
                   [](const Bookmark &a, const Bookmark &b) {
                     return compare(bytes_of(a.name), bytes_of(b.name)) < 0;
                   });
  std::stable_sort(view.tags.begin(), view.tags.end(),
                   [](const TagRef &a, const TagRef &b) {
                     return compare(bytes_of(a.name), bytes_of(b.name)) < 0;
                   });
  std::stable_sort(view.remote_refs.begin(), view.remote_refs.end(),
                   [](const RemoteRef &a, const RemoteRef &b) {
                     const int c =
                         compare(bytes_of(a.remote), bytes_of(b.remote));
                     if (c != 0)
                       return c < 0;
                     return compare(bytes_of(a.name), bytes_of(b.name)) < 0;
                   });
  std::stable_sort(view.working_copies.begin(), view.working_copies.end(),
                   [](const WorkspaceRef &a, const WorkspaceRef &b) {
                     return compare(bytes_of(a.workspace),
                                    bytes_of(b.workspace)) < 0;
                   });
}

void add_unique_head(View &view, const Id &id) {
  if (!contains_id(view.heads, id))
    view.heads.push_back(id);
}

void rebuild_heads(View &view) {
  view.heads.clear();
  for (const auto &bookmark : view.bookmarks) {
    for (const auto &id : bookmark.targets.adds) {
      if (id)
        add_unique_head(view, *id);
    }
  }
  for (const auto &tag : view.tags)
    add_unique_head(view, tag.target);
  for (const auto &workspace : view.working_copies)
    add_unique_head(view, workspace.target);
  sort_ids(view.heads);
}

void set_workspace(View &view, const Id &id) {
  for (auto &workspace : view.working_copies) {
    if (workspace.workspace == "default") {
      workspace.target = id;
      return;
    }
  }
  view.working_copies.push_back(WorkspaceRef{"default", id});
  std::stable_sort(view.working_copies.begin(), view.working_copies.end(),
                   [](const WorkspaceRef &a, const WorkspaceRef &b) {
                     return compare(bytes_of(a.workspace),
                                    bytes_of(b.workspace)) < 0;
                   });
}

void remove_head(View &view, const Id &id) {
  view.heads.erase(std::remove_if(view.heads.begin(), view.heads.end(),
                                  [&](const Id &x) { return id_equal(x, id); }),
                   view.heads.end());
}

void move_bookmarks(View &view, const Id &old_id, const Id &new_id) {
  if (id_equal(old_id, new_id))
    return;
  for (auto &bookmark : view.bookmarks) {
    if (target_contains(bookmark.targets.adds, old_id)) {
      bookmark.targets.adds = {new_id};
      bookmark.targets.removes.clear();
    }
  }
}

void set_bookmark_target(View &view, std::string_view name, const Id &id) {
  if (auto index = find_bookmark(view, name)) {
    view.bookmarks[*index].targets.adds = {id};
    view.bookmarks[*index].targets.removes.clear();
    return;
  }
  Bookmark bookmark;
  bookmark.name = std::string(name);
  bookmark.targets.adds = {id};
  view.bookmarks.push_back(std::move(bookmark));
}

std::optional<std::size_t> find_bookmark(const View &view,
                                         std::string_view name) {
  for (std::size_t i = 0; i < view.bookmarks.size(); ++i) {
    if (view.bookmarks[i].name == name)
      return i;
  }
  return std::nullopt;
}

std::optional<std::size_t> find_tag(const View &view, std::string_view name) {
  for (std::size_t i = 0; i < view.tags.size(); ++i) {
    if (view.tags[i].name == name)
      return i;
  }
  return std::nullopt;
}

std::vector<std::string> bookmark_names(const View &view, const Id &id) {
  std::vector<std::string> out;
  for (const auto &bookmark : view.bookmarks) {
    if (target_contains(bookmark.targets.adds, id))
      out.push_back(bookmark.name);
  }
  return out;
}

std::vector<std::string> tag_names(const View &view, const Id &id) {
  std::vector<std::string> out;
  for (const auto &tag : view.tags) {
    if (id_equal(tag.target, id))
      out.push_back(tag.name);
  }
  return out;
}

View empty_view() { return {}; }

std::vector<Id> read_heads(const fs::path &root) {
  std::vector<Id> out;
  for (const auto &name : list_directory(op_heads_dir(root))) {
    if (name.size() != 64)
      continue;
    Id id{};
    if (!hex_decode(name, MutBytes(id.data(), id.size())))
      continue;
    out.push_back(id);
  }
  sort_ids(out);
  return out;
}

bool write_head(const fs::path &root, const Id &id) {
  const std::string name = hex_encode(id);
  const fs::path final_path = op_heads_dir(root) / name;
  const fs::path tmp_path = tmp_dir(root) / (name + ".tmp");
  return write_atomic(tmp_path, final_path, Bytes{});
}

bool delete_head(const fs::path &root, const Id &id) {
  return remove_file(op_heads_dir(root) / hex_encode(id));
}

std::optional<View> current_view(const fs::path &root, Store &store) {
  const auto heads = read_heads(root);
  if (heads.empty())
    return std::nullopt;
  auto op = store.read_operation(heads.front());
  if (!op)
    return std::nullopt;
  return store.read_view(op->view);
}

static std::optional<View> load_view_for_head(Store &store, const Id &id) {
  auto op = store.read_operation(id);
  if (!op)
    return std::nullopt;
  return store.read_view(op->view);
}

static void merge_view_into(View &dst, const View &src) {
  for (const auto &head : src.heads)
    add_unique_head(dst, head);
  for (const auto &bookmark : src.bookmarks) {
    const auto found = find_bookmark(dst, bookmark.name);
    if (!found) {
      dst.bookmarks.push_back(bookmark);
      continue;
    }
    auto &existing = dst.bookmarks[*found];
    std::optional<Id> a = existing.targets.adds.empty()
                              ? std::optional<Id>{}
                              : existing.targets.adds.front();
    std::optional<Id> b = bookmark.targets.adds.empty()
                              ? std::optional<Id>{}
                              : bookmark.targets.adds.front();
    const bool same =
        a.has_value() == b.has_value() && (!a || id_equal(*a, *b));
    if (!same || existing.targets.adds.size() != bookmark.targets.adds.size()) {
      existing.targets.adds = {a, b};
      existing.targets.removes = {std::nullopt};
    }
  }
  for (const auto &tag : src.tags) {
    if (!find_tag(dst, tag.name))
      dst.tags.push_back(tag);
  }
  for (const auto &workspace : src.working_copies) {
    bool found = false;
    for (const auto &existing : dst.working_copies) {
      if (existing.workspace == workspace.workspace) {
        found = true;
        break;
      }
    }
    if (!found)
      dst.working_copies.push_back(workspace);
  }
}

// ---------------------------------------------------------------------------
// Transactions
// ---------------------------------------------------------------------------

Result<Txn> Txn::begin(const fs::path &root, Store &store) {
  Txn tx;
  tx.root_ = root;
  tx.store_ = &store;
  const auto heads = read_heads(root);
  if (heads.empty()) {
    tx.view_ = empty_view();
  } else if (heads.size() == 1) {
    auto view = load_view_for_head(store, heads.front());
    if (!view)
      return fail_io("cannot load repository state");
    tx.view_ = std::move(*view);
  } else {
    auto base = load_view_for_head(store, heads.front());
    if (!base)
      return fail_io("cannot load repository state");
    for (std::size_t i = 1; i < heads.size(); ++i) {
      auto extra = load_view_for_head(store, heads[i]);
      if (extra)
        merge_view_into(*base, *extra);
    }
    add_unique_head(*base, heads.front());
    tx.view_ = std::move(*base);
  }
  std::stable_sort(tx.view_.bookmarks.begin(), tx.view_.bookmarks.end(),
                   [](const Bookmark &a, const Bookmark &b) {
                     return compare(bytes_of(a.name), bytes_of(b.name)) < 0;
                   });
  std::stable_sort(tx.view_.tags.begin(), tx.view_.tags.end(),
                   [](const TagRef &a, const TagRef &b) {
                     return compare(bytes_of(a.name), bytes_of(b.name)) < 0;
                   });
  std::stable_sort(
      tx.view_.working_copies.begin(), tx.view_.working_copies.end(),
      [](const WorkspaceRef &a, const WorkspaceRef &b) {
        return compare(bytes_of(a.workspace), bytes_of(b.workspace)) < 0;
      });
  tx.parents_ = heads;
  tx.start_ms_ = unix_now_millis();
  return Result<Txn>(std::move(tx));
}

static std::string host_name() {
  if (const char *v = std::getenv("HOSTNAME"); v && *v)
    return v;
  return "localhost";
}

static std::string user_name() {
  if (const char *v = std::getenv("USER"); v && *v)
    return v;
#if defined(_WIN32)
  if (const char *w = std::getenv("USERNAME"); w && *w)
    return w;
#endif
  return "unknown";
}

Status Txn::finish(std::string_view description) {
  sort_view(view_);
  const auto view_body = encode_view(view_);
  const Id view_id = writer_.add(TYPE_VIEW, view_body);
  const std::int64_t now = unix_now_millis();

  Operation op;
  op.parents = parents_;
  op.view = view_id;
  op.start = Reader::TimeMs{start_ms_, 0};
  op.end = Reader::TimeMs{now, 0};
  op.hostname = host_name();
  op.username = user_name();
  op.description = std::string(description);
  op.tags.push_back(KeyValue{"command", std::string(description)});
  const auto op_body = encode_operation(op);
  const Id op_id = writer_.add(TYPE_OPERATION, op_body);

  if (writer_.finish(root_) != 0) {
    error_prefix();
    std::cout << "failed to write object pack\n";
    return fail_io("failed to write object pack");
  }
  if (!write_head(root_, op_id))
    return fail_io("failed to write operation head");
  for (const auto &parent : parents_)
    (void)delete_head(root_, parent);
  return {};
}

// ---------------------------------------------------------------------------
// Native commit map
// ---------------------------------------------------------------------------

static fs::path native_path(const fs::path &root) {
  return git_map_dir(root) / "native";
}

bool mark_native(const fs::path &root, const Id &id) {
  const std::string line = hex_encode(id) + "\n";
  return append_file(native_path(root), bytes_of(line));
}

std::vector<Id> load_native(const fs::path &root) {
  std::vector<Id> out;
  auto data = read_file_opt(native_path(root));
  if (!data)
    return out;
  std::string_view text(reinterpret_cast<const char *>(data->data()),
                        data->size());
  std::size_t start = 0;
  while (start <= text.size()) {
    std::size_t end = text.find('\n', start);
    if (end == std::string_view::npos)
      end = text.size();
    if (end - start >= 64) {
      Id id{};
      if (hex_decode(text.substr(start, 64), MutBytes(id.data(), id.size())))
        out.push_back(id);
    }
    if (end == text.size())
      break;
    start = end + 1;
  }
  return out;
}

bool is_native(const std::vector<Id> &native, const Id &id) {
  return contains_id(native, id);
}

// ---------------------------------------------------------------------------
// Graph
// ---------------------------------------------------------------------------

std::optional<LoadedCommit> load_commit(Store &store, const Id &id) {
  auto body = store.read_body(id, TYPE_COMMIT);
  if (!body)
    return std::nullopt;
  auto commit = decode_commit(bytes_of(*body));
  if (!commit)
    return std::nullopt;
  return LoadedCommit{std::move(*commit), std::move(*body)};
}

bool has_changes(Store &store, const LoadedCommit &loaded) {
  if (!loaded.commit.parents.empty()) {
    auto parent = load_commit(store, loaded.commit.parents.front());
    if (!parent)
      return true;
    return !id_equal(parent->commit.root_tree, loaded.commit.root_tree);
  }
  const auto entries = flatten_tree(store, loaded.commit.root_tree);
  return !entries.empty();
}

std::vector<Id> collect_commits(Store &store, std::span<const Id> start) {
  std::vector<Id> out;
  std::vector<Id> stack;
  std::unordered_set<Id, IdHash, IdEq> seen;
  for (const auto &id : start) {
    if (seen.insert(id).second)
      stack.push_back(id);
  }
  while (!stack.empty()) {
    const Id id = stack.back();
    stack.pop_back();
    out.push_back(id);
    auto loaded = load_commit(store, id);
    if (!loaded)
      continue;
    for (const auto &parent : loaded->commit.parents) {
      if (seen.insert(parent).second)
        stack.push_back(parent);
    }
  }
  return out;
}

std::vector<Id> view_roots(const View &view) {
  std::vector<Id> out;
  auto add = [&](const Id &id) {
    if (!contains_id(out, id))
      out.push_back(id);
  };
  for (const auto &head : view.heads)
    add(head);
  for (const auto &bookmark : view.bookmarks) {
    for (const auto &id : bookmark.targets.adds) {
      if (id)
        add(*id);
    }
  }
  for (const auto &tag : view.tags)
    add(tag.target);
  for (const auto &workspace : view.working_copies)
    add(workspace.target);
  return out;
}

std::vector<Id> all_commits(Store &store, const View &view) {
  const auto roots = view_roots(view);
  return collect_commits(store, roots);
}

static std::optional<Id> bookmark_target(const View &view,
                                         std::string_view name) {
  for (const auto &bookmark : view.bookmarks) {
    if (bookmark.name == name) {
      if (bookmark.targets.adds.size() == 1 && bookmark.targets.adds.front())
        return bookmark.targets.adds.front();
      return std::nullopt;
    }
  }
  return std::nullopt;
}

static std::optional<Id> tag_target(const View &view, std::string_view name) {
  for (const auto &tag : view.tags) {
    if (tag.name == name)
      return tag.target;
  }
  return std::nullopt;
}

static std::optional<Id> remote_target(const View &view,
                                       std::string_view text) {
  for (const auto &ref : view.remote_refs) {
    const std::string joined = ref.remote + "/" + ref.name;
    if (joined == text)
      return ref.target;
  }
  return std::nullopt;
}

static bool is_hex_char(char c) {
  return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') ||
         (c >= 'A' && c <= 'F');
}

static bool is_hex_prefix(std::string_view text) {
  if (text.size() < 4 || text.size() > 64)
    return false;
  for (char c : text) {
    if (!is_hex_char(c))
      return false;
  }
  return true;
}

std::optional<Id> resolve_revision(Store &store, const View &view,
                                   std::string_view rev) {
  if (rev.empty() || rev == "@")
    return working_copy_id(view);
  if (auto id = bookmark_target(view, rev))
    return id;
  if (auto id = tag_target(view, rev))
    return id;
  if (auto id = remote_target(view, rev))
    return id;

  const auto ids = all_commits(store, view);
  std::vector<Id> matches;
  if (is_hex_prefix(rev)) {
    for (const auto &id : ids) {
      const std::string full = hex_encode(id);
      if (base32_prefix_matches(full, rev))
        matches.push_back(id);
    }
  }
  if (matches.empty()) {
    for (const auto &id : ids) {
      auto loaded = load_commit(store, id);
      if (!loaded)
        continue;
      const std::string encoded = base32_encode(loaded->commit.change_id);
      if (base32_prefix_matches(encoded, rev))
        matches.push_back(id);
    }
  }
  if (matches.size() == 1)
    return matches.front();
  return std::nullopt;
}

// ---------------------------------------------------------------------------
// Tree walking
// ---------------------------------------------------------------------------

static void join_path(std::string &prefix, std::string_view name) {
  if (!prefix.empty())
    prefix.push_back('/');
  prefix.append(name);
}

static bool flatten_into(Store &store, const Id &tree_id, std::string &prefix,
                         std::vector<FlatEntry> &out, std::size_t depth) {
  if (depth > 4096)
    return false;
  auto body = store.read_body(tree_id, TYPE_TREE);
  if (!body)
    return false;
  auto tree = decode_tree(bytes_of(*body));
  if (!tree)
    return false;
  for (const auto &entry : tree->entries) {
    const std::size_t old_size = prefix.size();
    join_path(prefix, entry.name);
    if (entry.kind == KIND_SUBTREE) {
      if (!flatten_into(store, entry.target, prefix, out, depth + 1)) {
        prefix.resize(old_size);
        return false;
      }
      prefix.resize(old_size);
    } else {
      out.push_back(FlatEntry{prefix, entry.kind, entry.target});
      prefix.resize(old_size);
    }
  }
  return true;
}

std::vector<FlatEntry> flatten_tree(Store &store, const Id &tree_id) {
  std::vector<FlatEntry> out;
  std::string prefix;
  (void)flatten_into(store, tree_id, prefix, out, 0);
  std::stable_sort(out.begin(), out.end(),
                   [](const FlatEntry &a, const FlatEntry &b) {
                     return compare(bytes_of(a.path), bytes_of(b.path)) < 0;
                   });
  return out;
}

Result<std::vector<FlatEntry>> flatten_tree_checked(Store &store,
                                                    const Id &tree_id) {
  std::vector<FlatEntry> out;
  std::string prefix;
  if (!flatten_into(store, tree_id, prefix, out, 0))
    return fail(ErrorKind::Corrupt, 0);
  std::stable_sort(out.begin(), out.end(),
                   [](const FlatEntry &a, const FlatEntry &b) {
                     return compare(bytes_of(a.path), bytes_of(b.path)) < 0;
                   });
  return Result<std::vector<FlatEntry>>(std::move(out));
}

std::vector<FlatEntry> flatten_or_empty(Store &store,
                                        std::optional<Id> tree_id) {
  if (!tree_id)
    return {};
  return flatten_tree(store, *tree_id);
}

const FlatEntry *find_flat(const std::vector<FlatEntry> &entries,
                           std::string_view path) {
  std::size_t lo = 0;
  std::size_t hi = entries.size();
  while (lo < hi) {
    const std::size_t mid = lo + (hi - lo) / 2;
    const int c = compare(bytes_of(entries[mid].path), bytes_of(path));
    if (c == 0)
      return &entries[mid];
    if (c < 0)
      lo = mid + 1;
    else
      hi = mid;
  }
  return nullptr;
}

int find_tree_name(const Tree &tree, std::string_view name) {
  std::size_t lo = 0;
  std::size_t hi = tree.entries.size();
  while (lo < hi) {
    const std::size_t mid = lo + (hi - lo) / 2;
    const int c = compare(bytes_of(tree.entries[mid].name), bytes_of(name));
    if (c == 0)
      return static_cast<int>(mid);
    if (c < 0)
      lo = mid + 1;
    else
      hi = mid;
  }
  return -1;
}

static bool conflicted_into(Store &store, const Id &tree_id,
                            std::size_t depth) {
  if (depth > 4096)
    return true;
  auto body = store.read_body(tree_id, TYPE_TREE);
  if (!body)
    return true;
  auto tree = decode_tree(bytes_of(*body));
  if (!tree)
    return true;
  for (const auto &entry : tree->entries) {
    if (entry.kind == KIND_CONFLICT)
      return true;
    if (entry.kind == KIND_SUBTREE &&
        conflicted_into(store, entry.target, depth + 1))
      return true;
  }
  return false;
}

bool tree_conflicted(Store &store, const Id &tree_id) {
  return conflicted_into(store, tree_id, 0);
}

std::vector<TreeChange> compare_trees(Store &store, std::optional<Id> old_tree,
                                      std::optional<Id> new_tree) {
  const auto old_entries = flatten_or_empty(store, old_tree);
  const auto new_entries = flatten_or_empty(store, new_tree);
  std::vector<TreeChange> out;
  std::size_t i = 0;
  std::size_t j = 0;
  while (i < old_entries.size() || j < new_entries.size()) {
    int take = 0;
    if (i >= old_entries.size())
      take = 1;
    else if (j >= new_entries.size())
      take = -1;
    else
      take =
          compare(bytes_of(old_entries[i].path), bytes_of(new_entries[j].path));
    if (take < 0) {
      out.push_back(TreeChange{old_entries[i].path, old_entries[i].kind,
                               KIND_MISSING, old_entries[i].target,
                               std::nullopt});
      ++i;
    } else if (take > 0) {
      out.push_back(TreeChange{new_entries[j].path, KIND_MISSING,
                               new_entries[j].kind, std::nullopt,
                               new_entries[j].target});
      ++j;
    } else {
      const auto &o = old_entries[i];
      const auto &n = new_entries[j];
      const bool same = o.kind == n.kind && id_equal(o.target, n.target);
      if (!same)
        out.push_back(TreeChange{o.path, o.kind, n.kind, o.target, n.target});
      ++i;
      ++j;
    }
  }
  return out;
}

// ---------------------------------------------------------------------------
// Blob content
// ---------------------------------------------------------------------------

static bool append_blob_data(Store &store, const Id &id,
                             std::vector<std::uint8_t> &out,
                             std::size_t depth) {
  if (depth > 64)
    return false;
  if (is_lazy_blob(id)) {
    auto data = git_read_lazy_blob(store.root(), id);
    if (!data)
      return false;
    out.insert(out.end(), data->begin(), data->end());
    return true;
  }
  auto body = store.read_body(id, TYPE_BLOB);
  if (!body)
    return false;
  auto blob = decode_blob(bytes_of(*body));
  if (!blob)
    return false;
  if (blob->form == BlobForm::Inline) {
    out.insert(out.end(), blob->data.begin(), blob->data.end());
    return true;
  }
  if (blob->form == BlobForm::Leaf) {
    for (const auto &entry : blob->entries) {
      auto chunk = store.read_body(entry.id, TYPE_CHUNK);
      if (!chunk)
        return false;
      out.insert(out.end(), chunk->begin(), chunk->end());
    }
    return true;
  }
  for (const auto &entry : blob->entries) {
    if (!append_blob_data(store, entry.id, out, depth + 1))
      return false;
  }
  return true;
}

std::optional<std::vector<std::uint8_t>> read_blob(Store &store, const Id &id) {
  std::vector<std::uint8_t> out;
  if (!append_blob_data(store, id, out, 0))
    return std::nullopt;
  return out;
}

// ---------------------------------------------------------------------------
// fsck
// ---------------------------------------------------------------------------

namespace {

struct FsckCtx {
  fs::path root;
  bool promisor = false;
  bool verbose = false;
  std::size_t errors = 0;
  std::size_t warnings = 0;
};

void fsck_report(FsckCtx &ctx, const fs::path &path, std::string_view text) {
  ++ctx.errors;
  error_prefix();
  std::cout << "fsck: " << path_display(path) << ": " << text << "\n";
}

void fsck_report_id(FsckCtx &ctx, const fs::path &path, std::string_view text,
                    const Id &id) {
  ++ctx.errors;
  error_prefix();
  std::cout << "fsck: " << path_display(path) << ": " << text << " "
            << hex_encode(id) << "\n";
}

void fsck_warn(FsckCtx &ctx, const fs::path &path, std::string_view text) {
  ++ctx.warnings;
  if (ctx.verbose) {
    warning_prefix();
    std::cout << "fsck: " << path_display(path) << ": " << text << "\n";
  }
}

void fsck_report_decode(FsckCtx &ctx, const fs::path &path,
                        std::string_view what, const Error &error) {
  ++ctx.errors;
  error_prefix();
  std::cout << "fsck: " << path_display(path) << ": invalid " << what
            << " at byte " << error.offset << ": "
            << error_kind_name(error.kind) << "\n";
}

bool check_format(FsckCtx &ctx) {
  const fs::path path = format_path(ctx.root);
  auto data = read_file_opt(path);
  if (!data) {
    fsck_report(ctx, ctx.root, "missing .veins/format");
    return false;
  }
  const std::string_view expected = "veins-store 1";
  bool ok = equals(bytes_of(*data), bytes_of(expected));
  if (!ok && data->size() == expected.size() + 1) {
    ok = equals(bytes_of(*data).first(expected.size()), bytes_of(expected)) &&
         (*data)[expected.size()] == '\n';
  }
  if (!ok) {
    fsck_report(ctx, ctx.root, "unsupported .veins/format");
    return false;
  }
  return true;
}

std::uint8_t expected_type_for_value(std::uint8_t kind) {
  if (kind == 1 || kind == 2 || kind == 3)
    return TYPE_BLOB;
  if (kind == 4)
    return TYPE_TREE;
  if (kind == 6)
    return TYPE_CONFLICT;
  return 0;
}

bool check_ref(FsckCtx &ctx, Store &store, const fs::path &path, const Id &id,
               std::uint8_t expected, std::string_view what) {
  if (expected == TYPE_BLOB && is_lazy_blob(id))
    return true;
  const auto loc = store.find(id);
  if (!loc) {
    const bool promised =
        ctx.promisor && (expected == TYPE_CHUNK || expected == TYPE_BLOB);
    if (promised)
      fsck_warn(ctx, path, "missing promised object");
    if (!promised) {
      ++ctx.errors;
      error_prefix();
      std::cout << "fsck: " << path_display(path) << ": missing " << what
                << " object " << hex_encode(id) << "\n";
    }
    return promised;
  }
  if (loc->kind != expected) {
    ++ctx.errors;
    error_prefix();
    std::cout << "fsck: " << path_display(path) << ": object has type "
              << type_name(loc->kind) << ", expected " << type_name(expected)
              << " " << hex_encode(id) << "\n";
    return false;
  }
  return true;
}

void check_blob_refs(FsckCtx &ctx, Store &store, const fs::path &path,
                     const Blob &blob) {
  if (blob.form == BlobForm::Inline)
    return;
  const std::uint8_t expected =
      blob.form == BlobForm::Leaf ? TYPE_CHUNK : TYPE_BLOB;
  for (const auto &entry : blob.entries) {
    (void)check_ref(ctx, store, path, entry.id, expected, "blob");
  }
}

void check_tree_refs(FsckCtx &ctx, Store &store, const fs::path &path,
                     const Tree &tree) {
  for (const auto &entry : tree.entries) {
    std::uint8_t expected = 0;
    if (entry.kind == KIND_FILE || entry.kind == KIND_EXECUTABLE ||
        entry.kind == KIND_SYMLINK)
      expected = TYPE_BLOB;
    else if (entry.kind == KIND_SUBTREE)
      expected = TYPE_TREE;
    else if (entry.kind == KIND_CONFLICT)
      expected = TYPE_CONFLICT;
    if (expected != 0)
      (void)check_ref(ctx, store, path, entry.target, expected, "tree");
  }
}

void check_conflict_refs(FsckCtx &ctx, Store &store, const fs::path &path,
                         const Conflict &conflict) {
  for (const auto &value : conflict.adds) {
    const std::uint8_t expected = expected_type_for_value(value.kind);
    if (expected != 0 && value.target)
      (void)check_ref(ctx, store, path, *value.target, expected, "conflict");
  }
  for (const auto &value : conflict.removes) {
    const std::uint8_t expected = expected_type_for_value(value.kind);
    if (expected != 0 && value.target)
      (void)check_ref(ctx, store, path, *value.target, expected, "conflict");
  }
}

void check_commit_refs(FsckCtx &ctx, Store &store, const fs::path &path,
                       const Commit &commit) {
  for (const auto &parent : commit.parents)
    (void)check_ref(ctx, store, path, parent, TYPE_COMMIT, "parent commit");
  (void)check_ref(ctx, store, path, commit.root_tree, TYPE_TREE, "root tree");
}

void check_operation_refs(FsckCtx &ctx, Store &store, const fs::path &path,
                          const Operation &op) {
  for (const auto &parent : op.parents)
    (void)check_ref(ctx, store, path, parent, TYPE_OPERATION,
                    "parent operation");
  (void)check_ref(ctx, store, path, op.view, TYPE_VIEW, "view");
}

void check_view_refs(FsckCtx &ctx, Store &store, const fs::path &path,
                     const View &view) {
  for (const auto &head : view.heads)
    (void)check_ref(ctx, store, path, head, TYPE_COMMIT, "head commit");
  for (const auto &bookmark : view.bookmarks) {
    for (const auto &id : bookmark.targets.adds) {
      if (id)
        (void)check_ref(ctx, store, path, *id, TYPE_COMMIT, "bookmark");
    }
    for (const auto &id : bookmark.targets.removes) {
      if (id)
        (void)check_ref(ctx, store, path, *id, TYPE_COMMIT, "bookmark");
    }
  }
  for (const auto &tag : view.tags)
    (void)check_ref(ctx, store, path, tag.target, TYPE_COMMIT, "tag");
  for (const auto &ref : view.remote_refs)
    (void)check_ref(ctx, store, path, ref.target, TYPE_COMMIT, "remote ref");
  for (const auto &workspace : view.working_copies)
    (void)check_ref(ctx, store, path, workspace.target, TYPE_COMMIT,
                    "working copy");
}

void check_object(FsckCtx &ctx, Store &store, const fs::path &path,
                  const Id &id, std::uint8_t kind, Bytes body) {
  const Id computed = object_id(kind, body);
  if (!id_equal(computed, id)) {
    fsck_report_id(ctx, path, "hash mismatch for", id);
    return;
  }
  switch (kind) {
  case TYPE_CHUNK:
    if (body.empty() || body.size() > MAX_CHUNK_LEN)
      fsck_report_id(ctx, path, "invalid chunk length for", id);
    return;
  case TYPE_BLOB: {
    auto blob = decode_blob(body);
    if (!blob) {
      fsck_report_decode(ctx, path, "blob", blob.error());
      return;
    }
    check_blob_refs(ctx, store, path, *blob);
    return;
  }
  case TYPE_TREE: {
    auto tree = decode_tree(body);
    if (!tree) {
      fsck_report_decode(ctx, path, "tree", tree.error());
      return;
    }
    check_tree_refs(ctx, store, path, *tree);
    return;
  }
  case TYPE_CONFLICT: {
    auto conflict = decode_conflict(body);
    if (!conflict) {
      fsck_report_decode(ctx, path, "conflict", conflict.error());
      return;
    }
    check_conflict_refs(ctx, store, path, *conflict);
    return;
  }
  case TYPE_COMMIT: {
    auto commit = decode_commit(body);
    if (!commit) {
      fsck_report_decode(ctx, path, "commit", commit.error());
      return;
    }
    check_commit_refs(ctx, store, path, *commit);
    return;
  }
  case TYPE_OPERATION: {
    auto op = decode_operation(body);
    if (!op) {
      fsck_report_decode(ctx, path, "operation", op.error());
      return;
    }
    check_operation_refs(ctx, store, path, *op);
    return;
  }
  case TYPE_VIEW: {
    auto view = decode_view(body);
    if (!view) {
      fsck_report_decode(ctx, path, "view", view.error());
      return;
    }
    check_view_refs(ctx, store, path, *view);
    return;
  }
  default:
    return;
  }
}

} // namespace

static void check_op_log(FsckCtx &ctx, Store &store) {
  const fs::path dir = op_heads_dir(ctx.root);
  if (!path_is_dir(dir)) {
    fsck_report(ctx, dir, "missing op-heads directory");
    return;
  }
  std::vector<Id> frontier;
  for (const auto &name : list_directory(dir)) {
    if (name.size() != 64) {
      fsck_report(ctx, dir, "op-heads entry is not a 64-character id");
      continue;
    }
    Id id{};
    if (!hex_decode(name, MutBytes(id.data(), id.size()))) {
      fsck_report(ctx, dir, "op-heads entry is not hexadecimal");
      continue;
    }
    frontier.push_back(id);
  }
  std::unordered_set<Id, IdHash, IdEq> seen;
  while (!frontier.empty()) {
    const Id id = frontier.back();
    frontier.pop_back();
    if (!seen.insert(id).second)
      continue;
    const auto loc = store.find(id);
    if (!loc) {
      fsck_report_id(ctx, dir, "operation head or parent is missing:", id);
      continue;
    }
    if (loc->kind != TYPE_OPERATION) {
      fsck_report_id(ctx, dir, "op-log entry is not an operation:", id);
      continue;
    }
    auto body = store.get(*loc);
    if (!body) {
      fsck_report_decode(ctx, dir, "operation", body.error());
      continue;
    }
    auto op = decode_operation(bytes_of(*body));
    if (!op) {
      fsck_report_decode(ctx, dir, "operation", op.error());
      continue;
    }
    for (const auto &parent : op->parents)
      frontier.push_back(parent);
    (void)check_ref(ctx, store, dir, op->view, TYPE_VIEW, "operation view");
  }
}

int fsck_repository(const fs::path &root, bool verbose) {
  FsckCtx ctx;
  ctx.root = root;
  ctx.verbose = verbose;
  std::vector<StoreHandle> handles;
  if (check_format(ctx)) {
    auto cfg = read_file_opt(config_path(root));
    if (cfg) {
      const std::string_view text(reinterpret_cast<const char *>(cfg->data()),
                                  cfg->size());
      ctx.promisor = text.find("promisor") != std::string_view::npos;
    }
    const fs::path dir = packs_dir(root);
    if (!path_is_dir(dir)) {
      fsck_report(ctx, dir, "missing store/packs directory");
    } else {
      const auto names = list_directory(dir);
      for (const auto &name : names) {
        if (name.size() > 5 && name.compare(name.size() - 5, 5, ".vidx") == 0) {
          std::string pack_name = name.substr(0, name.size() - 5) + ".vpack";
          const fs::path ppath = dir / path_from_bytes(pack_name);
          if (!path_is_file(ppath))
            fsck_report(ctx, ppath, "index has no pack");
        }
      }
      for (const auto &name : names) {
        if (name.size() <= 6 || name.compare(name.size() - 6, 6, ".vpack") != 0)
          continue;
        const fs::path ppath = dir / path_from_bytes(name);
        auto pdata = read_file_opt(ppath);
        if (!pdata) {
          fsck_report(ctx, ppath, "cannot read pack");
          continue;
        }
        auto pack = decode_pack(std::move(*pdata));
        if (!pack) {
          fsck_report_decode(ctx, ppath, "pack", pack.error());
          continue;
        }
        std::string base = name.substr(0, name.size() - 6);
        const fs::path ipath = dir / path_from_bytes(base + ".vidx");
        auto idata = read_file_opt(ipath);
        if (!idata) {
          fsck_report(ctx, ppath, "pack has no index");
          continue;
        }
        auto index = decode_index(std::move(*idata), pack->trailer);
        if (!index) {
          fsck_report_decode(ctx, ipath, "index", index.error());
          continue;
        }
        bool eligible = true;
        if (index->ids.size() != pack->records.size()) {
          fsck_report(ctx, ppath, "pack and index object counts differ");
          eligible = false;
        }
        if (eligible) {
          std::vector<bool> visited(pack->records.size(), false);
          for (std::size_t j = 0; j < index->ids.size(); ++j) {
            const auto rec = pack->find_by_offset(index->offsets[j]);
            if (!rec) {
              fsck_report_id(ctx, ppath, "index offset names no record for",
                             index->ids[j]);
              eligible = false;
              continue;
            }
            if (!id_equal(pack->records[*rec].id, index->ids[j])) {
              fsck_report_id(ctx, ppath, "index id does not match record for",
                             index->ids[j]);
              eligible = false;
            }
            if (visited[*rec]) {
              fsck_report_id(ctx, ppath, "record indexed more than once",
                             index->ids[j]);
              eligible = false;
            }
            visited[*rec] = true;
          }
          for (std::size_t k = 0; k < pack->records.size(); ++k) {
            if (!visited[k]) {
              fsck_report_id(ctx, ppath, "record is not indexed",
                             pack->records[k].id);
              eligible = false;
            }
          }
        }
        if (!eligible)
          continue;
        StoreHandle handle;
        handle.path = ppath;
        handle.index = std::move(*index);
        handle.pack = std::move(*pack);
        handles.push_back(std::move(handle));
      }
    }

    Store store;
    store.handles() = std::move(handles);
    for (auto &handle : store.handles()) {
      if (!handle.pack)
        continue;
      for (std::size_t j = 0; j < handle.pack->records.size(); ++j) {
        const auto &rec = handle.pack->records[j];
        auto body = handle.pack->get(j);
        if (!body) {
          fsck_report_decode(ctx, handle.path, "record", body.error());
          continue;
        }
        check_object(ctx, store, handle.path, rec.id, rec.type,
                     bytes_of(*body));
      }
    }
    check_op_log(ctx, store);
  }

  if (ctx.warnings > 0 && ctx.verbose) {
    warning_prefix();
    std::cout << ctx.warnings << " warning(s)\n";
  }
  if (ctx.errors == 0) {
    info_prefix();
    std::cout << "fsck: clean\n";
    return 0;
  }
  error_prefix();
  std::cout << ctx.errors << " error(s)\n";
  return 1;
}

} // namespace vn
