// vDeepSeek: cache shape telemetry badge. Displays cache token count with
// a colored hit-rate bar in the trace viewer. Color thresholds are relative
// to output tokens (tokens_used) since the trace doesn't carry prompt miss
// tokens separately: green > 50%, yellow > 10%, red ≤ 10%.

export interface CacheShapeBadgeProps {
  cacheTokens: number | null | undefined;
  totalTokens: number | null | undefined;
}

function hitRate(cache: number, total: number): number {
  if (cache <= 0 || total <= 0) return 0;
  return cache / (cache + total);
}

function barColor(rate: number): string {
  if (rate > 0.5) return 'bg-green-500';
  if (rate > 0.1) return 'bg-yellow-500';
  return 'bg-red-500';
}

export function CacheShapeBadge({ cacheTokens, totalTokens }: CacheShapeBadgeProps) {
  if (cacheTokens == null || cacheTokens <= 0) return null;

  const rate = hitRate(cacheTokens, totalTokens ?? 0);
  const pct = Math.round(rate * 100);
  const color = barColor(rate);

  return (
    <span className="shrink-0 inline-flex items-center gap-1 font-mono tabular-nums text-[10px] text-muted-foreground/60" title={`cache hit rate ${pct}%`}>
      <span className={`inline-block w-1.5 h-3 rounded-sm ${color}`} />
      <span>{cacheTokens}c</span>
      {totalTokens != null && totalTokens > 0 && (
        <span className="text-muted-foreground/40">{pct}%</span>
      )}
    </span>
  );
}
