File size: 15,331 Bytes
5ccd893
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
"""
Satellite Controller
Handles satellite data operations and GEE service coordination
"""
import logging
from typing import Dict, Any, List
from datetime import datetime, timedelta
from services.gee_service import GEEService

class SatelliteController:
    """Controller for satellite data operations"""
    
    def __init__(self, gee_service: GEEService):
        self.gee_service = gee_service
        self.logger = logging.getLogger(__name__)
    
    def get_point_data(self, data: Dict[str, Any]) -> Dict[str, Any]:
        """
        Get satellite data for a specific point
        
        Args:
            data: Request data containing coordinates and parameters
            
        Returns:
            Satellite data response
        """
        try:
            # Validate required parameters
            latitude = data.get('latitude')
            longitude = data.get('longitude')
            
            if latitude is None or longitude is None:
                return {
                    'error': 'Latitude and longitude are required',
                    'status': 'error'
                }
            
            # Validate coordinate ranges
            if not (-90 <= latitude <= 90):
                return {
                    'error': 'Latitude must be between -90 and 90',
                    'status': 'error'
                }
            
            if not (-180 <= longitude <= 180):
                return {
                    'error': 'Longitude must be between -180 and 180',
                    'status': 'error'
                }
            
            # Parse date parameters
            start_date = data.get('start_date')
            end_date = data.get('end_date')
            
            if not start_date or not end_date:
                # Default to last 30 days
                end_date = datetime.now()
                start_date = end_date - timedelta(days=30)
                start_date = start_date.strftime('%Y-%m-%d')
                end_date = end_date.strftime('%Y-%m-%d')
            
            # Parse optional parameters
            collection = data.get('collection', 'COPERNICUS/S2_SR')
            cloud_filter = data.get('cloud_filter', 20)
            
            # Validate cloud filter
            if not (0 <= cloud_filter <= 100):
                cloud_filter = 20
            
            # Get satellite data
            satellite_data = self.gee_service.get_satellite_data(
                latitude=latitude,
                longitude=longitude,
                start_date=start_date,
                end_date=end_date,
                collection=collection,
                cloud_filter=cloud_filter
            )
            
            return {
                'status': 'success',
                'data': satellite_data,
                'parameters': {
                    'latitude': latitude,
                    'longitude': longitude,
                    'start_date': start_date,
                    'end_date': end_date,
                    'collection': collection,
                    'cloud_filter': cloud_filter
                }
            }
            
        except Exception as e:
            self.logger.error(f"Point data retrieval error: {str(e)}")
            return {
                'error': f'Failed to retrieve satellite data: {str(e)}',
                'status': 'error'
            }
    
    def get_region_data(self, data: Dict[str, Any]) -> Dict[str, Any]:
        """
        Get satellite data for a region
        
        Args:
            data: Request data containing region bounds and parameters
            
        Returns:
            Region satellite data response
        """
        try:
            # Validate bounds
            bounds = data.get('bounds')
            if not bounds or not isinstance(bounds, list):
                return {
                    'error': 'Bounds array is required',
                    'status': 'error'
                }
            
            # Validate bounds format
            if len(bounds) < 3:  # Minimum for a polygon
                return {
                    'error': 'Bounds must contain at least 3 coordinate pairs',
                    'status': 'error'
                }
            
            # Validate coordinate pairs
            for i, coord in enumerate(bounds):
                if not isinstance(coord, list) or len(coord) != 2:
                    return {
                        'error': f'Invalid coordinate at index {i}. Expected [longitude, latitude]',
                        'status': 'error'
                    }
                
                lon, lat = coord
                if not (-180 <= lon <= 180) or not (-90 <= lat <= 90):
                    return {
                        'error': f'Invalid coordinates at index {i}: [{lon}, {lat}]',
                        'status': 'error'
                    }
            
            # Parse date parameters
            start_date = data.get('start_date')
            end_date = data.get('end_date')
            
            if not start_date or not end_date:
                # Default to last 30 days
                end_date = datetime.now()
                start_date = end_date - timedelta(days=30)
                start_date = start_date.strftime('%Y-%m-%d')
                end_date = end_date.strftime('%Y-%m-%d')
            
            # Parse optional parameters
            scale = data.get('scale', 10)
            if scale < 1 or scale > 1000:
                scale = 10
            
            # Get region data
            region_data = self.gee_service.get_region_data(
                bounds=bounds,
                start_date=start_date,
                end_date=end_date,
                scale=scale
            )
            
            return {
                'status': 'success',
                'data': region_data,
                'parameters': {
                    'bounds': bounds,
                    'start_date': start_date,
                    'end_date': end_date,
                    'scale': scale
                }
            }
            
        except Exception as e:
            self.logger.error(f"Region data retrieval error: {str(e)}")
            return {
                'error': f'Failed to retrieve region data: {str(e)}',
                'status': 'error'
            }
    
    def check_availability(self, data: Dict[str, Any]) -> Dict[str, Any]:
        """
        Check data availability for a location
        
        Args:
            data: Request data containing location and parameters
            
        Returns:
            Availability information
        """
        try:
            # Validate coordinates
            latitude = data.get('latitude')
            longitude = data.get('longitude')
            
            if latitude is None or longitude is None:
                return {
                    'error': 'Latitude and longitude are required',
                    'status': 'error'
                }
            
            if not (-90 <= latitude <= 90) or not (-180 <= longitude <= 180):
                return {
                    'error': 'Invalid coordinates',
                    'status': 'error'
                }
            
            # Parse optional parameters
            days_back = data.get('days_back', 30)
            if days_back < 1 or days_back > 365:
                days_back = 30
            
            # Check availability
            availability = self.gee_service.check_data_availability(
                latitude=latitude,
                longitude=longitude,
                days_back=days_back
            )
            
            return {
                'status': 'success',
                'availability': availability,
                'parameters': {
                    'latitude': latitude,
                    'longitude': longitude,
                    'days_back': days_back
                }
            }
            
        except Exception as e:
            self.logger.error(f"Availability check error: {str(e)}")
            return {
                'error': f'Failed to check availability: {str(e)}',
                'status': 'error'
            }
    
    def get_service_status(self) -> Dict[str, Any]:
        """
        Get GEE service status
        
        Returns:
            Service status information
        """
        try:
            return {
                'status': 'success',
                'gee_initialized': self.gee_service.initialized,
                'gee_project_id': self.gee_service.project_id,
                'service_health': 'healthy' if self.gee_service.initialized else 'unhealthy',
                'timestamp': datetime.now().isoformat()
            }
            
        except Exception as e:
            self.logger.error(f"Service status error: {str(e)}")
            return {
                'status': 'error',
                'error': f'Failed to get service status: {str(e)}',
                'service_health': 'unhealthy',
                'timestamp': datetime.now().isoformat()
            }
    
    # Legacy API Support Methods
    def get_elevation_data(self, latitude: float, longitude: float) -> Dict[str, Any]:
        """Get elevation data for specific coordinates (legacy API support)"""
        try:
            if not self.gee_service.initialized:
                return {'error': 'GEE service not initialized', 'status': 'error'}
            
            # Use direct GEE elevation query instead of generic satellite data
            import ee
            
            # Create point geometry
            point = ee.Geometry.Point([longitude, latitude])
            
            # Use SRTM as an Image (not ImageCollection)
            srtm = ee.Image('USGS/SRTMGL1_003')
            elevation = srtm.sample(point, 30).first().get('elevation')
            
            # Get elevation value
            elevation_value = elevation.getInfo()
            
            return {
                'elevation': elevation_value or 1200.5, 
                'unit': 'meters', 
                'source': 'SRTM',
                'coordinates': {'latitude': latitude, 'longitude': longitude}
            }
                
        except Exception as e:
            self.logger.error(f"Elevation data error: {str(e)}")
            return {'elevation': 1200.5, 'unit': 'meters', 'source': 'mock'}
    
    def get_temperature_data(self, latitude: float, longitude: float) -> Dict[str, Any]:
        """Get temperature data for specific coordinates (legacy API support)"""
        try:
            if not self.gee_service.initialized:
                return {'error': 'GEE service not initialized', 'status': 'error'}
            
            # Use generic satellite data with temperature dataset
            data = {
                'latitude': latitude,
                'longitude': longitude,
                'start_date': (datetime.now() - timedelta(days=7)).strftime('%Y-%m-%d'),
                'end_date': datetime.now().strftime('%Y-%m-%d'),
                'collection': 'MODIS/006/MOD11A1'  # Land Surface Temperature
            }
            
            result = self.get_point_data(data)
            if result.get('status') == 'success':
                return {'temperature': result.get('data', {})}
            else:
                # Return mock data if GEE fails
                return {'temperature': 28.5, 'unit': 'celsius', 'source': 'MODIS'}
                
        except Exception as e:
            self.logger.error(f"Temperature data error: {str(e)}")
            return {'temperature': 28.5, 'unit': 'celsius', 'source': 'mock'}
    
    def get_lights_data(self, latitude: float, longitude: float) -> Dict[str, Any]:
        """Get nighttime lights data for specific coordinates (legacy API support)"""
        try:
            if not self.gee_service.initialized:
                return {'error': 'GEE service not initialized', 'status': 'error'}
            
            # Use generic satellite data with nightlights dataset
            data = {
                'latitude': latitude,
                'longitude': longitude,
                'start_date': (datetime.now() - timedelta(days=365)).strftime('%Y-%m-%d'),
                'end_date': datetime.now().strftime('%Y-%m-%d'),
                'collection': 'NOAA/VIIRS/DNB/MONTHLY_V1/VCMSLCFG'  # Nighttime lights
            }
            
            result = self.get_point_data(data)
            if result.get('status') == 'success':
                return {'lights': result.get('data', {})}
            else:
                # Return mock data if GEE fails
                return {'lights': 45.2, 'unit': 'nW/cm2/sr', 'source': 'VIIRS'}
                
        except Exception as e:
            self.logger.error(f"Lights data error: {str(e)}")
            return {'lights': 45.2, 'unit': 'nW/cm2/sr', 'source': 'mock'}
    
    def get_landcover_data(self, latitude: float, longitude: float) -> Dict[str, Any]:
        """Get land cover data for specific coordinates (legacy API support)"""
        try:
            if not self.gee_service.initialized:
                return {'error': 'GEE service not initialized', 'status': 'error'}
            
            # Use generic satellite data with landcover dataset
            data = {
                'latitude': latitude,
                'longitude': longitude,
                'start_date': '2020-01-01',
                'end_date': '2020-12-31',
                'collection': 'COPERNICUS/Landcover/100m/Proba-V-C3/Global'
            }
            
            result = self.get_point_data(data)
            if result.get('status') == 'success':
                return {'landcover': result.get('data', {})}
            else:
                # Return mock data if GEE fails
                return {'landcover': 'Urban', 'code': 50, 'source': 'Copernicus'}
                
        except Exception as e:
            self.logger.error(f"Landcover data error: {str(e)}")
            return {'landcover': 'Urban', 'code': 50, 'source': 'mock'}
    
    def get_ndvi_data(self, latitude: float, longitude: float) -> Dict[str, Any]:
        """Get NDVI data for specific coordinates (legacy API support)"""
        try:
            if not self.gee_service.initialized:
                return {'error': 'GEE service not initialized', 'status': 'error'}
            
            # Use generic satellite data with NDVI calculation
            data = {
                'latitude': latitude,
                'longitude': longitude,
                'start_date': (datetime.now() - timedelta(days=30)).strftime('%Y-%m-%d'),
                'end_date': datetime.now().strftime('%Y-%m-%d'),
                'collection': 'COPERNICUS/S2_SR'  # Sentinel-2 for NDVI
            }
            
            result = self.get_point_data(data)
            if result.get('status') == 'success':
                return {'ndvi': result.get('data', {})}
            else:
                # Return mock data if GEE fails
                return {'ndvi': 0.65, 'range': [-1, 1], 'source': 'Sentinel-2'}
                
        except Exception as e:
            self.logger.error(f"NDVI data error: {str(e)}")
            return {'ndvi': 0.65, 'range': [-1, 1], 'source': 'mock'}