""" OpenWeatherMap → CrisisSignal client. Why it lives here ----------------- This is the only module in CIRO that knows the shape of an OWM response. Every other phase consumes `CrisisSignal` instances and never touches OWM's wire format directly. If OWM ever changes their schema or we swap providers, this is the one file that has to follow. Failure policy -------------- A weather miss must NEVER take the pipeline down. Network timeouts, bad keys, OWM 5xx responses, and unparseable payloads all collapse to a single behaviour: `fetch_weather_signal()` returns `None` and logs. Callers (`signal_aggregator`) treat `None` as "no weather evidence" and move on. """ from __future__ import annotations import logging from datetime import datetime, timezone import httpx from backend.core.config import settings from backend.models.signal import ( TRUST_WEIGHT_WEATHER, CrisisSignal, SeverityHint, SignalType, ) logger = logging.getLogger(__name__) OWM_BASE_URL = "https://api.openweathermap.org/data/2.5/weather" OWM_TIMEOUT_SECONDS = 5.0 def _classify(weather_id: int, rain_1h: float) -> tuple[SignalType, SeverityHint | None]: """Map an OpenWeatherMap condition code to CIRO's (signal_type, severity). OWM groups conditions by leading digit: 2xx thunderstorm 3xx drizzle 5xx rain (502+ is heavy) 6xx snow 7xx atmosphere (mist/fog/smoke/dust) 800 clear 80x clouds For CIRO we collapse this onto our 5-category taxonomy: thunderstorm → "flood" (heaviest precipitation, flood risk) rain / drizzle → "rainfall" (severity inferred from code/rain_1h) otherwise → "rainfall" with severity_hint=None (i.e. "no precipitation worth flagging" — we still return a signal so the agent sees the *absence*). """ if 200 <= weather_id < 300: return "flood", "heavy" if 500 <= weather_id < 600: # 500 = light rain, 501 = moderate, 502+ = heavy rain / extreme if weather_id >= 502 or rain_1h >= 5.0: return "rainfall", "heavy" if weather_id == 501 or rain_1h >= 1.0: return "rainfall", "moderate" return "rainfall", "light" if 300 <= weather_id < 400: return "rainfall", "light" # drizzle if 600 <= weather_id < 700: return "rainfall", "moderate" # snow — rare in PK, treat as precip # Clear / clouds / atmospheric haze — no severity flag. return "rainfall", None async def fetch_weather_signal( lat: float, lon: float, *, location_label: str | None = None, ) -> CrisisSignal | None: """Fetch live atmospheric conditions for `(lat, lon)` and normalize. Args: lat: Latitude in WGS84 (e.g. 33.7 for Islamabad). lon: Longitude in WGS84. location_label: Optional override for the human-readable area name. If omitted, falls back to OWM's `name` field (usually a city, not a sector). Pass the precise label when you have it (e.g. "G-10, Islamabad"). Returns: A `CrisisSignal` with `source="weather"`, or `None` on any error. The aggregator treats `None` as "skip the weather signal" without failing the pipeline. """ if not settings.openweathermap_api_key: logger.warning("OPENWEATHERMAP_API_KEY not set — skipping weather signal") return None params = { "lat": lat, "lon": lon, "appid": settings.openweathermap_api_key, "units": "metric", } try: async with httpx.AsyncClient(timeout=OWM_TIMEOUT_SECONDS) as client: response = await client.get(OWM_BASE_URL, params=params) response.raise_for_status() payload = response.json() except httpx.HTTPError as exc: logger.warning("OpenWeatherMap request failed: %s", exc) return None except Exception as exc: # noqa: BLE001 — boundary; weather must not crash pipeline logger.warning("Unexpected error fetching weather: %s", exc) return None try: weather_block = payload["weather"][0] weather_id = int(weather_block["id"]) description = str(weather_block.get("description", "")) rain_1h = float(payload.get("rain", {}).get("1h", 0.0)) owm_name = str(payload.get("name") or "") except (KeyError, IndexError, TypeError, ValueError) as exc: logger.warning("OWM response missing expected fields: %s", exc) return None signal_type, severity_hint = _classify(weather_id, rain_1h) return CrisisSignal( source="weather", trust_weight=TRUST_WEIGHT_WEATHER, raw_text=description or None, location_label=location_label or owm_name or f"{lat:.4f},{lon:.4f}", coordinates=(lat, lon), signal_type=signal_type, severity_hint=severity_hint, timestamp=datetime.now(timezone.utc), )