import type { TouristPersona, TouristPersonaType } from '@/types/lead';
import { TOURIST_PERSONAS } from '@/types/persona';

interface ActivityInput {
  name?: string;
  type?: string;
  time_block?: string;
  [key: string]: any;
}

interface PersonaDetectionInput {
  interests?: string[];
  planned_activities?: string[] | ActivityInput[];
  number_of_travelers: number;
  start_date: string;
  end_date: string;
}

interface PersonaDetectionResult {
  persona: TouristPersona;
  confidence: number;
}

interface PersonaSignal {
  type: TouristPersonaType;
  confidence: number;
  signals: string[];
}

/**
 * Trip verilerinden persona tespiti yapar
 */
export function detectPersona(input: PersonaDetectionInput): PersonaDetectionResult {
  const signals = analyzeSignals(input);
  const bestMatch = findBestMatch(signals);
  
  const basePersona = TOURIST_PERSONAS[bestMatch.type];
  const persona: TouristPersona = {
    ...basePersona,
    key_signals: bestMatch.signals
  };

  return {
    persona,
    confidence: bestMatch.confidence
  };
}

function analyzeSignals(input: PersonaDetectionInput): PersonaSignal[] {
  const signals: PersonaSignal[] = [];
  
  // planned_activities'i normalize et: string veya obje olabilir
  const activityStrings = (input.planned_activities || []).map(a => {
    if (typeof a === 'string') return a.toLowerCase();
    // Obje ise: name + type + time_block bilgisini birleştir
    const timeBlockKeyword = a.time_block === 'dawn' ? 'sunrise dawn gündoğumu sabah' : '';
    return `${a.name || ''} ${a.type || ''} ${timeBlockKeyword}`.toLowerCase();
  });

  const allInterests = [
    ...(input.interests || []).map(i => i.toLowerCase()),
    ...activityStrings,
  ];

  // Romantic Couple sinyalleri
  const romanticSignals: string[] = [];
  let romanticConfidence = 0;

  if (input.number_of_travelers === 2) {
    romanticSignals.push('2 kişilik rezervasyon');
    romanticConfidence += 0.3;
  }

  if (allInterests.some(i => 
    ['romantik', 'balayı', 'özel', 'romantic', 'honeymoon', 'couple'].some(keyword => 
      i.toLowerCase().includes(keyword)
    )
  )) {
    romanticSignals.push('Romantik ilgi alanları');
    romanticConfidence += 0.4;
  }

  if (romanticConfidence > 0) {
    signals.push({
      type: 'romantic_couple',
      confidence: Math.min(romanticConfidence, 1),
      signals: romanticSignals
    });
  }

  // Budget Backpacker sinyalleri
  const budgetSignals: string[] = [];
  let budgetConfidence = 0;

  if (input.number_of_travelers === 1) {
    budgetSignals.push('Solo seyahat');
    budgetConfidence += 0.2;
  }

  if (allInterests.some(i => 
    ['hostel', 'backpack', 'budget', 'ekonomik', 'ucuz', 'cheap'].some(keyword => 
      i.toLowerCase().includes(keyword)
    )
  )) {
    budgetSignals.push('Bütçe odaklı ilgi alanları');
    budgetConfidence += 0.5;
  }

  if (budgetConfidence > 0) {
    signals.push({
      type: 'budget_backpacker',
      confidence: Math.min(budgetConfidence, 1),
      signals: budgetSignals
    });
  }

  // Luxury Traveler sinyalleri
  const luxurySignals: string[] = [];
  let luxuryConfidence = 0;

  if (allInterests.some(i => 
    ['vip', 'luxury', 'lüks', 'premium', '5 yıldız', 'exclusive', 'private'].some(keyword => 
      i.toLowerCase().includes(keyword)
    )
  )) {
    luxurySignals.push('Lüks ilgi alanları');
    luxuryConfidence += 0.6;
  }

  if (input.number_of_travelers <= 4 && luxuryConfidence > 0) {
    luxurySignals.push('Küçük grup (özel deneyim)');
    luxuryConfidence += 0.2;
  }

  if (luxuryConfidence > 0) {
    signals.push({
      type: 'luxury_traveler',
      confidence: Math.min(luxuryConfidence, 1),
      signals: luxurySignals
    });
  }

  // Content Creator sinyalleri
  const contentSignals: string[] = [];
  let contentConfidence = 0;

  if (allInterests.some(i => 
    ['fotoğraf', 'photo', 'instagram', 'video', 'content', 'drone', 'vlog', 'photography', 'camera'].some(keyword => 
      i.toLowerCase().includes(keyword)
    )
  )) {
    contentSignals.push('İçerik üretimi ilgi alanları');
    contentConfidence += 0.6;
  }

  if (input.number_of_travelers <= 2) {
    contentSignals.push('Küçük grup (içerik odaklı)');
    contentConfidence += 0.2;
  }

  if (contentConfidence > 0) {
    signals.push({
      type: 'content_creator',
      confidence: Math.min(contentConfidence, 1),
      signals: contentSignals
    });
  }

  // Family Explorer sinyalleri
  const familySignals: string[] = [];
  let familyConfidence = 0;

  if (input.number_of_travelers >= 3 && input.number_of_travelers <= 6) {
    familySignals.push('3-6 kişilik grup (aile boyutu)');
    familyConfidence += 0.3;
  }

  if (allInterests.some(i => 
    ['aile', 'çocuk', 'family', 'kids', 'children', 'child-friendly'].some(keyword => 
      i.toLowerCase().includes(keyword)
    )
  )) {
    familySignals.push('Aile odaklı ilgi alanları');
    familyConfidence += 0.5;
  }

  if (familyConfidence > 0) {
    signals.push({
      type: 'family_explorer',
      confidence: Math.min(familyConfidence, 1),
      signals: familySignals
    });
  }

  // Solo Adventurer sinyalleri
  const soloSignals: string[] = [];
  let soloConfidence = 0;

  if (input.number_of_travelers === 1) {
    soloSignals.push('Solo seyahat');
    soloConfidence += 0.4;
  }

  if (allInterests.some(i => 
    ['macera', 'adventure', 'trekking', 'hiking', 'solo', 'explore', 'backpacking'].some(keyword => 
      i.toLowerCase().includes(keyword)
    )
  )) {
    soloSignals.push('Macera odaklı ilgi alanları');
    soloConfidence += 0.4;
  }

  if (soloConfidence > 0) {
    signals.push({
      type: 'solo_adventurer',
      confidence: Math.min(soloConfidence, 1),
      signals: soloSignals
    });
  }

  // Group Tour sinyalleri
  const groupSignals: string[] = [];
  let groupConfidence = 0;

  if (input.number_of_travelers >= 8) {
    groupSignals.push('Büyük grup (8+ kişi)');
    groupConfidence += 0.5;
  }

  if (allInterests.some(i => 
    ['grup', 'group', 'tour', 'organize', 'kurumsal', 'corporate', 'team'].some(keyword => 
      i.toLowerCase().includes(keyword)
    )
  )) {
    groupSignals.push('Grup turu ilgi alanları');
    groupConfidence += 0.4;
  }

  if (groupConfidence > 0) {
    signals.push({
      type: 'group_tour',
      confidence: Math.min(groupConfidence, 1),
      signals: groupSignals
    });
  }

  return signals;
}

function findBestMatch(signals: PersonaSignal[]): PersonaSignal {
  if (signals.length === 0) {
    return {
      type: 'budget_backpacker',
      confidence: 0.3,
      signals: ['Varsayılan sınıflandırma']
    };
  }

  return signals.reduce((best, current) => 
    current.confidence > best.confidence ? current : best
  );
}

// Utility fonksiyonları tek noktadan erişilebilir kıl
export {
  getPersonaEmoji,
  getPersonaLabel,
  getSpendPotentialColor,
  getSpendPotentialLabel,
  getAllPersonaTypes,
} from './persona-detection';
