/*! © 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_purgeFromCode = require('../purger/optimized/purgeFromCode.cjs');
const require_entryPoints = require('../utils/entryPoints.cjs');
let node_fs = require("node:fs");
node_fs = require_runtime.__toESM(node_fs);
let node_module = require("node:module");
let node_path = require("node:path");
node_path = require_runtime.__toESM(node_path);
let fast_glob = require("fast-glob");
fast_glob = require_runtime.__toESM(fast_glob);

//#region src/css/nodeUtils.ts
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, includeAllClassNamePrimitives = false) => {
	const files = await (0, fast_glob.default)("**/*.{js,jsx,ts,tsx}", {
		cwd: dir,
		absolute: true,
		ignore: ["**/node_modules/**"]
	});
	const results = await Promise.all(files.map(async (filePath) => {
		return require_purgeFromCode.purgeFromCodeOptimized(node_fs.default.readFileSync(filePath, "utf-8"), {
			colorModes,
			variantDefaults,
			variants,
			autoVariants,
			componentData,
			includeAllClassNamePrimitives,
			filePath
		});
	}));
	return {
		safelist: results.flatMap((result) => result.safelist),
		components: [...new Set(results.flatMap((result) => result.components))],
		filesScanned: files.length
	};
};
const scanFileForSafelist = async (filePath, colorModes, variants, autoVariants, componentData, variantDefaults, includeAllClassNamePrimitives = false) => {
	const result = await require_purgeFromCode.purgeFromCodeOptimized(node_fs.default.readFileSync(filePath, "utf-8"), {
		colorModes,
		variantDefaults,
		variants,
		autoVariants,
		componentData,
		includeAllClassNamePrimitives
	});
	return {
		safelist: result.safelist,
		components: result.components,
		filesScanned: 1
	};
};
const scanDirectoriesForSafelist = async (dirs, colorModes, variants, autoVariants, componentData, variantDefaults, includeAllClassNamePrimitives = false) => {
	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, includeAllClassNamePrimitives);
		return scanDirectoryForSafelist(dir, colorModes, variants, autoVariants, componentData, variantDefaults, includeAllClassNamePrimitives);
	}));
	return {
		safelist: results.flatMap((result) => result.safelist),
		components: [...new Set(results.flatMap((result) => result.components))],
		filesScanned: results.reduce((total, result) => total + result.filesScanned, 0)
	};
};
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 resolvePackageRoot = (workspaceDir, packageName) => {
	const require = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href);
	try {
		const resolvedPackageJson = require.resolve(node_path.default.join(packageName, "package.json"), { paths: [workspaceDir] });
		return node_path.default.dirname(resolvedPackageJson);
	} catch {
		return null;
	}
};
const findPackageRootInMonorepo = (monorepoRoot, packageName) => {
	const matchingPath = fast_glob.default.sync("packages/**/package.json", {
		cwd: monorepoRoot,
		absolute: true,
		ignore: ["**/node_modules/**", "**/dist/**"]
	}).find((pkgJsonPath) => {
		try {
			return JSON.parse(node_fs.default.readFileSync(pkgJsonPath, "utf8")).name === packageName;
		} catch {
			return false;
		}
	});
	return matchingPath ? node_path.default.dirname(matchingPath) : null;
};
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) => {
	const workspaceDir = process.cwd();
	const monorepoRoot = findMonorepoRoot(workspaceDir);
	let packageRoot = resolvePackageRoot(workspaceDir, packageName);
	if (!packageRoot && monorepoRoot) packageRoot = findPackageRootInMonorepo(monorepoRoot, packageName);
	return getFirstExistingPath(buildPackageSourceCandidates(workspaceDir, packageName, packageRoot));
};
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'],

  // 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.findPackageSourceDir = findPackageSourceDir;
exports.loadConfigFile = loadConfigFile;
exports.scaffoldThemeConfig = scaffoldThemeConfig;
exports.scanDirectoriesForSafelist = scanDirectoriesForSafelist;
exports.scanDirectoryForSafelist = scanDirectoryForSafelist;