/**
 * Nutzer-sichtbare Textausgabe eines Workflow-Laufs – gleiche Logik wie
 * WorkflowResultViewer („Final Output“): primär aggregated_result.analysis_core.
 */
const AGG_META_KEYS = new Set([
  'combined_analysis',
  'all_signals',
  'total_nodes',
  'executed_nodes',
  'failed_nodes',
  'skipped_nodes',
])

export function getWorkflowDisplayContent(aggregatedResult) {
  if (aggregatedResult == null) return ''
  if (typeof aggregatedResult !== 'object' || Array.isArray(aggregatedResult)) {
    return typeof aggregatedResult === 'string'
      ? aggregatedResult
      : JSON.stringify(aggregatedResult, null, 2)
  }

  const core = aggregatedResult.analysis_core
  if (typeof core === 'string' && core.trim() !== '') return core

  const combined = aggregatedResult.combined_analysis
  if (typeof combined === 'string' && combined.trim() !== '') return combined

  const keys = Object.keys(aggregatedResult).filter((k) => !AGG_META_KEYS.has(k))
  if (keys.length === 1) {
    const v = aggregatedResult[keys[0]]
    if (typeof v === 'string') return v
    if (v != null && typeof v === 'object') return JSON.stringify(v, null, 2)
    return String(v)
  }

  return JSON.stringify(aggregatedResult, null, 2)
}
