/**
 * `olam kg savings` — cumulative KG-hit telemetry summary.
 *
 * Aggregates `/kg-data/savings.jsonl` (one append-only line per non-grep
 * /classify call) via the kg-service /savings endpoint. Output is a coarse
 * heuristic — see `SAVINGS_HEURISTIC` in packages/kg-service/src/server.py
 * for the per-layer model. Display always prefixes saved-token counts with
 * `~` so the approximation reads correctly.
 *
 * Surfaces:
 *   - Total hits + total estimated savings
 *   - Per-layer breakdown (L1 regex / L2 graph-probe / L4 embedding)
 *   - Per-workspace breakdown
 *   - First + last hit timestamps
 *
 * --json emits the raw response shape for monitoring pipelines.
 */
import { savings, KgServiceUnreachableError, } from '@olam/core/src/kg/kg-service-client.js';
import { printError, printInfo, printSuccess, printWarning } from '../output.js';
function formatTokens(n) {
    if (n >= 1_000_000)
        return `~${(n / 1_000_000).toFixed(1)}M`;
    if (n >= 1_000)
        return `~${Math.round(n / 1000)}k`;
    return `~${n}`;
}
function renderHumanReadable(stats) {
    if (stats.total_hits === 0) {
        printInfo('savings', 'no KG hits logged yet — run some grep/find Bash invocations to populate /kg-data/savings.jsonl');
        return;
    }
    printSuccess(`KG hits: ${stats.total_hits} · estimated savings: ${formatTokens(stats.total_saved_tokens_est)} tokens`);
    printInfo('first hit', stats.first_hit_at ?? '(unknown)');
    printInfo('last hit', stats.last_hit_at ?? '(unknown)');
    const layerPairs = Object.entries(stats.by_layer).map(([k, v]) => [k, v ?? 0]);
    const layers = [...layerPairs].sort((a, b) => a[0].localeCompare(b[0]));
    if (layers.length > 0) {
        printInfo('by layer', layers.map(([k, v]) => `L${k}=${formatTokens(v)}`).join(' · '));
    }
    const workspacePairs = Object.entries(stats.by_workspace).map(([k, v]) => [k, v ?? 0]);
    const workspaces = [...workspacePairs].sort((a, b) => b[1] - a[1]).slice(0, 5);
    if (workspaces.length > 0) {
        printInfo('top workspaces', workspaces.map(([k, v]) => `${k || '(none)'}=${formatTokens(v)}`).join(' · '));
    }
    if (stats.parse_errors > 0) {
        printWarning(`savings.jsonl had ${stats.parse_errors} unparseable lines (skipped)`);
    }
    printInfo('note', 'savings are a heuristic, not a measurement. See SAVINGS_HEURISTIC in server.py for the per-layer model.');
}
export function registerKgSavingsCommand(kg) {
    kg.command('savings')
        .description('Show cumulative KG-hit savings tallied by the kg-service container')
        .option('--json', 'emit raw response JSON instead of human-readable summary')
        .action(async (opts) => {
        let stats;
        try {
            stats = await savings();
        }
        catch (err) {
            if (err instanceof KgServiceUnreachableError) {
                printError(err.message);
                printInfo('remedy', '`olam services up` to start kg-service, then re-run');
                process.exitCode = 3;
                return;
            }
            printError(`kg-service /savings failed: ${err instanceof Error ? err.message : String(err)}`);
            process.exitCode = 1;
            return;
        }
        if (opts.json) {
            process.stdout.write(JSON.stringify(stats, null, 2) + '\n');
            return;
        }
        renderHumanReadable(stats);
    });
}
//# sourceMappingURL=kg-savings.js.map