File size: 3,527 Bytes
1ffd0a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
"""
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