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

const rootEnvPath = path.resolve(__dirname, "..", ".env.local");
const websiteEnvPath = path.resolve(__dirname, "..", "apps/website/.env.local");

function parseEnvFile(filePath) {
  let content;
  try {
    content = fs.readFileSync(filePath, "utf8");
  } catch (err) {
    if (err && err.code === "ENOENT") {
      return {};
    }
    console.error(`Error reading env file at ${filePath}:`, err.message || err);
    process.exitCode = 1;
    return {};
  }

  const result = {};

  const lines = content.split(/\r?\n/);
  for (const line of lines) {
    const trimmed = line.trim();

    if (!trimmed || trimmed.startsWith("#")) {
      continue;
    }

    const eqIndex = trimmed.indexOf("=");
    if (eqIndex === -1) {
      continue;
    }

    const key = trimmed.slice(0, eqIndex).trim();
    const value = trimmed.slice(eqIndex + 1);

    if (!key) {
      continue;
    }

    result[key] = value;
  }

  return result;
}

function mergeEnv() {
  const rootExists = fs.existsSync(rootEnvPath);
  const websiteExists = fs.existsSync(websiteEnvPath);

  if (!rootExists && !websiteExists) {
    return;
  }

  const rootEnv = rootExists ? parseEnvFile(rootEnvPath) : {};
  const websiteEnv = websiteExists ? parseEnvFile(websiteEnvPath) : {};

  const merged = { ...rootEnv, ...websiteEnv };

  const lines = Object.entries(merged).map(([key, value]) => `${key}=${value}`);
  const output = lines.join("\n") + "\n";

  try {
    fs.writeFileSync(websiteEnvPath, output, "utf8");
  } catch (err) {
    console.error(`Error writing merged env file to ${websiteEnvPath}:`, err.message || err);
    process.exit(1);
  }
}

mergeEnv();