/**
 * AI usage aggregation.
 *
 * Until the dedicated per-run metering table lands (Phase 4), usage is derived
 * from token totals already recorded in `actuate_audit_logs` (`details
 * .totalTokensUsed` / `details.tokensUsed`). This returns REAL counts — it is 0
 * when nothing has run, never a fabricated number.
 */
import { getAIConfig } from './config-store.js';
/** First instant of the current calendar month (UTC). */
function monthStart(now = new Date()) {
    return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1, 0, 0, 0, 0));
}
/** First instant of the next calendar month (UTC). */
function nextMonthStart(now = new Date()) {
    return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1, 0, 0, 0, 0));
}
function num(value) {
    return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0;
}
/**
 * Sum token usage from audit-log entries within the period. Recognizes the
 * fields current AI handlers write today and is tolerant of missing data.
 */
export async function getUsageSummary(db, period) {
    const start = period?.start ?? monthStart();
    const end = period?.end ?? nextMonthStart();
    const config = await getAIConfig(db);
    const monthlyTokenLimit = config.settings.budget.monthlyTokenLimit;
    const base = {
        totalTokens: 0,
        promptTokens: 0,
        completionTokens: 0,
        monthlyTokenLimit,
        periodStart: start.toISOString(),
        periodEnd: end.toISOString(),
        runCount: 0,
    };
    const d = db;
    if (!d?.auditLog?.findMany)
        return base;
    let rows = [];
    try {
        rows = await d.auditLog.findMany({
            where: { timestamp: { gte: start, lt: end } },
            select: { details: true },
        });
    }
    catch {
        return base;
    }
    let totalTokens = 0;
    let promptTokens = 0;
    let completionTokens = 0;
    let runCount = 0;
    for (const row of rows) {
        const details = (row?.details ?? {});
        const total = num(details.totalTokensUsed) + num(details.tokensUsed) + num(details.totalTokens);
        const prompt = num(details.promptTokens);
        const completion = num(details.completionTokens);
        if (total > 0 || prompt > 0 || completion > 0) {
            runCount += 1;
            totalTokens += total > 0 ? total : prompt + completion;
            promptTokens += prompt;
            completionTokens += completion;
        }
    }
    return { ...base, totalTokens, promptTokens, completionTokens, runCount };
}
//# sourceMappingURL=usage.js.map