const OUTPUT_BLOCK_PATTERN = /\n\[(?:stdout|stderr)\]\n/i;

export function summarizeSearchProgressMessage(message?: string | null) {
  const trimmed = String(message ?? '').trim();
  if (!trimmed) {
    return '';
  }

  const headlineBlock = trimmed.split(OUTPUT_BLOCK_PATTERN)[0]?.trim() ?? '';
  return headlineBlock
    .split('\n')
    .map((line) => line.trim())
    .find(Boolean) ?? '';
}

export function buildSearchDisplayErrors(errors?: string[] | null, resultError?: string | null) {
  const messages = [...(errors ?? [])];
  if (resultError) {
    messages.push(resultError);
  }

  return messages
    .map((message) => summarizeSearchProgressMessage(message))
    .filter(Boolean)
    .filter((message, index, list) => list.indexOf(message) === index);
}