import { readFile, writeFile, mkdir, unlink, rm } from "node:fs/promises";
import * as path from "node:path";
/**
 * Local filesystem storage backend for context records.
 *
 * Contexts are stored as JSON files in the following structure:
 * {rootDir}/.superblocks/context/{userId}/{contextName}.json
 *
 * This uses the same path structure as V1 for upload/download compatibility.
 * The migration system handles version detection and migration when loading.
 */
export class LocalContextStorageV2 {
    rootDir;
    SUPERBLOCKS_SYSTEM_DIR = ".superblocks";
    constructor(rootDir) {
        this.rootDir = rootDir;
    }
    async loadContext(id) {
        const filePath = this.getFilePath(id);
        try {
            const content = await readFile(filePath, "utf-8");
            // Return raw parsed JSON - migration system will handle version detection
            return JSON.parse(content);
        }
        catch (err) {
            if (err.code === "ENOENT") {
                return null;
            }
            throw err;
        }
    }
    async saveContext(id, record) {
        const filePath = this.getFilePath(id);
        await this.ensureBaseDirExists(filePath);
        await writeFile(filePath, JSON.stringify(record, null, 2));
    }
    async deleteContext(id) {
        const filePath = this.getFilePath(id);
        try {
            await unlink(filePath);
        }
        catch (err) {
            if (err.code === "ENOENT") {
                return;
            }
            throw err;
        }
    }
    async deleteAllContexts() {
        const contextDir = this.getContextDir();
        try {
            await rm(contextDir, { recursive: true, force: true });
        }
        catch (err) {
            if (err.code === "ENOENT") {
                return;
            }
            throw err;
        }
    }
    getContextDir() {
        return path.join(this.rootDir, this.SUPERBLOCKS_SYSTEM_DIR, "context");
    }
    async ensureBaseDirExists(filePath) {
        await mkdir(path.dirname(filePath), { recursive: true });
    }
    getFilePath(id) {
        return path.join(this.rootDir, this.SUPERBLOCKS_SYSTEM_DIR, "context", id.userId, `${id.name}.json`);
    }
}
//# sourceMappingURL=local.js.map