/*! © 2026 Yahoo, Inc. UDS v0.0.0-development */
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_runtime = require("../../_virtual/_rolldown/runtime.cjs");
const require_defaultTokensConfig = require("../../defaultTokensConfig.cjs");
const require_sortKeys = require("../../utils/dist/sortKeys.cjs");
const require_runtime_bottomSheetConfig = require("../../runtime/bottomSheetConfig.cjs");
const require_runtime_breakpointsConfig = require("../../runtime/breakpointsConfig.cjs");
const require_runtime_modalConfig = require("../../runtime/modalConfig.cjs");
const require_runtime_popoverConfig = require("../../runtime/popoverConfig.cjs");
const require_runtime_toastConfig = require("../../runtime/toastConfig.cjs");
const require_runtime_tooltipConfig = require("../../runtime/tooltipConfig.cjs");
const require_config = require("../dist/utils/rules/config.cjs");
const require_colors = require("../dist/lib/colors.cjs");
const require_print = require("../dist/lib/print.cjs");
const require_box = require("../dist/lib/box.cjs");
let node_path = require("node:path");
node_path = require_runtime.__toESM(node_path, 1);
let node_fs = require("node:fs");
let _yahoo_uds_package_json = require("@yahoo/uds/package.json");
_yahoo_uds_package_json = require_runtime.__toESM(_yahoo_uds_package_json, 1);
//#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}` : `/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");
			require_print.print(`${require_colors.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") {
			require_print.print(require_colors.red("❌ Output file must be a TypeScript or JavaScript file."));
			process.exitCode = 1;
			return;
		}
		try {
			const packageVersion = _yahoo_uds_package_json.default.version;
			const fetchUrl = getConfigEndpoint(id, autoMigrate, packageVersion);
			const fullPath = node_path.default.resolve(process.cwd(), outputPath);
			require_print.print(require_colors.yellow("Fetching from configurator..."));
			let config;
			if (process.env.DATABASE === "test") config = require_defaultTokensConfig.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?`);
				}
				config = (await resp.json()).config;
			}
			if (!config) throw new Error("Config JSON could not be parsed.");
			const sortedConfig = require_sortKeys.sortKeys(config);
			const importsTS = [`import type { UniversalTokensConfig } from '@yahoo/uds';`];
			const exportsTS = [`export const config: UniversalTokensConfig = ${JSON.stringify(sortedConfig, null, 2)} as UniversalTokensConfig;`];
			const exportsJS = [`export const config = ${JSON.stringify(sortedConfig, null, 2)};`];
			const runtimeConfigs = {
				bottomSheet: [require_runtime_bottomSheetConfig.configToBottomSheetConfigContext(sortedConfig), "UDSBottomSheetConfigContextType"],
				breakpoints: [require_runtime_breakpointsConfig.configToBreakpointsConfigContext(sortedConfig), "UDSBreakpointsConfigContextType"],
				modal: [require_runtime_modalConfig.configToModalConfigContext(sortedConfig), "UDSModalConfigContextType"],
				popover: [require_runtime_popoverConfig.configToPopoverConfigContext(sortedConfig), "UDSPopoverConfigContextType"],
				toast: [require_runtime_toastConfig.configToToastConfigContext(sortedConfig), "UDSToastConfigContextType"],
				tooltip: [require_runtime_tooltipConfig.configToTooltipConfigContext(sortedConfig), "UDSTooltipConfigContextType"]
			};
			const runtimeTypeImports = [];
			for (const [name, [json, type]] of Object.entries(runtimeConfigs)) {
				const content = require_sortKeys.sortKeys(json);
				runtimeTypeImports.push(type);
				exportsTS.push(`export const ${name}RuntimeConfig: ${type} = ${JSON.stringify(content, null, 2)};`);
				exportsJS.push(`export const ${name}RuntimeConfig = ${JSON.stringify(content, null, 2)};`);
			}
			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`;
			(0, node_fs.writeFileSync)(fullPath, outFileExtension === "js" ? configContentJs : configContentTs);
			require_print.print(require_colors.green(`✅ Synced UDS config ${id} to ${fullPath}`));
			const staleEditors = require_config.getEditorsWithStaleRules(process.cwd());
			if (staleEditors.length > 0) require_box.printBox([require_colors.bold(`Updated UDS rules are available for ${staleEditors.join(" and ")}.`), `Run ${require_colors.cyan("`uds editor-rules`")} to update.`]);
		} catch (error) {
			require_print.print(require_colors.red(`❌ ${error.message}`));
			require_print.print(require_colors.yellow("Please reach out to #uds-ask channel for support."));
			process.exitCode = 1;
		}
	}
};
//#endregion
exports.isAutoMigrateEnabled = isAutoMigrateEnabled;
exports.syncCommand = syncCommand;
