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

const projectRoot = path.resolve(__dirname, "..");
const environment = process.env.PLOTDIRECTOR_COMPANION_ENV || "development";
const configPath = path.join(projectRoot, "config", `${environment}.json`);
const templatePath = path.join(projectRoot, "manifest.template.xml");
const manifestPath = path.join(projectRoot, "manifest.xml");

if (!fs.existsSync(configPath)) {
  throw new Error(`Missing Word Companion manifest config: ${configPath}`);
}

const config = JSON.parse(fs.readFileSync(configPath, "utf8"));
const requiredKeys = ["appDomain", "taskpaneUrl", "iconUrl"];
for (const key of requiredKeys) {
  if (!config[key]) {
    throw new Error(`Missing required Word Companion manifest config value: ${key}`);
  }
}

const escapeXml = (value) =>
  String(value)
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;");

let manifest = fs.readFileSync(templatePath, "utf8");
for (const [key, value] of Object.entries(config)) {
  manifest = manifest.replaceAll(`{{${key}}}`, escapeXml(value));
}

fs.writeFileSync(manifestPath, manifest, "utf8");
console.log(`Rendered ${path.relative(projectRoot, manifestPath)} for ${environment}.`);
