import type { WorkflowExecutionStepView } from './workflowExecutionDetails';

/**
 * 汇总当前活动节点名称。
 */
export function summarizeWorkflowActiveNodes(
  steps: WorkflowExecutionStepView[],
  fallbackName = '',
): string {
  const names: string[] = [];
  for (const step of steps) {
    if (step.status !== 'running' && step.status !== 'waiting') {
      continue;
    }
    if (step.nodeName && !names.includes(step.nodeName)) {
      names.push(step.nodeName);
    }
  }
  if (names.length === 0) {
    return fallbackName;
  }
  const latestName = names[names.length - 1] || fallbackName;
  return names.length > 1
    ? `${latestName} 等 ${names.length} 个节点`
    : latestName;
}

/**
 * 生成包含当前节点的运行状态文案。
 */
export function formatWorkflowProgressLabel(
  prefix: string,
  steps: WorkflowExecutionStepView[],
  fallbackName = '',
): string {
  const nodeSummary = summarizeWorkflowActiveNodes(steps, fallbackName);
  return nodeSummary ? `${prefix} · ${nodeSummary}` : prefix;
}

/**
 * 将执行耗时格式化为紧凑文案。
 */
export function formatWorkflowElapsed(value?: number): string {
  if (value === undefined) {
    return '';
  }
  if (value < 1000) {
    return `${value} ms`;
  }
  const seconds = value / 1000;
  return `${seconds < 10 ? seconds.toFixed(1) : Math.round(seconds)} s`;
}
