// storage/budget-store.ts — Persists spec cost budgets (SPEC-393)
// Layout: data/projects/{hash}/config/budgets.json
import { readJson, writeJson, projectDataDir, hashProjectPath } from './base-store.js';
function budgetsFile(projectId) {
    return `${projectDataDir(projectId)}/config/budgets.json`;
}
async function loadBudgetsFile(projectPath) {
    const projectId = hashProjectPath(projectPath);
    return readJson(budgetsFile(projectId), { budgets: [] });
}
async function saveBudgetsFile(projectPath, data) {
    const projectId = hashProjectPath(projectPath);
    await writeJson(budgetsFile(projectId), data);
}
/**
 * Retrieve the budget for a single spec. Returns null when not found.
 */
export async function getBudget(projectPath, specId) {
    const data = await loadBudgetsFile(projectPath);
    return data.budgets.find((b) => b.specId === specId) ?? null;
}
/**
 * Persist (upsert) a budget entry.
 */
export async function saveBudget(projectPath, budget) {
    const data = await loadBudgetsFile(projectPath);
    const idx = data.budgets.findIndex((b) => b.specId === budget.specId);
    if (idx >= 0) {
        data.budgets[idx] = budget;
    }
    else {
        data.budgets.push(budget);
    }
    await saveBudgetsFile(projectPath, data);
}
/**
 * Return all budgets for a project.
 */
export async function listBudgets(projectPath) {
    const data = await loadBudgetsFile(projectPath);
    return data.budgets;
}
/**
 * Increment the usedUsdCents for a spec budget.
 * No-op when the spec has no budget entry.
 */
export async function recordSpend(projectPath, specId, usdCents) {
    const data = await loadBudgetsFile(projectPath);
    const idx = data.budgets.findIndex((b) => b.specId === specId);
    if (idx < 0) {
        return;
    }
    const existing = data.budgets[idx];
    if (existing === undefined) {
        return;
    }
    data.budgets[idx] = {
        ...existing,
        usedUsdCents: existing.usedUsdCents + usdCents,
        lastUpdated: new Date().toISOString(),
    };
    await saveBudgetsFile(projectPath, data);
}
//# sourceMappingURL=budget-store.js.map