// tools/cost-breakdown-handler.ts — Cost breakdown tool handler (SPEC-475)
import { readBreakdown } from '../engine/cost-tracking/ledger.js';
import { trackCost } from '../engine/cost-tracking/operation-tracker.js';
const DEFAULT_TOP_N = 10;
function formatUsd(amount) {
    return `$${amount.toFixed(6)}`;
}
function buildMarkdownTable(breakdown) {
    const lines = [];
    lines.push(`## Cost Breakdown — ${breakdown.period}`);
    lines.push('');
    lines.push(`**Total**: ${formatUsd(breakdown.total.cost)} | ${breakdown.total.tokens.toLocaleString('en-US')} tokens | ${breakdown.total.calls} calls`);
    lines.push('');
    // By tool table
    const toolEntries = Object.entries(breakdown.byTool).sort((a, b) => b[1].cost - a[1].cost);
    if (toolEntries.length > 0) {
        lines.push('### By Tool');
        lines.push('| Tool | Cost | Calls |');
        lines.push('|------|------|-------|');
        for (const [tool, stats] of toolEntries) {
            lines.push(`| ${tool} | ${formatUsd(stats.cost)} | ${stats.calls} |`);
        }
        lines.push('');
    }
    // By model table
    const modelEntries = Object.entries(breakdown.byModel).sort((a, b) => b[1].cost - a[1].cost);
    if (modelEntries.length > 0) {
        lines.push('### By Model');
        lines.push('| Model | Cost | Tokens |');
        lines.push('|-------|------|--------|');
        for (const [model, stats] of modelEntries) {
            lines.push(`| ${model} | ${formatUsd(stats.cost)} | ${stats.tokens.toLocaleString('en-US')} |`);
        }
        lines.push('');
    }
    // Top expensive calls
    if (breakdown.topExpensive.length > 0) {
        lines.push('### Top Expensive Calls');
        lines.push('| Tool | Cost | Timestamp |');
        lines.push('|------|------|-----------|');
        for (const entry of breakdown.topExpensive) {
            lines.push(`| ${entry.toolName} | ${formatUsd(entry.cost)} | ${entry.ts} |`);
        }
        lines.push('');
    }
    if (breakdown.total.calls === 0) {
        lines.push('_No cost entries recorded for this period._');
    }
    return lines.join('\n');
}
export async function handleCostBreakdown(input) {
    return trackCost(input.projectPath, 'cost_breakdown', async () => {
        const { projectPath, period = 'all', topN = DEFAULT_TOP_N } = input;
        const breakdown = await readBreakdown(projectPath, period, topN);
        const text = buildMarkdownTable(breakdown);
        return { content: [{ type: 'text', text }] };
    }); // end trackCost
}
//# sourceMappingURL=cost-breakdown-handler.js.map