import axios from 'axios'

const WEATHER_API_URL = 'https://gfeljm.tianqiapi.com/api'

/** 将 win_meter（如 10km/h）转为 m/s 展示 */
export function parseWinMeterToMs(winMeter) {
  if (winMeter == null || winMeter === '') {
    return '--'
  }
  const text = String(winMeter)
  const kmh = text.match(/([\d.]+)\s*km\s*\/\s*h/i)
  if (kmh) {
    return (Number(kmh[1]) / 3.6).toFixed(1)
  }
  const ms = text.match(/([\d.]+)\s*m\s*\/\s*s/i)
  if (ms) {
    return Number(ms[1]).toFixed(1)
  }
  return text
}

/** 巴青实时气象（天启 API v63） */
export async function getBaqingWeather() {
  const appid = import.meta.env.VITE_WEATHER_APP_ID
  const appsecret = import.meta.env.VITE_WEATHER_APP_SECRET
  if (!appid || !appsecret) {
    throw new Error('未配置气象接口密钥')
  }

  const { data } = await axios.get(WEATHER_API_URL, {
    timeout: 20000,
    params: {
      unescape: 1,
      version: 'v63',
      appid,
      appsecret,
      city: import.meta.env.VITE_WEATHER_CITY || '巴青'
    }
  })

  if (!data || typeof data !== 'object') {
    throw new Error('气象数据格式异常')
  }
  if (data.errcode != null && Number(data.errcode) !== 0) {
    throw new Error(data.errmsg || '气象接口返回错误')
  }
  return data
}
