import "dotenv/config";

import { readFile } from "node:fs/promises";

function fail(msg: string): never {
  // eslint-disable-next-line no-console
  console.error(`[verify:umami] ${msg}`);
  process.exit(1);
}

function info(msg: string) {
  // eslint-disable-next-line no-console
  console.log(`[verify:umami] ${msg}`);
}

async function main() {
  const html = await readFile("dist/index.html", "utf8");

  const scriptUrl = process.env.PUBLIC_UMAMI_SCRIPT_URL || "";
  const websiteId = process.env.PUBLIC_UMAMI_WEBSITE_ID || "";

  const expectsEnabled = Boolean(scriptUrl && websiteId);
  const hasWebsiteId = html.includes('data-website-id="');
  const hasScriptUrl = scriptUrl ? html.includes(`src="${scriptUrl}"`) : false;

  if (expectsEnabled) {
    if (!hasWebsiteId) fail(`expected Umami enabled, but data-website-id not found in dist/index.html`);
    if (!hasScriptUrl)
      fail(`expected Umami enabled, but src="${scriptUrl}" not found in dist/index.html`);
    info("ok (umami script present)");
    return;
  }

  // When not configured, the site should not render a script tag.
  if (hasWebsiteId) fail("expected Umami disabled, but data-website-id was found in dist/index.html");
  info("ok (umami disabled, no script rendered)");
}

main().catch((e) => fail(String(e)));
