"""Open-Meteo client and per-segment aggregation into four tiers.""" from __future__ import annotations from typing import Any import httpx from app.models.route import TrekkerRoute API_URL = "https://api.open-meteo.com/v1/forecast" HOURLY_VARS = "temperature_2m,precipitation_probability,precipitation,wind_speed_10m,wind_gusts_10m,weather_code" DAILY_VARS = "temperature_2m_max,temperature_2m_min,precipitation_probability_max,precipitation_sum,wind_speed_10m_max,weather_code" # Open-Meteo WMO codes indicating thunderstorms (lightning risk) THUNDER_CODES = {95, 96, 99} WIND_ADVISORY_KMH = 40.0 def fetch_forecast(lat: float, lon: float, days: int = 7) -> dict[str, Any]: if days not in (7, 10): raise ValueError("forecast window must be 7 or 10 days") resp = httpx.get( API_URL, params={ "latitude": round(lat, 4), "longitude": round(lon, 4), "hourly": HOURLY_VARS, "daily": DAILY_VARS, "forecast_days": days, "timezone": "auto", "wind_speed_unit": "kmh", "temperature_unit": "fahrenheit", "precipitation_unit": "inch", }, timeout=30, ) resp.raise_for_status() return resp.json() def _chunk_hours(hourly: dict[str, list], hours_per_bucket: int) -> list[dict[str, Any]]: times = hourly.get("time", []) buckets = [] for start in range(0, len(times), hours_per_bucket): end = min(start + hours_per_bucket, len(times)) sl = slice(start, end) def vals(key: str) -> list[float]: return [v for v in hourly.get(key, [])[sl] if v is not None] temps = vals("temperature_2m") winds = vals("wind_speed_10m") codes = vals("weather_code") precip_prob = vals("precipitation_probability") buckets.append({ "time_start": times[start], "time_end": times[end - 1], "temp_min_f": min(temps) if temps else None, "temp_max_f": max(temps) if temps else None, "precip_prob_max": max(precip_prob) if precip_prob else None, "precip_sum_in": round(sum(vals("precipitation")), 3), "wind_max_kmh": max(winds) if winds else None, "wind_advisory": bool(winds) and max(winds) >= WIND_ADVISORY_KMH, "lightning_risk": any(int(c) in THUNDER_CODES for c in codes), }) return buckets def build_tiers(forecast: dict[str, Any]) -> dict[str, Any]: """Hourly / 6h / 12h / daily tiers from a raw Open-Meteo response.""" hourly = forecast.get("hourly", {}) daily = forecast.get("daily", {}) return { "hourly": _chunk_hours(hourly, 1), "6h": _chunk_hours(hourly, 6), "12h": _chunk_hours(hourly, 12), "daily": [ { "date": daily["time"][i], "temp_min_f": daily["temperature_2m_min"][i], "temp_max_f": daily["temperature_2m_max"][i], "precip_prob_max": daily["precipitation_probability_max"][i], "precip_sum_in": daily["precipitation_sum"][i], "wind_max_kmh": daily["wind_speed_10m_max"][i], "lightning_risk": int(daily["weather_code"][i]) in THUNDER_CODES, } for i in range(len(daily.get("time", []))) ], } def segment_midpoints(route: TrekkerRoute) -> list[tuple[int, float, float]]: out = [] for seg in route.segments: mid = route.points[(seg.start_idx + seg.end_idx) // 2] out.append((seg.index, mid.lat, mid.lon)) return out def fetch_route_weather(route: TrekkerRoute, days: int = 7) -> dict[str, Any]: """Per-segment forecasts. Nearby midpoints share one fetch (0.05° grid).""" cache: dict[tuple[float, float], dict] = {} segments = {} for idx, lat, lon in segment_midpoints(route): key = (round(lat / 0.05) * 0.05, round(lon / 0.05) * 0.05) if key not in cache: cache[key] = build_tiers(fetch_forecast(lat, lon, days)) segments[str(idx)] = cache[key] return {"days": days, "segments": segments}