// base-store.ts — Shared JSON read/write logic for all stores
import { readFile, mkdir } from 'node:fs/promises';
import { dirname } from 'node:path';
import { createHash } from 'node:crypto';
import { writeJsonSafe } from '../engine/safety/atomic-writer.js';
/**
 * Hash a project path into a deterministic projectId using SHA-256.
 */
export function hashProjectPath(projectPath) {
    return createHash('sha256').update(projectPath).digest('hex').slice(0, 16);
}
/**
 * Ensure the parent directory for a file path exists.
 */
async function ensureDir(filePath) {
    await mkdir(dirname(filePath), { recursive: true });
}
/**
 * Read a JSON file from disk. Returns the parsed contents, or the provided
 * default value when the file does not exist.
 */
export async function readJson(filePath, defaultValue) {
    try {
        const raw = await readFile(filePath, 'utf-8');
        return JSON.parse(raw);
    }
    catch (err) {
        if (err instanceof SyntaxError) {
            console.warn(`[Planu] Corrupt JSON at ${filePath}, using default`);
            return defaultValue;
        }
        if (isNodeError(err) && err.code === 'ENOENT') {
            return defaultValue;
        }
        throw err;
    }
}
/**
 * Write a value to a JSON file, creating parent directories as needed.
 */
export async function writeJson(filePath, data) {
    await ensureDir(filePath);
    try {
        await writeJsonSafe(filePath, data);
    }
    catch (err) {
        /* v8 ignore start -- filesystem error guard */
        if (isNodeError(err) && (err.code === 'ENOSPC' || err.code === 'EACCES')) {
            console.warn(`[Planu] Cannot write ${filePath}: ${err.code}`);
        }
        /* v8 ignore stop */
        throw new Error(`[Planu] Failed to write ${filePath}: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
    }
}
/**
 * Resolve the data directory for a given project.
 * Layout: data/projects/{projectId}/
 */
export function projectDataDir(projectId) {
    return `data/projects/${projectId}`;
}
/**
 * Resolve the global data directory.
 * Layout: data/global/
 */
export function globalDataDir() {
    return 'data/global';
}
function isNodeError(err) {
    return err instanceof Error && 'code' in err;
}
//# sourceMappingURL=base-store.js.map