/*! © 2026 Yahoo, Inc. UDS v0.0.0-development */
import { cpus } from "node:os";
import { Worker } from "node:worker_threads";
//#region ../css/dist/css/workerPool.mjs
/*! © 2026 Yahoo, Inc. UDS CSS v0.0.0-development */
const createWorkerPool = async (config, numWorkers) => {
	const workerCount = numWorkers ?? Math.max(1, cpus().length - 1);
	const workerUrl = new URL("./purgeWorker.js", import.meta.url);
	const workers = [];
	const available = [];
	const pending = /* @__PURE__ */ new Map();
	const queue = [];
	let nextId = 0;
	await Promise.all(Array.from({ length: workerCount }, () => {
		return new Promise((resolve, reject) => {
			const worker = new Worker(workerUrl);
			let initialized = false;
			worker.on("message", (msg) => {
				if (msg.type === "ready") {
					initialized = true;
					workers.push(worker);
					available.push(worker);
					resolve();
					return;
				}
				if (msg.type === "result" || msg.type === "error") {
					const task = msg.id != null ? pending.get(msg.id) : void 0;
					if (task) {
						pending.delete(msg.id);
						if (msg.type === "result") task.resolve(msg.result);
						else task.reject(new Error(msg.error ?? "Unknown worker error"));
					}
					available.push(worker);
					if (queue.length > 0 && available.length > 0) {
						const next = queue.shift();
						const nextWorker = available.pop();
						pending.set(next.msg.id, next.task);
						nextWorker.postMessage(next.msg);
					}
				}
			});
			worker.on("error", (err) => {
				if (!initialized) reject(err);
			});
			worker.postMessage({
				type: "init",
				config: JSON.parse(JSON.stringify(config))
			});
		});
	}));
	const processFile = (options) => {
		return new Promise((resolve, reject) => {
			const id = nextId++;
			const msg = {
				type: "task",
				id,
				code: options.code,
				filePath: options.filePath,
				colorModes: options.colorModes,
				variantDefaults: options.variantDefaults,
				runtimeConfigValues: options.runtimeConfigValues,
				includeAllClassNamePrimitives: options.includeAllClassNamePrimitives
			};
			const task = {
				resolve,
				reject
			};
			if (available.length > 0) {
				const worker = available.pop();
				pending.set(id, task);
				worker.postMessage(msg);
			} else queue.push({
				msg,
				task
			});
		});
	};
	const destroy = async () => {
		for (const worker of workers) worker.postMessage({ type: "done" });
		await Promise.all(workers.map((w) => new Promise((res) => w.on("exit", () => res()))));
	};
	return {
		processFile,
		destroy,
		workerCount
	};
};
//#endregion
export { createWorkerPool };
