import { ref } from 'vue'
import { fetchReportMetricsRegistry } from '@/api/ops/report'

export type MetricRegistryOption = { label: string; value: string }

/** 统计 / TopN：按数据源加载逻辑指标目录下拉 */
export function useReportMetricRegistryOptions() {
  const metricOptions = ref<MetricRegistryOption[]>([])
  const metricOptionsLoading = ref(false)

  async function loadMetricRegistryOptions(dataSource: string) {
    metricOptions.value = []
    if (!dataSource) return

    metricOptionsLoading.value = true
    try {
      const res = await fetchReportMetricsRegistry({ data_source: dataSource })
      if (res.code !== 0 || !res.details) {
        metricOptions.value = []
        return
      }
      const rows = Array.isArray(res.details.metrics) ? res.details.metrics : []
      const acc: MetricRegistryOption[] = []
      for (const m of rows) {
        const id = (m?.ID ?? m?.id ?? '') as string
        const dn = (m?.DisplayName ?? m?.display_name ?? '') as string
        const metricName = (m?.MetricName ?? m?.metric_name ?? '') as string
        const key = String(id || metricName).trim()
        if (!key) continue
        const label = dn ? `${dn} (${key})` : key
        acc.push({ label, value: key })
      }
      metricOptions.value = acc
    } catch (e) {
      console.error('加载指标目录失败:', e)
      metricOptions.value = []
    } finally {
      metricOptionsLoading.value = false
    }
  }

  return {
    metricOptions,
    metricOptionsLoading,
    loadMetricRegistryOptions,
  }
}
