export function hasExplanation(alert) {
  return Boolean(alert?.explanation)
}

export function alertSummaryText(alert) {
  const narrative = alert?.explanation?.narrativeSummary
  if (narrative) return narrative
  return alert?.details ?? ''
}

export function elevatedContributors(explanation) {
  if (!explanation?.scoreContributors?.length) return []
  const elevated = explanation.scoreContributors.filter(c => c.points > 0)
  return elevated.length > 0 ? elevated : explanation.scoreContributors
}

export function formatDuration(duration) {
  if (!duration) return ''
  if (typeof duration !== 'string') return String(duration)

  const match = duration.match(/^(\d+):(\d{2}):(\d{2})$/)
  if (!match) return duration

  const hours = Number(match[1])
  const minutes = Number(match[2])
  if (hours > 0) return `${hours} hour${hours === 1 ? '' : 's'}`
  if (minutes > 0) return `${minutes} minute${minutes === 1 ? '' : 's'}`
  return 'under 1 minute'
}

export function formatTrendLine(trend) {
  if (!trend) return ''
  const direction = trend.direction?.toLowerCase() ?? 'changed'
  const duration = formatDuration(trend.duration)
  return `${trend.parameter} ${direction} ${Math.round(trend.percentChange)}% over ${duration}.`
}

export function formatMedicationContext(medication) {
  if (!medication) return ''
  const administered = medication.administeredAt
    ? new Date(medication.administeredAt).toLocaleString()
    : null
  let line = `${medication.drugName} ${medication.dose} ${medication.route}`
  if (administered) line += ` — ${administered}`
  if (medication.relevanceNote) line += ` (${medication.relevanceNote})`
  return line
}
