#include "auth.h"

#include "store.h"

#include <algorithm>
#include <cstdlib>
#include <cstring>

#if defined(_WIN32)
#include <io.h>
#else
#include <sys/stat.h>
#include <unistd.h>
#endif

namespace vn::auth {

namespace {

std::optional<std::string> env_value(const char *name) {
  const char *value = std::getenv(name);
  if (!value || !*value)
    return std::nullopt;
  return std::string(value);
}

std::string lower_ascii(std::string_view text) {
  std::string out(text);
  for (char &c : out) {
    if (c >= 'A' && c <= 'Z')
      c = static_cast<char>(c + 32);
  }
  return out;
}

std::string_view trim_view(std::string_view text) {
  std::size_t start = 0;
  std::size_t end = text.size();
  auto blank = [](char c) {
    return c == ' ' || c == '\t' || c == '\r' || c == '\n';
  };
  while (start < end && blank(text[start]))
    ++start;
  while (end > start && blank(text[end - 1]))
    --end;
  return text.substr(start, end - start);
}

int file_mode(const fs::path &path) {
#if defined(_WIN32)
  (void)path;
  return 0600;
#else
  struct stat info {};
  if (::stat(path.c_str(), &info) != 0)
    return -1;
  return static_cast<int>(info.st_mode & 07777);
#endif
}

bool set_mode(const fs::path &path, int mode) {
#if defined(_WIN32)
  (void)path;
  (void)mode;
  return true;
#else
  return ::chmod(path.c_str(), static_cast<mode_t>(mode)) == 0;
#endif
}

bool valid_key_name(std::string_view name) {
  if (name.empty() || name.size() > 128)
    return false;
  for (char c : name) {
    if (c == '/' || c == '\\' || c == '\0')
      return false;
  }
  return true;
}

std::string hex_encode(std::string_view data) {
  static constexpr char digits[] = "0123456789abcdef";
  std::string out;
  out.reserve(data.size() * 2);
  for (char raw : data) {
    const auto c = static_cast<unsigned char>(raw);
    out.push_back(digits[c >> 4]);
    out.push_back(digits[c & 15]);
  }
  return out;
}

std::optional<std::string> hex_decode(std::string_view text) {
  if (text.empty() || text.size() % 2 != 0)
    return std::nullopt;
  auto value = [](char c) -> int {
    if (c >= '0' && c <= '9')
      return c - '0';
    if (c >= 'a' && c <= 'f')
      return c - 'a' + 10;
    return -1;
  };
  std::string out;
  out.reserve(text.size() / 2);
  for (std::size_t i = 0; i < text.size(); i += 2) {
    const int high = value(text[i]);
    const int low = value(text[i + 1]);
    if (high < 0 || low < 0)
      return std::nullopt;
    out.push_back(static_cast<char>((high << 4) | low));
  }
  return out;
}

std::string_view strip_user(std::string_view authority) {
  const auto at = authority.rfind('@');
  if (at != std::string_view::npos)
    return authority.substr(at + 1);
  return authority;
}

std::optional<std::string> authority_of(std::string_view input) {
  std::size_t start = 0;
  const auto scheme = input.find("://");
  if (scheme != std::string_view::npos)
    start = scheme + 3;
  if (start >= input.size())
    return std::nullopt;
  const auto slash = input.find('/', start);
  const std::size_t end =
      slash == std::string_view::npos ? input.size() : slash;
  if (end <= start)
    return std::nullopt;
  const std::string_view raw = input.substr(start, end - start);
  const std::string_view host = strip_user(raw);
  if (host.empty())
    return std::nullopt;
  return lower_ascii(host);
}

std::optional<std::string> host_without_port(std::string_view host) {
  if (host.empty() || host.front() == '[')
    return std::nullopt;
  const auto colon = host.rfind(':');
  if (colon == std::string_view::npos || colon == 0)
    return std::nullopt;
  return std::string(host.substr(0, colon));
}

fs::path target_path(const fs::path &dir, std::string_view target) {
  return dir / hex_encode(target);
}

std::optional<std::string> read_credential(const fs::path &path) {
  auto data = read_file_opt(path);
  if (!data)
    return std::nullopt;
  const std::string_view text(reinterpret_cast<const char *>(data->data()),
                              data->size());
  const std::string_view value = trim_view(text);
  if (value.empty())
    return std::nullopt;
  return std::string(value);
}

std::optional<std::string> lookup_credential(const fs::path &dir,
                                             std::string_view target) {
  return read_credential(target_path(dir, target));
}

std::vector<std::string_view> tokenize(std::string_view line) {
  std::vector<std::string_view> out;
  std::size_t start = 0;
  for (std::size_t i = 0; i <= line.size(); ++i) {
    const bool at_end = i == line.size();
    if (at_end || line[i] == ' ' || line[i] == '\t') {
      if (i > start)
        out.push_back(line.substr(start, i - start));
      start = i + 1;
    }
  }
  return out;
}

Access invalid_access(std::int64_t line) {
  Access out;
  out.valid = false;
  out.error_line = line;
  return out;
}

} // namespace

// ---------------------------------------------------------------------------
// Client keys
// ---------------------------------------------------------------------------

fs::path key_dir() {
  if (auto xdg = env_value("XDG_CONFIG_HOME"))
    return path_from_bytes(*xdg) / "veins" / "keys";
  if (auto home = env_value("HOME"))
    return path_from_bytes(*home) / ".config" / "veins" / "keys";
#if defined(_WIN32)
  if (auto appdata = env_value("APPDATA"))
    return path_from_bytes(*appdata) / "veins" / "keys";
#endif
  return fs::path(".veins-keys");
}

fs::path key_path(std::string_view name) {
  return key_dir() / (std::string(name) + ".key");
}

std::optional<Key> load_key(std::string_view name) {
  if (!valid_key_name(name))
    return std::nullopt;
  const fs::path path = key_path(name);
  const int mode = file_mode(path);
  if (mode < 0 || (mode & 63) != 0)
    return std::nullopt;
  auto data = read_file_opt(path);
  if (!data || data->size() != 33 || (*data)[0] != 1)
    return std::nullopt;
  std::vector<std::uint8_t> seed(data->begin() + 1, data->end());
  auto public_key = ed25519_public_from_seed(Bytes(seed.data(), seed.size()));
  if (!public_key)
    return std::nullopt;
  Key key;
  key.name = std::string(name);
  key.seed = std::move(seed);
  key.public_key = *public_key;
  key.fingerprint = key_fingerprint(*public_key);
  return key;
}

std::optional<Key> generate_key(std::string_view name) {
  if (!valid_key_name(name))
    return std::nullopt;
  const fs::path dir = key_dir();
  if (!ensure_directory(dir))
    return std::nullopt;
  (void)set_mode(dir, 0700);
  const auto seed = secure_random(32);
  if (seed.size() != 32)
    return std::nullopt;
  auto public_key = ed25519_public_from_seed(Bytes(seed.data(), seed.size()));
  if (!public_key)
    return std::nullopt;
  std::vector<std::uint8_t> body;
  body.reserve(33);
  body.push_back(1);
  body.insert(body.end(), seed.begin(), seed.end());
  const fs::path path = key_path(name);
  if (!write_file(path, Bytes(body.data(), body.size())))
    return std::nullopt;
  (void)set_mode(path, 0600);
  Key key;
  key.name = std::string(name);
  key.seed = seed;
  key.public_key = *public_key;
  key.fingerprint = key_fingerprint(*public_key);
  return key;
}

std::vector<std::string> list_key_names() {
  std::vector<std::string> out;
  const fs::path dir = key_dir();
  if (!path_is_dir(dir))
    return out;
  for (const auto &name : list_directory(dir)) {
    if (name.size() > 4 && name.compare(name.size() - 4, 4, ".key") == 0)
      out.push_back(name.substr(0, name.size() - 4));
  }
  return out;
}

// ---------------------------------------------------------------------------
// Per-user key selection
// ---------------------------------------------------------------------------

fs::path auth_dir() {
  const fs::path dir = key_dir();
  const fs::path parent = dir.parent_path();
  if (parent.empty())
    return fs::path(".veins-auth");
  return parent / "auth";
}

std::string normalize_target(std::string_view input) {
  const std::string_view trimmed = trim_view(input);
  if (trimmed.empty() || trimmed == "default")
    return "default";
  if (auto authority = authority_of(trimmed))
    return *authority;
  const auto slash = trimmed.find('/');
  const std::string_view raw =
      slash == std::string_view::npos ? trimmed : trimmed.substr(0, slash);
  const std::string_view host = strip_user(raw);
  if (host.empty())
    return "default";
  return lower_ascii(host);
}

bool set_key(std::string_view target, std::string_view key_name) {
  if (target.empty() || key_name.empty())
    return false;
  const fs::path dir = auth_dir();
  if (!ensure_directory(dir))
    return false;
  return write_file(target_path(dir, target), bytes_of(key_name));
}

bool remove_key(std::string_view target) {
  return remove_file(target_path(auth_dir(), target));
}

std::vector<std::string> list_credential_lines() {
  std::vector<std::string> out;
  const fs::path dir = auth_dir();
  if (!path_is_dir(dir))
    return out;
  for (const auto &name : list_directory(dir)) {
    auto decoded = hex_decode(name);
    if (!decoded)
      continue;
    auto key = read_credential(target_path(dir, *decoded));
    if (!key)
      continue;
    out.push_back(*decoded + ": " + *key + "\n");
  }
  return out;
}

bool local_key_exists(std::string_view name) {
  if (name.empty() || name.starts_with("ed25519:"))
    return false;
  return load_key(name).has_value();
}

std::optional<std::string> key_for_url(std::string_view url) {
  const fs::path dir = auth_dir();
  if (auto host = authority_of(url)) {
    if (auto exact = lookup_credential(dir, *host))
      return exact;
    if (auto base = host_without_port(*host)) {
      if (auto without_port = lookup_credential(dir, *base))
        return without_port;
    }
  }
  return lookup_credential(dir, "default");
}

// ---------------------------------------------------------------------------
// Server access policy
// ---------------------------------------------------------------------------

Access empty_access() { return Access{}; }

fs::path access_path(const fs::path &repo_root) {
  return veins_dir(repo_root) / "access";
}

Access load_access(const fs::path &repo_root) {
  const fs::path path = access_path(repo_root);
  const int mode = file_mode(path);
  if (mode >= 0 && (mode & 18) != 0)
    return invalid_access(0);
  auto data = read_file_opt(path);
  if (!data)
    return empty_access();
  const std::string_view text(reinterpret_cast<const char *>(data->data()),
                              data->size());
  Access access;
  std::size_t start = 0;
  std::int64_t line_no = 0;
  std::size_t i = 0;
  for (;;) {
    const bool at_end = i >= text.size();
    if (at_end || text[i] == '\n') {
      ++line_no;
      const std::string_view line = trim_view(text.substr(start, i - start));
      if (!line.empty() && line.front() != '#') {
        const auto tokens = tokenize(line);
        bool bad = false;
        if (tokens.size() == 2 && tokens[0] == "anonymous") {
          if (tokens[1] == "read")
            access.anonymous_read = true;
          else
            bad = true;
        } else if (tokens.size() >= 3 && tokens[0] == "allow") {
          std::uint8_t role = 0;
          if (tokens[1] == "read")
            role = ROLE_READ;
          else if (tokens[1] == "write")
            role = ROLE_WRITE;
          else
            bad = true;
          auto public_key = parse_public_key(tokens[2]);
          if (!public_key)
            bad = true;
          if (!bad) {
            const bool duplicate =
                std::any_of(access.entries.begin(), access.entries.end(),
                            [&](const AccessEntry &entry) {
                              return std::memcmp(entry.public_key.data(),
                                                 public_key->data(),
                                                 public_key->size()) == 0;
                            });
            if (duplicate) {
              bad = true;
            } else {
              AccessEntry entry;
              entry.public_key = *public_key;
              entry.role = role;
              if (tokens.size() >= 4)
                entry.name = std::string(tokens[3]);
              access.entries.push_back(std::move(entry));
            }
          }
        } else {
          bad = true;
        }
        if (bad)
          return invalid_access(line_no);
      }
      start = i + 1;
    }
    if (at_end)
      break;
    ++i;
  }
  return access;
}

bool write_access(const fs::path &repo_root, const Access &access) {
  std::string body = "# veins access policy\n";
  if (access.anonymous_read)
    body += "anonymous read\n";
  for (const auto &entry : access.entries) {
    if (entry.name.size() > 64)
      return false;
    body += "allow ";
    body += entry.role == ROLE_WRITE ? "write" : "read";
    body += " ";
    body += format_public_key(entry.public_key);
    if (!entry.name.empty()) {
      body += " ";
      body += entry.name;
    }
    body += "\n";
  }
  const fs::path path = access_path(repo_root);
  if (!write_file(path, bytes_of(body)))
    return false;
  (void)set_mode(path, 0600);
  return true;
}

std::uint8_t role_for(const Access &access, const PublicKey *public_key) {
  if (!public_key) {
    if (access.anonymous_read)
      return ROLE_READ;
    return ROLE_ANONYMOUS;
  }
  for (const auto &entry : access.entries) {
    if (std::memcmp(entry.public_key.data(), public_key->data(),
                    public_key->size()) == 0) {
      return entry.role;
    }
  }
  return ROLE_UNKNOWN;
}

bool add_access(const fs::path &repo_root, std::uint8_t role,
                const PublicKey &public_key, std::string_view name) {
  Access access = load_access(repo_root);
  if (!access.valid)
    return false;
  for (const auto &entry : access.entries) {
    if (std::memcmp(entry.public_key.data(), public_key.data(),
                    public_key.size()) == 0)
      return false;
  }
  AccessEntry entry;
  entry.public_key = public_key;
  entry.role = role;
  entry.name = std::string(name);
  access.entries.push_back(std::move(entry));
  return write_access(repo_root, access);
}

bool remove_access(const fs::path &repo_root, std::string_view fingerprint,
                   std::string_view name) {
  Access access = load_access(repo_root);
  if (!access.valid)
    return false;
  bool removed = false;
  std::vector<AccessEntry> kept;
  kept.reserve(access.entries.size());
  for (const auto &entry : access.entries) {
    const bool match_fingerprint =
        !fingerprint.empty() &&
        key_fingerprint(entry.public_key) == fingerprint;
    const bool match_name = !name.empty() && entry.name == name;
    if (match_fingerprint || match_name) {
      removed = true;
    } else {
      kept.push_back(entry);
    }
  }
  access.entries = std::move(kept);
  return removed && write_access(repo_root, access);
}

bool set_anonymous(const fs::path &repo_root, bool enabled) {
  Access access = load_access(repo_root);
  if (!access.valid)
    return false;
  access.anonymous_read = enabled;
  return write_access(repo_root, access);
}

} // namespace vn::auth
