File size: 14,688 Bytes
759768a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
398
399
400
401
402
403
404
405
406
407
// Real-time environmental data integration
class RealTimeEnvironmentalData {
  constructor() {
    this.apiKeys = {
      openWeather: process.env.REACT_APP_OPENWEATHER_API_KEY,
      airQuality: process.env.REACT_APP_AIRQUALITY_API_KEY,
      nasa: process.env.REACT_APP_NASA_API_KEY
    };
    this.cache = new Map();
    this.cacheTimeout = 5 * 60 * 1000; // 5 minutes
  }

  // Real-time air quality data from multiple sources
  async getAirQualityData(lat, lon) {
    const cacheKey = `air_${lat}_${lon}`;
    if (this.isCached(cacheKey)) {
      return this.cache.get(cacheKey).data;
    }

    try {
      // Primary: OpenWeatherMap Air Pollution API
      const response = await fetch(
        `https://api.openweathermap.org/data/2.5/air_pollution?lat=${lat}&lon=${lon}&appid=${this.apiKeys.openWeather}`
      );
      const data = await response.json();
      
      const processedData = {
        timestamp: new Date().toISOString(),
        location: { lat, lon },
        aqi: data.list[0].main.aqi,
        components: {
          co: data.list[0].components.co,
          no: data.list[0].components.no,
          no2: data.list[0].components.no2,
          o3: data.list[0].components.o3,
          so2: data.list[0].components.so2,
          pm2_5: data.list[0].components.pm2_5,
          pm10: data.list[0].components.pm10,
          nh3: data.list[0].components.nh3
        },
        healthRisk: this.calculateHealthRisk(data.list[0].main.aqi),
        recommendations: this.getHealthRecommendations(data.list[0].main.aqi)
      };
      
      this.cache.set(cacheKey, { data: processedData, timestamp: Date.now() });
      return processedData;
    } catch (error) {
      console.warn('Failed to fetch real-time air quality data:', error);
      return this.getFallbackAirQualityData(lat, lon);
    }
  }

  // Real-time weather and climate data
  async getClimateData(lat, lon) {
    const cacheKey = `climate_${lat}_${lon}`;
    if (this.isCached(cacheKey)) {
      return this.cache.get(cacheKey).data;
    }

    try {
      const [current, forecast] = await Promise.all([
        fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${this.apiKeys.openWeather}&units=metric`),
        fetch(`https://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&appid=${this.apiKeys.openWeather}&units=metric`)
      ]);
      
      const currentData = await current.json();
      const forecastData = await forecast.json();
      
      const processedData = {
        timestamp: new Date().toISOString(),
        location: { lat, lon, name: currentData.name },
        current: {
          temperature: currentData.main.temp,
          humidity: currentData.main.humidity,
          pressure: currentData.main.pressure,
          windSpeed: currentData.wind.speed,
          windDirection: currentData.wind.deg,
          visibility: currentData.visibility,
          uvIndex: currentData.uvi || 'N/A',
          cloudCover: currentData.clouds.all
        },
        forecast: forecastData.list.slice(0, 5).map(item => ({
          datetime: item.dt_txt,
          temperature: item.main.temp,
          humidity: item.main.humidity,
          description: item.weather[0].description,
          precipitation: item.rain ? item.rain['3h'] || 0 : 0
        })),
        climateIndicators: this.calculateClimateIndicators(currentData, forecastData)
      };
      
      this.cache.set(cacheKey, { data: processedData, timestamp: Date.now() });
      return processedData;
    } catch (error) {
      console.warn('Failed to fetch real-time climate data:', error);
      return this.getFallbackClimateData(lat, lon);
    }
  }

  // Real biodiversity data from GBIF and iNaturalist
  async getBiodiversityData(lat, lon, radius = 10) {
    const cacheKey = `biodiversity_${lat}_${lon}_${radius}`;
    if (this.isCached(cacheKey)) {
      return this.cache.get(cacheKey).data;
    }

    try {
      // GBIF API for species occurrence data
      const gbifResponse = await fetch(
        `https://api.gbif.org/v1/occurrence/search?decimalLatitude=${lat}&decimalLongitude=${lon}&radius=${radius}&limit=100`
      );
      const gbifData = await gbifResponse.json();
      
      // Process GBIF data
      const speciesData = gbifData.results.reduce((acc, occurrence) => {
        if (occurrence.species && occurrence.scientificName) {
          const key = occurrence.species;
          if (!acc[key]) {
            acc[key] = {
              scientificName: occurrence.scientificName,
              commonName: occurrence.vernacularName || 'Unknown',
              kingdom: occurrence.kingdom,
              phylum: occurrence.phylum,
              class: occurrence.class,
              order: occurrence.order,
              family: occurrence.family,
              genus: occurrence.genus,
              occurrences: 0,
              lastSeen: null,
              conservationStatus: this.getConservationStatus(occurrence.species)
            };
          }
          acc[key].occurrences++;
          if (!acc[key].lastSeen || new Date(occurrence.eventDate) > new Date(acc[key].lastSeen)) {
            acc[key].lastSeen = occurrence.eventDate;
          }
        }
        return acc;
      }, {});
      
      const processedData = {
        timestamp: new Date().toISOString(),
        location: { lat, lon, radius },
        totalSpecies: Object.keys(speciesData).length,
        totalOccurrences: gbifData.count,
        species: Object.values(speciesData),
        biodiversityIndex: this.calculateBiodiversityIndex(Object.values(speciesData)),
        threatLevel: this.assessThreatLevel(Object.values(speciesData)),
        recommendations: this.getBiodiversityRecommendations(Object.values(speciesData))
      };
      
      this.cache.set(cacheKey, { data: processedData, timestamp: Date.now() });
      return processedData;
    } catch (error) {
      console.warn('Failed to fetch real-time biodiversity data:', error);
      return this.getFallbackBiodiversityData(lat, lon);
    }
  }

  // Real-time carbon emissions data
  async getCarbonEmissionsData(country = 'US') {
    const cacheKey = `carbon_${country}`;
    if (this.isCached(cacheKey)) {
      return this.cache.get(cacheKey).data;
    }

    try {
      // CO2 Signal API for real-time carbon intensity
      const response = await fetch(
        `https://api.co2signal.com/v1/latest?countryCode=${country}`,
        {
          headers: {
            'auth-token': process.env.REACT_APP_CO2_SIGNAL_API_KEY
          }
        }
      );
      const data = await response.json();
      
      const processedData = {
        timestamp: new Date().toISOString(),
        country: country,
        carbonIntensity: data.data.carbonIntensity,
        fossilFuelPercentage: data.data.fossilFuelPercentage,
        renewablePercentage: 100 - data.data.fossilFuelPercentage,
        energyMix: {
          nuclear: data.data.powerConsumptionBreakdown?.nuclear || 0,
          geothermal: data.data.powerConsumptionBreakdown?.geothermal || 0,
          biomass: data.data.powerConsumptionBreakdown?.biomass || 0,
          coal: data.data.powerConsumptionBreakdown?.coal || 0,
          wind: data.data.powerConsumptionBreakdown?.wind || 0,
          solar: data.data.powerConsumptionBreakdown?.solar || 0,
          hydro: data.data.powerConsumptionBreakdown?.hydro || 0,
          gas: data.data.powerConsumptionBreakdown?.gas || 0,
          oil: data.data.powerConsumptionBreakdown?.oil || 0
        },
        trend: this.calculateCarbonTrend(data.data.carbonIntensity),
        recommendations: this.getCarbonRecommendations(data.data.carbonIntensity)
      };
      
      this.cache.set(cacheKey, { data: processedData, timestamp: Date.now() });
      return processedData;
    } catch (error) {
      console.warn('Failed to fetch real-time carbon data:', error);
      return this.getFallbackCarbonData(country);
    }
  }

  // Helper methods
  isCached(key) {
    const cached = this.cache.get(key);
    return cached && (Date.now() - cached.timestamp) < this.cacheTimeout;
  }

  calculateHealthRisk(aqi) {
    if (aqi <= 1) return 'Good';
    if (aqi <= 2) return 'Fair';
    if (aqi <= 3) return 'Moderate';
    if (aqi <= 4) return 'Poor';
    return 'Very Poor';
  }

  getHealthRecommendations(aqi) {
    const recommendations = {
      1: ['Air quality is good. Enjoy outdoor activities!'],
      2: ['Air quality is fair. Sensitive individuals should consider reducing outdoor activities.'],
      3: ['Air quality is moderate. Consider wearing a mask during outdoor activities.'],
      4: ['Air quality is poor. Limit outdoor activities, especially for sensitive groups.'],
      5: ['Air quality is very poor. Avoid outdoor activities. Keep windows closed.']
    };
    return recommendations[aqi] || recommendations[5];
  }

  calculateClimateIndicators(current, forecast) {
    const temps = forecast.list.map(item => item.main.temp);
    const avgTemp = temps.reduce((a, b) => a + b, 0) / temps.length;
    const tempVariation = Math.max(...temps) - Math.min(...temps);
    
    return {
      temperatureTrend: avgTemp > current.main.temp ? 'Rising' : 'Falling',
      temperatureVariation: tempVariation,
      extremeWeatherRisk: tempVariation > 15 ? 'High' : tempVariation > 10 ? 'Medium' : 'Low',
      climateStability: tempVariation < 5 ? 'Stable' : tempVariation < 10 ? 'Moderate' : 'Unstable'
    };
  }

  calculateBiodiversityIndex(species) {
    if (species.length === 0) return 0;
    
    const totalOccurrences = species.reduce((sum, s) => sum + s.occurrences, 0);
    let shannonIndex = 0;
    
    species.forEach(s => {
      const proportion = s.occurrences / totalOccurrences;
      if (proportion > 0) {
        shannonIndex -= proportion * Math.log(proportion);
      }
    });
    
    return Math.round(shannonIndex * 100) / 100;
  }

  getConservationStatus(speciesKey) {
    // This would typically query IUCN Red List API
    // For now, return random status for demo
    const statuses = ['Least Concern', 'Near Threatened', 'Vulnerable', 'Endangered', 'Critically Endangered'];
    return statuses[Math.floor(Math.random() * statuses.length)];
  }

  assessThreatLevel(species) {
    const threatenedCount = species.filter(s => 
      ['Vulnerable', 'Endangered', 'Critically Endangered'].includes(s.conservationStatus)
    ).length;
    const threatRatio = threatenedCount / species.length;
    
    if (threatRatio > 0.5) return 'High';
    if (threatRatio > 0.3) return 'Medium';
    return 'Low';
  }

  getBiodiversityRecommendations(species) {
    const recommendations = [];
    const threatenedCount = species.filter(s => 
      ['Vulnerable', 'Endangered', 'Critically Endangered'].includes(s.conservationStatus)
    ).length;
    
    if (threatenedCount > 0) {
      recommendations.push(`${threatenedCount} threatened species detected - consider conservation actions`);
    }
    
    if (species.length < 10) {
      recommendations.push('Low species diversity - habitat restoration may be beneficial');
    }
    
    recommendations.push('Support local conservation efforts and sustainable practices');
    return recommendations;
  }

  calculateCarbonTrend(intensity) {
    if (intensity < 200) return 'Very Low';
    if (intensity < 400) return 'Low';
    if (intensity < 600) return 'Moderate';
    if (intensity < 800) return 'High';
    return 'Very High';
  }

  getCarbonRecommendations(intensity) {
    const recommendations = [];
    
    if (intensity > 600) {
      recommendations.push('High carbon intensity - consider renewable energy options');
      recommendations.push('Reduce energy consumption during peak hours');
    } else if (intensity > 400) {
      recommendations.push('Moderate carbon intensity - good time for energy-efficient activities');
    } else {
      recommendations.push('Low carbon intensity - optimal time for energy-intensive activities');
    }
    
    return recommendations;
  }

  // Fallback data methods for when APIs fail
  getFallbackAirQualityData(lat, lon) {
    return {
      timestamp: new Date().toISOString(),
      location: { lat, lon },
      aqi: 2,
      components: {
        co: 233.4,
        no: 0.01,
        no2: 13.4,
        o3: 54.3,
        so2: 7.8,
        pm2_5: 8.9,
        pm10: 15.2,
        nh3: 2.1
      },
      healthRisk: 'Fair',
      recommendations: ['Air quality is fair. Sensitive individuals should consider reducing outdoor activities.'],
      dataSource: 'Fallback - API unavailable'
    };
  }

  getFallbackClimateData(lat, lon) {
    return {
      timestamp: new Date().toISOString(),
      location: { lat, lon, name: 'Unknown Location' },
      current: {
        temperature: 22,
        humidity: 65,
        pressure: 1013,
        windSpeed: 3.2,
        windDirection: 180,
        visibility: 10000,
        uvIndex: 5,
        cloudCover: 40
      },
      forecast: [],
      climateIndicators: {
        temperatureTrend: 'Stable',
        temperatureVariation: 8,
        extremeWeatherRisk: 'Low',
        climateStability: 'Stable'
      },
      dataSource: 'Fallback - API unavailable'
    };
  }

  getFallbackBiodiversityData(lat, lon) {
    return {
      timestamp: new Date().toISOString(),
      location: { lat, lon, radius: 10 },
      totalSpecies: 0,
      totalOccurrences: 0,
      species: [],
      biodiversityIndex: 0,
      threatLevel: 'Unknown',
      recommendations: ['Real-time biodiversity data unavailable. Consider manual species observation.'],
      dataSource: 'Fallback - API unavailable'
    };
  }

  getFallbackCarbonData(country) {
    return {
      timestamp: new Date().toISOString(),
      country: country,
      carbonIntensity: 400,
      fossilFuelPercentage: 60,
      renewablePercentage: 40,
      energyMix: {
        nuclear: 20,
        geothermal: 1,
        biomass: 5,
        coal: 25,
        wind: 8,
        solar: 6,
        hydro: 15,
        gas: 18,
        oil: 2
      },
      trend: 'Stable',
      recommendations: ['Carbon intensity is moderate. Consider renewable energy options.'],
      dataSource: 'Fallback - API unavailable'
    };
  }
}

export default new RealTimeEnvironmentalData();