export interface GeocodeResult {
  country?: string | null;
  city?: string | null;
  address?: string | null;
}

interface GeocodingProvider {
  name: string;
  baseUrl: string;
  requestDelay: number;
  parseResponse: (data: any) => GeocodeResult;
}

export class GeocodingService {
  // Multiple free geocoding providers for redundancy
  private static readonly PROVIDERS: GeocodingProvider[] = [
    {
      name: 'Nominatim (OpenStreetMap)',
      baseUrl: 'https://nominatim.openstreetmap.org',
      requestDelay: 1000, // 1 second as per usage policy
      parseResponse: GeocodingService.parseNominatimResponse,
    },
    {
      name: 'Photon (Komoot)',
      baseUrl: 'https://photon.komoot.io',
      requestDelay: 500, // More lenient rate limiting
      parseResponse: GeocodingService?.parsePhotonResponse,
    },
  ];

  private static lastRequestTimes: Map<string, number> = new Map();
  private static currentProviderIndex = 0;

  /**
   * Reverse geocode coordinates to get address information
   * Uses multiple free geocoding providers with automatic fallback
   */
  public static async reverseGeocode(
    latitude: number,
    longitude: number
  ): Promise<GeocodeResult> {
    // Validate coordinates
    if (latitude < -90 || latitude > 90) {
      throw new Error('Invalid latitude: must be between -90 and 90');
    }
    if (longitude < -180 || longitude > 180) {
      throw new Error('Invalid longitude: must be between -180 and 180');
    }

    // Try each provider until one succeeds
    for (let i = 0; i < this.PROVIDERS.length; i++) {
      const providerIndex = (this.currentProviderIndex + i) % this.PROVIDERS.length;
      const provider = this.PROVIDERS[providerIndex];

      try {
        const result = await this.tryProvider(provider, latitude, longitude);

        // If successful, update current provider for next request
        this.currentProviderIndex = providerIndex;
        return result;
      } catch (error) {
        console.warn(`Provider ${provider.name} failed:`, error);

        // If this was the last provider, log error and return default
        if (i === this.PROVIDERS.length - 1) {
          console.error('All geocoding providers failed');
        }
      }
    }

    return this.getDefaultResult();
  }

  /**
   * Try a specific geocoding provider
   */
  private static async tryProvider(
    provider: GeocodingProvider,
    latitude: number,
    longitude: number
  ): Promise<GeocodeResult> {
    // Respect rate limiting for this provider
    await this.respectRateLimit(provider.name, provider.requestDelay);

    let url: string;
    let headers: Record<string, string> = {};

    // Build URL based on provider
    if (provider.name.includes('Nominatim')) {
      url = `${provider.baseUrl}/reverse?format=json&lat=${latitude}&lon=${longitude}&addressdetails=1&accept-language=en`;
      headers['User-Agent'] = 'QuickConnect-Backend/1.0.0 (contact@quickconnect.com)';
    } else if (provider.name.includes('Photon')) {
      url = `${provider.baseUrl}/reverse?lat=${latitude}&lon=${longitude}&lang=en`;
    } else {
      throw new Error(`Unknown provider: ${provider.name}`);
    }

    // Dynamically import node-fetch
    const fetchModule = await import('node-fetch');
    const fetch = fetchModule.default;

    const response = await fetch(url, {
      headers,
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }

    const data = (await response.json()) as any;

    if (!data || data.error) {
      throw new Error(data?.error || 'API returned error');
    }

    return provider.parseResponse(data);
  }

  /**
   * Parse Photon API response to extract relevant address information
   */
  private static parsePhotonResponse(data: any): GeocodeResult {
    try {
      const features = data.features;
      if (!features || !Array.isArray(features) || features.length === 0) {
        return GeocodingService.getDefaultResult();
      }

      const feature = features[0];
      const properties = feature.properties || {};

      // Extract country
      const country = properties.country || undefined;

      // Extract city (try multiple fields)
      const city =
        properties.city ||
        properties.town ||
        properties.village ||
        properties.municipality ||
        properties.county ||
        undefined;

      // Build formatted address
      let addressParts: string[] = [];

      // Add house number and street
      if (properties.housenumber && properties.street) {
        addressParts.push(`${properties.housenumber} ${properties.street}`);
      } else if (properties.street) {
        addressParts.push(properties.street);
      }

      // Add district/suburb
      if (properties.district) {
        addressParts.push(properties.district);
      }

      // Add city
      if (city) {
        addressParts.push(city);
      }

      // Add state
      if (properties.state) {
        addressParts.push(properties.state);
      }

      // Add country
      if (country) {
        addressParts.push(country);
      }

      const formattedAddress =
        addressParts.length > 0 ? addressParts.join(', ') : undefined;

      return {
        country,
        city,
        address: formattedAddress,
      };
    } catch (error) {
      console.error('Error parsing Photon response:', error);
      return GeocodingService.getDefaultResult();
    }
  }

  /**
   * Parse Nominatim API response to extract relevant address information
   */
  private static parseNominatimResponse(data: any): GeocodeResult {
    try {
      const address = data.address || {};

      // Extract country
      const country = address.country || undefined;

      // Extract city (try multiple fields in order of preference)
      const city =
        address.city ||
        address.town ||
        address.village ||
        address.municipality ||
        address.county ||
        undefined;

      // Build formatted address
      let addressParts: string[] = [];

      // Add house number and street
      if (address.house_number && address.road) {
        addressParts.push(`${address.house_number} ${address.road}`);
      } else if (address.road) {
        addressParts.push(address.road);
      }

      // Add suburb/neighborhood
      if (address.suburb || address.neighbourhood) {
        addressParts.push(address.suburb || address.neighbourhood);
      }

      // Add city if not already included
      if (city && !addressParts.some(part => part.includes(city))) {
        addressParts.push(city);
      }

      // Add state/province
      if (address.state) {
        addressParts.push(address.state);
      }

      // Add country if not already included
      if (country && !addressParts.some(part => part.includes(country))) {
        addressParts.push(country);
      }

      const formattedAddress =
        addressParts.length > 0 ? addressParts.join(', ') : undefined;

      return {
        country,
        city,
        address: formattedAddress,
      };
    } catch (error) {
      console.error('Error parsing geocoding response:', error);
      return this.getDefaultResult();
    }
  }

  /**
   * Respect rate limiting for specific provider
   */
  private static async respectRateLimit(
    providerName: string,
    delay: number
  ): Promise<void> {
    const now = Date.now();
    const lastRequestTime = this.lastRequestTimes.get(providerName) || 0;
    const timeSinceLastRequest = now - lastRequestTime;

    if (timeSinceLastRequest < delay) {
      const waitTime = delay - timeSinceLastRequest;
      await new Promise(resolve => setTimeout(resolve, waitTime));
    }

    this.lastRequestTimes.set(providerName, Date.now());
  }

  /**
   * Get default result when geocoding fails
   */
  private static getDefaultResult(): GeocodeResult {
    return {
      country: undefined,
      city: undefined,
      address: undefined,
    };
  }

  /**
   * Batch reverse geocode multiple coordinates (with proper rate limiting)
   */
  public static async batchReverseGeocode(
    coordinates: Array<{ latitude: number; longitude: number }>
  ): Promise<GeocodeResult[]> {
    const results: GeocodeResult[] = [];

    for (const coord of coordinates) {
      const result = await this.reverseGeocode(coord.latitude, coord.longitude);
      results.push(result);
    }

    return results;
  }

  /**
   * Get provider status and health check
   */
  public static async getProviderStatus(): Promise<
    Array<{ name: string; status: 'healthy' | 'unhealthy' | 'unknown' }>
  > {
    const statuses: Array<{
      name: string;
      status: 'healthy' | 'unhealthy' | 'unknown';
    }> = [];

    // Use configurable test coordinates with fallback to New York City
    const testLatitude = parseFloat(process.env.GEOCODING_TEST_LATITUDE || '40.7128');
    const testLongitude = parseFloat(process.env.GEOCODING_TEST_LONGITUDE || '-74.006');

    for (const provider of this.PROVIDERS) {
      try {
        // Test with a known coordinate
        const testResult = await this.tryProvider(provider, testLatitude, testLongitude);
        statuses.push({
          name: provider.name,
          status: testResult.country ? ('healthy' as const) : ('unhealthy' as const),
        });
      } catch (error) {
        statuses.push({
          name: provider.name,
          status: 'unhealthy' as const,
        });
      }
    }

    return statuses;
  }

  /**
   * Force switch to next available provider
   */
  public static switchProvider(): void {
    this.currentProviderIndex = (this.currentProviderIndex + 1) % this.PROVIDERS.length;
    console.log(
      `Switched to provider: ${this.PROVIDERS[this.currentProviderIndex].name}`
    );
  }

  /**
   * Get current active provider name
   */
  public static getCurrentProvider(): string {
    return this.PROVIDERS[this.currentProviderIndex].name;
  }
}
