import { readJson, projectDataDir, specStore } from '../../storage/index.js';
import { loadJournal, saveJournal, listSessions } from '../../storage/session-journal-store.js';
import { applyEventToSessions, buildBrief, createJournalEvent, } from '../../engine/session-journal.js';
import { ok } from './utils.js';
// ---------------------------------------------------------------------------
// Action: brief
// ---------------------------------------------------------------------------
export async function handleBrief(projectId, experienceLevel = 'expert') {
    const [specs, journal] = await Promise.all([specStore.listSpecs(projectId), loadJournal()]);
    // Try to read token budget (SPEC-012 integration — optional)
    let tokenBudget;
    try {
        const usage = await readJson(`${projectDataDir(projectId)}/token-usage.json`, {});
        if (typeof usage.remainingTokens === 'number') {
            tokenBudget = usage.remainingTokens;
        }
    }
    catch {
        /* no-op: token budget is optional */
    }
    const brief = buildBrief({ specs, journal, tokenBudget, experienceLevel });
    const result = {
        action: 'brief',
        ...brief,
        experienceLevel,
        message: `Brief generado: ${brief.inProgress.length} en progreso, ${brief.pendingUnblocked.length} disponibles, ${brief.blockers.length} bloqueadas`,
    };
    return ok(result);
}
// ---------------------------------------------------------------------------
// Action: journal
// ---------------------------------------------------------------------------
export async function handleJournal(sessionId, journalAction, eventType, specId, commitHash, limit = 10) {
    const action = journalAction ?? 'list';
    if (action === 'list') {
        const sessions = await listSessions(limit);
        return ok({ action: 'journal', sessions, message: `Últimas ${sessions.length} sesiones` });
    }
    // emit
    if (!sessionId) {
        return {
            content: [
                {
                    type: 'text',
                    text: JSON.stringify({ error: 'sessionId required for journal emit' }, null, 2),
                },
            ],
            isError: true,
        };
    }
    const type = (eventType ?? 'spec-status-changed');
    const event = createJournalEvent(type, { specId, commitHash });
    const journal = await loadJournal();
    const updated = applyEventToSessions(journal.entries, sessionId, event);
    await saveJournal({ entries: updated });
    return ok({
        action: 'journal',
        sessionId,
        event,
        message: `Evento '${type}' registrado para sesión '${sessionId}'`,
    });
}
//# sourceMappingURL=journal-brief-handlers.js.map