export interface WeatherData {
  temperature: number
  windspeed: number
  winddirection: number
  weathercode: number
  time: string
  source: 'openmeteo'
}

export async function fetchOpenMeteo(lat: number, lng: number): Promise<WeatherData> {
  const url = new URL('https://api.open-meteo.com/v1/forecast')
  url.searchParams.set('latitude', lat.toFixed(4))
  url.searchParams.set('longitude', lng.toFixed(4))
  url.searchParams.set('current', 'temperature_2m,windspeed_10m,winddirection_10m,weathercode')
  url.searchParams.set('wind_speed_unit', 'kmh')
  url.searchParams.set('timezone', 'Europe/Lisbon')
  const res = await fetch(url.toString(), { next: { revalidate: 1800 } })
  if (!res.ok) throw new Error(`Open-Meteo error: ${res.status}`)
  const json = await res.json()
  const c = json.current
  return { temperature: c.temperature_2m, windspeed: c.windspeed_10m, winddirection: c.winddirection_10m, weathercode: c.weathercode, time: c.time, source: 'openmeteo' }
}

export function wmoCodeToLabel(code: number): string {
  if (code === 0) return 'Céu limpo'
  if (code <= 3) return 'Nuvens'
  if (code <= 9) return 'Nevoeiro'
  if (code <= 29) return 'Precipitação'
  if (code <= 69) return 'Chuva'
  if (code <= 79) return 'Neve'
  if (code <= 84) return 'Aguaceiros'
  if (code <= 99) return 'Trovoada'
  return 'Condições severas'
}

export function isGoodForFlying(weather: WeatherData): boolean {
  return weather.windspeed < 30 && weather.weathercode <= 3
}
