// Formatting utilities

export function formatDuration(isoStart) {
  if (!isoStart) return '';
  const start = new Date(isoStart);
  const now = new Date();
  const mins = Math.max(0, Math.floor((now - start) / 60000));
  if (mins < 60) return mins + 'm';
  const hrs = Math.floor(mins / 60);
  const remainMins = mins % 60;
  return hrs + 'h ' + remainMins + 'm';
}

export function formatTime(isoTime) {
  if (!isoTime) return '';
  const date = new Date(isoTime);
  return date.toLocaleTimeString('en-US', {
    hour: 'numeric',
    minute: '2-digit',
    hour12: true
  });
}

export function formatTokenCount(value) {
  if (!Number.isFinite(value)) return '';
  return Math.round(value).toLocaleString('en-US');
}

export function getContextUsageSummary(usage) {
  if (!usage || typeof usage !== 'object') return null;

  const current = Number(usage.current_tokens);
  const windowTokens = Number(usage.window_tokens);
  const sessionTotal = usage.session_total_tokens != null ? Number(usage.session_total_tokens) : null;
  const hasCurrent = Number.isFinite(current) && current > 0;
  const hasWindow = Number.isFinite(windowTokens) && windowTokens > 0;
  const hasSessionTotal = sessionTotal != null && Number.isFinite(sessionTotal) && sessionTotal > 0;

  if (hasCurrent && hasWindow) {
    const percent = (current / windowTokens) * 100;
    return {
      headline: `${percent >= 10 ? percent.toFixed(0) : percent.toFixed(1)}% ctx`,
      detail: `${formatTokenCount(current)} / ${formatTokenCount(windowTokens)}`,
      trail: hasSessionTotal ? `Σ ${formatTokenCount(sessionTotal)}` : '',
      title: `Context window usage: ${formatTokenCount(current)} / ${formatTokenCount(windowTokens)} tokens`,
    };
  }

  if (hasCurrent) {
    const inputTokens = Number(usage.input_tokens);
    const outputTokens = Number(usage.output_tokens);
    const hasInput = Number.isFinite(inputTokens);
    const hasOutput = Number.isFinite(outputTokens);
    const ioDetail = hasInput || hasOutput
      ? ` • in ${formatTokenCount(hasInput ? inputTokens : 0)} out ${formatTokenCount(hasOutput ? outputTokens : 0)}`
      : '';
    return {
      headline: 'Ctx usage',
      detail: `${formatTokenCount(current)} tok${ioDetail}`,
      trail: '',
      title: `Token usage: ${formatTokenCount(current)} tokens`,
    };
  }

  return null;
}
