import { isNode as e } from "../../constants/vite.constants.mjs";
import { stealthAddressCacheDevice as t, stealthPairCacheDevice as n } from "../crypto-keys/keys.mjs";
import { Utxo as r } from "../utxo/Utxo.mjs";
import { WorkerVariant as i } from "../../webworker/worker.registry.mjs";
import { performTaskWithWorker as a } from "../../webworker/performTaskWithWorker.mjs";
import { UtxoWorkerActionType as o } from "../../webworker/utxoWorker/utxoWorker.types.mjs";
//#region libs/shared/common/src/data-structures/MultiThreadedUtxoUtils/MultiThreadedUtxoUtils.ts
var s = 16, c = class {
	NUM_WORKERS;
	NUM_WORKERS_BATCH_PROCESS;
	constructor() {
		e ? (this.NUM_WORKERS = 1, this.NUM_WORKERS_BATCH_PROCESS = 1) : (this.NUM_WORKERS = 3, this.NUM_WORKERS_BATCH_PROCESS = Math.min(s, Math.ceil(navigator.deviceMemory ?? 4)));
	}
	async createUtxoPromise(e) {
		return await a({
			type: i.UTXO,
			payload: e
		});
	}
	async batchFilterUtxosWithNullifier(e, i) {
		let a = this.sliceArrayIntoParts(e, this.NUM_WORKERS).map((e) => this.createUtxoPromise({
			type: o.BATCH_FILTER_UTXOS_WITH_NULLIFIER,
			data: {
				utxos: e.map((e) => e.getConstructableParams()),
				nullifiers: i
			}
		})), s = await Promise.all(a);
		return s.forEach((e) => {
			n.mergeWithSerialized(e.stealthPairCache), t.mergeWithSerialized(e.stealthAddressCache);
		}), s.flatMap((e) => e.utxoConstructors).map((e) => new r(e));
	}
	async buildBatchProcess(e, t, n) {
		let i = this.sliceArrayIntoParts(e, this.NUM_WORKERS).map((e) => this.createUtxoPromise({
			type: o.BUILD_UTXOS,
			data: {
				signature: t.getSignature(),
				encryptedOutputs: e,
				chainId: n
			}
		}));
		return (await Promise.all(i)).flat().map((e) => new r(e));
	}
	sliceArrayIntoParts(e, t) {
		let n = Math.ceil(e.length / t);
		return Array.from({ length: t }, (t, r) => e.slice(n * r, n * (r + 1))).filter((e) => e.length > 0);
	}
	findLastOutput(e, t) {
		let n = t;
		return e.forEach((e) => {
			e !== t && (n = e);
		}), n;
	}
	async batchProcess(e, t, n, r) {
		let i = this.sliceArrayIntoParts(e, this.NUM_WORKERS_BATCH_PROCESS), a = n.getSignature(), s = i.map((e) => {
			let n = {
				type: o.DECIPHER_OUTPUTS,
				data: {
					encryptedOutputs: e,
					lastOutput: t,
					signature: a,
					chainId: r
				}
			};
			return this.createUtxoPromise(n);
		}), c = await Promise.all(s), l = c.map(({ additionalEncryptedOutputs: e }) => e).flat(), u = /* @__PURE__ */ new Set();
		return {
			additionalEncryptedOutputs: l.reduce((e, t) => u.has(t.value) ? e : (u.add(t.value), [...e, t]), []),
			lastOutput: this.findLastOutput(c.map((e) => e.lastOutput), t) ?? t
		};
	}
};
//#endregion
export { c as MultiThreadedUtxoUtils };
