// storage/usage-store.ts — Persistence layer for usage tracking (data/global/usage.json + first-run.json).
import { rename } from 'node:fs/promises';
import { readJson, writeJson, globalDataDir } from './base-store.js';
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const MAX_EVENTS = 10_000;
// ---------------------------------------------------------------------------
// Paths
// ---------------------------------------------------------------------------
function usageFile() {
    return `${globalDataDir()}/usage.json`;
}
function firstRunFile() {
    return `${globalDataDir()}/first-run.json`;
}
// ---------------------------------------------------------------------------
// Usage log (data/global/usage.json)
// ---------------------------------------------------------------------------
export async function getUsageLog() {
    return readJson(usageFile(), { events: [] });
}
export async function appendUsageEvent(event) {
    const log = await getUsageLog();
    const events = [...log.events, event];
    if (events.length > MAX_EVENTS) {
        await rotateUsageLog();
        await writeJson(usageFile(), { events: [event] });
        return;
    }
    await writeJson(usageFile(), { events });
}
export async function rotateUsageLog() {
    const isoDate = new Date().toISOString().slice(0, 10);
    const archivePath = `${globalDataDir()}/usage-${isoDate}.json`;
    try {
        await rename(usageFile(), archivePath);
    }
    catch {
        // If the current log doesn't exist there is nothing to rotate.
    }
    await writeJson(usageFile(), { events: [] });
}
// ---------------------------------------------------------------------------
// Trial state (data/global/first-run.json)
// ---------------------------------------------------------------------------
export async function getTrialState() {
    return readJson(firstRunFile(), null);
}
export async function ensureTrialState() {
    const existing = await getTrialState();
    if (existing !== null) {
        return existing;
    }
    const state = { firstRunAt: new Date().toISOString() };
    await writeJson(firstRunFile(), state);
    return state;
}
// ---------------------------------------------------------------------------
// Computed helpers (derived from usage.json — no extra file)
// ---------------------------------------------------------------------------
export async function getDailyCallCount(date) {
    const log = await getUsageLog();
    return log.events.filter((event) => event.timestamp.startsWith(date)).length;
}
export async function getLastCallTimestamp() {
    const log = await getUsageLog();
    if (log.events.length === 0) {
        return null;
    }
    const last = log.events[log.events.length - 1];
    /* v8 ignore next -- always defined when length > 0 */
    return last?.timestamp ?? null;
}
//# sourceMappingURL=usage-store.js.map