/**
 * Provider Suggestion Service
 * 
 * AI-powered service that analyzes trips and suggests tours/guides/providers
 * when it makes more sense than self-planning.
 * 
 * REFACTORED: Now uses shared service type enum and provides display metadata
 * for AI-driven UI rendering without client-side string matching.
 */

import type { RecommendationDisplayMetadata, TravelerProfile } from '@/types';
import { getServiceTypeMetadata, ServiceType, type ServiceTypeValue } from '@/types/service-types';

export interface ProviderSuggestion {
  type: ServiceTypeValue;
  reason: string;
  confidence: number; // 0-1
  benefits: string[];
  display_metadata: RecommendationDisplayMetadata;
}

/**
 * Generate display metadata based on service type and traveler profile
 */
function generateDisplayMetadata(
  serviceType: ServiceTypeValue,
  travelerProfile?: TravelerProfile
): RecommendationDisplayMetadata {
  const metadata = getServiceTypeMetadata(serviceType);
  
  // Generate segment-specific message based on traveler profile
  let segmentMessage = 'Bu günü bireysel gezmek yerine profesyonel destek almak daha mantıklı olabilir.';
  
  if (travelerProfile) {
    const { group_type, pace } = travelerProfile;
    
    if (group_type === 'couple') {
      segmentMessage = 'Çiftler için daha rahat ve romantik bir deneyim sunabilir.';
    } else if (group_type === 'family') {
      segmentMessage = 'Aileniz için daha az yorucu ve çocuklarla daha uygun olabilir.';
    } else if (group_type === 'friends') {
      segmentMessage = 'Grup için daha verimli ve eğlenceli bir rota sağlayabilir.';
    } else if (group_type === 'solo') {
      segmentMessage = 'Tek başına gezerken güvenlik ve yerel bilgi açısından avantaj sağlayabilir.';
    }
    
    if (pace === 'fast') {
      segmentMessage = 'Yoğun programınız için zaman kazandırabilir.';
    } else if (pace === 'slow') {
      segmentMessage = 'Rahat tempoda daha keyifli bir deneyim sunabilir.';
    }
  }
  
  const label = metadata?.label || serviceType || 'Önerilen Hizmet';
  const icon = metadata?.icon || '✨';
  
  return {
    service_type_label: label,
    service_type_icon: icon,
    group_label: 'Önerilen Turlar',
    group_description: `${label} ile daha iyi bir deneyim`,
    segment_message: segmentMessage,
  };
}

/**
 * Check if provider suggestion should be triggered
 */
export function shouldSuggestProvider(trip: any): boolean {
  const totalDays = trip.days?.length || 0;
  const totalPlaces = trip.days?.reduce((sum: number, day: any) => sum + (day.places?.length || 0), 0) || 0;
  
  // Minimum requirements
  if (totalDays < 2) return false;
  if (totalPlaces < 3) return false;
  
  // Check for special activities
  const hasSpecialActivities = trip.days?.some((day: any) =>
    day.places?.some((p: any) => {
      const type = p.place?.type || '';
      return ['hot-air-balloon', 'atv', 'horse-riding', 'tour'].includes(type);
    })
  );
  
  return hasSpecialActivities;
}

/**
 * AI decision engine - determines which provider type to recommend
 * Now returns display metadata for UI rendering
 */
export function suggestProvider(trip: any, travelerProfile?: TravelerProfile): ProviderSuggestion | null {
  // Check for balloon
  const hasBalloon = trip.has_balloon || false;
  
  if (hasBalloon) {
    const serviceType = ServiceType.HOT_AIR_BALLOON;
    return {
      type: serviceType,
      reason: 'Balon + transfer sabah çok erken saatlerde daha verimli',
      confidence: 0.9,
      benefits: [
        'Otel transferi dahil (sabah 04:00-05:00)',
        'Profesyonel pilot ve ekip',
        'Uçuş sertifikası',
        'Kahvaltı ikramı',
        'Güvenli ve organize deneyim',
      ],
      display_metadata: generateDisplayMetadata(serviceType, travelerProfile),
    };
  }
  
  // Check for many attractions on same day
  const hasManyAttractionsSameDay = trip.days?.some((day: any) => {
    const placesCount = day.places?.length || 0;
    return placesCount >= 4;
  });
  
  if (hasManyAttractionsSameDay) {
    const serviceType = ServiceType.GUIDED_TOUR;
    return {
      type: serviceType,
      reason: 'Zaman ve ulaşım açısından rehberli tur daha mantıklı',
      confidence: 0.85,
      benefits: [
        'Tüm ulaşım dahil',
        'Profesyonel rehber eşliğinde',
        'Giriş ücretleri dahil',
        'Zaman tasarrufu',
        'Yerel bilgi ve hikayeler',
      ],
      display_metadata: generateDisplayMetadata(serviceType, travelerProfile),
    };
  }
  
  // Check for distant places
  const hasDistantPlaces = checkDistantPlaces(trip);
  
  if (hasDistantPlaces) {
    const serviceType = ServiceType.DRIVER_CAR;
    return {
      type: serviceType,
      reason: 'Yerler arası mesafe uzun, şoförlü araç daha konforlu',
      confidence: 0.8,
      benefits: [
        'Konforlu ulaşım',
        'Esnek program',
        'Yerel şoför',
        'Yorulmadan gezin',
        'Bagaj sorunu yok',
      ],
      display_metadata: generateDisplayMetadata(serviceType, travelerProfile),
    };
  }
  
  // Check for multiple activities
  const hasMultipleActivities = trip.days?.some((day: any) => {
    const activityTypes = new Set();
    day.places?.forEach((p: any) => {
      const type = p.place?.type || '';
      if (['atv', 'horse-riding', 'tour', 'adventure'].includes(type)) {
        activityTypes.add(type);
      }
    });
    return activityTypes.size >= 2;
  });
  
  if (hasMultipleActivities) {
    const serviceType = ServiceType.ACTIVITY_BUNDLE;
    return {
      type: serviceType,
      reason: 'Birden fazla aktivite için paket tur daha ekonomik',
      confidence: 0.75,
      benefits: [
        'Paket fiyat avantajı',
        'Tek rezervasyon',
        'Koordinasyon sorunu yok',
        'Ekipman dahil',
        'Güvenlik garantisi',
      ],
      display_metadata: generateDisplayMetadata(serviceType, travelerProfile),
    };
  }
  
  return null;
}

/**
 * Check if trip has distant places
 */
function checkDistantPlaces(trip: any): boolean {
  // Simple check: if 4+ places and in different regions
  const totalPlaces = trip.days?.reduce((sum: number, day: any) => sum + (day.places?.length || 0), 0) || 0;
  
  if (totalPlaces >= 4) {
    // Real distance calculation could use lat/lng
    // For now, simple check
    return true;
  }
  
  return false;
}

/**
 * Format provider suggestion for UI (legacy support)
 * Note: With new refactoring, UI should use display_metadata directly
 */
export function formatProviderSuggestion(suggestion: ProviderSuggestion): string {
  return `${suggestion.display_metadata.service_type_label}: ${suggestion.reason}`;
}

/**
 * Analyze trip and suggest provider
 */
export function analyzeAndSuggest(trip: any, travelerProfile?: TravelerProfile): {
  shouldSuggest: boolean;
  suggestion: ProviderSuggestion | null;
  formattedMessage: string | null;
} {
  const shouldSuggest = shouldSuggestProvider(trip);
  
  if (!shouldSuggest) {
    return {
      shouldSuggest: false,
      suggestion: null,
      formattedMessage: null,
    };
  }
  
  const suggestion = suggestProvider(trip, travelerProfile);
  
  if (!suggestion) {
    return {
      shouldSuggest: false,
      suggestion: null,
      formattedMessage: null,
    };
  }
  
  return {
    shouldSuggest: true,
    suggestion,
    formattedMessage: formatProviderSuggestion(suggestion),
  };
}
