// resources/usage-stats-resource.ts — MCP resource for planu://usage/stats
// Returns aggregated usage statistics for the current installation (last 30 days).
// No parameters required.
import { usageStore } from '../storage/index.js';
import { filterEventsByPeriod } from '../engine/usage-tracker/core.js';
import { calculateUsageStats } from '../engine/usage-tracker/stats.js';
import { calculateDaysSinceFirstRun, isTrialActive } from '../engine/usage-tracker/trial.js';
import { getCurrentTier } from '../tools/license-gate.js';
import { estimateTokenSavings } from '../engine/token-savings-estimator.js';
import { existsSync } from 'node:fs';
import { join } from 'node:path';
/**
 * MCP resource handler for planu://usage/stats
 * Uses a fixed 30-day window — use the usage_stats tool for custom periods.
 */
export async function handleUsageStatsResource() {
    const period = '30d';
    const tier = await getCurrentTier();
    const usageLog = await usageStore.getUsageLog();
    const trialState = await usageStore.ensureTrialState();
    const today = new Date().toISOString().slice(0, 10);
    const todayCount = await usageStore.getDailyCallCount(today);
    const daysSinceFirstRun = calculateDaysSinceFirstRun(trialState.firstRunAt);
    const trialActive = isTrialActive(trialState.firstRunAt);
    let remainingDailyCalls = -1;
    if (tier === 'free') {
        const dailyLimit = trialActive ? 50 : 30;
        remainingDailyCalls = Math.max(0, dailyLimit - todayCount);
    }
    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 projectPath = process.cwd();
    const hasRules = existsSync(join(projectPath, '.claude/rules/planu-response-style.md'));
    const tokenSavings = estimateTokenSavings({
        totalCalls: stats.totalCalls,
        activeSpecs: stats.activeSpecs,
        doneSpecs: 0, // placeholder — no cross-layer access to spec store
    }, hasRules);
    return JSON.stringify({
        period,
        generatedAt: new Date().toISOString(),
        tier,
        trialActive,
        ...stats,
        tokenSavings,
    }, null, 2);
}
export const usageStatsResourceDefinition = {
    uri: 'planu://usage/stats',
    name: 'Usage Stats',
    description: 'Aggregated usage statistics for the last 30 days: tool call counts, tier info, trial status. ' +
        'Read-only. For custom periods use the usage_stats tool.',
    mimeType: 'application/json',
};
//# sourceMappingURL=usage-stats-resource.js.map