import { log } from "../log.js";
import { getMatches, getWorkspaces } from "../file-matching.js";
import { batchMap } from "../utilities/formatting.js";
import { defineSource } from "../source.js";
import { stat } from "node:fs/promises";
import path, { dirname } from "node:path";
//#region src/lib/sources/file-stats.ts
const fileStatsSource = defineSource({
	async discover(context) {
		return [context.options.path, ...getWorkspaces(context.options.path, context.options.workspaces)];
	},
	key: "fileStats",
	async parse(input, context) {
		log.debug("Extracting file statistics metadata...");
		const allFiles = await getMatches({
			...context.options,
			path: input,
			recursive: false,
			workspaces: false
		}, ["**"]);
		const totalFileCount = allFiles.length;
		const uniqueDirectories = /* @__PURE__ */ new Set();
		for (const file of allFiles) {
			const directory = dirname(file);
			if (directory !== input) uniqueDirectories.add(directory);
		}
		const totalDirectoryCount = uniqueDirectories.size;
		const totalSizeBytes = (await batchMap(allFiles, async (file) => {
			try {
				return (await stat(file)).size;
			} catch {
				return 0;
			}
		}, 100)).reduce((sum, size) => sum + size, 0);
		return {
			data: {
				folderName: input.split(path.sep).at(-1),
				totalDirectoryCount,
				totalFileCount,
				totalSizeBytes
			},
			source: input
		};
	},
	phase: 1
});
//#endregion
export { fileStatsSource };
