import { readJson, writeJson } from './base-store.js';
import { readdir } from 'node:fs/promises';
import { join } from 'node:path';
// --- internal helpers ---
function risksDir(projectDataDir) {
    return join(projectDataDir, 'risks');
}
function riskFile(projectDataDir, specId) {
    return join(risksDir(projectDataDir), `${specId}.json`);
}
// --- public API ---
/**
 * Load the risk register for a given spec.
 * Returns null when no register has been saved yet.
 */
export async function loadRiskRegister(projectDataDir, specId) {
    return readJson(riskFile(projectDataDir, specId), null);
}
/**
 * Persist a risk register for a spec.
 */
export async function saveRiskRegister(projectDataDir, register) {
    await writeJson(riskFile(projectDataDir, register.specId), register);
}
/**
 * Load all risk registers for a project.
 * Returns an empty array when the risks directory does not exist.
 */
export async function loadAllRiskRegisters(projectDataDir) {
    const dir = risksDir(projectDataDir);
    let files;
    try {
        files = await readdir(dir);
    }
    catch (err) {
        if (isNodeError(err) && err.code === 'ENOENT') {
            return [];
        }
        /* v8 ignore next */
        throw err;
    }
    const jsonFiles = files.filter((f) => f.endsWith('.json'));
    const registers = await Promise.all(jsonFiles.map(async (file) => {
        const specId = file.replace(/\.json$/, '');
        return loadRiskRegister(projectDataDir, specId);
    }));
    return registers.filter((r) => r !== null);
}
// --- internal helpers ---
function isNodeError(err) {
    return err instanceof Error && 'code' in err;
}
//# sourceMappingURL=risk-store.js.map