/*! © 2026 Yahoo, Inc. UDS v0.0.0-development */
import { defaultTokensConfig } from "../../defaultTokensConfig.js";
import { sortKeys } from "../../utils/dist/sortKeys.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 path from "node:path";
import { writeFileSync } from "node:fs";
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}` : `/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);
			print(yellow("Fetching from configurator..."));
			let config;
			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?`);
				}
				config = (await resp.json()).config;
			}
			if (!config) throw new Error("Config JSON could not be parsed.");
			const sortedConfig = 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: [configToBottomSheetConfigContext(sortedConfig), "UDSBottomSheetConfigContextType"],
				breakpoints: [configToBreakpointsConfigContext(sortedConfig), "UDSBreakpointsConfigContextType"],
				modal: [configToModalConfigContext(sortedConfig), "UDSModalConfigContextType"],
				popover: [configToPopoverConfigContext(sortedConfig), "UDSPopoverConfigContextType"],
				toast: [configToToastConfigContext(sortedConfig), "UDSToastConfigContextType"],
				tooltip: [configToTooltipConfigContext(sortedConfig), "UDSTooltipConfigContextType"]
			};
			const runtimeTypeImports = [];
			for (const [name, [json, type]] of Object.entries(runtimeConfigs)) {
				const content = 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`;
			writeFileSync(fullPath, outFileExtension === "js" ? configContentJs : configContentTs);
			print(green(`✅ Synced UDS config ${id} to ${fullPath}`));
			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 { isAutoMigrateEnabled, syncCommand };
