import { createClient } from 'jsr:@supabase/supabase-js@2';

const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
};

interface HistoricalWeatherRequest {
  lat: number;
  lon: number;
  start_date: string; // ISO date string (YYYY-MM-DD)
  end_date: string;   // ISO date string (YYYY-MM-DD)
  units?: 'metric' | 'imperial' | 'standard';
  lang?: string;
}

interface DayHistoricalData {
  year: number;
  date: string;
  temp_min: number;
  temp_max: number;
  temp_avg: number;
  precipitation: number;
  humidity: number;
  wind_speed: number;
  cloud_cover: number;
  pressure: number;
}

interface HistoricalAnalysis {
  date: string; // Trip date
  avg_temp_min: number;
  avg_temp_max: number;
  avg_temp: number;
  avg_precipitation: number;
  avg_humidity: number;
  avg_wind_speed: number;
  avg_cloud_cover: number;
  precipitation_probability: number; // 0-1
  most_common_condition: string;
  confidence_score: number; // 0-1 based on data consistency
  historical_data: DayHistoricalData[];
  insights: string[];
}

Deno.serve(async (req) => {
  // Handle CORS preflight
  if (req.method === 'OPTIONS') {
    return new Response(null, { headers: corsHeaders });
  }

  try {
    const { lat, lon, start_date, end_date, units = 'metric', lang = 'tr' }: HistoricalWeatherRequest = await req.json();

    // Validate input
    if (!lat || !lon || !start_date || !end_date) {
      return new Response(
        JSON.stringify({ error: 'lat, lon, start_date ve end_date gereklidir' }),
        { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

    // Get API key from environment
    const apiKey = Deno.env.get('INTEGRATIONS_API_KEY');
    if (!apiKey) {
      console.error('INTEGRATIONS_API_KEY bulunamadı');
      return new Response(
        JSON.stringify({ error: 'Hava durumu servisi yapılandırılmamış' }),
        { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

    // Parse dates
    const startDate = new Date(start_date);
    const endDate = new Date(end_date);
    const tripDuration = Math.floor((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24)) + 1;

    console.log('Geçmiş hava durumu analizi başlatılıyor:', { lat, lon, start_date, end_date, tripDuration });

    const analyses: HistoricalAnalysis[] = [];

    // For each day in the trip
    for (let dayOffset = 0; dayOffset < tripDuration; dayOffset++) {
      const tripDate = new Date(startDate);
      tripDate.setDate(startDate.getDate() + dayOffset);
      
      const month = String(tripDate.getMonth() + 1).padStart(2, '0');
      const day = String(tripDate.getDate()).padStart(2, '0');
      
      const historicalData: DayHistoricalData[] = [];
      
      // Fetch data for the same date in the past 5 years
      const currentYear = new Date().getFullYear();
      const yearsToAnalyze = 5;
      
      for (let yearOffset = 1; yearOffset <= yearsToAnalyze; yearOffset++) {
        const historicalYear = currentYear - yearOffset;
        const historicalDate = `${historicalYear}-${month}-${day}`;
        
        try {
          const url = `https://app-9w9pd00g5j41-api-2Y00zmgJ8lBY.gateway.appmedo.com/data/3.0/onecall/day_summary?lat=${lat}&lon=${lon}&date=${historicalDate}&units=${units}&lang=${lang}`;
          
          console.log(`${historicalDate} için veri çekiliyor...`);
          
          const response = await fetch(url, {
            method: 'GET',
            headers: {
              'X-Gateway-Authorization': `Bearer ${apiKey}`,
              'Accept': 'application/json',
            },
          });

          if (response.ok) {
            const data = await response.json();
            
            // Extract relevant data
            const tempMin = data.temperature?.min ?? data.temperature?.morning ?? 0;
            const tempMax = data.temperature?.max ?? data.temperature?.afternoon ?? 0;
            const tempAvg = (tempMin + tempMax) / 2;
            
            historicalData.push({
              year: historicalYear,
              date: historicalDate,
              temp_min: tempMin,
              temp_max: tempMax,
              temp_avg: tempAvg,
              precipitation: data.precipitation?.total ?? 0,
              humidity: data.humidity?.afternoon ?? 0,
              wind_speed: data.wind?.max?.speed ?? 0,
              cloud_cover: data.cloud_cover?.afternoon ?? 0,
              pressure: data.pressure?.afternoon ?? 0,
            });
          } else {
            console.warn(`${historicalDate} için veri alınamadı: ${response.status}`);
          }
        } catch (error) {
          console.error(`${historicalDate} için hata:`, error);
        }
        
        // Add small delay to avoid rate limiting
        await new Promise(resolve => setTimeout(resolve, 100));
      }

      // Analyze the collected data
      if (historicalData.length > 0) {
        const avgTempMin = historicalData.reduce((sum, d) => sum + d.temp_min, 0) / historicalData.length;
        const avgTempMax = historicalData.reduce((sum, d) => sum + d.temp_max, 0) / historicalData.length;
        const avgTemp = historicalData.reduce((sum, d) => sum + d.temp_avg, 0) / historicalData.length;
        const avgPrecipitation = historicalData.reduce((sum, d) => sum + d.precipitation, 0) / historicalData.length;
        const avgHumidity = historicalData.reduce((sum, d) => sum + d.humidity, 0) / historicalData.length;
        const avgWindSpeed = historicalData.reduce((sum, d) => sum + d.wind_speed, 0) / historicalData.length;
        const avgCloudCover = historicalData.reduce((sum, d) => sum + d.cloud_cover, 0) / historicalData.length;

        // Calculate precipitation probability (days with >1mm rain)
        const rainyDays = historicalData.filter(d => d.precipitation > 1).length;
        const precipitationProbability = rainyDays / historicalData.length;

        // Determine most common condition
        let mostCommonCondition = 'Açık';
        if (avgCloudCover > 70) {
          mostCommonCondition = 'Bulutlu';
        } else if (avgCloudCover > 40) {
          mostCommonCondition = 'Parçalı Bulutlu';
        }
        if (precipitationProbability > 0.5) {
          mostCommonCondition = 'Yağmurlu';
        }

        // Calculate confidence score based on data consistency
        const tempVariance = historicalData.reduce((sum, d) => {
          return sum + Math.pow(d.temp_avg - avgTemp, 2);
        }, 0) / historicalData.length;
        const tempStdDev = Math.sqrt(tempVariance);
        const confidenceScore = Math.max(0, Math.min(1, 1 - (tempStdDev / 10)));

        // Generate insights
        const insights: string[] = [];
        
        if (avgTemp > 25) {
          insights.push('Bu tarihlerde genellikle sıcak hava beklenir');
        } else if (avgTemp < 10) {
          insights.push('Bu tarihlerde genellikle serin hava beklenir');
        } else {
          insights.push('Bu tarihlerde genellikle ılıman hava beklenir');
        }

        if (precipitationProbability > 0.6) {
          insights.push('Yağış olasılığı yüksek, şemsiye almanızı öneririz');
        } else if (precipitationProbability > 0.3) {
          insights.push('Ara sıra yağış görülebilir');
        } else {
          insights.push('Genellikle kuru hava beklenir');
        }

        if (avgWindSpeed > 7) {
          insights.push('Rüzgarlı hava koşulları olabilir');
        }

        if (confidenceScore > 0.8) {
          insights.push('Geçmiş veriler tutarlı, tahmin güvenilir');
        } else if (confidenceScore < 0.5) {
          insights.push('Hava koşulları değişken olabilir');
        }

        analyses.push({
          date: tripDate.toISOString().split('T')[0],
          avg_temp_min: Math.round(avgTempMin * 10) / 10,
          avg_temp_max: Math.round(avgTempMax * 10) / 10,
          avg_temp: Math.round(avgTemp * 10) / 10,
          avg_precipitation: Math.round(avgPrecipitation * 10) / 10,
          avg_humidity: Math.round(avgHumidity),
          avg_wind_speed: Math.round(avgWindSpeed * 10) / 10,
          avg_cloud_cover: Math.round(avgCloudCover),
          precipitation_probability: Math.round(precipitationProbability * 100) / 100,
          most_common_condition: mostCommonCondition,
          confidence_score: Math.round(confidenceScore * 100) / 100,
          historical_data: historicalData,
          insights,
        });
      }
    }

    console.log(`${analyses.length} günlük geçmiş analiz tamamlandı`);

    return new Response(
      JSON.stringify({ 
        analyses,
        location: { lat, lon },
        units,
        years_analyzed: 5,
      }),
      { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    );

  } catch (error: any) {
    console.error('Geçmiş hava durumu analizi hatası:', error);
    return new Response(
      JSON.stringify({ error: error.message || 'Sunucu hatası' }),
      { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    );
  }
});
