File size: 8,391 Bytes
d69447e
 
7ed6008
d69447e
 
 
7ed6008
d69447e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7ed6008
d69447e
 
7ed6008
 
d69447e
 
7ed6008
 
d69447e
7ed6008
 
 
 
 
 
 
d69447e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7ed6008
d69447e
7ed6008
d69447e
 
7ed6008
 
 
 
 
d69447e
7ed6008
 
 
 
d69447e
7ed6008
 
 
d69447e
7ed6008
 
 
 
 
 
d69447e
7ed6008
 
 
d69447e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18f4b6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d69447e
 
 
7ed6008
d69447e
7ed6008
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
"""
Geocoding service for FleetMind
Handles address validation with Google Maps API and smart mock fallback
"""

import os
import googlemaps
import logging
from typing import Dict, Optional

logger = logging.getLogger(__name__)

# Common city coordinates for mock geocoding
CITY_COORDINATES = {
    "san francisco": (37.7749, -122.4194),
    "sf": (37.7749, -122.4194),
    "new york": (40.7128, -74.0060),
    "nyc": (40.7128, -74.0060),
    "los angeles": (34.0522, -118.2437),
    "la": (34.0522, -118.2437),
    "chicago": (41.8781, -87.6298),
    "houston": (29.7604, -95.3698),
    "phoenix": (33.4484, -112.0740),
    "philadelphia": (39.9526, -75.1652),
    "san antonio": (29.4241, -98.4936),
    "san diego": (32.7157, -117.1611),
    "dallas": (32.7767, -96.7970),
    "austin": (30.2672, -97.7431),
    "seattle": (47.6062, -122.3321),
    "boston": (42.3601, -71.0589),
    "denver": (39.7392, -104.9903),
    "miami": (25.7617, -80.1918),
    "atlanta": (33.7490, -84.3880),
    "portland": (45.5152, -122.6784),
}


class GeocodingService:
    """Handle address geocoding with Google Maps API and smart mock fallback"""

    def __init__(self):
        self.google_maps_key = os.getenv("GOOGLE_MAPS_API_KEY", "")
        self.use_mock = not self.google_maps_key or self.google_maps_key.startswith("your_")

        if self.use_mock:
            logger.info("Geocoding: Using mock (GOOGLE_MAPS_API_KEY not configured)")
            self.gmaps_client = None
        else:
            try:
                self.gmaps_client = googlemaps.Client(key=self.google_maps_key)
                logger.info("Geocoding: Using Google Maps API")
            except Exception as e:
                logger.error(f"Failed to initialize Google Maps client: {e}")
                self.use_mock = True
                self.gmaps_client = None

    def geocode(self, address: str) -> Dict:
        """
        Geocode address, using mock if API unavailable

        Args:
            address: Street address to geocode

        Returns:
            Dict with keys: lat, lng, formatted_address, confidence
        """
        if self.use_mock:
            return self._geocode_mock(address)
        else:
            try:
                return self._geocode_google(address)
            except Exception as e:
                logger.error(f"Google Maps API failed: {e}, falling back to mock")
                return self._geocode_mock(address)

    def _geocode_google(self, address: str) -> Dict:
        """Real Google Maps API geocoding"""
        try:
            # Call Google Maps Geocoding API
            result = self.gmaps_client.geocode(address)

            if not result:
                # No results found, fall back to mock
                logger.warning(f"Google Maps API found no results for: {address}")
                return self._geocode_mock(address)

            # Get first result
            first_result = result[0]
            location = first_result['geometry']['location']

            return {
                "lat": location['lat'],
                "lng": location['lng'],
                "formatted_address": first_result.get('formatted_address', address),
                "confidence": "high (Google Maps API)"
            }

        except Exception as e:
            logger.error(f"Google Maps geocoding error: {e}")
            raise

    def _geocode_mock(self, address: str) -> Dict:
        """
        Smart mock geocoding for testing
        Tries to detect city name and use approximate coordinates
        """
        address_lower = address.lower()

        # Try to find a city match
        for city, coords in CITY_COORDINATES.items():
            if city in address_lower:
                logger.info(f"Mock geocoding detected city: {city}")
                return {
                    "lat": coords[0],
                    "lng": coords[1],
                    "formatted_address": address,
                    "confidence": f"medium (mock - {city})"
                }

        # Default to San Francisco if no city detected
        logger.info("Mock geocoding: Using default SF coordinates")
        return {
            "lat": 37.7749,
            "lng": -122.4194,
            "formatted_address": address,
            "confidence": "low (mock - default)"
        }

    def reverse_geocode(self, lat: float, lng: float) -> Dict:
        """
        Reverse geocode coordinates to address

        Args:
            lat: Latitude
            lng: Longitude

        Returns:
            Dict with keys: address, city, state, country, formatted_address
        """
        if self.use_mock:
            return self._reverse_geocode_mock(lat, lng)
        else:
            try:
                return self._reverse_geocode_google(lat, lng)
            except Exception as e:
                logger.error(f"Google Maps reverse geocoding failed: {e}, falling back to mock")
                return self._reverse_geocode_mock(lat, lng)

    def _reverse_geocode_google(self, lat: float, lng: float) -> Dict:
        """Real Google Maps API reverse geocoding"""
        try:
            # Call Google Maps Reverse Geocoding API
            result = self.gmaps_client.reverse_geocode((lat, lng))

            if not result:
                logger.warning(f"Google Maps API found no results for: ({lat}, {lng})")
                return self._reverse_geocode_mock(lat, lng)

            # Get first result
            first_result = result[0]

            # Extract address components
            address_components = first_result.get('address_components', [])
            city = ""
            state = ""
            country = ""

            for component in address_components:
                types = component.get('types', [])
                if 'locality' in types:
                    city = component.get('long_name', '')
                elif 'administrative_area_level_1' in types:
                    state = component.get('short_name', '')
                elif 'country' in types:
                    country = component.get('long_name', '')

            return {
                "address": first_result.get('formatted_address', f"{lat}, {lng}"),
                "city": city,
                "state": state,
                "country": country,
                "formatted_address": first_result.get('formatted_address', f"{lat}, {lng}"),
                "confidence": "high (Google Maps API)"
            }

        except Exception as e:
            logger.error(f"Google Maps reverse geocoding error: {e}")
            raise

    def _reverse_geocode_mock(self, lat: float, lng: float) -> Dict:
        """
        Mock reverse geocoding
        Tries to match coordinates to known cities
        """
        # Find closest city
        min_distance = float('inf')
        closest_city = "Unknown Location"

        for city, coords in CITY_COORDINATES.items():
            # Simple distance calculation
            distance = ((lat - coords[0]) ** 2 + (lng - coords[1]) ** 2) ** 0.5
            if distance < min_distance:
                min_distance = distance
                closest_city = city

        # If very close to a known city (within ~0.1 degrees, roughly 11km)
        if min_distance < 0.1:
            logger.info(f"Mock reverse geocoding: Matched to {closest_city}")
            return {
                "address": f"Near {closest_city.title()}",
                "city": closest_city.title(),
                "state": "CA" if "san francisco" in closest_city or "la" in closest_city else "",
                "country": "USA",
                "formatted_address": f"Near {closest_city.title()}, USA",
                "confidence": f"medium (mock - near {closest_city})"
            }
        else:
            logger.info(f"Mock reverse geocoding: Unknown location at ({lat}, {lng})")
            return {
                "address": f"{lat}, {lng}",
                "city": "",
                "state": "",
                "country": "",
                "formatted_address": f"Coordinates: {lat}, {lng}",
                "confidence": "low (mock - no match)"
            }

    def get_status(self) -> str:
        """Get geocoding service status"""
        if self.use_mock:
            return "⚠️ Using mock geocoding (add GOOGLE_MAPS_API_KEY for real)"
        else:
            return "✅ Google Maps API connected"