/**
 * Post-processes the sitemap generated by `vite-plugin-sitemap` to inject
 * language alternates for the English / Arabic SPA.
 *
 * Because DoItEasy serves both languages from the same URL (the language is
 * toggled client-side and persisted in `localStorage`), every `<url>` entry
 * should declare `hreflang="en"`, `hreflang="ar"` and `hreflang="x-default"`
 * alternates that all point back to the same `<loc>`. The upstream plugin's
 * built-in `i18n` option only supports `prefix` / `suffix` strategies, so we
 * rewrite the file ourselves after the build.
 *
 * Usage:
 *   node prerender/sitemap-hreflang.js [sitemapPath]
 *
 * Defaults to `<repo>/dist/sitemap.xml`.
 */
import { readFileSync, writeFileSync, existsSync } from 'node:fs';
import { resolve, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';

const __dirname = dirname(fileURLToPath(import.meta.url));

/**
 * Inject hreflang alternates into every `<url>` block of the given sitemap.
 *
 * @param {string} xml Raw sitemap XML.
 * @returns {string} Rewritten XML with alternates inserted.
 */
export function injectHreflangAlternates(xml) {
  // Match each <url> ... </url> block (non-greedy, multi-line).
  return xml.replace(/<url>[\s\S]*?<\/url>/g, (block) => {
    const locMatch = block.match(/<loc>\s*([^<\s]+)\s*<\/loc>/);
    if (!locMatch) return block;
    const loc = locMatch[1].trim();

    // Remove any pre-existing xhtml:link alternates so we don't double up.
    const stripped = block.replace(/\s*<xhtml:link[^/]*\/>/g, '');

    const alternates = [
      `        <xhtml:link rel="alternate" hreflang="en" href="${loc}"/>`,
      `        <xhtml:link rel="alternate" hreflang="ar" href="${loc}"/>`,
      `        <xhtml:link rel="alternate" hreflang="x-default" href="${loc}"/>`,
    ].join('\n');

    // Insert alternates just before the closing </url> tag.
    return stripped.replace(
      /(\s*)<\/url>\s*$/,
      (_match, indent) => `\n${alternates}${indent}</url>`,
    );
  });
}

function runCli() {
  const defaultPath = resolve(__dirname, '..', 'dist', 'sitemap.xml');
  const targetPath = resolve(process.argv[2] ?? defaultPath);

  if (!existsSync(targetPath)) {
    console.warn(`[sitemap-hreflang] sitemap not found at ${targetPath}, skipping`);
    return;
  }

  const original = readFileSync(targetPath, 'utf8');
  const rewritten = injectHreflangAlternates(original);
  writeFileSync(targetPath, rewritten, 'utf8');
  console.log(`[sitemap-hreflang] injected hreflang alternates into ${targetPath}`);
}

runCli();