const fs = require("fs");
const crypto = require("crypto");

const VISITORS_FILE = "/opt/peercortex-app/visitors.json";

function loadVisitors() {
  try { return JSON.parse(fs.readFileSync(VISITORS_FILE, "utf8")); } catch (_) { return { hashes: [] }; }
}

function trackVisitor(req) {
  const ip = (req.headers["x-forwarded-for"] || "").split(",")[0].trim() || (req.socket && req.socket.remoteAddress) || "";
  const hash = crypto.createHash("sha256").update(ip + "peercortex-salt-2026").digest("hex");
  const data = loadVisitors();
  if (!data.hashes.includes(hash)) {
    data.hashes.push(hash);
    try { fs.writeFileSync(VISITORS_FILE, JSON.stringify(data)); } catch (_) {}
  }
  return data.hashes.length;
}

module.exports = { loadVisitors, trackVisitor };
