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

// Repo root (where server.js itself lives) -- NOT this module's own directory.
// Preserves the original server.js `__dirname` fallback behavior (only ever
// exercised locally; Erik always has /opt/peercortex-app and takes that branch).
const REPO_ROOT = path.join(__dirname, "..", "..");
const DATA_DIR = process.env.DATA_DIR || (fs.existsSync('/opt/peercortex-app') ? '/opt/peercortex-app' : REPO_ROOT);
const HIJACK_SUBS_FILE   = DATA_DIR + '/hijack-subs.json';
const HIJACK_ALERTS_FILE = DATA_DIR + '/hijack-alerts.json';
const WEBHOOK_SUBS_FILE  = DATA_DIR + '/webhook-subs.json';

function loadHijackSubs()    { try { return JSON.parse(fs.readFileSync(HIJACK_SUBS_FILE,'utf8')); } catch(_){ return []; } }
function loadHijackAlerts()  { try { return JSON.parse(fs.readFileSync(HIJACK_ALERTS_FILE,'utf8')); } catch(_){ return []; } }
function loadWebhookSubs()   { try { return JSON.parse(fs.readFileSync(WEBHOOK_SUBS_FILE,'utf8')); } catch(_){ return []; } }
function saveWebhookSubs(s)  { try { fs.writeFileSync(WEBHOOK_SUBS_FILE, JSON.stringify(s, null, 2)); } catch(_){} }
function saveHijackAlerts(a) { try { fs.writeFileSync(HIJACK_ALERTS_FILE, JSON.stringify(a.slice(-1000), null, 2)); } catch(_){} }
function saveHijackSubs(s)   { try { fs.writeFileSync(HIJACK_SUBS_FILE, JSON.stringify(s, null, 2)); } catch(_){} }

module.exports = {
  DATA_DIR,
  HIJACK_SUBS_FILE,
  HIJACK_ALERTS_FILE,
  WEBHOOK_SUBS_FILE,
  loadHijackSubs,
  loadHijackAlerts,
  loadWebhookSubs,
  saveWebhookSubs,
  saveHijackAlerts,
  saveHijackSubs,
};
