import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { readFileSync } from "node:fs";
import path from "node:path";
import { describe, it } from "node:test";
import { fileURLToPath } from "node:url";

// The committed AppStream metainfo files are snapshots generated by
// scripts/render-linux-metainfo.sh. Guard against them silently drifting from
// the shared template (description, keywords, screenshot, etc.) by re-rendering
// each with the version/date it declares and asserting an exact match. The
// check is version-agnostic, so it only fails on real template drift.
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const script = path.join(repoRoot, "scripts", "render-linux-metainfo.sh");

const files = ["packaging/linux/org.geolibre.desktop.metainfo.xml"];

describe("render-linux-metainfo.sh committed copies", () => {
  for (const file of files) {
    it(`${file} is in sync with the template`, () => {
      const committed = readFileSync(path.join(repoRoot, file), "utf8");
      const release = committed.match(/<release version="([^"]+)" date="([^"]+)"/);
      assert.ok(release, `no <release> element found in ${file}`);
      const [, version, date] = release;
      const rendered = execFileSync("bash", [script], {
        env: { ...process.env, VERSION: version, DATE: date },
        encoding: "utf8",
      });
      assert.equal(
        rendered,
        committed,
        `${file} is stale; re-run scripts/render-linux-metainfo.sh`,
      );
    });
  }
});
