// Pick the newest DMG enclosure URL out of a Sparkle appcast.
//
// `generate_appcast` emits one `<item>` per release, each carrying a self-closing
//   <enclosure url="…/beta/Nucleic-Beta-0.2.0.829.dmg" sparkle:version="829" …/>
// where `sparkle:version` is the app's CFBundleVersion — the monotonic build number that
// scripts/release-macos.sh bumps by exactly 1 on every release. The largest build number is
// therefore unambiguously the latest, so we rank by it rather than trusting document order
// (and parse all items defensively rather than grabbing the first enclosure).
//
// Pure + dependency-free so it unit-tests under Node's runner without a Workers runtime.

export function latestDmgUrl(appcastXml: string): string | null {
  let best: { build: number; url: string } | null = null;
  for (const match of appcastXml.matchAll(/<enclosure\b[^>]*>/g)) {
    const tag = match[0];
    const url = attr(tag, "url");
    if (!url || !/\.dmg(?:$|[?#])/i.test(url)) continue; // only DMG enclosures
    const build = Number(attr(tag, "sparkle:version"));
    const rank = Number.isFinite(build) ? build : -1; // missing/odd version → lowest priority
    if (!best || rank > best.build) best = { build: rank, url };
  }
  return best?.url ?? null;
}

function attr(tag: string, name: string): string | null {
  // Attribute names here are plain ASCII (incl. the ':' in `sparkle:version`), all regex-safe.
  return new RegExp(`\\b${name}\\s*=\\s*["']([^"']+)["']`, "i").exec(tag)?.[1] ?? null;
}
