import { normalizeResponseData, requestJson } from "./request"

const OPEN_API_BASE = import.meta.env.VITE_OPEN_API_BASE || "/openApi"

function joinBase(path) {
  if (/^https?:\/\//.test(path)) return path
  return `${OPEN_API_BASE}${path.startsWith("/") ? path : `/${path}`}`
}

function unwrapResponse(response) {
  const failed =
    response?.success === false ||
    (response?.code !== undefined && ![0, 200, "0", "200"].includes(response.code))

  if (failed) {
    const error = new Error(response?.msg || response?.message || "图表接口请求失败")
    error.code = response?.code
    throw error
  }

  return normalizeResponseData(response)
}

export async function getSmartChartsForQuestion(question, pagePath = window.location.hash || window.location.pathname, pageName = "智慧管理") {
  const data = await requestJson(joinBase("/ai/stat/charts"), {
    params: {
      question,
      pagePath,
      pageName,
    },
    timeout: 30000,
  }).then(unwrapResponse)

  const charts = Array.isArray(data?.charts) ? data.charts : []
  return charts
    .map(normalizeChart)
    .filter((chart) => chart.rows.length)
}

function normalizeChart(chart, index) {
  const rows = Array.isArray(chart?.rows) ? chart.rows : []
  return {
    id: chart?.id || `smart-chart-${index}`,
    type: normalizeChartType(chart?.type),
    title: chart?.title || `统计图表${index + 1}`,
    subtitle: chart?.subtitle || buildSourceSubtitle(chart?.source),
    unit: chart?.unit || "",
    source: chart?.source || {},
    rows: rows
      .map((row, rowIndex) => ({
        key: row?.key || `${row?.name || "row"}-${rowIndex}`,
        name: String(row?.name || `指标${rowIndex + 1}`),
        value: toNumber(row?.value),
        rawValue: row?.value,
        unit: row?.unit || chart?.unit || "",
        extra: row?.extra || "",
      }))
      .filter((row) => row.name && Number.isFinite(row.value)),
  }
}

function normalizeChartType(type) {
  if (["pie", "donut"].includes(type)) return "pie"
  if (["line", "trend"].includes(type)) return "line"
  return "bar"
}

function buildSourceSubtitle(source = {}) {
  const table = source.table ? `来源：${source.table}` : "来源：openApi 统计库"
  const period = source.period ? `，${source.period}` : ""
  return `${table}${period}`
}

function toNumber(value) {
  if (value === undefined || value === null || value === "") return NaN
  const number = Number(String(value).replace(/,/g, "").replace(/%/g, ""))
  return Number.isFinite(number) ? number : NaN
}
