From aad968a174bcb972c793da50220dcfeb9b322e9b Mon Sep 17 00:00:00 2001
From: Edward Betts <edward@4angle.com>
Date: Sun, 13 Oct 2024 09:39:02 +0100
Subject: [PATCH] Unbooked flight great circle goes to airport (Closes: #179)

---
 agenda/trip.py | 19 ++++++++++++++++---
 web_view.py    |  2 +-
 2 files changed, 17 insertions(+), 4 deletions(-)

diff --git a/agenda/trip.py b/agenda/trip.py
index fe49bdf..95dd802 100644
--- a/agenda/trip.py
+++ b/agenda/trip.py
@@ -277,6 +277,19 @@ def collect_trip_coordinates(trip: Trip) -> list[StrDict]:
     return coords
 
 
+def latlon_tuple_prefer_airport(stop: StrDict, data_dir: str) -> tuple[float, float]:
+    airport_lookup = {
+        ("Berlin", "de"): "BER",
+        ("Hamburg", "de"): "HAM",
+    }
+    iata = airport_lookup.get((stop["location"], stop["country"]))
+    if not iata:
+        return latlon_tuple(stop)
+
+    airports = typing.cast(dict[str, StrDict], travel.parse_yaml("airports", data_dir))
+    return latlon_tuple(airports[iata])
+
+
 def latlon_tuple(stop: StrDict) -> tuple[float, float]:
     """Given a transport stop return the lat/lon as a tuple."""
     return (stop["latitude"], stop["longitude"])
@@ -287,7 +300,7 @@ def read_geojson(data_dir: str, filename: str) -> str:
     return open(os.path.join(data_dir, filename + ".geojson")).read()
 
 
-def get_trip_routes(trip: Trip) -> list[StrDict]:
+def get_trip_routes(trip: Trip, data_dir: str) -> list[StrDict]:
     """Get routes for given trip to show on map."""
     routes: list[StrDict] = []
     seen_geojson = set()
@@ -358,7 +371,7 @@ def get_trip_routes(trip: Trip) -> list[StrDict]:
             "type": "unbooked_flight",
             "key": f'LHR_{item["location"]}_{item["country"]}',
             "from": lhr,
-            "to": latlon_tuple(item),
+            "to": latlon_tuple_prefer_airport(item, data_dir),
         }
         for item in trip.conferences
         if "latitude" in item
@@ -385,7 +398,7 @@ def get_coordinates_and_routes(
             coordinates.append(stop)
             seen_coordinates.add(key)
 
-        for route in get_trip_routes(trip):
+        for route in get_trip_routes(trip, data_dir):
             if route["key"] in seen_routes:
                 continue
             routes.append(route)
diff --git a/web_view.py b/web_view.py
index 6944841..045874f 100755
--- a/web_view.py
+++ b/web_view.py
@@ -542,7 +542,7 @@ def trip_page(start: str) -> str:
     today = date.today()
 
     coordinates = agenda.trip.collect_trip_coordinates(trip)
-    routes = agenda.trip.get_trip_routes(trip)
+    routes = agenda.trip.get_trip_routes(trip, app.config["PERSONAL_DATA"])
 
     agenda.trip.add_coordinates_for_unbooked_flights(routes, coordinates)