'use strict';

function normalizeTokenUsage(value) {
  if (value && typeof value === 'object') {
    return {
      prompt: Number(value.prompt) || 0,
      completion: Number(value.completion) || 0,
      total: Number(value.total) || 0,
    };
  }
  const num = Number(value);
  return {
    prompt: 0,
    completion: 0,
    total: Number.isFinite(num) ? num : 0,
  };
}

function applyUsage(base, usage) {
  const normalized = normalizeTokenUsage(base);
  if (!usage) return normalized;
  if (Number.isFinite(usage.prompt_tokens)) normalized.prompt += usage.prompt_tokens;
  if (Number.isFinite(usage.completion_tokens)) normalized.completion += usage.completion_tokens;
  if (Number.isFinite(usage.total_tokens)) normalized.total = usage.total_tokens;
  return normalized;
}

function normalizeUsagePayload(usage) {
  if (!usage || typeof usage !== 'object') return null;
  const toNum = (value) => (Number.isFinite(Number(value)) ? Number(value) : 0);
  const prompt = toNum(usage.prompt_tokens ?? usage.input_tokens ?? usage.prompt ?? usage.input);
  const completion = toNum(usage.completion_tokens ?? usage.output_tokens ?? usage.completion ?? usage.output);
  let total = toNum(usage.total_tokens ?? usage.total);
  if (!total && (prompt || completion)) total = prompt + completion;
  if (!prompt && !completion && !total) return null;
  return { prompt_tokens: prompt, completion_tokens: completion, total_tokens: total };
}

module.exports = { normalizeTokenUsage, applyUsage, normalizeUsagePayload };
