#include "pathspec.h"

#include <vector>

namespace vn {

namespace {

// Collapse "." and ".." components and drop empty components.
std::optional<std::string> normalize_components(std::string_view input) {
  std::vector<std::string_view> comps;
  std::size_t start = 0;
  for (std::size_t i = 0; i <= input.size(); ++i) {
    const bool at_end = i == input.size();
    if (!at_end && input[i] != '/')
      continue;
    const std::string_view comp = input.substr(start, i - start);
    if (!comp.empty() && comp != ".") {
      if (comp == "..") {
        if (comps.empty())
          return std::nullopt;
        comps.pop_back();
      } else {
        comps.push_back(comp);
      }
    }
    start = i + 1;
  }
  std::string out;
  for (std::size_t i = 0; i < comps.size(); ++i) {
    if (i != 0)
      out.push_back('/');
    out.append(comps[i]);
  }
  return out;
}

std::string join_relative(std::string_view base, std::string_view arg) {
  if (base.empty())
    return std::string(arg);
  if (arg.empty())
    return std::string(base);
  std::string out(base);
  out.push_back('/');
  out.append(arg);
  return out;
}

} // namespace

std::optional<std::string> cwd_relative(const fs::path &root) {
  std::error_code ec;
  fs::path cwd = fs::current_path(ec);
  if (ec)
    return std::nullopt;
  cwd = fs::weakly_canonical(cwd, ec);
  if (ec)
    return std::nullopt;
  const std::string canon = path_to_bytes(cwd);
  const std::string root_bytes = path_to_bytes(root);
  if (canon == root_bytes)
    return std::string();
  if (canon.size() > root_bytes.size() &&
      canon.compare(0, root_bytes.size(), root_bytes) == 0 &&
      canon[root_bytes.size()] == '/')
    return canon.substr(root_bytes.size() + 1);
  return std::nullopt;
}

std::optional<std::string> pathspec_normalize(const fs::path &root,
                                              std::string_view cwd_rel,
                                              std::string_view arg) {
  if (arg.empty())
    return std::nullopt;
  if (arg.front() == '/') {
    auto norm = normalize_components(arg);
    if (!norm)
      return std::nullopt;
    std::string root_view = path_to_bytes(root);
    if (!root_view.empty() && root_view.front() == '/')
      root_view.erase(0, 1);
    if (norm->size() > root_view.size() &&
        norm->compare(0, root_view.size(), root_view) == 0 &&
        (*norm)[root_view.size()] == '/')
      return norm->substr(root_view.size() + 1);
    return std::nullopt;
  }
  return normalize_components(join_relative(cwd_rel, arg));
}

bool pathspec_has_glob(std::string_view value) {
  return value.find('*') != std::string_view::npos ||
         value.find('?') != std::string_view::npos;
}

} // namespace vn
