const fs = require("fs");
const { getSirayaDataRoot, ensureDir } = require("./paths");

function getEnvFilePath() {
  return (
    process.env.DOTENV_CONFIG_PATH ||
    require("path").join(getSirayaDataRoot(), ".env")
  );
}

/** Upsert KEY=value lines in the Siraya data .env file. */
function upsertEnvVars(updates) {
  const envPath = getEnvFilePath();
  ensureDir(require("path").dirname(envPath));

  let lines = [];
  if (fs.existsSync(envPath)) {
    lines = fs.readFileSync(envPath, "utf8").split(/\r?\n/);
  }

  for (const [key, value] of Object.entries(updates)) {
    const re = new RegExp(`^\\s*${key}=`);
    const line = `${key}=${value}`;
    const idx = lines.findIndex((l) => re.test(l));
    if (idx >= 0) {
      lines[idx] = line;
    } else {
      lines.push(line);
    }
  }

  const body = lines.filter((l) => l !== "").join("\n");
  fs.writeFileSync(envPath, body ? `${body}\n` : "");
  return envPath;
}

module.exports = { getEnvFilePath, upsertEnvVars };
