/*! © 2026 Yahoo, Inc. UDS v0.0.0-development */
import { defaultTokensConfig } from "../../defaultTokensConfig.js";
import { serializeToJS } from "../../utils/dist/serializeToJS.js";
import { configToBottomSheetConfigContext } from "../../runtime/bottomSheetConfig.js";
import { configToBreakpointsConfigContext } from "../../runtime/breakpointsConfig.js";
import { configToModalConfigContext } from "../../runtime/modalConfig.js";
import { configToPopoverConfigContext } from "../../runtime/popoverConfig.js";
import { configToToastConfigContext } from "../../runtime/toastConfig.js";
import { configToTooltipConfigContext } from "../../runtime/tooltipConfig.js";
import { getEditorsWithStaleRules } from "../dist/utils/rules/config.js";
import { bold, cyan, green, magenta, red, yellow } from "../dist/lib/colors.js";
import { print } from "../dist/lib/print.js";
import { printBox } from "../dist/lib/box.js";
import { MIGRATION_SCHEMA_VERSION } from "../../uds/generated/migrationSchemaVersion.js";
import { writeFileSync } from "node:fs";
import path from "node:path";
import packageJSON from "@yahoo/uds/package.json" with { type: "json" };
//#region src/cli/commands/sync.ts
const PRODUCTION_ENDPOINT = "https://config.uds.build";
const STAGING_ENDPOINT = "https://staging.config.uds.build";
const BETA_ENDPOINT = "https://configurator-git-beta-yahoo-design.vercel.app";
const getConfigEndpoint = (id, autoMigrate, packageVersion) => {
	const isDevelopment = packageVersion.endsWith("-development");
	const suffix = autoMigrate && !isDevelopment ? `/api/config/for-package-version?branchId=${id}&packageVersion=${packageVersion}&schemaVersion=${MIGRATION_SCHEMA_VERSION}` : `/api/config?id=${id}`;
	switch (process.env.DATABASE) {
		case "staging": return `${STAGING_ENDPOINT}${suffix}`;
		case "beta": return `${BETA_ENDPOINT}${suffix}`;
		case "local": return `http://localhost:${process.env.PORT || 4001}${suffix}`;
		default: return `${PRODUCTION_ENDPOINT}${suffix}`;
	}
};
const isEnabledOption = (value) => value === true || value === "true";
const isAutoMigrateEnabled = (options) => isEnabledOption(options["auto-migrate"]) || isEnabledOption(options.autoMigrate);
const syncCommand = {
	name: "sync",
	description: "🔄 Update to latest design config 🎨",
	aliases: ["update"],
	run: async ({ name, commandPath, options }) => {
		const id = options.id || process.env.UDS_ID;
		const outFile = options.outFile || process.env.UDS_OUT_FILE;
		const autoMigrate = isAutoMigrateEnabled(options);
		if (!id || typeof id === "boolean") {
			console.error("\nMissing config ID. Please pass an --id flag or set the UDS_ID env variable.\n");
			print(`${magenta("Usage:")} ${name} ${commandPath} --id <config-id>\n`);
			return;
		}
		const outputPath = outFile ?? "./uds.config.ts";
		const outFileExtension = outputPath.split(".").pop()?.toLowerCase();
		if (outFileExtension !== "ts" && outFileExtension !== "js") {
			print(red("❌ Output file must be a TypeScript or JavaScript file."));
			process.exitCode = 1;
			return;
		}
		try {
			const packageVersion = packageJSON.version;
			const fetchUrl = getConfigEndpoint(id, autoMigrate, packageVersion);
			const fullPath = path.resolve(process.cwd(), outputPath);
			if (process.env.DEBUG_UDS_CLI === "1") print(`[uds:debug] fetchUrl=${fetchUrl}`);
			print(yellow("Fetching from configurator..."));
			let config;
			let degraded = false;
			let warnings = [];
			let nonReversibleMigrations = [];
			if (process.env.DATABASE === "test") config = defaultTokensConfig;
			else {
				const resp = await fetch(fetchUrl);
				if (!resp.ok) {
					if (resp.status === 401) throw new Error(`${resp.status} error: ${resp.statusText}\nYou're not authorized to fetch from ${fetchUrl}\nMake sure you have a valid VERCEL_PROTECTION_BYPASS token in your root .env.local`);
					throw new Error(`Error fetching config id '${id}'. Does it exist in the Configurator?`);
				}
				const data = await resp.json();
				config = data.config;
				degraded = data.degraded === true;
				warnings = Array.isArray(data.warnings) ? data.warnings : [];
				nonReversibleMigrations = Array.isArray(data.nonReversibleMigrations) ? data.nonReversibleMigrations : [];
			}
			if (!config) throw new Error("Config JSON could not be parsed.");
			const serializedConfig = serializeToJS(config);
			const importsTS = [`import type { UniversalTokensConfig } from '@yahoo/uds';`];
			const exportsTS = [`export const config: UniversalTokensConfig = ${serializedConfig} as UniversalTokensConfig;`];
			const exportsJS = [`export const config = ${serializedConfig};`];
			const runtimeConfigs = {
				bottomSheet: [configToBottomSheetConfigContext(config), "UDSBottomSheetConfigContextType"],
				breakpoints: [configToBreakpointsConfigContext(config), "UDSBreakpointsConfigContextType"],
				modal: [configToModalConfigContext(config), "UDSModalConfigContextType"],
				popover: [configToPopoverConfigContext(config), "UDSPopoverConfigContextType"],
				toast: [configToToastConfigContext(config), "UDSToastConfigContextType"],
				tooltip: [configToTooltipConfigContext(config), "UDSTooltipConfigContextType"]
			};
			const runtimeTypeImports = [];
			for (const [name, [json, type]] of Object.entries(runtimeConfigs)) {
				const serialized = serializeToJS(json);
				runtimeTypeImports.push(type);
				exportsTS.push(`export const ${name}RuntimeConfig: ${type} = ${serialized};`);
				exportsJS.push(`export const ${name}RuntimeConfig = ${serialized};`);
			}
			runtimeTypeImports.push("UDSConfigContextType");
			importsTS.push(`import type { ${runtimeTypeImports.sort().join(", ")} } from '@yahoo/uds/runtime';`);
			exportsTS.push(`export const runtimeConfig: UDSConfigContextType = {
  bottomSheet: bottomSheetRuntimeConfig,
  breakpoints: breakpointsRuntimeConfig,
  modal: modalRuntimeConfig,
  popover: popoverRuntimeConfig,
  toast: toastRuntimeConfig,
  tooltip: tooltipRuntimeConfig,
};`);
			exportsJS.push(`export const runtimeConfig = {
  bottomSheet: bottomSheetRuntimeConfig,
  breakpoints: breakpointsRuntimeConfig,
  modal: modalRuntimeConfig,
  popover: popoverRuntimeConfig,
  toast: toastRuntimeConfig,
  tooltip: tooltipRuntimeConfig,
};`);
			const configContentTs = `${importsTS.join("\n")}\n\n${exportsTS.join("\n\n")}\n`;
			const configContentJs = `${exportsJS.join("\n\n")}\n`;
			writeFileSync(fullPath, outFileExtension === "js" ? configContentJs : configContentTs);
			print(green(`✅ Synced UDS config ${id} to ${fullPath}`));
			if (degraded || warnings.length > 0) {
				const lines = [bold(yellow("⚠️  Auto-migration was degraded."))];
				if (nonReversibleMigrations.length > 0) lines.push(`Non-reversible migrations applied: ${nonReversibleMigrations.join(", ")}.`);
				for (const warning of warnings) lines.push(warning);
				lines.push(`Open the configurator to restore an accurate config: https://config.uds.build/branches/${id}`);
				printBox(lines);
			}
			const staleEditors = getEditorsWithStaleRules(process.cwd());
			if (staleEditors.length > 0) printBox([bold(`Updated UDS rules are available for ${staleEditors.join(" and ")}.`), `Run ${cyan("`uds editor-rules`")} to update.`]);
		} catch (error) {
			print(red(`❌ ${error.message}`));
			print(yellow("Please reach out to #uds-ask channel for support."));
			process.exitCode = 1;
		}
	}
};
//#endregion
export { getConfigEndpoint, isAutoMigrateEnabled, syncCommand };
