import type { Message } from '@/api/types';
import { CacheShapeBadge } from '@/components/CacheShapeBadge';

export function StatsLine({ message }: { message: Message }) {
  const tokens = message.tokens_used;
  if (typeof tokens !== 'number' || tokens <= 0) return null;
  const started = message.started_at ? Date.parse(message.started_at) : NaN;
  const finished = message.finished_at ? Date.parse(message.finished_at) : NaN;
  let tps: number | null = null;
  if (!Number.isNaN(started) && !Number.isNaN(finished) && finished > started) {
    const seconds = (finished - started) / 1000;
    if (seconds > 0) tps = Math.round((tokens / seconds) * 10) / 10;
  }
  const ctxUsed = message.ctx_used;
  const ctxMax = message.ctx_max;
  const ctxPart =
    typeof ctxUsed === 'number'
      ? typeof ctxMax === 'number' && ctxMax > 0
        ? `${ctxUsed} / ${ctxMax} ctx`
        : `${ctxUsed} ctx`
      : null;

  const cacheHit = message.cache_tokens;
  const reasoning = message.reasoning_tokens;
  const cachePart = typeof cacheHit === 'number' && cacheHit > 0 ? `cache ${cacheHit}` : null;
  const reasoningPart = typeof reasoning === 'number' && reasoning > 0 ? `think ${reasoning}` : null;

  const parts: string[] = [`${tokens} tokens`];
  if (tps !== null) parts.push(`${tps.toFixed(1)} tok/s`);
  if (ctxPart) parts.push(ctxPart);
  if (cachePart) parts.push(cachePart);
  if (reasoningPart) parts.push(reasoningPart);

  return (
    <div className="flex items-center gap-1.5 flex-wrap">
      <div className="text-[10px] font-mono text-muted-foreground">
        {parts.join(' · ')}
      </div>
      <CacheShapeBadge cacheTokens={cacheHit} totalTokens={tokens} />
    </div>
  );
}
