""" Google Maps Directions API client. Failure policy -------------- Any error returns [] — a maps miss must never crash the pipeline. The planning agent falls back to a plan without concrete route data and notes the absence in plan_summary. """ from __future__ import annotations import logging import httpx from pydantic import BaseModel, ConfigDict from backend.core.config import settings logger = logging.getLogger(__name__) DIRECTIONS_BASE_URL = "https://maps.googleapis.com/maps/api/directions/json" MAPS_TIMEOUT_SECONDS = 8.0 class RouteOption(BaseModel): """A single route returned by the Google Maps Directions API.""" model_config = ConfigDict(extra="forbid") summary: str distance_km: float duration_minutes: int polyline: str is_recommended: bool = False async def fetch_routes( origin: str, destination: str, *, avoid_area: str | None = None, ) -> list[RouteOption]: """Fetch up to 3 alternate routes from the Directions API. Args: origin: Starting point as Pakistani address or "lat,lon". destination: End point that bypasses the affected area. avoid_area: Textual description of the crisis area — logged for context only. The Directions API does not support arbitrary coordinate avoidance, so alternatives=true is used instead. Returns: Up to 3 RouteOption objects sorted by duration ascending, with the fastest marked is_recommended=True. Returns [] on any failure or missing API key. """ if not settings.google_maps_api_key: logger.warning("GOOGLE_MAPS_API_KEY not set — skipping Maps routes") return [] if avoid_area: logger.info("Route fetch: %s → %s (avoiding %s)", origin, destination, avoid_area) params: dict[str, str] = { "origin": origin, "destination": destination, "alternatives": "true", "key": settings.google_maps_api_key, } try: async with httpx.AsyncClient(timeout=MAPS_TIMEOUT_SECONDS) as client: response = await client.get(DIRECTIONS_BASE_URL, params=params) response.raise_for_status() payload = response.json() except httpx.HTTPError as exc: logger.warning("Google Maps HTTP error: %s", exc) return [] except Exception as exc: # noqa: BLE001 — boundary; must not crash pipeline logger.warning("Unexpected Maps error: %s", exc) return [] if payload.get("status") != "OK": logger.warning( "Maps API status=%s: %s", payload.get("status"), payload.get("error_message", "(no detail)"), ) return [] routes: list[RouteOption] = [] try: for idx, route in enumerate(payload.get("routes", [])[:3]): leg = route["legs"][0] routes.append(RouteOption( summary=route.get("summary") or f"Route {idx + 1}", distance_km=round(int(leg["distance"]["value"]) / 1000, 2), duration_minutes=round(int(leg["duration"]["value"]) / 60), polyline=route["overview_polyline"]["points"], )) except (KeyError, IndexError, TypeError, ValueError) as exc: logger.warning("Failed to parse Maps response: %s", exc) return [] if not routes: return [] routes.sort(key=lambda r: r.duration_minutes) routes[0] = routes[0].model_copy(update={"is_recommended": True}) return routes