/*! © 2026 Yahoo, Inc. UDS Tailwind and Purger v0.0.0-development */
import { cyan, green, magenta, red } from "../cli/dist/lib/colors.js";
import { print } from "../cli/dist/lib/print.js";
import { purgeFromCodeOptimized } from "../purger/optimized/purgeFromCode.js";
import { formatEntryValue } from "../utils/entryPoints.js";
import fs from "node:fs";
import { createRequire } from "node:module";
import path from "node:path";
import fg from "fast-glob";

//#region src/css/nodeUtils.ts
const loadConfigFile = async (configPath) => {
	const absolutePath = path.isAbsolute(configPath) ? configPath : path.join(process.cwd(), configPath);
	if (!fs.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 fg("**/*.{js,jsx,ts,tsx}", {
		cwd: dir,
		absolute: true,
		ignore: ["**/node_modules/**"]
	});
	const results = await Promise.all(files.map(async (filePath) => {
		return purgeFromCodeOptimized(fs.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 purgeFromCodeOptimized(fs.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 (fs.existsSync(dir) && fs.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 (fs.existsSync(path.join(currentDir, "packages"))) return currentDir;
		const parentDir = path.dirname(currentDir);
		return parentDir === currentDir ? null : findUp(parentDir);
	};
	return findUp(startDir);
};
const resolvePackageRoot = (workspaceDir, packageName) => {
	const require = createRequire(import.meta.url);
	try {
		const resolvedPackageJson = require.resolve(path.join(packageName, "package.json"), { paths: [workspaceDir] });
		return path.dirname(resolvedPackageJson);
	} catch {
		return null;
	}
};
const findPackageRootInMonorepo = (monorepoRoot, packageName) => {
	const matchingPath = fg.sync("packages/**/package.json", {
		cwd: monorepoRoot,
		absolute: true,
		ignore: ["**/node_modules/**", "**/dist/**"]
	}).find((pkgJsonPath) => {
		try {
			return JSON.parse(fs.readFileSync(pkgJsonPath, "utf8")).name === packageName;
		} catch {
			return false;
		}
	});
	return matchingPath ? path.dirname(matchingPath) : null;
};
const buildPackageSourceCandidates = (workspaceDir, packageName, packageRoot) => {
	return [
		packageRoot ? path.join(packageRoot, "src") : null,
		packageRoot ? path.join(packageRoot, "lib") : null,
		packageRoot ? path.join(packageRoot, "dist") : null,
		packageRoot,
		path.join(workspaceDir, "node_modules", packageName, "src"),
		path.join(workspaceDir, "node_modules", packageName, "lib"),
		path.join(workspaceDir, "node_modules", packageName, "dist"),
		path.join(workspaceDir, "node_modules", packageName)
	].filter(Boolean);
};
const getFirstExistingPath = (candidates) => candidates.find((candidate) => fs.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 = path.isAbsolute(outputPath) ? outputPath : path.join(workspaceDir, outputPath);
	if (fs.existsSync(absoluteOutputPath) && !options.force) {
		print(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: ${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
  //   }
  // }
});
`;
	fs.writeFileSync(absoluteOutputPath, template);
	print("");
	print(green("✅ Created uds.theme.ts"));
	print("");
	print(`${magenta("Next steps:")}`);
	print(`   1. Review and customize ${cyan(outputPath)}`);
	print(`   2. Run ${cyan("uds css")} to generate CSS`);
	print("");
};

//#endregion
export { findPackageSourceDir, loadConfigFile, scaffoldThemeConfig, scanDirectoriesForSafelist, scanDirectoryForSafelist };
//# sourceMappingURL=nodeUtils.js.map