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

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

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 get(base, path, params, options = {}) {
  return requestJson(joinBase(base, path), {
    params,
    timeout: options.timeout,
  }).then(unwrapResponse)
}

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

async function firstMeaningful(requests, isMeaningful = (data) => Boolean(data)) {
  let lastError
  for (const request of requests) {
    try {
      const data = await request()
      if (isMeaningful(data)) return data
    } catch (error) {
      lastError = error
    }
  }
  if (lastError) throw lastError
  return null
}

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 function askStatQuestion(question, pagePath = window.location.hash || window.location.pathname, pageName = "智慧管理") {
  return get(
    OPEN_API_BASE,
    "/ai/stat/question",
    {
      question,
      pagePath,
      pageName,
    },
    { timeout: 45000 },
  )
}

export async function queryBalanceTargets(question) {
  const rows = await firstMeaningful(
    [
      () => get(JSY_API_BASE, "/ai/question/balance", { question }, { timeout: 18000 }),
      () => get(OPEN_API_BASE, "/ai/balance/targets", { question }, { timeout: 18000 }),
    ],
    (data) => normalizeRows(data).length > 0,
  )
  return normalizeRows(rows)
}

export async function getLivestockBalance({ areaCode, pasturesId } = {}) {
  return firstMeaningful(
    [
      () => get(JSY_API_BASE, "/ai/livestockBalance", { areaCode, pasturesId }, { timeout: 18000 }),
      () => get(OPEN_API_BASE, "/ai/balance/advice", { areaCode, pasturesId }, { timeout: 18000 }),
    ],
    (data) => data && typeof data === "object" && Object.keys(data).length > 0,
  )
}

export function getXiaomuWelcome() {
  return get(OPEN_API_BASE, "/ai/balance/welcome", undefined, { timeout: 12000 })
}
