import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'

import {
  fetchDigitalEmployeeDashboard,
  fetchFinanceDashboard,
  fetchSystemDashboard
} from '../services/analytics.js'
import { fetchRiskObservationDashboard } from '../services/riskObservations.js'
import {
  buildDigitalEmployeeCategoryRows,
  buildDigitalEmployeeDailyRows,
  buildDigitalEmployeeKpiMetrics,
  buildDigitalEmployeeTaskRanking,
  emptyDigitalEmployeeDashboard
} from '../views/scripts/overviewDigitalEmployeeDashboardModel.js'
import {
  buildRiskDistributionLegend,
  emptyFinanceBudgetMetrics,
  emptyFinanceBudgetSummary,
  emptyFinanceDonut,
  emptyFinanceTotals,
  emptyFinanceTrend,
  emptySystemDashboardTotals,
  emptySystemLoginWave,
  formatCompact,
  formatCurrency,
  formatMetricValue,
  formatNumberCompact,
  formatPercent,
  formatRiskSignalName,
  formatSystemMetricValue as formatSystemMetricValueModel,
  isMissingDimension,
  resolveFinanceMetricMeta as resolveFinanceMetricMetaModel,
  resolveSystemMetricMeta as resolveSystemMetricMetaModel
} from './overviewViewDisplayModel.js'
import {
  aggregateRiskDailyTrendRows,
  DEFAULT_OVERVIEW_RANGE,
  resolveTopRangeDays,
  resolveTopRangeKey
} from './overviewViewRangeModel.js'

import {
  metricBlueprints,
  systemMetricBlueprints,
  systemAgentDailyRatio as fallbackSystemAgentDailyRatio,
  systemTokenDailyWave as fallbackSystemTokenDailyWave,
  systemUsageDurationSummary as fallbackSystemUsageDurationSummary,
  systemUserTokenUsage as fallbackSystemUserTokenUsage,
  systemAccuracyComparison as fallbackSystemAccuracyComparison,
  systemTrendSeries,
  systemToolCallMix,
  systemExecutionMix,
  systemToolRankings,
  systemModelUsage,
  systemFeedbackSummary as fallbackSystemFeedbackSummary,
  systemLoadHeatmap,
  systemToolDetailRows as fallbackSystemToolDetailRows
} from '../data/metrics.js'

export function useOverviewView(options = {}) {
  const activeDashboardKey = computed(() => {
    const dashboard = String(options.dashboard || '').trim()
    if (dashboard === 'commercial') return 'commercial'
    if (dashboard === 'value') return 'value'
    if (dashboard === 'system') return 'system'
    if (dashboard === 'risk') return 'risk'
    if (dashboard === 'digitalEmployee') return 'digitalEmployee'
    return 'finance'
  })
  const activeRangeValue = computed(() => String(options.activeRange || DEFAULT_OVERVIEW_RANGE).trim() || DEFAULT_OVERVIEW_RANGE)
  const customRangeValue = computed(() => options.customRange || {})
  const activeRangeLabel = computed(() => {
    if (activeRangeValue.value !== 'custom') {
      return activeRangeValue.value
    }
    const start = String(customRangeValue.value.start || '').trim()
    const end = String(customRangeValue.value.end || '').trim()
    return start && end ? `${start} ~ ${end}` : '\u81ea\u5b9a\u4e49'
  })
  const topRangeDays = computed(() => resolveTopRangeDays(activeRangeValue.value, customRangeValue.value))
  const financeDashboardPayload = ref(null)
  const financeDashboardLoading = ref(false)
  const financeDashboardError = ref(null)
  const financeDashboardRenderKey = ref(0)
  const financeDashboardLoaded = computed(() => Boolean(financeDashboardPayload.value))
  let financeDashboardRequestSeq = 0
  const systemDashboardPayload = ref(null)
  const systemDashboardLoading = ref(false)
  const systemDashboardError = ref(null)
  const systemDashboardLoaded = computed(() => Boolean(systemDashboardPayload.value))
  const riskDashboardPayload = ref(null)
  const riskDashboardLoading = ref(false)
  const riskDashboardError = ref(null)
  const riskDashboardLoaded = computed(() => Boolean(riskDashboardPayload.value))
  const riskDashboardLastUpdatedAt = ref('')
  let riskDashboardRefreshTimer = 0
  let riskDashboardRequestSeq = 0
  const digitalEmployeeDashboardPayload = ref(null)
  const digitalEmployeeDashboardLoading = ref(false)
  const digitalEmployeeDashboardError = ref(null)
  const digitalEmployeeDashboardLoaded = computed(() => Boolean(digitalEmployeeDashboardPayload.value))

  const formatSystemMetricValue = (metric, value) => (
    formatSystemMetricValueModel(metric, value, systemDashboardTotals.value)
  )

  const getFinanceRangeParams = () => {
    const activeRange = activeRangeValue.value
    const customRange = customRangeValue.value
    const isCustomRange = activeRange === 'custom'

    return {
      rangeKey: activeRange,
      startDate: isCustomRange ? customRange.start : '',
      endDate: isCustomRange ? customRange.end : '',
      trendRange: resolveTopRangeKey(activeRange, customRange),
      departmentRange: resolveTopRangeKey(activeRange, customRange)
    }
  }

  const loadFinanceDashboard = async () => {
    const requestSeq = ++financeDashboardRequestSeq
    financeDashboardLoading.value = true
    financeDashboardError.value = null

    try {
      const payload = await fetchFinanceDashboard(getFinanceRangeParams())
      if (requestSeq !== financeDashboardRequestSeq) {
        return
      }
      financeDashboardPayload.value = payload
      financeDashboardRenderKey.value += 1
    } catch (error) {
      if (requestSeq !== financeDashboardRequestSeq) {
        return
      }
      financeDashboardPayload.value = null
      financeDashboardError.value = error
    } finally {
      if (requestSeq === financeDashboardRequestSeq) {
        financeDashboardLoading.value = false
      }
    }
  }

  const loadSystemDashboard = async () => {
    systemDashboardLoading.value = true
    systemDashboardError.value = null

    try {
      systemDashboardPayload.value = await fetchSystemDashboard({ days: topRangeDays.value })
    } catch (error) {
      systemDashboardPayload.value = null
      systemDashboardError.value = error
    } finally {
      systemDashboardLoading.value = false
    }
  }

  const loadRiskDashboard = async () => {
    const requestSeq = ++riskDashboardRequestSeq
    riskDashboardLoading.value = true
    riskDashboardError.value = null

    try {
      const payload = await fetchRiskObservationDashboard({
        windowDays: topRangeDays.value,
        limit: 500
      })
      if (requestSeq !== riskDashboardRequestSeq) {
        return
      }
      riskDashboardPayload.value = payload
      riskDashboardLastUpdatedAt.value = new Date().toISOString()
    } catch (error) {
      if (requestSeq !== riskDashboardRequestSeq) {
        return
      }
      riskDashboardPayload.value = null
      riskDashboardError.value = error
    } finally {
      if (requestSeq === riskDashboardRequestSeq) {
        riskDashboardLoading.value = false
      }
    }
  }

  const startRiskDashboardRealtimeRefresh = () => {
    if (riskDashboardRefreshTimer) {
      window.clearInterval(riskDashboardRefreshTimer)
    }
    riskDashboardRefreshTimer = window.setInterval(() => {
      if (document.visibilityState === 'hidden' || riskDashboardLoading.value) {
        return
      }
      void loadRiskDashboard()
    }, 30_000)
  }

  const stopRiskDashboardRealtimeRefresh = () => {
    if (!riskDashboardRefreshTimer) {
      return
    }
    window.clearInterval(riskDashboardRefreshTimer)
    riskDashboardRefreshTimer = 0
  }

  const loadDigitalEmployeeDashboard = async () => {
    digitalEmployeeDashboardLoading.value = true
    digitalEmployeeDashboardError.value = null

    try {
      digitalEmployeeDashboardPayload.value = await fetchDigitalEmployeeDashboard({
        days: topRangeDays.value,
        limit: 300
      })
    } catch (error) {
      digitalEmployeeDashboardPayload.value = null
      digitalEmployeeDashboardError.value = error
    } finally {
      digitalEmployeeDashboardLoading.value = false
    }
  }

  const loadActiveDashboard = () => {
    if (activeDashboardKey.value === 'commercial' || activeDashboardKey.value === 'value') {
      stopRiskDashboardRealtimeRefresh()
      return
    }
    if (activeDashboardKey.value === 'system') {
      void loadSystemDashboard()
      stopRiskDashboardRealtimeRefresh()
      return
    }
    if (activeDashboardKey.value === 'risk') {
      void loadRiskDashboard()
      startRiskDashboardRealtimeRefresh()
      return
    }
    if (activeDashboardKey.value === 'digitalEmployee') {
      void loadDigitalEmployeeDashboard()
      stopRiskDashboardRealtimeRefresh()
      return
    }

    void loadFinanceDashboard()
    stopRiskDashboardRealtimeRefresh()
  }

  onMounted(() => {
    loadActiveDashboard()
  })

  onBeforeUnmount(() => {
    stopRiskDashboardRealtimeRefresh()
  })

  watch(
    () => [
      options.activeRange,
      options.customRange?.start,
      options.customRange?.end
    ],
    () => {
      loadActiveDashboard()
    }
  )

  watch(activeDashboardKey, () => {
    loadActiveDashboard()
  })

  const systemDashboardTotals = computed(() => (
    systemDashboardPayload.value?.totals || emptySystemDashboardTotals
  ))
  const systemAgentDailyRatio = computed(() => (
    systemDashboardPayload.value?.agentDailyRatio || fallbackSystemAgentDailyRatio
  ))
  const systemLoginWave = computed(() => (
    systemDashboardPayload.value?.loginWave || emptySystemLoginWave
  ))
  const systemTokenDailyWave = computed(() => (
    systemDashboardPayload.value?.tokenDailyWave || fallbackSystemTokenDailyWave
  ))
  const systemUsageDurationSummary = computed(() => (
    systemDashboardPayload.value?.usageDurationSummary || fallbackSystemUsageDurationSummary
  ))
  const systemUserTokenUsage = computed(() => (
    systemDashboardPayload.value?.userTokenUsage || fallbackSystemUserTokenUsage
  ))
  const systemAccuracyComparison = computed(() => (
    systemDashboardPayload.value?.accuracyComparison || fallbackSystemAccuracyComparison
  ))
  const systemFeedbackSummary = computed(() => (
    systemDashboardPayload.value?.feedbackSummary || fallbackSystemFeedbackSummary
  ))
  const systemToolDetailRows = computed(() => (
    systemDashboardPayload.value?.toolDetailRows || fallbackSystemToolDetailRows
  ))
  const riskDashboard = computed(() => (
    riskDashboardPayload.value || {
      windowDays: topRangeDays.value,
      totalObservations: 0,
      pendingCount: 0,
      riskClueCount: 0,
      highOrAboveCount: 0,
      confirmedCount: 0,
      falsePositiveCount: 0,
      feedbackSampleCount: 0,
      totalAmount: 0,
      averageScore: 0,
      confirmationRate: 0,
      falsePositiveRate: 0,
      levelDistribution: {},
      statusDistribution: {},
      signalDistribution: {},
      sourceDistribution: {},
      automationDistribution: {},
      departmentDistribution: {},
      expenseTypeDistribution: {},
      riskTypeDistribution: {},
      supplierDistribution: {},
      employeeGradeDistribution: {},
      dailyTrend: [],
      topRiskSignals: [],
      topDepartments: [],
      topEmployees: [],
      topSuppliers: [],
      topExpenseTypes: [],
      topRules: [],
      recentHighObservations: []
    }
  ))
  const digitalEmployeeDashboard = computed(() => (
    digitalEmployeeDashboardPayload.value || emptyDigitalEmployeeDashboard
  ))
  const financeDashboardTotals = computed(() => (
    financeDashboardPayload.value?.totals || emptyFinanceTotals
  ))
  const financeMetricMeta = computed(() => (
    financeDashboardPayload.value?.metricMeta || {}
  ))
  const financeTrend = computed(() => (
    financeDashboardPayload.value?.trend || emptyFinanceTrend
  ))
  const financeSpendByCategory = computed(() => (
    financeDashboardPayload.value?.spendByCategory || emptyFinanceDonut
  ))
  const financeExceptionMix = computed(() => (
    financeDashboardPayload.value?.exceptionMix || emptyFinanceDonut
  ))
  const financeDepartmentRanking = computed(() => (
    financeDashboardPayload.value?.departmentRanking || []
  ))
  const financeDepartmentEmployeeMix = computed(() => (
    financeDashboardPayload.value?.departmentEmployeeMix || emptyFinanceDonut
  ))
  const financeEmployeeRanking = computed(() => (
    financeDashboardPayload.value?.employeeRanking || []
  ))
  const financeTopClaims = computed(() => (
    financeDashboardPayload.value?.topClaims || []
  ))
  const financeBottlenecks = computed(() => (
    financeDashboardPayload.value?.bottlenecks || []
  ))
  const financeBudgetSummary = computed(() => (
    financeDashboardPayload.value?.budgetSummary || emptyFinanceBudgetSummary
  ))
  const financeBudgetMetrics = computed(() => (
    financeDashboardPayload.value?.budgetMetrics || emptyFinanceBudgetMetrics
  ))

  const resolveSystemMetricMeta = (metric) => (
    resolveSystemMetricMetaModel(metric, systemDashboardTotals.value, Boolean(systemDashboardPayload.value))
  )

  const resolveFinanceMetricMeta = (metric) => resolveFinanceMetricMetaModel({
    metric,
    meta: financeMetricMeta.value[metric.key],
    dashboardLoaded: Boolean(financeDashboardPayload.value),
    loading: financeDashboardLoading.value,
    error: financeDashboardError.value
  })

  const kpiMetrics = computed(() => metricBlueprints.map((metric, index) => {
    const rawValue = Number(financeDashboardTotals.value[metric.key] || 0)
    const displayValue = formatMetricValue(metric, rawValue)
    const metricMeta = resolveFinanceMetricMeta(metric)

    return {
      ...metric,
      ...metricMeta,
      displayValue,
      delay: index * 55
    }
  }))

  const systemKpiMetrics = computed(() => systemMetricBlueprints.map((metric, index) => {
    const rawValue = systemDashboardTotals.value[metric.key]
    const displayValue = formatSystemMetricValue(metric, rawValue)
    const metricMeta = resolveSystemMetricMeta(metric)

    return {
      ...metric,
      ...metricMeta,
      displayValue,
      delay: index * 55
    }
  }))

  const riskKpiMetrics = computed(() => {
    const data = riskDashboard.value
    const rows = [
      {
        label: '新增风险数',
        value: formatNumberCompact(data.totalObservations),
        changeText: `${data.windowDays}天`,
        delta: '统一观察池',
        trend: 'up',
        icon: 'mdi mdi-shield-search',
        accent: 'var(--theme-primary)'
      },
      {
        label: '高风险待处置',
        value: formatNumberCompact(data.highOrAboveCount),
        changeText: data.highOrAboveCount > 0 ? '需关注' : '稳定',
        delta: '高/重大风险',
        trend: data.highOrAboveCount > 0 ? 'down' : 'up',
        icon: 'mdi mdi-alert-octagon-outline',
        accent: '#ef4444'
      },
      {
        label: '涉及金额',
        value: formatCurrency(Number(data.totalAmount || 0)),
        changeText: '归集',
        delta: '关联单据金额',
        trend: 'up',
        icon: 'mdi mdi-cash-multiple',
        accent: '#0f766e'
      },
      {
        label: '已确认风险',
        value: formatNumberCompact(data.confirmedCount),
        changeText: formatPercent(data.confirmationRate),
        delta: '人工确认',
        trend: 'up',
        icon: 'mdi mdi-check-decagram-outline',
        accent: 'var(--success)'
      },
      {
        label: '误报数量',
        value: formatNumberCompact(data.falsePositiveCount),
        changeText: formatPercent(data.falsePositiveRate),
        delta: '反馈校准',
        trend: data.falsePositiveRate > 0.2 ? 'down' : 'up',
        icon: 'mdi mdi-tune-variant',
        accent: '#8b5cf6'
      },
      {
        label: '待复核',
        value: formatNumberCompact(data.pendingCount),
        changeText: '待处理',
        delta: '人工闭环',
        trend: data.pendingCount > 0 ? 'down' : 'up',
        icon: 'mdi mdi-account-clock-outline',
        accent: '#f59e0b'
      }
    ]

    return rows.map((item, index) => ({
      ...item,
      displayValue: item.value,
      delay: index * 55
    }))
  })

  const digitalEmployeeKpiMetrics = computed(() => (
    buildDigitalEmployeeKpiMetrics(digitalEmployeeDashboard.value, formatNumberCompact)
  ))

  const activeTrend = computed(() => financeTrend.value)
  const spendTotal = computed(() => financeSpendByCategory.value.reduce((sum, item) => sum + Number(item.value || 0), 0))
  const riskTotal = computed(() => financeExceptionMix.value.reduce((sum, item) => sum + Number(item.value || 0), 0))
  const departmentEmployeeTotal = computed(() => (
    financeDepartmentEmployeeMix.value.reduce((sum, item) => sum + Number(item.value || item.amount || 0), 0)
  ))
  const spendCenterValue = computed(() => formatCurrency(Math.round(spendTotal.value)))
  const departmentEmployeeCenterValue = computed(() => formatCurrency(Math.round(departmentEmployeeTotal.value)))

  const spendLegend = computed(() => financeSpendByCategory.value.map((item) => ({
    ...item,
    display: spendTotal.value ? `${Math.round((Number(item.value || 0) / spendTotal.value) * 100)}%` : '0%'
  })))

  const riskLegend = computed(() => financeExceptionMix.value.map((item) => ({
    ...item,
    display: `${item.value} 单`
  })))

  const departmentEmployeeLegend = computed(() => financeDepartmentEmployeeMix.value.map((item) => ({
    ...item,
    value: Number(item.value || item.amount || 0),
    display: departmentEmployeeTotal.value
      ? `${Math.round((Number(item.value || item.amount || 0) / departmentEmployeeTotal.value) * 100)}%`
      : '0%'
  })))

  const systemToolTotal = computed(() =>
    systemToolCallMix.reduce((sum, item) => sum + item.value, 0)
  )
  const systemExecutionTotal = computed(() =>
    systemExecutionMix.reduce((sum, item) => sum + item.value, 0)
  )
  const systemToolCallLegend = computed(() => systemToolCallMix.map((item) => ({
    ...item,
    display: `${Math.round((item.value / systemToolTotal.value) * 100)}%`
  })))
  const systemExecutionLegend = computed(() => systemExecutionMix.map((item) => ({
    ...item,
    display: `${Math.round((item.value / systemExecutionTotal.value) * 1000) / 10}%`
  })))

  const rankedDepartments = computed(() => {
    const rows = financeDepartmentRanking.value
      .filter((item) => !isMissingDimension(item.name))
      .map((item) => ({
        ...item,
        amount: Number(item.amount || item.value || 0)
      }))
    const max = Math.max(...rows.map((item) => item.amount), 1)

    return rows.slice(0, 6).map((item, index) => ({
      ...item,
      rank: index + 1,
      shortName: item.name,
      amountLabel: formatCurrency(item.amount),
      meta: `${Number(item.employeeCount || 0)} 人 / ${Number(item.count || 0)} 单`,
      width: `${Math.max((item.amount / max) * 100, 18)}%`,
      color: item.color
    }))
  })

  const rankedEmployees = computed(() => {
    const rows = financeEmployeeRanking.value
      .filter((item) => !isMissingDimension(item.name))
      .map((item) => ({
        ...item,
        amount: Number(item.amount || item.value || 0)
      }))
    const max = Math.max(...rows.map((item) => item.amount), 1)

    return rows.slice(0, 6).map((item, index) => ({
      ...item,
      rank: index + 1,
      shortName: item.name,
      amountLabel: formatCurrency(item.amount),
      meta: `${item.department || '未归属部门'} / ${Number(item.count || 0)} 单`,
      width: `${Math.max((item.amount / max) * 100, 18)}%`,
      color: item.color
    }))
  })

  const topClaims = computed(() => (
    financeTopClaims.value.map((item) => ({
      ...item,
      amountLabel: item.amountLabel || formatCurrency(Number(item.amount || 0))
    }))
  ))

  const systemToolRankingItems = computed(() => systemToolRankings.map((item, index) => ({
    ...item,
    rank: index + 1,
    shortName: item.name,
    amount: item.value
  })))

  const systemModelUsageRows = computed(() => systemModelUsage.map((item) => ({
    ...item,
    tokenLabel: `${formatNumberCompact(item.tokens)} tokens`,
    width: `${Math.max(Math.min(item.share, 100), 8)}%`
  })))

  const systemExecutionRows = computed(() => systemExecutionMix.map((item) => ({
    ...item,
    display: `${Math.round((item.value / systemExecutionTotal.value) * 1000) / 10}%`,
    width: `${Math.max((item.value / systemExecutionTotal.value) * 100, 1)}%`
  })))

  const systemToolDetailItems = computed(() => {
    const maxCalls = Math.max(...systemToolDetailRows.value.map((item) => item.calls), 1)

    return systemToolDetailRows.value.map((item) => ({
      ...item,
      callLabel: `${formatNumberCompact(item.calls)} 次`,
      tokenLabel: `${formatNumberCompact(item.tokens)} tokens`,
      width: `${Math.max((item.calls / maxCalls) * 100, 10)}%`
    }))
  })

  const systemUsageDurationRows = computed(() => {
    const rows = systemUsageDurationSummary.value.rows || []
    const maxValue = Math.max(...rows.map((item) => item.value), 1)

    return rows.map((item) => ({
      ...item,
      width: `${Math.max((item.value / maxValue) * 100, 12)}%`
    }))
  })

  const riskLevelLegend = computed(() => buildRiskDistributionLegend(
    riskDashboard.value.levelDistribution,
    {
      critical: '重大风险',
      high: '高风险',
      medium: '中风险',
      low: '低风险'
    },
    {
      critical: '#b91c1c',
      high: '#ef4444',
      medium: '#f59e0b',
      low: '#3b82f6'
    }
  ))
  const riskCompositionLegend = computed(() => {
    const signalDistribution = riskDashboard.value.signalDistribution || {}
    const fallbackDistribution = Object.fromEntries(
      (Array.isArray(riskDashboard.value.topRiskSignals) ? riskDashboard.value.topRiskSignals : [])
        .map((item) => [item.name, Number(item.count || 0)])
    )

    return buildRiskDistributionLegend(
      Object.keys(signalDistribution).length ? signalDistribution : fallbackDistribution,
      {},
      {
        duplicate_invoice: '#ef4444',
        budget_pressure: '#f59e0b',
        amount_outlier: '#8b5cf6',
        weekend_or_holiday: '#2563eb',
        supplier_anomaly: '#0f766e',
        split_billing: '#dc2626',
        missing_material: '#64748b'
      },
      formatRiskSignalName
    )
  })
  const riskSignalRanking = computed(() => {
    const rows = Array.isArray(riskDashboard.value.topRiskSignals)
      ? riskDashboard.value.topRiskSignals
      : []
    const fallbackRows = Object.entries(riskDashboard.value.signalDistribution || {})
      .map(([name, count]) => ({ name, count }))

    return (rows.length ? rows : fallbackRows)
      .slice(0, 6)
      .map((item, index) => ({
        name: formatRiskSignalName(item.name),
        shortName: formatRiskSignalName(item.name),
        value: Number(item.count || 0),
        color: [
          '#ef4444',
          '#f59e0b',
          'var(--theme-primary)',
          '#3b82f6',
          '#8b5cf6',
          '#0f766e'
        ][index] || '#64748b'
      }))
  })
  const riskDailyTrendRows = computed(() => {
    const rows = Array.isArray(riskDashboard.value.dailyTrend) ? riskDashboard.value.dailyTrend : []
    const normalizedRows = aggregateRiskDailyTrendRows(rows)
    const maxValue = Math.max(...normalizedRows.map((item) => item.total), 1)

    return normalizedRows.map((item) => ({
      ...item,
      width: `${Math.max((item.total / maxValue) * 100, 4)}%`,
      highWidth: `${Math.max((item.highOrAbove / maxValue) * 100, item.highOrAbove ? 4 : 0)}%`
    }))
  })
  const digitalEmployeeDailyRows = computed(() => buildDigitalEmployeeDailyRows(digitalEmployeeDashboard.value))
  const digitalEmployeeTaskRanking = computed(() => buildDigitalEmployeeTaskRanking(digitalEmployeeDashboard.value))
  const digitalEmployeeCategoryRows = computed(() => buildDigitalEmployeeCategoryRows(digitalEmployeeDashboard.value))

  const bottlenecks = financeBottlenecks
  const budgetSummary = financeBudgetSummary
  const budgetMetrics = financeBudgetMetrics
  const spendByCategory = financeSpendByCategory
  const exceptionMix = financeExceptionMix

  return {
    activeRangeLabel,
    activeTrend,
    bottlenecks,
    budgetMetrics,
    budgetSummary,
    departmentEmployeeCenterValue,
    departmentEmployeeLegend,
    digitalEmployeeCategoryRows,
    digitalEmployeeDashboard,
    digitalEmployeeDashboardError,
    digitalEmployeeDashboardLoaded,
    digitalEmployeeDashboardLoading,
    digitalEmployeeDailyRows,
    digitalEmployeeKpiMetrics,
    digitalEmployeeTaskRanking,
    exceptionMix,
    financeDashboardError,
    financeDashboardLoaded,
    financeDashboardLoading,
    financeDashboardRenderKey,
    formatCompact,
    formatCurrency,
    formatMetricValue,
    formatNumberCompact,
    formatSystemMetricValue,
    kpiMetrics,
    metricBlueprints,
    rankedDepartments,
    rankedEmployees,
    riskDashboard,
    riskDashboardError,
    riskDashboardLoaded,
    riskDashboardLastUpdatedAt,
    riskDashboardLoading,
    riskDailyTrendRows,
    riskLegend,
    riskKpiMetrics,
    riskLevelLegend,
    riskSignalRanking,
    riskCompositionLegend,
    riskTotal,
    spendByCategory,
    spendCenterValue,
    spendLegend,
    spendTotal,
    systemDashboardTotals,
    systemDashboardError,
    systemDashboardLoaded,
    systemDashboardLoading,
    systemAgentDailyRatio,
    systemLoginWave,
    systemTokenDailyWave,
    systemUsageDurationRows,
    systemUsageDurationSummary,
    systemUserTokenUsage,
    systemAccuracyComparison,
    systemExecutionLegend,
    systemExecutionMix,
    systemExecutionTotal,
    systemFeedbackSummary,
    systemKpiMetrics,
    systemLoadHeatmap,
    systemExecutionRows,
    systemMetricBlueprints,
    systemModelUsageRows,
    systemToolDetailItems,
    systemToolCallLegend,
    systemToolCallMix,
    systemToolRankingItems,
    systemToolRankings,
    systemToolTotal,
    systemTrendSeries,
    topClaims
  }
}
