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

const projectRoot = path.join(__dirname, '..');
const envPath = path.join(projectRoot, '.env');
const dataDir = path.join(projectRoot, 'data');
const historyPath = path.join(dataDir, 'read-backend-switch-history.json');

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

function readLines() {
  try {
    return fs.readFileSync(envPath, 'utf8').split(/\r?\n/);
  } catch (err) {
    return [];
  }
}

function readHistory() {
  try {
    const body = JSON.parse(fs.readFileSync(historyPath, 'utf8'));
    return Array.isArray(body.history) ? body.history : [];
  } catch (err) {
    return [];
  }
}

function writeHistory(entry) {
  ensureDataDir();
  const history = readHistory().slice(-49);
  history.push(entry);
  fs.writeFileSync(historyPath, `${JSON.stringify({ history }, null, 2)}\n`);
}

function getReadBackend() {
  const line = readLines().find((row) => /^\s*AISFOR_CHAIN_LEDGER_READ_BACKEND\s*=/.test(row));
  if (!line) return 'json-file';
  const index = line.indexOf('=');
  return index >= 0 ? line.slice(index + 1).trim() || 'json-file' : 'json-file';
}

function setReadBackend(value, { actor = 'admin', reason = '' } = {}) {
  const nextValue = value === 'mongodb' ? 'mongodb' : 'json-file';
  ensureDataDir();
  const backupPath = path.join(dataDir, `env-read-backend-${Date.now()}.env`);
  if (fs.existsSync(envPath)) fs.copyFileSync(envPath, backupPath);

  const lines = readLines();
  let found = false;
  const nextLines = lines.map((line) => {
    if (/^\s*AISFOR_CHAIN_LEDGER_READ_BACKEND\s*=/.test(line)) {
      found = true;
      return `AISFOR_CHAIN_LEDGER_READ_BACKEND=${nextValue}`;
    }
    return line;
  });
  if (!found) nextLines.push(`AISFOR_CHAIN_LEDGER_READ_BACKEND=${nextValue}`);

  fs.writeFileSync(envPath, `${nextLines.join('\n').replace(/\n+$/u, '')}\n`);
  const entry = {
    action: nextValue === 'mongodb' ? 'request-mongodb-read' : 'rollback-json-read',
    readBackend: nextValue,
    actor: String(actor || 'admin'),
    reason: String(reason || ''),
    backupPath,
    changedAt: new Date().toISOString()
  };
  writeHistory(entry);
  return getStatus();
}

function getStatus() {
  return {
    envPath,
    historyPath,
    readBackend: getReadBackend(),
    history: readHistory().slice(-10)
  };
}

module.exports = {
  getStatus,
  getReadBackend,
  setReadBackend
};
