import { t as getBinaryTemplatesRoot } from "./template-reader-BjQIVD2E.mjs";
import { dirname, join } from "pathe";
import * as fs from "node:fs/promises";

//#region src/fs-writer.ts
const BINARY_FILE_MARKER = "[Binary file]";
async function writeTreeToFilesystem(tree, destDir) {
	for (const child of tree.root.children) await writeNode(child, destDir, "");
}
async function writeNode(node, baseDir, relativePath) {
	const fullPath = join(baseDir, relativePath, node.name);
	const nodePath = relativePath ? join(relativePath, node.name) : node.name;
	if (node.type === "file") {
		const fileNode = node;
		await fs.mkdir(dirname(fullPath), { recursive: true });
		if (fileNode.content === BINARY_FILE_MARKER && fileNode.sourcePath) await copyBinaryFile(fileNode.sourcePath, fullPath);
		else if (fileNode.content !== BINARY_FILE_MARKER) await fs.writeFile(fullPath, fileNode.content, "utf-8");
	} else {
		await fs.mkdir(fullPath, { recursive: true });
		for (const child of node.children) await writeNode(child, baseDir, nodePath);
	}
}
async function writeSelectedFiles(tree, destDir, filter) {
	const writtenFiles = [];
	await writeSelectedNode(tree.root, destDir, "", filter, writtenFiles);
	return writtenFiles;
}
async function writeSelectedNode(node, baseDir, relativePath, filter, writtenFiles) {
	const nodePath = relativePath ? `${relativePath}/${node.name}` : node.name;
	if (node.type === "file") {
		if (filter(nodePath)) {
			const fileNode = node;
			await fs.mkdir(dirname(join(baseDir, nodePath)), { recursive: true });
			if (fileNode.content === BINARY_FILE_MARKER && fileNode.sourcePath) await copyBinaryFile(fileNode.sourcePath, join(baseDir, nodePath));
			else if (fileNode.content !== BINARY_FILE_MARKER) await fs.writeFile(join(baseDir, nodePath), fileNode.content, "utf-8");
			writtenFiles.push(nodePath);
		}
	} else for (const child of node.children) await writeSelectedNode(child, baseDir, nodePath, filter, writtenFiles);
}
async function copyBinaryFile(templatePath, destPath) {
	const sourcePath = join(getBinaryTemplatesRoot(), templatePath);
	try {
		await fs.copyFile(sourcePath, destPath);
	} catch (error) {
		console.warn(`Failed to copy binary file: ${templatePath}`, error);
	}
}

//#endregion
export { writeSelectedFiles, writeTreeToFilesystem };
//# sourceMappingURL=fs-writer.mjs.map