// tools/usage-stats.ts — Handler for the usage_stats MCP tool.
// Returns aggregated usage statistics for the current installation.
import { usageStore } from '../storage/index.js';
import { filterEventsByPeriod } from '../engine/usage-tracker/core.js';
import { calculateUsageStats, formatStatsAsMarkdown } from '../engine/usage-tracker/stats.js';
import { calculateDaysSinceFirstRun, isTrialActive } from '../engine/usage-tracker/trial.js';
import { getCurrentTier } from './license-gate.js';
import { addNextSteps } from './response-helpers.js';
import { t } from '../i18n/index.js';
export async function handleUsageStats(args) {
    const period = args.period ?? '30d';
    const tier = await getCurrentTier();
    // Gather data from storage
    const usageLog = await usageStore.getUsageLog();
    const trialState = await usageStore.ensureTrialState();
    const today = new Date().toISOString().slice(0, 10);
    const todayCount = await usageStore.getDailyCallCount(today);
    // Compute context values
    const daysSinceFirstRun = calculateDaysSinceFirstRun(trialState.firstRunAt);
    const trialActive = isTrialActive(trialState.firstRunAt);
    // Remaining daily calls: only relevant for Starter tier
    let remainingDailyCalls = -1;
    if (tier === 'free') {
        const dailyLimit = trialActive ? 50 : 30;
        remainingDailyCalls = Math.max(0, dailyLimit - todayCount);
    }
    // Filter events by period and calculate stats
    const filteredEvents = filterEventsByPeriod(usageLog.events, period);
    const stats = calculateUsageStats(filteredEvents, 0, // activeSpecs — placeholder, no cross-layer access to spec store
    0, // activeProjects — placeholder
    tier, daysSinceFirstRun, trialActive, remainingDailyCalls);
    const markdown = formatStatsAsMarkdown(stats);
    const header = t('tools.response.statsTitle');
    const withHeader = `${header}\n\n${markdown}`;
    const text = addNextSteps(withHeader, [
        'Use `context_budget` to optimize token usage',
        'Use `recommend_model` for cost-effective model selection',
        'Run `token_usage` for detailed per-spec breakdown',
    ]);
    return { content: [{ type: 'text', text }] };
}
//# sourceMappingURL=usage-stats.js.map