import type { SearchProgress } from '@/services/automationService';

export type SearchProgressMetrics = NonNullable<NonNullable<SearchProgress['searchProgress']>['metrics']>;

function formatCount(value: unknown) {
  const numeric = Number(value);
  return Number.isFinite(numeric) && numeric >= 0 ? String(Math.floor(numeric)) : null;
}

export function buildSearchProgressMetricItems(metrics?: SearchProgressMetrics | null) {
  if (!metrics) return [];

  const items: Array<{ label: string; value: string }> = [];
  const candidateCount = formatCount(metrics.candidateCount);
  const nameMatchedCount = formatCount(metrics.nameMatchedCount);
  const judgedCount = formatCount(metrics.judgedCount);
  const attemptedContactCount = formatCount(metrics.attemptedContactCount);
  const qualifiedResultCount = formatCount(metrics.qualifiedResultCount);
  const targetResultCount = metrics.targetResultCount == null ? null : formatCount(metrics.targetResultCount);

  if (candidateCount != null) {
    items.push({ label: '已获取商品', value: candidateCount });
  }
  if (nameMatchedCount != null) {
    items.push({ label: '名称匹配', value: nameMatchedCount });
  }
  if (qualifiedResultCount != null) {
    items.push({
      label: '有效商家',
      value: targetResultCount != null ? `${qualifiedResultCount} / ${targetResultCount}` : qualifiedResultCount,
    });
  }
  if (judgedCount != null) {
    items.push({ label: '已判断', value: judgedCount });
  }
  if (attemptedContactCount != null) {
    items.push({ label: '联系方式尝试', value: attemptedContactCount });
  }

  return items;
}

export function formatSearchProgressMetricsCompact(metrics?: SearchProgressMetrics | null) {
  if (!metrics) return '';

  const parts: string[] = [];
  const candidateCount = formatCount(metrics.candidateCount);
  const nameMatchedCount = formatCount(metrics.nameMatchedCount);
  const qualifiedResultCount = formatCount(metrics.qualifiedResultCount);
  const targetResultCount = metrics.targetResultCount == null ? null : formatCount(metrics.targetResultCount);

  if (candidateCount != null) {
    parts.push(`商品 ${candidateCount}`);
  }
  if (nameMatchedCount != null) {
    parts.push(`匹配 ${nameMatchedCount}`);
  }
  if (qualifiedResultCount != null) {
    parts.push(targetResultCount != null ? `有效 ${qualifiedResultCount}/${targetResultCount}` : `有效 ${qualifiedResultCount}`);
  }

  return parts.join(' · ');
}
