/*! © 2026 Yahoo, Inc. UDS v0.0.0-development */
const require_runtime = require("../../../_virtual/_rolldown/runtime.cjs");
const require_colors = require("../packages/cli/dist/lib/colors.cjs");
const require_print = require("../packages/cli/dist/lib/print.cjs");
const require_perf = require("./perf.cjs");
const require_entryPoints = require("../../../tailwind-internal/dist/utils/entryPoints.cjs");
const require_nodeUtils = require("./nodeUtils.cjs");
const require_spinner = require("../packages/cli/dist/lib/spinner.cjs");
const require_logger = require("../packages/cli/dist/lib/logger.cjs");
const require_index = require("../packages/config/dist/index.cjs");
const require_safelist = require("../purger/optimized/utils/safelist.cjs");
const require_runner_helpers = require("./runner.helpers.cjs");
const require_utils = require("./utils.cjs");
const require_generate_helpers = require("./generate.helpers.cjs");
const require_generate = require("./generate.cjs");
const require_workerPool = require("./workerPool.cjs");
let node_fs = require("node:fs");
node_fs = require_runtime.__toESM(node_fs, 1);
//#region ../css/dist/css/runner.mjs
/*! © 2026 Yahoo, Inc. UDS CSS v0.0.0-development */
const getScopedPackageOutputPath = (packageName, outFile) => {
	if (typeof outFile === "string" && outFile.trim().length > 0) return outFile;
	return `dist/${packageName.split("/").pop() ?? packageName}.css`;
};
const normalizeScopedPackageConfig = (scopedPackageValue) => {
	if (typeof scopedPackageValue === "string") return { config: scopedPackageValue };
	return scopedPackageValue;
};
const resolveScopedEntryDirs = (packageRoot, packageDir, entry) => {
	if (entry === void 0) return [packageDir];
	return require_entryPoints.resolveEntryPaths(entry, packageRoot).map((resolvedEntry) => resolvedEntry.absolutePath);
};
const PATH_SEPARATOR = "/";
const normalizePath = (value) => value.replace(/\\/g, PATH_SEPARATOR);
const isAbsolutePath = (value) => {
	const normalizedValue = normalizePath(value);
	return normalizedValue.startsWith(PATH_SEPARATOR) || /^[A-Za-z]:\//.test(normalizedValue);
};
const joinPath = (...parts) => {
	const filteredParts = parts.filter((part) => part.length > 0);
	if (filteredParts.length === 0) return "";
	return filteredParts.map((part, index) => {
		const normalizedPart = normalizePath(part);
		if (index === 0) return normalizedPart.replace(/\/+$/g, "");
		return normalizedPart.replace(/^\/+|\/+$/g, "");
	}).join(PATH_SEPARATOR).replace(/\/+/g, PATH_SEPARATOR).replace(/\/\.\//g, PATH_SEPARATOR);
};
const dirnamePath = (value) => {
	const normalizedValue = normalizePath(value).replace(/\/+$/g, "");
	const lastSeparatorIndex = normalizedValue.lastIndexOf(PATH_SEPARATOR);
	if (lastSeparatorIndex <= 0) return lastSeparatorIndex === 0 ? PATH_SEPARATOR : ".";
	return normalizedValue.slice(0, lastSeparatorIndex);
};
const basenamePath = (value) => {
	const normalizedValue = normalizePath(value).replace(/\/+$/g, "");
	const lastSeparatorIndex = normalizedValue.lastIndexOf(PATH_SEPARATOR);
	return lastSeparatorIndex >= 0 ? normalizedValue.slice(lastSeparatorIndex + 1) : normalizedValue;
};
const resolveOutputPath = (workspaceDir, outFile) => isAbsolutePath(outFile) ? outFile : joinPath(workspaceDir, outFile);
const ensureOutputDirectory = (outputPath) => {
	const outputDir = dirnamePath(outputPath);
	if (!node_fs.default.existsSync(outputDir)) node_fs.default.mkdirSync(outputDir, { recursive: true });
};
const SOURCE_FILE_PATTERN = /\.(jsx?|tsx?)$/i;
const getWatchDirs = (dirs) => [...new Set(dirs.filter((dir) => !normalizePath(dir).split(PATH_SEPARATOR).includes("node_modules")))];
const isCoveredByRecursiveWatch = (watchPath, targetPath) => targetPath === watchPath || targetPath.startsWith(`${watchPath}${PATH_SEPARATOR}`);
const getEntryWatchTargets = (entries) => {
	const directoryTargets = getWatchDirs(entries.filter((entry) => entry.kind === "directory").map((entry) => entry.absolutePath)).map((watchPath) => ({
		watchPath,
		recursive: true
	}));
	const fileNamesByDirectory = /* @__PURE__ */ new Map();
	entries.filter((entry) => entry.kind === "file" && typeof entry.fileName === "string").forEach((entry) => {
		if (directoryTargets.some((target) => isCoveredByRecursiveWatch(target.watchPath, entry.absolutePath))) return;
		const fileNames = fileNamesByDirectory.get(entry.watchDirectory) ?? /* @__PURE__ */ new Set();
		fileNames.add(entry.fileName);
		fileNamesByDirectory.set(entry.watchDirectory, fileNames);
	});
	const fileTargets = [...fileNamesByDirectory.entries()].map(([watchPath, fileNames]) => ({
		watchPath,
		recursive: false,
		fileNames: [...fileNames]
	}));
	return [...directoryTargets, ...fileTargets];
};
const watchSourceFiles = (targets, onFileChange) => {
	targets.forEach((target) => {
		node_fs.default.watch(target.watchPath, { recursive: target.recursive }, (_eventType, filename) => {
			if (!filename || !SOURCE_FILE_PATTERN.test(filename)) return;
			if (target.fileNames && !target.fileNames.includes(basenamePath(String(filename)))) return;
			onFileChange();
		});
	});
};
const createDebouncedAction = (action, delayMs) => {
	let debounceTimer = null;
	return () => {
		if (debounceTimer) clearTimeout(debounceTimer);
		debounceTimer = setTimeout(action, delayMs);
	};
};
const createQueuedRegenerator = (options) => {
	let isGenerating = false;
	let pendingRegenerate = false;
	const regenerate = async () => {
		if (isGenerating) {
			pendingRegenerate = true;
			return;
		}
		isGenerating = true;
		try {
			options.onStart?.();
			const result = await options.regenerateOnce();
			options.onSuccess?.(result);
		} catch (error) {
			const message = error instanceof Error ? error.message : "CSS generation failed";
			options.onError(message);
		} finally {
			isGenerating = false;
			if (pendingRegenerate) {
				pendingRegenerate = false;
				await regenerate();
			}
		}
	};
	return regenerate;
};
const printVerboseScanFiles = (log, workspaceDir, filePaths) => {
	require_runner_helpers.getVerboseScanFileList(workspaceDir, filePaths).forEach((filePath) => {
		log.listItem(filePath);
	});
};
const runCssCommand = async (options, context) => {
	if (!node_fs.default.existsSync(joinPath(options.workspaceDir, String(options.themeConfigPath)))) {
		await runSimpleMode(options, context);
		return;
	}
	await runThemeMode(options, context);
};
const runSimpleMode = async (options, context) => {
	const entry = options.entryOption ?? "./src";
	const configPath = typeof options.configOption === "string" ? options.configOption : void 0;
	if (!options.watch && !options.silent) require_spinner.spinStart("Generating CSS...");
	try {
		const result = await require_generate.generateSimpleModeCSS({
			workspaceDir: options.workspaceDir,
			entry,
			outFile: String(options.outFile),
			variants: context.variants,
			autoVariants: context.autoVariants,
			componentData: context.componentData,
			scope: options.scope,
			configPath,
			isWatch: options.watch,
			silent: options.silent,
			verbose: options.verbose
		});
		if (!options.watch && !options.silent) require_spinner.spinStop("✅", "CSS generated");
		if (options.watch) await runSimpleModeWatch(options, context, entry, configPath, result.packageDirs ?? []);
	} catch (error) {
		require_spinner.spinStop("❌", error instanceof Error ? error.message : "CSS generation failed");
		process.exitCode = 1;
	}
};
const runSimpleModeWatch = async (options, context, entry, configPath, packageDirs) => {
	const entryWatchTargets = getEntryWatchTargets(require_entryPoints.resolveEntryPaths(entry, options.workspaceDir));
	const fallbackTargets = getWatchDirs(packageDirs).map((watchPath) => ({
		watchPath,
		recursive: true
	}));
	const watchTargets = packageDirs.length > 0 ? fallbackTargets : entryWatchTargets;
	if (!options.silent) {
		require_print.print("");
		require_print.print(`${require_colors.magenta("Watching for changes...")}`);
		watchTargets.forEach((target) => require_print.print(`   ${require_colors.gray("•")} ${target.watchPath}`));
		require_print.print(`${require_colors.gray("Press Ctrl+C to stop")}`);
		require_print.print("");
	}
	const regenerate = createQueuedRegenerator({
		onStart: () => {
			if (!options.silent) require_print.print(`${require_colors.gray(`[${(/* @__PURE__ */ new Date()).toLocaleTimeString()}]`)} Change detected, regenerating...`);
		},
		regenerateOnce: async () => {
			await require_generate.generateSimpleModeCSS({
				workspaceDir: options.workspaceDir,
				entry,
				outFile: String(options.outFile),
				variants: context.variants,
				autoVariants: context.autoVariants,
				componentData: context.componentData,
				scope: options.scope,
				configPath,
				isWatch: true,
				silent: true
			});
		},
		onSuccess: () => {
			if (!options.silent) {
				require_print.print(`${require_colors.gray(`[${(/* @__PURE__ */ new Date()).toLocaleTimeString()}]`)} ${require_colors.green("CSS updated")}`);
				require_print.print("");
			}
		},
		onError: (message) => {
			require_print.print(`Error: ${message}`);
		}
	});
	watchSourceFiles(watchTargets, createDebouncedAction(() => {
		regenerate();
	}, 100));
	await new Promise(() => {});
};
const loadThemeModeSetup = async (options) => {
	const themeConfigInput = await require_nodeUtils.loadConfigFile(String(options.themeConfigPath));
	if (!themeConfigInput) return null;
	const themeContext = {
		cwd: options.workspaceDir,
		watch: options.watch
	};
	const themeConfig = typeof themeConfigInput === "function" ? await themeConfigInput(themeContext) : themeConfigInput;
	let appConfig = require_index.defaultTokensConfig;
	if (themeConfig.config) {
		const loadedConfig = await require_nodeUtils.loadConfigFile(themeConfig.config);
		if (loadedConfig) appConfig = loadedConfig;
	}
	return {
		themeConfig,
		colorModes: themeConfig.colorModes ?? ["dark"],
		entries: require_entryPoints.resolveEntryPaths(themeConfig.entry, options.workspaceDir),
		appConfig,
		appVariantDefaults: require_utils.extractVariantDefaults(appConfig),
		runtimeConfigValues: require_utils.extractRuntimeConfigValues(appConfig),
		effectiveSilent: options.silent || themeConfig.silent === true
	};
};
const runThemeMode = async (options, context) => {
	const workspaceDir = options.workspaceDir;
	const outputPath = resolveOutputPath(workspaceDir, String(options.outFile));
	let effectiveSilent = options.silent;
	let log = require_logger.createLogger({ silent: effectiveSilent });
	log.spinStart("Loading theme configuration...");
	try {
		const setup = await loadThemeModeSetup(options);
		if (!setup) {
			log.spinStop("❌", `Theme config not found: ${options.themeConfigPath}`);
			process.exitCode = 1;
			return;
		}
		const { themeConfig, colorModes, entries, appConfig, appVariantDefaults, runtimeConfigValues } = setup;
		effectiveSilent = setup.effectiveSilent;
		log = require_logger.createLogger({ silent: effectiveSilent });
		const entryDirs = entries.map((entry) => entry.absolutePath);
		if (!effectiveSilent) log.spinStop("✅", "Theme configuration loaded");
		if (themeConfig.config && appConfig === require_index.defaultTokensConfig) log.warn(`App config not found: ${themeConfig.config}, using defaults`);
		const packageDirs = [];
		const generateThemeModeCSS = async (opts) => {
			require_perf.clearTimings();
			require_perf.captureMemory("start");
			const genStartTime = performance.now();
			const genLog = opts?.isWatch ? require_logger.createLogger({ silent: true }) : log;
			const scopedCssOutputs = [];
			let pool;
			try {
				pool = await require_workerPool.createWorkerPool({
					variants: context.variants,
					autoVariants: context.autoVariants,
					componentData: context.componentData
				}, options.workers);
			} catch {}
			try {
				if (pool) genLog.spinStart(`Scanning app and packages... (${pool.workerCount} worker${pool.workerCount === 1 ? "" : "s"})`);
				else genLog.spinStart("Scanning app and packages... (sync mode)");
				const scopedPackageTargets = [];
				const processInheritedPackage = async (packageName) => {
					const packageDir = require_nodeUtils.findPackageSourceDir(packageName);
					if (!packageDir) return {
						packageName,
						status: "not-found"
					};
					if (!packageDirs.includes(packageDir)) packageDirs.push(packageDir);
					return {
						packageName,
						status: "ok",
						scanResult: await require_nodeUtils.scanDirectoryForSafelist(packageDir, colorModes, context.variants, context.autoVariants, context.componentData, appVariantDefaults, runtimeConfigValues, true, pool)
					};
				};
				const processScopedPackage = async (packageName, scopedPackageValue) => {
					const scopedPackageConfig = normalizeScopedPackageConfig(scopedPackageValue);
					const packageRoot = require_nodeUtils.findPackageRoot(packageName);
					const packageDir = require_nodeUtils.findPackageSourceDir(packageName);
					if (!packageRoot || !packageDir) return;
					const scopeClass = require_nodeUtils.getPackageUdsScope(packageName);
					if (!scopeClass) return;
					const entryDirs = resolveScopedEntryDirs(packageRoot, packageDir, scopedPackageConfig.entry);
					entryDirs.forEach((entryDir) => {
						if (!packageDirs.includes(entryDir)) packageDirs.push(entryDir);
					});
					scopedPackageTargets.push({
						packageName,
						packageRoot,
						packageDir,
						entryDirs,
						scopeClass,
						config: scopedPackageConfig
					});
				};
				const [appScanResult, inheritedResults] = await Promise.all([
					require_perf.measureAsync("scan", () => require_nodeUtils.scanDirectoriesForSafelist(entryDirs, colorModes, context.variants, context.autoVariants, context.componentData, appVariantDefaults, runtimeConfigValues, false, pool)),
					Promise.all((themeConfig.inherit ?? []).map((packageName) => require_perf.measureAsync(`scan:inherit:${packageName}`, () => processInheritedPackage(packageName)))),
					Promise.all(Object.entries(themeConfig.scoped ?? {}).map(([packageName, scopedPackageConfig]) => processScopedPackage(packageName, scopedPackageConfig)))
				]);
				genLog.spinStop("✅", require_runner_helpers.getScanSummaryMessage({
					label: "app",
					filesScanned: appScanResult.filesScanned,
					filesWithComponents: appScanResult.filesWithComponents,
					componentCount: appScanResult.components.length,
					mode: "app"
				}));
				if (options.verbose) printVerboseScanFiles(genLog, workspaceDir, appScanResult.filePaths);
				for (const result of inheritedResults) if (result.status === "not-found") genLog.spinStop("⚠️", `Package not found: ${result.packageName}`);
				else {
					genLog.spinStop("✅", require_runner_helpers.getScanSummaryMessage({
						label: result.packageName,
						filesScanned: result.scanResult.filesScanned,
						filesWithComponents: result.scanResult.filesWithComponents,
						componentCount: result.scanResult.components.length,
						mode: "inherit"
					}));
					if (options.verbose) printVerboseScanFiles(genLog, workspaceDir, result.scanResult.filePaths);
				}
				const inheritedClasses = [...appScanResult.safelist];
				const inheritedComponents = new Set(appScanResult.components);
				for (const result of inheritedResults) if (result.status === "ok") {
					inheritedClasses.push(...result.scanResult.safelist);
					result.scanResult.components.forEach((comp) => inheritedComponents.add(comp));
				}
				genLog.spinStart("Generating main CSS...");
				const mainSafelist = require_safelist.deduplicateSafelist([
					...inheritedClasses,
					...require_safelist.getThemeAndScaleClasses(colorModes),
					...require_safelist.getInternalSafelistClasses()
				]);
				const allMotionComponents = [...inheritedComponents];
				require_perf.captureMemory("before-gen");
				const mainCssResult = await require_perf.measureAsync("gen", () => require_generate.generateCSS([...themeConfig.css?.safelist ?? [], ...mainSafelist], appConfig, {
					scope: options.scope,
					contentDir: entryDirs,
					cssOptions: themeConfig.css,
					safeVarPrefixes: [
						...require_utils.getMotionVarPrefixes(context.componentData, allMotionComponents),
						...require_utils.getConfigurableCssVariables(),
						...require_generate_helpers.getPruneVarSafelist(themeConfig.css)
					]
				}));
				require_perf.captureMemory("after-gen");
				ensureOutputDirectory(outputPath);
				node_fs.default.writeFileSync(outputPath, mainCssResult.css);
				for (const scopedPackageTarget of scopedPackageTargets) {
					const packageConfig = await require_nodeUtils.loadConfigFile(isAbsolutePath(scopedPackageTarget.config.config) ? scopedPackageTarget.config.config : joinPath(scopedPackageTarget.packageRoot, scopedPackageTarget.config.config)) ?? require_index.defaultTokensConfig;
					const packageVariantDefaults = require_utils.extractVariantDefaults(packageConfig);
					const packageRuntimeConfigValues = require_utils.extractRuntimeConfigValues(packageConfig);
					const packageScanResult = await require_nodeUtils.scanDirectoriesForSafelist(scopedPackageTarget.entryDirs, colorModes, context.variants, context.autoVariants, context.componentData, packageVariantDefaults, packageRuntimeConfigValues, true, pool);
					genLog.spinStop("✅", require_runner_helpers.getScanSummaryMessage({
						label: scopedPackageTarget.packageName,
						filesScanned: packageScanResult.filesScanned,
						filesWithComponents: packageScanResult.filesWithComponents,
						componentCount: packageScanResult.components.length,
						mode: "scoped"
					}));
					if (options.verbose) printVerboseScanFiles(genLog, workspaceDir, packageScanResult.filePaths);
					const packageSafelist = require_safelist.deduplicateSafelist([
						...packageScanResult.safelist,
						...require_safelist.getThemeAndScaleClasses(colorModes),
						...require_safelist.getInternalSafelistClasses()
					]);
					const scopedCssResult = await require_generate.generateCSS([...themeConfig.css?.safelist ?? [], ...packageSafelist], packageConfig, {
						scope: scopedPackageTarget.scopeClass,
						contentDir: scopedPackageTarget.entryDirs,
						cssOptions: themeConfig.css,
						referenceCss: themeConfig.css?.optimization?.deduplicateScopedCss === false ? void 0 : mainCssResult.css,
						safeVarPrefixes: [
							...require_utils.getMotionVarPrefixes(context.componentData, [...packageScanResult.components]),
							...require_utils.getConfigurableCssVariables(),
							...require_generate_helpers.getPruneVarSafelist(themeConfig.css)
						]
					});
					const scopedOutputPath = resolveOutputPath(workspaceDir, getScopedPackageOutputPath(scopedPackageTarget.packageName, scopedPackageTarget.config.outFile));
					ensureOutputDirectory(scopedOutputPath);
					node_fs.default.writeFileSync(scopedOutputPath, scopedCssResult.css);
					scopedCssOutputs.push({
						label: scopedPackageTarget.packageName,
						outputPath: scopedOutputPath,
						sizeGzipBytes: scopedCssResult.sizeGzipBytes,
						optimizationStats: scopedCssResult.optimizationStats
					});
				}
				const mainCssSummary = require_runner_helpers.getMainCssSummaryMessage({
					sizeGzipBytes: mainCssResult.sizeGzipBytes,
					optimizationStats: mainCssResult.optimizationStats,
					formatBytes: require_utils.formatBytes
				});
				genLog.spinStop("✅", mainCssSummary.summaryLine);
				mainCssSummary.detailLines.forEach((detailLine) => {
					genLog.print(detailLine);
				});
				scopedCssOutputs.forEach((scopedCssOutput) => {
					const scopedCssSummary = require_runner_helpers.getScopedCssSummaryMessage(scopedCssOutput.label, {
						sizeGzipBytes: scopedCssOutput.sizeGzipBytes,
						optimizationStats: scopedCssOutput.optimizationStats,
						formatBytes: require_utils.formatBytes
					});
					genLog.spinStop("✅", scopedCssSummary.summaryLine);
					scopedCssSummary.detailLines.forEach((detailLine) => {
						genLog.print(detailLine);
					});
				});
				const duration = Math.round(performance.now() - genStartTime);
				const outputFileSection = require_runner_helpers.getOutputFileSection(workspaceDir, [outputPath, ...scopedCssOutputs.map((scopedCssOutput) => scopedCssOutput.outputPath)]);
				genLog.newline();
				genLog.print(outputFileSection.label);
				outputFileSection.paths.forEach((filePath) => {
					genLog.listItem(filePath);
				});
				genLog.newline();
				genLog.print(`${require_colors.magenta("Total time:")} ${require_runner_helpers.formatCssDuration(duration)}`);
				require_perf.printPerfSummary(duration);
				return {
					duration,
					outputPath,
					outputPaths: outputFileSection.paths,
					packageDirs
				};
			} finally {
				if (pool) await pool.destroy();
			}
		};
		await generateThemeModeCSS();
		if (options.watch) {
			const entryWatchTargets = getEntryWatchTargets(entries);
			const { filteredPackageDirs } = require_runner_helpers.getWatchDirectoryGroups(getWatchDirs(entryWatchTargets.map((target) => target.watchPath)), [...entryDirs, ...packageDirs]);
			if (!effectiveSilent) {
				log.newline();
				log.print(`${require_colors.magenta("Watching for changes...")}`);
				entryDirs.forEach((entryDir) => {
					log.listItem(`App: ${entryDir}`);
				});
				filteredPackageDirs.forEach((dir) => {
					log.listItem(`Package: ${dir}`);
				});
				log.print(`${require_colors.gray("Press Ctrl+C to stop")}`);
				log.newline();
			}
			const regenerate = createQueuedRegenerator({
				onStart: () => {
					if (!effectiveSilent) {
						const timestamp = (/* @__PURE__ */ new Date()).toLocaleTimeString();
						log.print(`${require_colors.gray(`[${timestamp}]`)} Change detected, regenerating...`);
					}
				},
				regenerateOnce: async () => generateThemeModeCSS({ isWatch: true }),
				onSuccess: (result) => {
					if (!effectiveSilent) {
						const updatedAt = (/* @__PURE__ */ new Date()).toLocaleTimeString();
						const updatedMessage = result?.duration == null ? "CSS updated" : `CSS updated (${require_runner_helpers.formatCssDuration(result.duration)})`;
						log.print(`${require_colors.gray(`[${updatedAt}]`)} ${require_colors.green(updatedMessage)}`);
						log.newline();
					}
				},
				onError: (message) => {
					log.print(message);
				}
			});
			const watchDebounce = themeConfig.css?.watchDebounce ?? 100;
			watchSourceFiles([...entryWatchTargets, ...filteredPackageDirs.filter((packageDir) => !entryWatchTargets.some((target) => isCoveredByRecursiveWatch(target.watchPath, packageDir))).map((watchPath) => ({
				watchPath,
				recursive: true
			}))], createDebouncedAction(() => {
				regenerate();
			}, watchDebounce));
			await new Promise(() => {});
		}
	} catch (error) {
		const message = error instanceof Error ? error.message : "CSS generation failed";
		if (effectiveSilent) require_spinner.spinStop("❌", message);
		else log.spinStop("❌", message);
		process.exitCode = 1;
	}
};
//#endregion
exports.runCssCommand = runCssCommand;
