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

const JSY_API_BASE = import.meta.env.VITE_JSY_API_BASE || "/jsyApi"
const AMAP_WEATHER_KEY = import.meta.env.VITE_AMAP_WEATHER_KEY || "b72b3e3b2023760dae2cdf2e00561812"
const HONGYUAN_CITY_CODE = "513233"

function unwrapWeatherResponse(response) {
  const failed = response?.success === false
    || (response?.code !== undefined && ![0, 200, "0", "200"].includes(response.code))
  if (failed) throw new Error(response?.msg || response?.message || "天气接口请求失败")
  return normalizeResponseData(response)
}

function normalizeWeatherRow(data) {
  const source = data?.data ?? data?.result ?? data
  const row = Array.isArray(source)
    ? source[0]
    : Array.isArray(source?.rows)
      ? source.rows[0]
      : Array.isArray(source?.list)
        ? source.list[0]
        : source
  if (!row || typeof row !== "object") return null

  const firstValue = (...values) => values.find((value) => value !== undefined && value !== null && value !== "")
  const temperature = firstValue(row.temp, row.temperature, row.temperature_float, row.tempDay, row.temperatureDay)
  const humidity = firstValue(row.humidity, row.humidity_float, row.pop, row.relativeHumidity)
  return {
    condition: row.conditionDay || row.condition || row.weather || row.weatherText || "",
    temperature: temperature === undefined || temperature === null || temperature === "" ? "--" : temperature,
    humidity: humidity === undefined || humidity === null || humidity === "" ? "--" : humidity,
    windDirection: row.windDir || row.windDirection || "",
    windLevel: row.windLevel || row.windScale || row.windPower || "",
    icon: row.icon ?? row.weatherIcon ?? null,
  }
}

async function requestWeather(path) {
  const response = await requestJson(`${JSY_API_BASE}${path}`, { timeout: 8000 })
  return normalizeWeatherRow(unwrapWeatherResponse(response))
}

function requestAmapWeather() {
  return new Promise((resolve, reject) => {
    const callbackName = `__hongyuanWeather${Date.now()}${Math.random().toString(16).slice(2)}`
    const script = document.createElement("script")
    const cleanup = () => {
      window.clearTimeout(timer)
      script.remove()
      delete window[callbackName]
    }
    const timer = window.setTimeout(() => {
      cleanup()
      reject(new Error("高德天气接口响应超时"))
    }, 8000)

    window[callbackName] = (response) => {
      const row = response?.lives?.[0]
      cleanup()
      if (!row) {
        reject(new Error(response?.info || "高德天气暂无数据"))
        return
      }
      resolve(normalizeWeatherRow(row))
    }
    script.onerror = () => {
      cleanup()
      reject(new Error("高德天气接口加载失败"))
    }
    const search = new URLSearchParams({
      city: HONGYUAN_CITY_CODE,
      key: AMAP_WEATHER_KEY,
      extensions: "base",
      output: "JSON",
      callback: callbackName,
    })
    script.src = `https://restapi.amap.com/v3/weather/weatherInfo?${search}`
    document.head.appendChild(script)
  })
}

export async function getCurrentWeather() {
  const endpoints = ["/api/home/realTimeWeather", "/api/home/weatherForecast"]
  let lastError = null
  for (const endpoint of endpoints) {
    try {
      const weather = await requestWeather(endpoint)
      if (weather) return weather
    } catch (error) {
      lastError = error
    }
  }
  try {
    const weather = await requestAmapWeather()
    if (weather) return weather
  } catch (error) {
    lastError = error
  }
  throw lastError || new Error("天气数据暂不可用")
}
