export type StatisticsReportOutputMode = 'scalar' | 'timeseries' | ''

export interface StatisticsReportViewContent {
  outputMode: StatisticsReportOutputMode
  scalarRows: Record<string, any>[]
  seriesRows: Record<string, any>[]
  hasContent: boolean
}

const toRows = (value: unknown): Record<string, any>[] => {
  if (!Array.isArray(value)) return []
  return value.filter((item): item is Record<string, any> => item !== null && typeof item === 'object' && !Array.isArray(item))
}

const normalizeOutputMode = (value: unknown): StatisticsReportOutputMode => {
  if (value === 'scalar' || value === 'timeseries') return value
  return ''
}

/** 将后端统计报表 payload 归一化为弹窗可渲染的数据结构。 */
export const normalizeStatisticsReportContent = (content: Record<string, any> | null | undefined): StatisticsReportViewContent => {
  if (!content) {
    return {
      outputMode: '',
      scalarRows: [],
      seriesRows: [],
      hasContent: false,
    }
  }

  const scalarRows = toRows(content.rows)
  const legacyScalarRows =
    content.scalars && typeof content.scalars === 'object' && !Array.isArray(content.scalars) ? [content.scalars] : []
  const seriesRows = toRows(content.series)
  let outputMode = normalizeOutputMode(content.output_mode || content.params?.output_mode)

  if (!outputMode) {
    if (seriesRows.length > 0) {
      outputMode = 'timeseries'
    } else if (scalarRows.length > 0 || legacyScalarRows.length > 0) {
      outputMode = 'scalar'
    }
  }

  const normalizedScalarRows = scalarRows.length > 0 ? scalarRows : legacyScalarRows
  const hasContent = outputMode === 'timeseries' ? seriesRows.length > 0 : normalizedScalarRows.length > 0

  return {
    outputMode,
    scalarRows: normalizedScalarRows,
    seriesRows,
    hasContent,
  }
}
