const NDVI_TIMELINE_URL = "/jsyApi/api/map/ndvi_timeline"

export async function getGrasslandNdviTimeline() {
  const response = await fetch(NDVI_TIMELINE_URL, {
    credentials: "include",
    headers: {
      Accept: "application/json",
    },
  })
  if (!response.ok) {
    const error = new Error(`HTTP ${response.status}`)
    error.status = response.status
    throw error
  }
  const data = await response.json().catch(() => ({}))
  if (data?.code === 401 || data?.code === "401") {
    const error = new Error(data?.msg || data?.message || "NDVI 时间轴未授权")
    error.status = 401
    throw error
  }
  const rows = Array.isArray(data?.data) ? data.data : Array.isArray(data) ? data : []
  return normalizeNdviTimelineRows(rows)
}

function normalizeNdviTimelineRows(rows = []) {
  const seen = new Set()
  return rows
    .map((row, index) => {
      const layerName = normalizeTimelineLayerName(pickValue(row, ["url", "layerName", "layer_name", "layer", "name"]))
      if (!layerName) return null
      const rawDate = pickValue(row, ["date", "month", "time", "label"]) || layerName
      const label = formatTimelineLabel(rawDate)
      const key = `${layerName}-${rawDate || index}`
      return {
        key,
        label,
        date: String(rawDate),
        layerName,
        source: row,
      }
    })
    .filter(Boolean)
    .filter((item) => {
      if (seen.has(item.key)) return false
      seen.add(item.key)
      return true
    })
}

function pickValue(item, keys) {
  for (const key of keys) {
    if (item?.[key] !== undefined && item?.[key] !== null && item?.[key] !== "") {
      return item[key]
    }
  }
  return undefined
}

function normalizeTimelineLayerName(value) {
  const text = String(value || "").trim()
  if (!text) return ""
  if (text.includes(":") || /^https?:\/\//i.test(text)) return text
  return `ne:${text}`
}

function formatTimelineLabel(value) {
  const text = String(value || "").trim()
  if (!text) return ""
  const match = text.match(/(\d{4})[-_/年. ]?(0?[1-9]|1[0-2])(?:月)?/)
  if (match) return `${match[1]}.${String(Number(match[2])).padStart(2, "0")}`
  return text
}
