// tools/update-status-reconcile.ts — Auto-reconcile token costs when spec reaches done (SPEC-182)
import { reconcile, formatReconciliation } from '../engine/token-optimizer/reconciler.js';
import { getEntries } from '../storage/token-ledger-store.js';
import { join } from 'node:path';
const DEFAULT_DATA_DIR = join(process.cwd(), 'data');
/**
 * Auto-reconcile token costs when a spec transitions to 'done'.
 * Compares pre-execution estimates stored in ledger entries against actuals.
 * Fire-and-forget safe: always returns null on any error.
 */
export async function autoReconcileOnDone(specId, projectHash) {
    try {
        const entries = await getEntries(projectHash, DEFAULT_DATA_DIR, {
            specId,
            period: 'all_time',
        });
        if (entries.length === 0) {
            return null; // No token data recorded for this spec
        }
        const withEstimates = entries.filter((e) => e.estimatedTokens !== undefined && e.estimatedCostUsd !== undefined);
        if (withEstimates.length === 0) {
            return null; // No estimates to compare against
        }
        const estimatedTokens = withEstimates.reduce((sum, e) => sum + (e.estimatedTokens ?? 0), 0);
        const estimatedCost = withEstimates.reduce((sum, e) => sum + (e.estimatedCostUsd ?? 0), 0);
        // Derive model from the most common model in entries with estimates
        const modelCounts = {};
        for (const e of withEstimates) {
            modelCounts[e.model] = (modelCounts[e.model] ?? 0) + 1;
        }
        const estimatedModel = Object.entries(modelCounts).sort((a, b) => b[1] - a[1])[0]?.[0] ?? 'claude-sonnet';
        const input = {
            specId,
            estimatedInputTokens: Math.round(estimatedTokens * 0.4),
            estimatedOutputTokens: Math.round(estimatedTokens * 0.6),
            estimatedCostUsd: estimatedCost,
            estimatedModel,
            actualEntries: entries,
        };
        const result = reconcile(input);
        return formatReconciliation(result);
    }
    catch {
        return null;
    }
}
//# sourceMappingURL=update-status-reconcile.js.map