/*! © 2026 Yahoo, Inc. UDS Tailwind and Purger v0.0.0-development */
const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
const require_colors = require('../cli/dist/lib/colors.cjs');
const require_print = require('../cli/dist/lib/print.cjs');
const require_spinner = require('../cli/dist/lib/spinner.cjs');
const require_logger = require('../cli/dist/lib/logger.cjs');
const require_entryPoints = require('../utils/entryPoints.cjs');
const require_nodeUtils = require('./nodeUtils.cjs');
const require_index = require('../config/dist/index.cjs');
const require_safelist = require('../purger/optimized/utils/safelist.cjs');
const require_utils = require('./utils.cjs');
const require_generate_helpers = require('./generate.helpers.cjs');
const require_generate = require('./generate.cjs');
const require_runner_helpers = require('./runner.helpers.cjs');
let node_fs = require("node:fs");
node_fs = require_runtime.__toESM(node_fs);
let node_path = require("node:path");
node_path = require_runtime.__toESM(node_path);

//#region src/css/runner.ts
const SOURCE_FILE_PATTERN = /\.(jsx?|tsx?)$/i;
const getWatchDirs = (dirs) => [...new Set(dirs.filter((dir) => !dir.split(node_path.default.sep).includes("node_modules")))];
const isCoveredByRecursiveWatch = (watchPath, targetPath) => targetPath === watchPath || targetPath.startsWith(`${watchPath}${node_path.default.sep}`);
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(node_path.default.basename(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 runCssCommand = async (options, context) => {
	if (!node_fs.default.existsSync(node_path.default.join(options.workspaceDir, String(options.themeConfigPath)))) {
		await runSimpleMode(options, context);
		return;
	}
	await runThemeMode(options, context);
};
const runSimpleMode = async (options, context) => {
	const entry = options.entryOption ?? require_entryPoints.DEFAULT_ENTRY;
	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
		});
		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),
		effectiveSilent: options.silent || themeConfig.silent === true
	};
};
const runThemeMode = async (options, context) => {
	const workspaceDir = options.workspaceDir;
	const outputPath = node_path.default.isAbsolute(options.outFile) ? options.outFile : node_path.default.join(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 } = 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) => {
			const genStartTime = performance.now();
			const genLog = opts?.isWatch ? require_logger.createLogger({ silent: true }) : log;
			genLog.spinStart("Scanning app code...");
			const appScanResult = await require_nodeUtils.scanDirectoriesForSafelist(entryDirs, colorModes, context.variants, context.autoVariants, context.componentData, appVariantDefaults);
			genLog.spinStop("✅", `Scanned ${appScanResult.filesScanned} files`);
			genLog.spinStart("Generating main CSS...");
			const inheritedClasses = [...appScanResult.safelist];
			const inheritedComponents = new Set(appScanResult.components);
			const processInheritedPackage = async (packageName) => {
				genLog.spinStart(`Processing package: ${packageName}...`);
				const packageDir = require_nodeUtils.findPackageSourceDir(packageName);
				if (!packageDir) {
					genLog.spinStop("⚠️", `Package not found: ${packageName}`);
					return;
				}
				if (!packageDirs.includes(packageDir)) packageDirs.push(packageDir);
				const packageScanResult = await require_nodeUtils.scanDirectoryForSafelist(packageDir, colorModes, context.variants, context.autoVariants, context.componentData, appVariantDefaults, true);
				inheritedClasses.push(...packageScanResult.safelist);
				packageScanResult.components.forEach((comp) => inheritedComponents.add(comp));
				genLog.spinStop("✅", `${packageName}: ${packageScanResult.filesScanned} files (inherit)`);
			};
			await (themeConfig.inherit ?? []).reduce(async (promise, packageName) => {
				await promise;
				await processInheritedPackage(packageName);
			}, Promise.resolve());
			const mainSafelist = require_safelist.deduplicateSafelist([...inheritedClasses, ...require_safelist.getThemeAndScaleClasses(colorModes)]);
			const allMotionComponents = [...inheritedComponents];
			const mainCssResult = await 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)
				]
			});
			const outputDir = node_path.default.dirname(outputPath);
			if (!node_fs.default.existsSync(outputDir)) node_fs.default.mkdirSync(outputDir, { recursive: true });
			node_fs.default.writeFileSync(outputPath, mainCssResult.css);
			genLog.spinStop("✅", require_runner_helpers.getMainCssSummaryMessage({
				sizeGzipBytes: mainCssResult.sizeGzipBytes,
				optimizationStats: mainCssResult.optimizationStats,
				formatBytes: require_utils.formatBytes
			}));
			const duration = Math.round(performance.now() - genStartTime);
			genLog.newline();
			genLog.print(require_colors.green("CSS generation complete!"));
			genLog.newline();
			genLog.label("Output file:", outputPath);
			genLog.newline();
			genLog.print(`${require_colors.magenta("Total time:")} ${duration}ms`);
			return {
				duration,
				outputPath,
				packageDirs
			};
		};
		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();
						log.print(`${require_colors.gray(`[${updatedAt}]`)} ${require_colors.green(`CSS updated (${result?.duration}ms)`)}`);
						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;