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

const JSY_API_BASE = normalizeJsyApiBase(import.meta.env.VITE_JSY_API_BASE || "/jsyApi")
const OPEN_API_BASE = import.meta.env.VITE_OPEN_API_BASE || "/openApi"

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

function normalizeJsyApiBase(base) {
  const normalized = String(base || "/jsyApi").replace(/\/+$/, "")
  return normalized.endsWith("/api") ? normalized : `${normalized}/api`
}

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)
}

function get(base, path, params, options = {}) {
  return requestJson(joinBase(base, path), {
    params,
    timeout: options.timeout || 16000,
  }).then(unwrapResponse)
}

function normalizeRows(data) {
  if (Array.isArray(data)) return data
  if (Array.isArray(data?.rows)) return data.rows
  if (Array.isArray(data?.list)) return data.list
  if (Array.isArray(data?.data)) return data.data
  return []
}

function hasMeaningfulBalanceResult(data) {
  if (Array.isArray(data)) return data.length > 0
  if (!data || typeof data !== "object") return data !== undefined && data !== null && data !== ""

  const balanceKeys = [
    "areaRange",
    "area_range",
    "acreage",
    "grasslandArea",
    "grassland_area",
    "arearange",
    "area",
    "yakNumber",
    "yak_number",
    "yaknumber",
    "number",
    "yakCount",
    "yak_count",
    "livestockCount",
    "livestock_count",
    "bearingCapacity",
    "bearing_capacity",
    "bearingcapacity",
    "capacity",
    "theoryCapacity",
    "livestockCapacity",
    "livestock_capacity",
    "livestockcapacity",
    "carryingCapacity",
    "actualCapacity",
    "overloadRate",
    "overload_rate",
    "overloadrate",
    "rate",
    "level",
    "conclusion",
    "advice",
    "balanceAdvice",
    "balance_advice",
  ]

  return balanceKeys.some((key) => data[key] !== undefined && data[key] !== null && data[key] !== "")
}

export async function getBalanceAdvice({ areaCode } = {}) {
  const params = {
    areaCode,
  }
  const requests = [
    () => get(JSY_API_BASE, "/ai/livestockBalance", params, { timeout: 18000 }),
    () => get(OPEN_API_BASE, "/ai/balance/advice", params, { timeout: 18000 }),
  ]

  let lastError
  for (const request of requests) {
    try {
      const result = await request()
      if (hasMeaningfulBalanceResult(result)) return result
    } catch (error) {
      lastError = error
    }
  }
  throw lastError || new Error("草畜平衡接口不可用")
}

export async function queryBalanceTargets(question) {
  const requests = [
    () => get(JSY_API_BASE, "/ai/question/balance", { question }, { timeout: 16000 }),
    () => get(OPEN_API_BASE, "/ai/balance/targets", { question }, { timeout: 16000 }),
  ]

  let lastError
  for (const request of requests) {
    try {
      const rows = normalizeRows(await request())
      if (rows.length) return rows
    } catch (error) {
      lastError = error
    }
  }
  if (lastError) throw lastError
  return []
}

export async function getAreaChildren(areaCode) {
  const requests = [
    () => get(JSY_API_BASE, "/area/children", { areaCode }, { timeout: 12000 }),
    () => get(JSY_API_BASE, "/map/areaCode", { areaCode }, { timeout: 12000 }),
  ]

  let lastError
  let hasEmptyResult = false
  for (const request of requests) {
    try {
      const rows = normalizeRows(await request())
      if (rows.length) return rows
      hasEmptyResult = true
    } catch (error) {
      lastError = error
    }
  }
  if (hasEmptyResult) return []
  throw lastError || new Error("区划接口不可用")
}
