/*! © 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_purgeFromCode = require("../purger/optimized/purgeFromCode.cjs");
const require_entryPoints = require("../../../tailwind-internal/dist/utils/entryPoints.cjs");
let node_path = require("node:path");
node_path = require_runtime.__toESM(node_path, 1);
let node_fs = require("node:fs");
node_fs = require_runtime.__toESM(node_fs, 1);
let node_module = require("node:module");
let fast_glob = require("fast-glob");
fast_glob = require_runtime.__toESM(fast_glob, 1);
//#region ../css/dist/css/nodeUtils.mjs
/*! © 2026 Yahoo, Inc. UDS CSS v0.0.0-development */
const loadConfigFile = async (configPath) => {
	const absolutePath = node_path.default.isAbsolute(configPath) ? configPath : node_path.default.join(process.cwd(), configPath);
	if (!node_fs.default.existsSync(absolutePath)) return null;
	try {
		const module = await import(absolutePath);
		return module.default ?? module.config ?? module;
	} catch (error) {
		throw new Error(`Failed to load config file: ${absolutePath}\n${error instanceof Error ? error.message : "Unknown error"}`);
	}
};
const scanDirectoryForSafelist = async (dir, colorModes, variants, autoVariants, componentData, variantDefaults, runtimeConfigValues, includeAllClassNamePrimitives = false, pool) => {
	const files = await require_perf.measureAsync("scan:glob", () => (0, fast_glob.default)("**/*.{js,jsx,mjs,cjs,ts,tsx}", {
		cwd: dir,
		absolute: true,
		ignore: ["**/node_modules/**"]
	}).then((f) => f.sort((left, right) => left.localeCompare(right))));
	const processFile = (filePath) => {
		const code = node_fs.default.readFileSync(filePath, "utf-8");
		if (pool) return pool.processFile({
			code,
			filePath,
			colorModes,
			variantDefaults,
			runtimeConfigValues,
			includeAllClassNamePrimitives
		});
		return require_purgeFromCode.purgeFromCodeOptimized(code, {
			colorModes,
			variantDefaults,
			runtimeConfigValues,
			variants,
			autoVariants,
			componentData,
			includeAllClassNamePrimitives,
			filePath
		});
	};
	const results = await require_perf.measureAsync("scan:purge-all-files", () => Promise.all(files.map(processFile)));
	const allClasses = results.flatMap((result) => result.safelist);
	const allComponents = new Set(results.flatMap((result) => result.components));
	const filesWithComponents = results.filter((result) => result.components.length > 0).length;
	return {
		safelist: allClasses,
		components: [...allComponents],
		filesScanned: files.length,
		filesWithComponents,
		filePaths: files
	};
};
const scanFileForSafelist = async (filePath, colorModes, variants, autoVariants, componentData, variantDefaults, runtimeConfigValues, includeAllClassNamePrimitives = false) => {
	const result = await require_purgeFromCode.purgeFromCodeOptimized(node_fs.default.readFileSync(filePath, "utf-8"), {
		colorModes,
		variantDefaults,
		runtimeConfigValues,
		variants,
		autoVariants,
		componentData,
		includeAllClassNamePrimitives
	});
	return {
		safelist: result.safelist,
		components: result.components,
		filesScanned: 1,
		filesWithComponents: result.components.length > 0 ? 1 : 0,
		filePaths: [filePath]
	};
};
const scanDirectoriesForSafelist = async (dirs, colorModes, variants, autoVariants, componentData, variantDefaults, runtimeConfigValues, includeAllClassNamePrimitives = false, pool) => {
	const results = await Promise.all(dirs.map((dir) => {
		if (node_fs.default.existsSync(dir) && node_fs.default.statSync(dir).isFile()) return scanFileForSafelist(dir, colorModes, variants, autoVariants, componentData, variantDefaults, runtimeConfigValues, includeAllClassNamePrimitives);
		return scanDirectoryForSafelist(dir, colorModes, variants, autoVariants, componentData, variantDefaults, runtimeConfigValues, includeAllClassNamePrimitives, pool);
	}));
	return {
		safelist: results.flatMap((result) => result.safelist),
		components: [...new Set(results.flatMap((result) => result.components))],
		filesScanned: results.reduce((total, result) => total + result.filesScanned, 0),
		filesWithComponents: results.reduce((total, result) => total + result.filesWithComponents, 0),
		filePaths: results.flatMap((result) => result.filePaths).sort((left, right) => left.localeCompare(right))
	};
};
const findMonorepoRoot = (startDir) => {
	const findUp = (currentDir) => {
		if (node_fs.default.existsSync(node_path.default.join(currentDir, "packages"))) return currentDir;
		const parentDir = node_path.default.dirname(currentDir);
		return parentDir === currentDir ? null : findUp(parentDir);
	};
	return findUp(startDir);
};
const readPackageName = (packageJsonPath) => {
	try {
		const pkgJson = JSON.parse(node_fs.default.readFileSync(packageJsonPath, "utf8"));
		return typeof pkgJson.name === "string" ? pkgJson.name : null;
	} catch {
		return null;
	}
};
const findPackageRootFromResolvedEntry = (resolvedEntryPath, packageName) => {
	let currentPath = node_fs.default.statSync(resolvedEntryPath).isDirectory() ? resolvedEntryPath : node_path.default.dirname(resolvedEntryPath);
	while (true) {
		const packageJsonPath = node_path.default.join(currentPath, "package.json");
		if (node_fs.default.existsSync(packageJsonPath) && readPackageName(packageJsonPath) === packageName) return currentPath;
		const parentPath = node_path.default.dirname(currentPath);
		if (parentPath === currentPath) return null;
		currentPath = parentPath;
	}
};
const findPackageRootInNodeModules = (startDir, packageName) => {
	let currentDir = startDir;
	while (true) {
		const packageJsonPath = node_path.default.join(currentDir, "node_modules", packageName, "package.json");
		if (node_fs.default.existsSync(packageJsonPath)) return node_path.default.dirname(packageJsonPath);
		const parentDir = node_path.default.dirname(currentDir);
		if (parentDir === currentDir) return null;
		currentDir = parentDir;
	}
};
const resolvePackageRoot = (workspaceDir, packageName) => {
	const requireFromWorkspace = (0, node_module.createRequire)(node_path.default.join(workspaceDir, "package.json"));
	try {
		const resolvedPackageJson = requireFromWorkspace.resolve(node_path.default.join(packageName, "package.json"));
		return node_path.default.dirname(resolvedPackageJson);
	} catch {
		try {
			const packageRoot = findPackageRootFromResolvedEntry(requireFromWorkspace.resolve(packageName), packageName);
			if (packageRoot) return packageRoot;
		} catch {}
		return findPackageRootInNodeModules(workspaceDir, packageName);
	}
};
const findPackageRootInMonorepo = (monorepoRoot, packageName) => {
	const matchingPath = fast_glob.default.sync("packages/**/package.json", {
		cwd: monorepoRoot,
		absolute: true,
		ignore: ["**/node_modules/**", "**/dist/**"]
	}).find((pkgJsonPath) => {
		return readPackageName(pkgJsonPath) === packageName;
	});
	return matchingPath ? node_path.default.dirname(matchingPath) : null;
};
const findPackageRoot = (packageName) => {
	const workspaceDir = process.cwd();
	const monorepoRoot = findMonorepoRoot(workspaceDir);
	let packageRoot = resolvePackageRoot(workspaceDir, packageName);
	if (!packageRoot && monorepoRoot) packageRoot = findPackageRootInMonorepo(monorepoRoot, packageName);
	return packageRoot;
};
const buildPackageSourceCandidates = (workspaceDir, packageName, packageRoot) => {
	return [
		packageRoot ? node_path.default.join(packageRoot, "src") : null,
		packageRoot ? node_path.default.join(packageRoot, "lib") : null,
		packageRoot ? node_path.default.join(packageRoot, "dist") : null,
		packageRoot,
		node_path.default.join(workspaceDir, "node_modules", packageName, "src"),
		node_path.default.join(workspaceDir, "node_modules", packageName, "lib"),
		node_path.default.join(workspaceDir, "node_modules", packageName, "dist"),
		node_path.default.join(workspaceDir, "node_modules", packageName)
	].filter(Boolean);
};
const getFirstExistingPath = (candidates) => candidates.find((candidate) => node_fs.default.existsSync(candidate)) ?? null;
const findPackageSourceDir = (packageName) => {
	return getFirstExistingPath(buildPackageSourceCandidates(process.cwd(), packageName, findPackageRoot(packageName)));
};
const getPackageUdsScope = (packageName) => {
	const packageRoot = findPackageRoot(packageName);
	if (!packageRoot) return null;
	const packageJsonPath = node_path.default.join(packageRoot, "package.json");
	if (!node_fs.default.existsSync(packageJsonPath)) return null;
	try {
		const scope = JSON.parse(node_fs.default.readFileSync(packageJsonPath, "utf8")).uds?.scope;
		return typeof scope === "string" && scope.trim().length > 0 ? scope.trim() : null;
	} catch {
		return null;
	}
};
const scaffoldThemeConfig = async (options) => {
	const workspaceDir = process.cwd();
	const outputPath = options.outputPath ?? "uds.theme.ts";
	const absoluteOutputPath = node_path.default.isAbsolute(outputPath) ? outputPath : node_path.default.join(workspaceDir, outputPath);
	if (node_fs.default.existsSync(absoluteOutputPath) && !options.force) {
		require_print.print(require_colors.red(`Error: ${outputPath} already exists. Use --force to overwrite.`));
		process.exitCode = 1;
		return;
	}
	const template = `import { defineTheme } from '@yahoo/uds';

/**
 * UDS Theme Configuration
 * 
 * This file configures CSS generation for your app and shared packages.
 * Run \`uds css\` to generate optimized CSS.
 */
export default defineTheme({
  // Path to your uds.config.ts file
  config: '${options.configPath ?? "./uds.config.ts"}',

  // Entry directory or .tsx file path for scanning your app code
  entry: ${require_entryPoints.formatEntryValue(options.entry ?? "./src")},

  // Color modes to include (light mode is always in :root)
  colorModes: ['dark'],

  // Packages that inherit your app's theme (merged into main uds.css)
  // inherit: ['@your-org/shared-ui'],

  // Packages that generate separate scoped CSS outputs.
  // Scope class is discovered from each package.json uds.scope.
  // When entry is omitted, the package is scanned the same way as inherit.
  // scoped: {
  //   '@your-org/shared-ui': './packages/shared-ui/uds.config.ts'
  // }
  //
  // Or use the expanded form for custom output paths:
  // scoped: {
  //   '@your-org/shared-ui': {
  //     config: './packages/shared-ui/uds.config.ts',
  //     entry: './src',
  //     // outFile defaults to dist/shared-ui.css
  //     outFile: 'dist/shared-ui.css'
  //   },
  // },

  // CSS generation options (all optional)
  // css: {
  //   safelist: [],
  //   preflight: true,
  //   fontFaceDeclarations: true,
  //   optimization: {
  //     removeUnusedFonts: false,
  //     removeEmptyRules: true,
  //     deduplicateScopedCss: true
  //   }
  // }
});
`;
	node_fs.default.writeFileSync(absoluteOutputPath, template);
	require_print.print("");
	require_print.print(require_colors.green("✅ Created uds.theme.ts"));
	require_print.print("");
	require_print.print(`${require_colors.magenta("Next steps:")}`);
	require_print.print(`   1. Review and customize ${require_colors.cyan(outputPath)}`);
	require_print.print(`   2. Run ${require_colors.cyan("uds css")} to generate CSS`);
	require_print.print("");
};
//#endregion
exports.findPackageRoot = findPackageRoot;
exports.findPackageSourceDir = findPackageSourceDir;
exports.getPackageUdsScope = getPackageUdsScope;
exports.loadConfigFile = loadConfigFile;
exports.scaffoldThemeConfig = scaffoldThemeConfig;
exports.scanDirectoriesForSafelist = scanDirectoriesForSafelist;
exports.scanDirectoryForSafelist = scanDirectoryForSafelist;
