#include "passwords.h"
#include <cstdlib>
#include <fstream>
#include <pwd.h>
#include <sstream>
#include <sys/stat.h>
#include <unistd.h>

namespace {

std::string toLower(const std::string &s) {
  std::string out = s;
  for (auto &c : out) {
    if (c >= 'A' && c <= 'Z') {
      c += 'a' - 'A';
    }
  }
  return out;
}

// Split one CSV line into fields. Handles quoted fields and "" escapes.
std::vector<std::string> parseCsvLine(const std::string &line) {
  std::vector<std::string> fields;
  std::string field;
  bool in_quotes = false;
  for (size_t i = 0; i < line.size(); i++) {
    char c = line[i];
    if (in_quotes) {
      if (c == '"') {
        if (i + 1 < line.size() && line[i + 1] == '"') {
          field += '"';
          i++;
        } else {
          in_quotes = false;
        }
      } else {
        field += c;
      }
    } else if (c == '"') {
      in_quotes = true;
    } else if (c == ',') {
      fields.push_back(field);
      field.clear();
    } else {
      field += c;
    }
  }
  fields.push_back(field);
  return fields;
}

std::string csvEscape(const std::string &s) {
  std::string out = "\"";
  for (char c : s) {
    if (c == '"') {
      out += "\"\"";
    } else {
      out += c;
    }
  }
  out += '"';
  return out;
}

} // namespace

std::string UrlHost(const std::string &url) {
  size_t start = url.find("://");
  start = (start == std::string::npos) ? 0 : start + 3;
  // Skip user:pass@ if present
  size_t at = url.find('@', start);
  if (at != std::string::npos && at < url.find('/', start)) {
    start = at + 1;
  }
  size_t end = url.find('/', start);
  if (end == std::string::npos) {
    end = url.size();
  }
  size_t host_len = end - start;
  // Strip port
  size_t colon = url.rfind(':', start + host_len);
  if (colon != std::string::npos && colon > start) {
    host_len = colon - start;
  }
  return toLower(url.substr(start, host_len));
}

PasswordManager::PasswordManager() { load(); }

std::string PasswordManager::getPasswordsFilePath() const {
  const char *home = getenv("HOME");
  if (!home) {
    home = getpwuid(getuid())->pw_dir;
  }
  std::string config_dir = "/etc/peak";
  mkdir(config_dir.c_str(), 0755);
  return config_dir + "/passwords";
}

void PasswordManager::load() {
  entries_.clear();

  std::ifstream file(getPasswordsFilePath());
  if (!file.is_open()) {
    return;
  }

  std::string line;
  bool first = true;
  while (std::getline(file, line)) {
    if (!line.empty() && line.back() == '\r') {
      line.pop_back();
    }
    if (line.empty()) {
      continue;
    }
    if (first) {
      first = false;
      continue; // header row
    }
    std::vector<std::string> f = parseCsvLine(line);
    PasswordEntry e;
    e.url = f.size() > 0 ? f[0] : "";
    e.username = f.size() > 1 ? f[1] : "";
    e.password = f.size() > 2 ? f[2] : "";
    e.http_realm = f.size() > 3 ? f[3] : "";
    e.form_action_origin = f.size() > 4 ? f[4] : "";
    e.guid = f.size() > 5 ? f[5] : "";
    e.time_created = f.size() > 6 ? f[6] : "";
    e.time_last_used = f.size() > 7 ? f[7] : "";
    e.time_password_changed = f.size() > 8 ? f[8] : "";
    if (!e.url.empty()) {
      entries_.push_back(e);
    }
  }
}

void PasswordManager::save() {
  std::ofstream file(getPasswordsFilePath());
  if (!file.is_open()) {
    return;
  }

  file << "\"url\",\"username\",\"password\",\"httpRealm\","
          "\"formActionOrigin\",\"guid\",\"timeCreated\",\"timeLastUsed\","
          "\"timePasswordChanged\"\n";
  for (const auto &e : entries_) {
    file << csvEscape(e.url) << "," << csvEscape(e.username) << ","
         << csvEscape(e.password) << "," << csvEscape(e.http_realm) << ","
         << csvEscape(e.form_action_origin) << "," << csvEscape(e.guid) << ","
         << csvEscape(e.time_created) << "," << csvEscape(e.time_last_used)
         << "," << csvEscape(e.time_password_changed) << "\n";
  }
  file.close();
  chmod(getPasswordsFilePath().c_str(), 0600);
}

int PasswordManager::importFirefoxCsv(const std::string &csv_path) {
  std::ifstream file(csv_path);
  if (!file.is_open()) {
    return -1;
  }

  int added = 0;
  std::string line;
  bool first = true;
  while (std::getline(file, line)) {
    if (!line.empty() && line.back() == '\r') {
      line.pop_back();
    }
    if (line.empty()) {
      continue;
    }
    if (first) {
      first = false;
      continue; // header row
    }
    std::vector<std::string> f = parseCsvLine(line);
    if (f.size() < 3 || f[0].empty()) {
      continue;
    }
    // Only keep http(s) entries; skips Firefox-internal rows like
    // chrome://FirefoxAccounts
    if (f[0].compare(0, 7, "http://") != 0 &&
        f[0].compare(0, 8, "https://") != 0) {
      continue;
    }

    bool exists = false;
    for (const auto &e : entries_) {
      if (e.url == f[0] && e.username == f[1]) {
        exists = true;
        break;
      }
    }
    if (exists) {
      continue;
    }

    PasswordEntry e;
    e.url = f[0];
    e.username = f[1];
    e.password = f[2];
    e.http_realm = f.size() > 3 ? f[3] : "";
    e.form_action_origin = f.size() > 4 ? f[4] : "";
    e.guid = f.size() > 5 ? f[5] : "";
    e.time_created = f.size() > 6 ? f[6] : "";
    e.time_last_used = f.size() > 7 ? f[7] : "";
    e.time_password_changed = f.size() > 8 ? f[8] : "";
    entries_.push_back(e);
    added++;
  }

  if (added > 0) {
    save();
  }
  return added;
}

void PasswordManager::removeEntry(size_t index) {
  if (index < entries_.size()) {
    entries_.erase(entries_.begin() + index);
    save();
  }
}
