"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SummaryPlugin = void 0;
const chalk_1 = __importDefault(require("chalk"));
const ui_1 = require("../../../ui");
const agent_interface_1 = require("../../agent-interface");
function fmtDuration(ms) {
    const s = Math.round(ms / 1000);
    const m = Math.floor(s / 60);
    return m > 0 ? `${m}m ${s % 60}s` : `${s}s`;
}
function fmtTok(n) {
    if (n >= 1_000_000)
        return `${(n / 1_000_000).toFixed(1)}M`;
    if (n >= 1_000)
        return `${(n / 1000).toFixed(1)}K`;
    return n.toLocaleString();
}
function fmtCost(usd) {
    if (usd > 0 && usd < 0.01)
        return `$${usd.toFixed(4)}`;
    return `$${usd.toFixed(2)}`;
}
function printPhase(s) {
    const baseIn = Math.max(0, s.inputTokens - s.cacheRead - s.cacheCreation5m - s.cacheCreation1h);
    return [
        `${chalk_1.default.bold(s.phase)}: ${fmtDuration(s.durationMs)}, ${s.turns} turns, cost: ${fmtCost(s.cost)}`,
        `  in: ${fmtTok(baseIn)}, out: ${fmtTok(s.outputTokens)}, cache_read: ${fmtTok(s.cacheRead)}, cache_5m: ${fmtTok(s.cacheCreation5m)}, cache_1h: ${fmtTok(s.cacheCreation1h)}`,
        s.compactions > 0 ? `  ${s.compactions} compaction(s)` : null,
        s.contextOut !== undefined ? `  ctx_out: ${fmtTok(s.contextOut)}` : null,
    ]
        .filter(Boolean)
        .join('\n');
}
function getPhaseStats(i, ctx) {
    const duration = ctx.get('duration');
    const dur = duration?.phaseSnapshots[i];
    if (!dur)
        return null;
    const tokens = ctx.get('tokens');
    const turns = ctx.get('turns');
    const cost = ctx.get('cost');
    const compactions = ctx.get('compactions');
    const contextSize = ctx.get('contextSize');
    const cache = ctx.get('cache');
    return {
        phase: dur.phase,
        durationMs: dur.durationMs,
        turns: turns?.phaseSnapshots[i]?.turns ?? 0,
        inputTokens: tokens?.phaseSnapshots[i]?.inputTokens ?? 0,
        outputTokens: tokens?.phaseSnapshots[i]?.outputTokens ?? 0,
        cacheRead: cache?.phaseSnapshots[i]?.cacheReadTokens ?? 0,
        cacheCreation5m: cache?.phaseSnapshots[i]?.cacheCreation5m ?? 0,
        cacheCreation1h: cache?.phaseSnapshots[i]?.cacheCreation1h ?? 0,
        cost: cost?.phaseCosts[i]?.cost ?? 0,
        compactions: compactions?.phaseSnapshots[i]?.compactions ?? 0,
        contextOut: contextSize?.phaseSnapshots[i]?.contextTokensOut,
    };
}
class SummaryPlugin {
    name = 'summary';
    spinner;
    constructor(spinner) {
        this.spinner = spinner;
    }
    onPhaseTransition(fromPhase, toPhase, ctx, _store) {
        const duration = ctx.get('duration');
        const idx = (duration?.phaseSnapshots.length ?? 1) - 1;
        const stats = getPhaseStats(idx, ctx);
        if (stats) {
            this.spinner.stop(`${chalk_1.default.cyan(agent_interface_1.AgentSignals.BENCHMARK)} ${printPhase(stats)}`);
        }
        else {
            this.spinner.stop(`${chalk_1.default.cyan(agent_interface_1.AgentSignals.BENCHMARK)} ${fromPhase}`);
        }
        (0, ui_1.getUI)().log.info(`${chalk_1.default.cyan(agent_interface_1.AgentSignals.BENCHMARK)} Starting phase: ${chalk_1.default.bold(toPhase)}`);
        this.spinner.start(`Integrating Amplitude (${toPhase})...`);
    }
    onFinalize(_resultMessage, totalDurationMs, ctx, _store) {
        const duration = ctx.get('duration');
        const cost = ctx.get('cost');
        const tokens = ctx.get('tokens');
        const cache = ctx.get('cache');
        const phaseCount = duration?.phaseSnapshots.length ?? 0;
        const totalCost = cost?.totalCost ?? 0;
        (0, ui_1.getUI)().log.info('');
        (0, ui_1.getUI)().log.info(`${chalk_1.default.green('◇')} ${chalk_1.default.cyan(agent_interface_1.AgentSignals.BENCHMARK)} ${phaseCount} phases in ${fmtDuration(totalDurationMs)}, cost: ${fmtCost(totalCost)}`);
        (0, ui_1.getUI)().log.info(`  total in: ${fmtTok(tokens?.totalInput ?? 0)}, out: ${fmtTok(tokens?.totalOutput ?? 0)}, cache_read: ${fmtTok(cache?.totalRead ?? 0)}, cache_5m: ${fmtTok(cache?.totalCreation5m ?? 0)}, cache_1h: ${fmtTok(cache?.totalCreation1h ?? 0)}`);
        (0, ui_1.getUI)().log.info('');
        (0, ui_1.getUI)().log.info(`${chalk_1.default.blue('●')} ${chalk_1.default.cyan(agent_interface_1.AgentSignals.BENCHMARK)} Summary by phase:`);
        if (duration?.phaseSnapshots) {
            for (let i = 0; i < duration.phaseSnapshots.length; i++) {
                const stats = getPhaseStats(i, ctx);
                if (stats) {
                    (0, ui_1.getUI)().log.info(printPhase(stats));
                }
            }
        }
        (0, ui_1.getUI)().log.info('');
    }
}
exports.SummaryPlugin = SummaryPlugin;
