import fs from "node:fs";
import path from "pathe";
import { Resource } from "../resource.js";
import { ignore } from "../util/ignore.js";
import { logger } from "../util/logger.js";
import { alchemy } from "../alchemy.js";
alchemy.file = async (path) => ({
    kind: "fs::FileRef",
    path,
});
alchemy.files = async (...args) => {
    const paths = typeof args[0] === "string" ? args : args[0];
    return {
        type: "fs::FileCollection",
        files: Object.fromEntries(await Promise.all(paths.map(async (path) => [
            path,
            await fs.promises.readFile(path, "utf-8"),
        ]))),
    };
};
alchemy.folder = async (dir, props) => {
    const files = await fs.promises.readdir(dir, {
        recursive: props?.recursive ?? false,
    });
    return alchemy.files(files.map((file) => path.join(dir, file)));
};
/**
 * File Resource
 *
 * Creates and manages files in the filesystem with automatic directory creation
 * and proper cleanup on deletion.
 *
 * @example
 * // Create a simple text file
 * const config = await File("config.txt", {
 *   path: "config.txt",
 *   content: "some configuration data"
 * });
 *
 * @example
 * // Create a file in a nested directory
 * const log = await File("logs/app.log", {
 *   path: "logs/app.log",
 *   content: "application log entry"
 * });
 *
 * @example
 * // Update file content and path
 * let file = await File("config.json", {
 *   path: "config.json",
 *   content: '{ "version": "1.0.0" }'
 * });
 *
 * // Later, update the path and content (old file will be removed)
 * file = await File("config.json", {
 *   path: "config/config.json",
 *   content: '{ "version": "1.0.1" }'
 * });
 */
export const File = Resource("fs::File", async function (id, props) {
    const filePath = props?.path ?? id;
    if (this.phase === "delete") {
        await ignore("ENOENT", async () => fs.promises.unlink(filePath));
        return this.destroy();
    }
    if (this.phase === "update" &&
        this.output &&
        this.output.path !== filePath) {
        // If path has changed, delete the old file
        logger.log(`File: Path changed from ${this.output.path} to ${filePath}, removing old file`);
        await ignore("ENOENT", async () => fs.promises.unlink(this.output.path));
    }
    // Create directory and write file
    const dirName = path.dirname(filePath);
    if (dirName !== ".") {
        await fs.promises.mkdir(dirName, {
            recursive: true,
        });
    }
    await fs.promises.writeFile(filePath, props.content);
    return {
        path: filePath,
        content: props.content,
    };
});
//# sourceMappingURL=file.js.map