// Regenerates src/op-cli-installer/version/fallback-versions.ts from app-updates.agilebits.com.
// Run before cutting a release (see release instructions) so the last resort
// versions stay current. On failure it leaves the existing file untouched.
import { writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";

const APP_UPDATES_URL = "https://app-updates.agilebits.com/latest";
const outFile = join(
	dirname(fileURLToPath(import.meta.url)),
	"../src/op-cli-installer/version/fallback-versions.ts",
);

const render = (latest, latestBeta) =>
	[
		"// AUTO-GENERATED by scripts/update-fallback-versions.mjs — do not edit by hand.",
		"// Last-resort CLI versions, used only when both app-updates and Docker Hub are",
		"// unavailable. Refresh with `npm run op-version` (see release docs).",
		'import { ReleaseChannel } from "./constants";',
		"",
		"export const FALLBACK_VERSIONS: Record<ReleaseChannel, string> = {",
		`\t[ReleaseChannel.latest]: "${latest}",`,
		`\t[ReleaseChannel.latestBeta]: "${latestBeta}",`,
		"};",
		"",
	].join("\n");

const main = async () => {
	const res = await fetch(APP_UPDATES_URL);
	if (!res.ok) {
		throw new Error(`app-updates.agilebits.com returned status ${res.status}`);
	}

	const json = await res.json();
	const latest = json?.CLI2?.release?.version;
	const latestBeta = json?.CLI2?.beta?.version;
	if (!latest || !latestBeta) {
		throw new Error("app-updates response missing CLI2 release/beta version");
	}

	writeFileSync(outFile, render(latest, latestBeta));
	console.log(
		`Updated fallback versions → latest=${latest}, latest-beta=${latestBeta}`,
	);
};

main().catch((error) => {
	console.error(`Failed to update fallback versions: ${String(error)}`);
	console.error("Existing fallback-versions.ts left unchanged.");
	process.exit(1);
});
