'use strict';

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

const dataDir = process.env.ARKHON_MULTIBRANCH_DATA_DIR
  ? path.resolve(process.env.ARKHON_MULTIBRANCH_DATA_DIR)
  : path.join(__dirname, '..', '..', '..', 'data', 'multibranch-sync');

function filePath(name) {
  return path.join(dataDir, `${name}.json`);
}

function ensureDir() {
  fs.mkdirSync(dataDir, { recursive: true });
}

function read(name, fallback) {
  try {
    return JSON.parse(fs.readFileSync(filePath(name), 'utf8'));
  } catch (_) {
    return structuredClone(fallback);
  }
}

function write(name, value) {
  ensureDir();
  const destination = filePath(name);
  const temp = `${destination}.${process.pid}.${Date.now()}.tmp`;
  fs.writeFileSync(temp, JSON.stringify(value, null, 2), { encoding: 'utf8', mode: 0o600 });
  try {
    fs.renameSync(temp, destination);
  } catch (_) {
    fs.copyFileSync(temp, destination);
    fs.unlinkSync(temp);
  }
}

function update(name, fallback, mutator) {
  const value = read(name, fallback);
  const next = mutator(value) || value;
  write(name, next);
  return next;
}

module.exports = { dataDir, read, write, update };
