/*! © 2026 Yahoo, Inc. UDS Tailwind and Purger v0.0.0-development */
import { cyan, magenta, yellow } from "../cli/dist/lib/colors.js";
import { print } from "../cli/dist/lib/print.js";
import { spinStop } from "../cli/dist/lib/spinner.js";
import { resolveEntryPaths } from "../utils/entryPoints.js";
import { loadConfigFile, scanDirectoriesForSafelist } from "./nodeUtils.js";
import { defaultTokensConfig } from "../config/dist/index.js";
import { deduplicateSafelist, getThemeAndScaleClasses } from "../purger/optimized/utils/safelist.js";
import { extractVariantDefaults, getConfigurableCssVariables, getMotionVarPrefixes } from "./utils.js";
import { applyScopedColorModeFix, buildPostcssPlugins, createTailwindPlugin, getCssFeatureFlags, optimizeGeneratedCss, printSimpleModeStats } from "./generate.helpers.js";
import fs from "node:fs";
import path from "node:path";
import { gzipSync } from "node:zlib";
import postcss from "postcss";

//#region src/css/generate.ts
const normalizeScope = (scope) => {
	const trimmedScope = scope?.trim();
	return trimmedScope ? trimmedScope : void 0;
};
const getArbitrarySafelistRawContent = (safelist) => {
	const arbitraryClasses = safelist.filter((entry) => typeof entry === "string" && entry.includes("["));
	if (arbitraryClasses.length === 0) return [];
	return [`<div class="${arbitraryClasses.join(" ")}"></div>`];
};
/**
* Generate CSS from a safelist using Tailwind + PostCSS
* @param safelist - UDS component classes to include
* @param config - Token configuration
* @param options - Additional options
*/
const generateCSS = async (safelist, config, options) => {
	const sourceCSS = "@tailwind base; @tailwind components; @tailwind utilities";
	const contentDir = options?.contentDir ?? path.join(process.cwd(), "src");
	const cssFlags = getCssFeatureFlags(options?.cssOptions);
	const optimizationConfig = options?.cssOptions?.optimization;
	const scopeClass = normalizeScope(options?.scope) ?? normalizeScope(options?.cssOptions?.scope);
	let css = await applyScopedColorModeFix((await postcss(buildPostcssPlugins({
		tailwindPlugin: createTailwindPlugin({
			contentDir,
			rawContents: getArbitrarySafelistRawContent(safelist),
			safelist,
			config,
			enablePreflight: cssFlags.enablePreflight,
			enableFontFaceDeclarations: cssFlags.enableFontFaceDeclarations
		}),
		shouldPruneVars: cssFlags.shouldPruneVars,
		safeVarPrefixes: options?.safeVarPrefixes ?? [],
		scopeClass
	})).process(sourceCSS, { from: void 0 })).css, scopeClass);
	const optimizedCss = await optimizeGeneratedCss({
		css,
		shouldOptimize: cssFlags.shouldOptimize,
		optimizationConfig,
		referenceCss: options?.referenceCss,
		scopeClass
	});
	css = optimizedCss.css;
	const sizeBytes = Buffer.byteLength(css, "utf8");
	const sizeGzipBytes = gzipSync(css).length;
	return {
		css,
		sizeBytes,
		sizeGzipBytes,
		classCount: safelist.length,
		optimizationStats: optimizedCss.optimizationStats
	};
};
/**
* Generate CSS in simple mode (no uds.theme.ts)
*/
const generateSimpleModeCSS = async (options) => {
	const isWatch = options.isWatch === true;
	const shouldLogStats = !(options.silent === true) && !isWatch;
	const startTime = performance.now();
	const colorModes = ["dark"];
	let tokensConfig = defaultTokensConfig;
	if (options.configPath) {
		const loadedConfig = await loadConfigFile(options.configPath);
		if (loadedConfig) tokensConfig = loadedConfig;
		else if (shouldLogStats) spinStop("⚠️", `Config file not found: ${options.configPath}, using defaults`);
	}
	const variantDefaults = extractVariantDefaults(tokensConfig);
	const resolvedEntries = resolveEntryPaths(options.entry, options.workspaceDir);
	const entryDirs = resolvedEntries.map((entry) => entry.absolutePath);
	const scanResult = await scanDirectoriesForSafelist(entryDirs, colorModes, options.variants, options.autoVariants, options.componentData, variantDefaults);
	const totalFilesScanned = scanResult.filesScanned;
	const allClasses = [...scanResult.safelist];
	const allComponents = new Set(scanResult.components);
	const packageDirs = [...new Set(resolvedEntries.map((entry) => entry.kind === "directory" ? entry.absolutePath : entry.watchDirectory))];
	const cssResult = await generateCSS(deduplicateSafelist([...allClasses, ...getThemeAndScaleClasses(colorModes)]), tokensConfig, {
		scope: options.scope,
		contentDir: entryDirs,
		safeVarPrefixes: [...getMotionVarPrefixes(options.componentData, [...allComponents]), ...getConfigurableCssVariables()]
	});
	const outputPath = path.isAbsolute(options.outFile) ? options.outFile : path.join(options.workspaceDir, options.outFile);
	const outputDir = path.dirname(outputPath);
	if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir, { recursive: true });
	fs.writeFileSync(outputPath, cssResult.css);
	const duration = Math.round(performance.now() - startTime);
	if (shouldLogStats) printSimpleModeStats({
		outputPath,
		totalFilesScanned,
		classCount: cssResult.classCount,
		sizeBytes: cssResult.sizeBytes,
		sizeGzipBytes: cssResult.sizeGzipBytes,
		duration,
		scope: options.scope,
		optimizationStats: cssResult.optimizationStats,
		print,
		magenta,
		cyan,
		yellow
	});
	return {
		success: true,
		outputPath,
		packageDirs
	};
};

//#endregion
export { generateCSS, generateSimpleModeCSS };
//# sourceMappingURL=generate.js.map