import { readJson, writeJson } from './base-store.js';
import { withFileLock } from './file-mutex.js';
import { readdir } from 'node:fs/promises';
import { join } from 'node:path';
// --- internal helpers ---
function sanitizeId(id) {
    const sanitized = id.replace(/[/\\]/g, '_').replace(/\.\./g, '_');
    if (!sanitized || sanitized === '.' || sanitized === '..') {
        throw new Error(`Invalid ID: ${id}`);
    }
    return sanitized;
}
function risksDir(projectDataDir) {
    return join(projectDataDir, 'risks');
}
function riskFile(projectDataDir, specId) {
    return join(risksDir(projectDataDir), `${sanitizeId(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) {
    const file = riskFile(projectDataDir, register.specId);
    await withFileLock(file, async () => {
        await writeJson(file, 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) {
        /* v8 ignore next 3 -- non-ENOENT errors are rare and untestable in ESM */
        if (!(isNodeError(err) && err.code === 'ENOENT')) {
            throw err;
        }
        return [];
    }
    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