import { TokenOptimizer } from '../engine/token-optimizer/index.js';
// Singleton optimizer instance for the current session
let optimizer = null;
/**
 * Get or create the global optimizer instance.
 */
export function getOptimizer() {
    optimizer ??= new TokenOptimizer(`session-${String(Date.now())}`);
    return optimizer;
}
/**
 * Reset the optimizer (for testing).
 */
export function resetOptimizer() {
    optimizer = null;
}
/**
 * Handle the token_usage tool call.
 */
export function handleTokenUsage(args) {
    const opt = getOptimizer();
    const report = opt.getReport();
    const formatted = opt.getFormattedReport();
    const period = args.period ?? 'current_session';
    const groupBy = args.groupBy ?? 'tool';
    const toolRecords = opt.reporter.getToolRecords();
    let details;
    if (groupBy === 'tool' && toolRecords.length > 0) {
        const lines = toolRecords.map((r) => `| ${r.toolName} | ${String(r.totalTokens)} | ${String(r.callCount)} | ` +
            `${String(r.cacheHits)}/${String(r.cacheHits + r.cacheMisses)} | ${String(r.tokensSaved)} |`);
        details = [
            '| Tool | Tokens | Calls | Cache H/T | Saved |',
            '|------|--------|-------|-----------|-------|',
            ...lines,
        ].join('\n');
    }
    else {
        details = 'No tool usage recorded yet.';
    }
    const text = [
        formatted,
        '',
        `### Filter: period=${period}, groupBy=${groupBy}`,
        '',
        details,
        '',
        `Budget status: ${report.totalTokensProcessed > 0 ? `${String(report.totalTokensProcessed)} tokens processed` : 'No activity'}`,
    ].join('\n');
    return Promise.resolve({
        content: [{ type: 'text', text }],
    });
}
//# sourceMappingURL=token-usage-handler.js.map