#!/usr/bin/env python3
"""
Ultimate Lotto 6aus49 Generator mit Multi-Ziehungs-Trend-Analyse

Speziell optimiert für deutsches Lotto 6 aus 49:
- 6 Zahlen aus 49 (statt 5 aus 50)
- 1 Superzahl 0-9 (statt 2 Eurozahlen)
- Angepasste N/M/H-Bereiche für 49er-System
- Multi-Ziehungs-Trend-Analyse
- Momentum-Tracking über mehrere Ziehungen
- Sequenzielle Abhängigkeiten
- Zyklische Muster-Erkennung
"""

import pandas as pd
import random
import numpy as np
from itertools import combinations
from collections import Counter, defaultdict, deque
import datetime

class UltimateLotto6aus49Generator:
    def __init__(self, data_path=None):
        # Pfad zur Lotto-Daten CSV-Datei
        self.data_path = data_path or input("Pfad zur Lotto 6aus49 CSV-Datei: ").strip()
        self.df = None
        self.drawn_combinations = set()
        
        # Basis-Analyse
        self.number_frequencies = Counter()
        self.position_frequencies = defaultdict(Counter)
        self.pattern_frequencies = Counter()
        self.supernumber_frequencies = Counter()  # Nur 1 Superzahl beim Lotto
        self.number_distances = []
        
        # Multi-Ziehungs-Trend-Analyse
        self.number_sequences = defaultdict(list)
        self.momentum_scores = {}
        self.trend_predictions = {}
        self.sequential_dependencies = defaultdict(lambda: defaultdict(int))
        self.cycle_patterns = {}
        self.hot_numbers = []
        self.warm_numbers = []
        self.cold_numbers = []
        
        # Lotto 6aus49 spezifische Bereiche (angepasst für 1-49)
        self.lotto_ranges = {
            'N': list(range(1, 17)),    # Niedrig: 1-16 (etwa 1/3)
            'M': list(range(17, 33)),   # Mittel: 17-32 (etwa 1/3)
            'H': list(range(33, 50))    # Hoch: 33-49 (etwa 1/3)
        }
        
        # Initialisierung
        if self._file_exists():
            self.load_and_analyze_all_data()
    
    def _file_exists(self):
        """Prüft ob Datei existiert."""
        try:
            with open(self.data_path, 'r'):
                return True
        except FileNotFoundError:
            print(f"❌ Datei nicht gefunden: {self.data_path}")
            print("💡 Bitte stellen Sie sicher, dass die Lotto-Daten im korrekten Format vorliegen:")
            print("   Spalten: Datum, Z1, Z2, Z3, Z4, Z5, Z6, SZ (Superzahl)")
            return False
    
    def load_and_analyze_all_data(self):
        """Lädt Lotto-Daten und führt alle Analysen durch."""
        try:
            # CSV laden mit flexibler Spaltenerkennung
            self.df = pd.read_csv(self.data_path, sep=';')
            
            # Spalten-Mapping für verschiedene CSV-Formate
            column_mapping = {
                'Ziehungsdatum': 'Datum',
                'Gewinnzahl1': 'Z1', 'Gewinnzahl2': 'Z2', 'Gewinnzahl3': 'Z3',
                'Gewinnzahl4': 'Z4', 'Gewinnzahl5': 'Z5', 'Gewinnzahl6': 'Z6',
                'Superzahl': 'SZ', 'SuperZahl': 'SZ'
            }
            
            # Spalten umbenennen falls nötig
            for old_name, new_name in column_mapping.items():
                if old_name in self.df.columns and new_name not in self.df.columns:
                    self.df.rename(columns={old_name: new_name}, inplace=True)
            
            # Benötigte Spalten prüfen
            required_columns = ['Z1', 'Z2', 'Z3', 'Z4', 'Z5', 'Z6']
            missing_columns = [col for col in required_columns if col not in self.df.columns]
            
            if missing_columns:
                print(f"❌ Fehlende Spalten: {missing_columns}")
                print(f"🔍 Verfügbare Spalten: {list(self.df.columns)}")
                return False
            
            # Chronologische Sortierung
            if 'Datum' in self.df.columns:
                # Verschiedene Datumsformate versuchen
                date_formats = ['%d.%m.%Y', '%Y-%m-%d', '%d/%m/%Y']
                for date_format in date_formats:
                    try:
                        self.df['Datum'] = pd.to_datetime(self.df['Datum'], format=date_format)
                        break
                    except:
                        continue
                
                if pd.api.types.is_datetime64_any_dtype(self.df['Datum']):
                    self.df = self.df.sort_values('Datum')
            
            print(f"🎲 ULTIMATE LOTTO 6AUS49 GENERATOR")
            print("=" * 60)
            print(f"📊 Analysiere {len(self.df)} Lotto-Ziehungen...")
            print(f"🎯 System: 6 aus 49 + Superzahl (0-9)")
            
            # Alle Analysen durchführen
            self._perform_lotto_basic_analysis()
            self._perform_lotto_momentum_analysis()
            self._perform_lotto_sequential_analysis()
            self._perform_lotto_cycle_analysis()
            self._generate_lotto_trend_predictions()
            
            print(f"✅ Komplette Lotto-Analyse abgeschlossen!")
            self._print_lotto_analysis_summary()
            
        except Exception as e:
            print(f"❌ Fehler beim Laden der Lotto-Daten: {e}")
            print("💡 Stellen Sie sicher, dass die CSV-Datei das korrekte Format hat.")
            return False
        
        return True
    
    def _perform_lotto_basic_analysis(self):
        """Führt Basis-Analysen für Lotto 6aus49 durch."""
        for _, row in self.df.iterrows():
            # 6 Gewinnzahlen
            numbers = [row['Z1'], row['Z2'], row['Z3'], row['Z4'], row['Z5'], row['Z6']]
            combo = tuple(sorted(numbers))
            self.drawn_combinations.add(combo)
            
            # Zahlenfrequenzen (1-49)
            for num in numbers:
                if 1 <= num <= 49:  # Validierung für Lotto-Bereich
                    self.number_frequencies[num] += 1
            
            # Positionsfrequenzen
            sorted_numbers = sorted(numbers)
            for i, num in enumerate(sorted_numbers):
                self.position_frequencies[f'pos_{i+1}'][num] += 1
            
            # Lotto-Muster analysieren (angepasste Bereiche)
            pattern = self._get_lotto_pattern(sorted_numbers)
            self.pattern_frequencies[pattern] += 1
            
            # Superzahl (0-9)
            if 'SZ' in row and pd.notna(row['SZ']):
                superzahl = int(row['SZ'])
                if 0 <= superzahl <= 9:
                    self.supernumber_frequencies[superzahl] += 1
            
            # Zahlenabstände (für 6 Zahlen)
            distances = [sorted_numbers[i+1] - sorted_numbers[i] for i in range(5)]
            self.number_distances.extend(distances)
    
    def _get_lotto_pattern(self, numbers):
        """Bestimmt N/M/H-Muster für Lotto 6aus49."""
        pattern = []
        for num in numbers:
            if 1 <= num <= 16:
                pattern.append('N')  # Niedrig
            elif 17 <= num <= 32:
                pattern.append('M')  # Mittel
            else:
                pattern.append('H')  # Hoch (33-49)
        return ''.join(pattern)
    
    def _perform_lotto_momentum_analysis(self, window_size=12):
        """Momentum-Analyse für Lotto 6aus49."""
        print(f"\n🔥 LOTTO MOMENTUM-ANALYSE (Fenster: {window_size})")
        
        # Zahlensequenzen für 1-49
        for number in range(1, 50):
            sequence = []
            for _, row in self.df.iterrows():
                drawn_numbers = [row['Z1'], row['Z2'], row['Z3'], row['Z4'], row['Z5'], row['Z6']]
                sequence.append(1 if number in drawn_numbers else 0)
            self.number_sequences[number] = sequence
        
        # Momentum-Scores
        momentum_results = {}
        for number in range(1, 50):
            recent_sequence = self.number_sequences[number][-window_size:]
            
            hit_rate = sum(recent_sequence) / len(recent_sequence)
            trend_score = self._calculate_trend_score(recent_sequence)
            recency_score = self._calculate_recency_score(recent_sequence)
            
            # Lotto-angepasste Gewichtung (6 aus 49 vs 5 aus 50)
            momentum_score = (hit_rate * 0.45) + (trend_score * 0.35) + (recency_score * 0.2)
            
            momentum_results[number] = {
                'hit_rate': hit_rate,
                'trend_score': trend_score,
                'recency_score': recency_score,
                'momentum_score': momentum_score,
                'status': self._get_momentum_status(momentum_score)
            }
        
        self.momentum_scores = momentum_results
        
        # Kategorisierung für Lotto
        sorted_momentum = sorted(momentum_results.items(), 
                               key=lambda x: x[1]['momentum_score'], reverse=True)
        
        self.hot_numbers = [num for num, data in sorted_momentum[:18] 
                           if data['momentum_score'] > 0.25]  # Angepasst für 6aus49
        self.warm_numbers = [num for num, data in sorted_momentum[18:30] 
                            if 0.15 <= data['momentum_score'] <= 0.25]
        self.cold_numbers = [num for num, data in sorted_momentum[30:] 
                            if data['momentum_score'] < 0.15][:20]
        
        print(f"🔥 {len(self.hot_numbers)} heiße Lotto-Zahlen identifiziert")
        print(f"🌡️ {len(self.warm_numbers)} warme Lotto-Zahlen identifiziert") 
        print(f"🧊 {len(self.cold_numbers)} kalte Lotto-Zahlen identifiziert")
    
    def _perform_lotto_sequential_analysis(self, look_back=3):
        """Sequenzielle Abhängigkeiten für Lotto."""
        print(f"\n🔗 LOTTO SEQUENZIELLE ABHÄNGIGKEITEN")
        
        for i in range(look_back, len(self.df)):
            current_numbers = set([self.df.iloc[i]['Z1'], self.df.iloc[i]['Z2'], 
                                 self.df.iloc[i]['Z3'], self.df.iloc[i]['Z4'], 
                                 self.df.iloc[i]['Z5'], self.df.iloc[i]['Z6']])
            
            for j in range(1, look_back + 1):
                prev_numbers = set([self.df.iloc[i-j]['Z1'], self.df.iloc[i-j]['Z2'], 
                                  self.df.iloc[i-j]['Z3'], self.df.iloc[i-j]['Z4'], 
                                  self.df.iloc[i-j]['Z5'], self.df.iloc[i-j]['Z6']])
                
                for prev_num in prev_numbers:
                    for curr_num in current_numbers:
                        self.sequential_dependencies[f"lag_{j}"][f"{prev_num}_{curr_num}"] += 1
    
    def _perform_lotto_cycle_analysis(self, max_cycle_length=15):
        """Zyklische Muster-Analyse für Lotto."""
        print(f"\n🔄 LOTTO ZYKLUS-ANALYSE")
        
        pattern_sequence = []
        for _, row in self.df.iterrows():
            numbers = sorted([row['Z1'], row['Z2'], row['Z3'], row['Z4'], row['Z5'], row['Z6']])
            pattern = self._get_lotto_pattern(numbers)
            pattern_sequence.append(pattern)
        
        self.cycle_patterns = {}
        for cycle_length in range(3, max_cycle_length + 1):
            cycles = self._find_pattern_cycles(pattern_sequence, cycle_length)
            if cycles:
                self.cycle_patterns[cycle_length] = cycles
        
        cycle_count = sum(len(cycles) for cycles in self.cycle_patterns.values())
        print(f"🔄 {cycle_count} Lotto-Zyklen erkannt")
    
    def _generate_lotto_trend_predictions(self):
        """Trend-Vorhersagen für Lotto 6aus49."""
        print(f"\n🎯 LOTTO TREND-VORHERSAGEN")
        
        for number in range(1, 50):
            if number in self.momentum_scores:
                momentum_data = self.momentum_scores[number]
                
                # Lotto-spezifische Gewichtung
                momentum_weight = momentum_data['momentum_score'] * 0.4
                frequency_weight = (self.number_frequencies[number] / (len(self.df) * 6)) * 0.35  # 6 Zahlen pro Ziehung
                trend_weight = max(0, momentum_data['trend_score']) * 0.25
                
                prediction_score = momentum_weight + frequency_weight + trend_weight
                
                self.trend_predictions[number] = {
                    'prediction_score': prediction_score,
                    'recommendation': self._get_prediction_recommendation(prediction_score),
                    'confidence': self._get_confidence_level(prediction_score)
                }
    
    def generate_lotto_ultimate_combination(self):
        """Generiert ultimative Lotto 6aus49 Kombination."""
        max_attempts = 1000
        
        for attempt in range(max_attempts):
            numbers = []
            
            # Lotto-Strategie: 6 Zahlen aus 49
            # 50% Top-Trend, 30% Heiß, 20% Balance
            
            # 3 Zahlen aus Top-Trends
            top_trend_numbers = [num for num, data in sorted(self.trend_predictions.items(), 
                               key=lambda x: x[1]['prediction_score'], reverse=True)[:20]
                               if data['recommendation'] in ['SEHR EMPFOHLEN', 'EMPFOHLEN']]
            
            if len(top_trend_numbers) >= 3:
                trend_picks = random.sample(top_trend_numbers[:12], 3)
                numbers.extend(trend_picks)
            
            # 2 heiße Zahlen
            if len(self.hot_numbers) >= 2:
                remaining_hot = [n for n in self.hot_numbers if n not in numbers]
                if len(remaining_hot) >= 2:
                    hot_picks = random.sample(remaining_hot[:10], min(2, len(remaining_hot)))
                    numbers.extend(hot_picks)
            
            # 1 warme/kalte Zahl für Balance
            remaining_slots = 6 - len(numbers)
            if remaining_slots > 0:
                balance_pool = self.warm_numbers + self.cold_numbers[:5]
                remaining_balance = [n for n in balance_pool if n not in numbers]
                if remaining_balance:
                    balance_picks = random.sample(remaining_balance, min(remaining_slots, len(remaining_balance)))
                    numbers.extend(balance_picks)
            
            # Auffüllen bis 6 Zahlen
            while len(numbers) < 6:
                available_numbers = [n for n in range(1, 50) if n not in numbers]
                weights = [self.trend_predictions[n]['prediction_score'] for n in available_numbers]
                
                if sum(weights) > 0:
                    additional_number = random.choices(available_numbers, weights=weights)[0]
                else:
                    additional_number = random.choice(available_numbers)
                
                numbers.append(additional_number)
            
            # Sortieren und validieren
            numbers = sorted(numbers[:6])
            
            if self._validate_lotto_combination(numbers):
                return numbers
        
        # Fallback
        return self._generate_lotto_fallback()
    
    def _validate_lotto_combination(self, numbers):
        """Validierung für Lotto 6aus49."""
        if tuple(numbers) in self.drawn_combinations:
            return False
        
        if len(set(numbers)) != 6:
            return False
        
        # Lotto-spezifische Validierungen
        hot_count = sum(1 for n in numbers if n in self.hot_numbers)
        trend_count = sum(1 for n in numbers 
                         if self.trend_predictions[n]['recommendation'] == 'SEHR EMPFOHLEN')
        
        # Mindestens 1 heiße oder sehr empfohlene Zahl
        if hot_count == 0 and trend_count == 0:
            return False
        
        # Abstände prüfen (für 6 Zahlen)
        distances = [numbers[i+1] - numbers[i] for i in range(5)]
        if min(distances) < 1 or max(distances) > 15:
            return False
        
        # Gerade/Ungerade Balance
        even_count = sum(1 for n in numbers if n % 2 == 0)
        if even_count == 0 or even_count == 6:
            return False
        
        # Summen-Validierung für 6aus49
        total = sum(numbers)
        if total < 90 or total > 200:
            return False
        
        return True
    
    def _generate_lotto_fallback(self):
        """Fallback für Lotto 6aus49."""
        numbers = []
        
        # Erweiterte Verteilung für 6 Zahlen: 2N + 2M + 2H
        numbers.extend(random.sample(self.lotto_ranges['N'], 2))
        numbers.extend(random.sample(self.lotto_ranges['M'], 2))
        numbers.extend(random.sample(self.lotto_ranges['H'], 2))
        
        return sorted(numbers)
    
    def get_optimized_supernumber(self):
        """Optimierte Superzahl-Auswahl (0-9)."""
        if not self.supernumber_frequencies:
            return random.randint(0, 9)
        
        # Trend-gewichtete Superzahl-Auswahl
        recent_df = self.df.tail(8) if len(self.df) >= 8 else self.df
        supernumber_trends = {}
        
        for sz in range(0, 10):
            recent_count = (recent_df['SZ'] == sz).sum() if 'SZ' in recent_df.columns else 0
            total_count = self.supernumber_frequencies[sz]
            trend_score = (recent_count / len(recent_df)) * 0.6 + (total_count / len(self.df)) * 0.4
            supernumber_trends[sz] = trend_score
        
        # Gewichtete Auswahl
        candidates = list(supernumber_trends.keys())
        weights = list(supernumber_trends.values())
        
        if sum(weights) > 0:
            return random.choices(candidates, weights=weights)[0]
        else:
            return random.randint(0, 9)
    
    def generate_lotto_ultimate_tips(self, num_tips=10):
        """Generiert ultimate Lotto 6aus49 Tipps."""
        print(f"\n🚀 ULTIMATE LOTTO 6AUS49 TIPP-GENERIERUNG")
        print("=" * 55)
        print(f"🎯 System: 6 Zahlen aus 49 + 1 Superzahl (0-9)")
        print(f"🔬 Multi-Trend-Analyse für maximale Trefferquote")
        
        generated_tips = []
        strategy_distribution = Counter()
        
        print(f"\n🎲 GENERIERE {num_tips} ULTIMATE LOTTO-TIPPS:")
        print("=" * 65)
        print(f"{'Nr':<3} {'6 Zahlen aus 49':<25} {'SZ':<3} {'Muster':<8} {'🔥':<3} {'🎯':<3} {'Strategie'}")
        print("-" * 65)
        
        attempts = 0
        max_attempts = num_tips * 50
        
        while len(generated_tips) < num_tips and attempts < max_attempts:
            attempts += 1
            
            combination = self.generate_lotto_ultimate_combination()
            
            if combination and tuple(combination) not in [tuple(tip['zahlen']) for tip in generated_tips]:
                pattern = self._get_lotto_pattern(combination)
                
                # Lotto-Trend-Analyse
                hot_count = sum(1 for n in combination if n in self.hot_numbers)
                trend_count = sum(1 for n in combination 
                                if self.trend_predictions[n]['recommendation'] in ['SEHR EMPFOHLEN', 'EMPFOHLEN'])
                
                # Superzahl
                superzahl = self.get_optimized_supernumber()
                
                # Strategie-Klassifikation
                if hot_count >= 4:
                    strategy = "🔥 MOMENTUM"
                elif trend_count >= 4:
                    strategy = "🎯 TREND"
                elif pattern in ['NNMMHH', 'NMMHHH', 'NNNMMM']:
                    strategy = "🎨 MUSTER"
                else:
                    strategy = "⚖️ BALANCE"
                
                strategy_distribution[strategy] += 1
                
                tip = {
                    'tipp_nr': len(generated_tips) + 1,
                    'zahlen': combination,
                    'z1': combination[0], 'z2': combination[1], 'z3': combination[2],
                    'z4': combination[3], 'z5': combination[4], 'z6': combination[5],
                    'superzahl': superzahl,
                    'muster': pattern,
                    'summe': sum(combination),
                    'hot_count': hot_count,
                    'trend_count': trend_count,
                    'strategy': strategy
                }
                
                generated_tips.append(tip)
                
                # Output
                zahlen_str = f"{combination[0]:2}-{combination[1]:2}-{combination[2]:2}-{combination[3]:2}-{combination[4]:2}-{combination[5]:2}"
                print(f"{len(generated_tips):2}. {zahlen_str:<25} {superzahl:<3} {pattern:<8} {hot_count:<3} {trend_count:<3} {strategy}")
        
        # Lotto-Zusammenfassung
        self._print_lotto_summary(generated_tips, attempts, strategy_distribution)
        
        # Export
        self._export_lotto_tips(generated_tips)
        
        return generated_tips
    
    def _print_lotto_summary(self, tips, attempts, strategy_distribution):
        """Druckt Lotto-spezifische Zusammenfassung."""
        print(f"\n🏆 ULTIMATE LOTTO 6AUS49 ZUSAMMENFASSUNG:")
        print("=" * 50)
        print(f"✅ {len(tips)} Ultimate Lotto-Tipps generiert")
        print(f"🎯 Erfolgsrate: {(len(tips)/attempts)*100:.1f}%")
        print(f"🔥 Durchschnitt {sum(tip['hot_count'] for tip in tips)/len(tips):.1f} heiße Zahlen pro Tipp")
        print(f"📈 Durchschnitt {sum(tip['trend_count'] for tip in tips)/len(tips):.1f} Trend-Zahlen pro Tipp")
        
        # Strategie-Verteilung
        print(f"\n📊 STRATEGIE-VERTEILUNG:")
        for strategy, count in strategy_distribution.most_common():
            print(f"  {strategy}: {count} Tipps")
        
        # Lotto-spezifische Insights
        print(f"\n💡 LOTTO 6AUS49 INSIGHTS:")
        
        # Top Trend-Zahlen
        top_trend = sorted(self.trend_predictions.items(), 
                          key=lambda x: x[1]['prediction_score'], reverse=True)[:6]
        print(f"🎯 TOP 6 TREND-ZAHLEN:")
        for i, (number, data) in enumerate(top_trend):
            status = self.momentum_scores[number]['status']
            print(f"   {i+1}. Zahl {number:2}: {data['recommendation']} {status}")
        
        # Häufigste Superzahlen
        if self.supernumber_frequencies:
            top_sz = self.supernumber_frequencies.most_common(3)
            print(f"\n🎲 TOP 3 SUPERZAHLEN:")
            for sz, count in top_sz:
                percentage = (count / len(self.df)) * 100
                print(f"   Superzahl {sz}: {count}x ({percentage:.1f}%)")
        
        # Empfohlene Muster
        top_patterns = self.pattern_frequencies.most_common(3)
        print(f"\n🎨 TOP 3 LOTTO-MUSTER:")
        for pattern, count in top_patterns:
            percentage = (count / len(self.drawn_combinations)) * 100
            print(f"   {pattern}: {count}x ({percentage:.1f}%)")
    
    def _export_lotto_tips(self, tips):
        """Exportiert Lotto-Tipps."""
        timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        output_file = f"ultimate_lotto_6aus49_tipps_{timestamp}.csv"
        
        # Export-Daten erweitern
        export_data = []
        for tip in tips:
            tip_data = tip.copy()
            tip_data['trend_scores'] = [self.trend_predictions[n]['prediction_score'] 
                                      for n in tip['zahlen']]
            tip_data['avg_trend_score'] = np.mean(tip_data['trend_scores'])
            export_data.append(tip_data)
        
        tips_df = pd.DataFrame(export_data)
        tips_df.to_csv(output_file, sep=';', index=False)
        
        print(f"\n💾 LOTTO-EXPORT:")
        print("=" * 25)
        print(f"✅ Lotto-Tipps gespeichert: {output_file}")
        print(f"🎲 Format: 6 Zahlen aus 49 + Superzahl")
        print(f"🚀 Ultimate Multi-Trend-Optimierung")
    
    def _print_lotto_analysis_summary(self):
        """Druckt Lotto-Analyse-Zusammenfassung."""
        print(f"\n📈 LOTTO 6AUS49 ANALYSE-ZUSAMMENFASSUNG:")
        print("=" * 55)
        
        # Top Zahlen
        print(f"\n🔢 HÄUFIGSTE LOTTO-ZAHLEN:")
        for i, (number, count) in enumerate(self.number_frequencies.most_common(10)):
            percentage = (count / (len(self.df) * 6)) * 100
            print(f"{i+1:2}. Zahl {number:2}: {count:3}x ({percentage:.2f}%)")
        
        # Top Muster  
        print(f"\n🎨 ERFOLGREICHSTE LOTTO-MUSTER:")
        for pattern, count in self.pattern_frequencies.most_common(5):
            percentage = (count / len(self.drawn_combinations)) * 100
            print(f"  {pattern}: {count}x ({percentage:.1f}%)")
    
    # Hilfsfunktionen (gleich wie Eurojackpot)
    def _calculate_trend_score(self, sequence):
        if len(sequence) < 2:
            return 0
        x = np.arange(len(sequence))
        y = np.array(sequence)
        weights = np.exp(x / len(x))
        try:
            coeffs = np.polyfit(x, y, 1, w=weights)
            return coeffs[0]
        except:
            return 0
    
    def _calculate_recency_score(self, sequence):
        try:
            last_hit_index = len(sequence) - 1 - sequence[::-1].index(1)
            recency = 1 - (len(sequence) - 1 - last_hit_index) / len(sequence)
            return recency
        except ValueError:
            return 0
    
    def _get_momentum_status(self, score):
        if score > 0.4:
            return "🔥 SEHR HEISS"
        elif score > 0.25:
            return "🌡️ HEISS"
        elif score > 0.15:
            return "😐 WARM"
        elif score > 0.08:
            return "🧊 KÜHL"
        else:
            return "❄️ EISKALT"
    
    def _get_prediction_recommendation(self, score):
        if score > 0.3:
            return "SEHR EMPFOHLEN"
        elif score > 0.2:
            return "EMPFOHLEN"
        elif score > 0.12:
            return "NEUTRAL"
        else:
            return "VERMEIDEN"
    
    def _get_confidence_level(self, score):
        if score > 0.3:
            return "HOCH"
        elif score > 0.2:
            return "MITTEL"
        else:
            return "NIEDRIG"
    
    def _find_pattern_cycles(self, sequence, cycle_length):
        cycle_patterns = defaultdict(list)
        for i in range(len(sequence) - cycle_length):
            pattern = ''.join(sequence[i:i+cycle_length])
            cycle_patterns[pattern].append(i)
        return {pattern: positions for pattern, positions in cycle_patterns.items() 
                if len(positions) >= 2}

# Zusätzliche Lotto-spezifische Analysefunktionen

def analyze_lotto_tip_quality(generator, tip_numbers):
    """Analysiert Qualität eines Lotto 6aus49 Tipps."""
    quality_score = 0
    analysis = {}
    
    # Momentum-Analyse
    hot_count = sum(1 for n in tip_numbers if n in generator.hot_numbers)
    analysis['hot_numbers'] = hot_count
    quality_score += hot_count * 0.15  # Angepasst für 6 Zahlen
    
    # Trend-Analyse
    trend_scores = [generator.trend_predictions[n]['prediction_score'] for n in tip_numbers]
    avg_trend = np.mean(trend_scores)
    analysis['avg_trend_score'] = avg_trend
    quality_score += avg_trend * 0.35
    
    # Positions-Analyse (6 Positionen)
    position_quality = 0
    for i, num in enumerate(sorted(tip_numbers)):
        pos_freq = generator.position_frequencies[f'pos_{i+1}'][num]
        if pos_freq > 0:
            position_quality += pos_freq
    analysis['position_quality'] = position_quality
    quality_score += (position_quality / len(generator.df)) * 0.25
    
    # Muster-Analyse
    pattern = generator._get_lotto_pattern(sorted(tip_numbers))
    pattern_freq = generator.pattern_frequencies[pattern]
    pattern_score = pattern_freq / len(generator.df)
    analysis['pattern'] = pattern
    analysis['pattern_score'] = pattern_score
    quality_score += pattern_score * 0.25
    
    analysis['total_quality_score'] = quality_score
    analysis['quality_rating'] = get_lotto_quality_rating(quality_score)
    
    return analysis

def get_lotto_quality_rating(score):
    """Lotto-spezifische Quality-Ratings."""
    if score > 0.7:
        return "🏆 LOTTO PREMIUM"
    elif score > 0.5:
        return "🥇 SEHR GUT"
    elif score > 0.35:
        return "🥈 GUT"
    elif score > 0.2:
        return "🥉 DURCHSCHNITT"
    else:
        return "⚠️ SCHWACH"

def predict_lotto_jackpot_probability(generator, tip_numbers):
    """Schätzt Lotto-Jackpot-Wahrscheinlichkeit."""
    base_probability = 1 / 13983816  # Lotto 6aus49 Grundwahrscheinlichkeit
    
    trend_multiplier = 1.0
    for number in tip_numbers:
        momentum_score = generator.momentum_scores[number]['momentum_score']
        trend_score = generator.trend_predictions[number]['prediction_score']
        
        # Lotto-angepasste Gewichtung
        number_multiplier = 1 + (momentum_score * 0.08) + (trend_score * 0.12)
        trend_multiplier *= number_multiplier
    
    # Pattern-Bonus für Lotto
    pattern = generator._get_lotto_pattern(sorted(tip_numbers))
    pattern_frequency = generator.pattern_frequencies[pattern] / len(generator.df)
    pattern_multiplier = 1 + (pattern_frequency * 0.15)
    
    estimated_probability = base_probability * trend_multiplier * pattern_multiplier
    
    return {
        'base_probability': base_probability,
        'trend_multiplier': trend_multiplier,
        'pattern_multiplier': pattern_multiplier,
        'estimated_probability': estimated_probability,
        'improvement_factor': (estimated_probability / base_probability)
    }

def create_lotto_sample_data():
    """Erstellt Beispiel-Daten für Lotto 6aus49 (für Tests)."""
    print("📋 BEISPIEL LOTTO-DATEN ERSTELLEN")
    print("=" * 35)
    
    sample_data = []
    base_date = datetime.datetime(2020, 1, 4)  # Erster Samstag 2020
    
    for i in range(100):  # 100 Beispiel-Ziehungen
        # Datum (jeden Samstag)
        date = base_date + datetime.timedelta(weeks=i)
        
        # 6 zufällige Zahlen aus 1-49
        numbers = sorted(random.sample(range(1, 50), 6))
        
        # Superzahl 0-9
        superzahl = random.randint(0, 9)
        
        sample_data.append({
            'Datum': date.strftime('%d.%m.%Y'),
            'Z1': numbers[0], 'Z2': numbers[1], 'Z3': numbers[2],
            'Z4': numbers[3], 'Z5': numbers[4], 'Z6': numbers[5],
            'SZ': superzahl
        })
    
    # CSV speichern
    df_sample = pd.DataFrame(sample_data)
    sample_file = "lotto_sample_data.csv"
    df_sample.to_csv(sample_file, sep=';', index=False)
    
    print(f"✅ Beispiel-Daten erstellt: {sample_file}")
    print(f"📊 {len(sample_data)} Lotto-Ziehungen")
    print(f"💡 Verwenden Sie diese Datei zum Testen des Generators!")
    
    return sample_file

def main():
    """Hauptfunktion für Ultimate Lotto 6aus49 Generator."""
    print("🎲 ULTIMATE LOTTO 6AUS49 GENERATOR")
    print("🚀 Mit Multi-Ziehungs-Trend-Analyse")
    print("=" * 50)
    
    # Datei-Pfad abfragen
    print("📁 LOTTO-DATEN LADEN:")
    print("Geben Sie den Pfad zur Lotto 6aus49 CSV-Datei ein.")
    print("(Oder drücken Sie Enter für Beispiel-Daten)")
    
    data_path = input("CSV-Pfad: ").strip()
    
    # Beispiel-Daten erstellen falls kein Pfad angegeben
    if not data_path:
        print("\n🔧 Erstelle Beispiel-Daten für Demonstration...")
        data_path = create_lotto_sample_data()
        print(f"📂 Verwende Beispiel-Datei: {data_path}")
    
    try:
        # Generator initialisieren
        generator = UltimateLotto6aus49Generator(data_path)
        
        if not hasattr(generator, 'df') or generator.df is None:
            print("❌ Generator konnte nicht initialisiert werden!")
            return
        
        # Ultimate Tipps generieren
        tips = generator.generate_lotto_ultimate_tips(10)
        
        if tips:
            print(f"\n🏆 ULTIMATE LOTTO 6AUS49 OPTIMIERUNG ABGESCHLOSSEN!")
            print("=" * 55)
            print(f"🎲 10 Ultimate Lotto-Tipps generiert")
            print(f"📈 Maximale Trefferwahrscheinlichkeit durch:")
            print(f"   • Multi-Ziehungs-Momentum-Analyse")
            print(f"   • Sequenzielle Abhängigkeiten")
            print(f"   • Zyklische Muster-Erkennung")
            print(f"   • Lotto-spezifische Optimierungen")
            print(f"🍀 Viel Erfolg bei der nächsten Lotto-Ziehung!")
            
            # Erweiterte Analyse (optional)
            print(f"\n📊 ERWEITERTE LOTTO-ANALYSE:")
            print("=" * 35)
            
            # Beispiel-Analyse für ersten Tipp
            if len(tips) > 0:
                sample_tip = tips[0]['zahlen']
                quality_analysis = analyze_lotto_tip_quality(generator, sample_tip)
                probability_analysis = predict_lotto_jackpot_probability(generator, sample_tip)
                
                print(f"\n🔍 BEISPIEL-ANALYSE für Lotto-Tipp 1:")
                tip_str = '-'.join([f"{n:2}" for n in sample_tip])
                print(f"   🎲 Zahlen: {tip_str} + SZ: {tips[0]['superzahl']}")
                print(f"   🏆 Quality: {quality_analysis['quality_rating']}")
                print(f"   📈 Score: {quality_analysis['total_quality_score']:.3f}")
                print(f"   🔥 Heiße Zahlen: {quality_analysis['hot_numbers']}/6")
                print(f"   🎯 Trend-Score: {quality_analysis['avg_trend_score']:.3f}")
                print(f"   🎨 Muster: {quality_analysis['pattern']}")
                print(f"   📊 Verbesserungs-Faktor: {probability_analysis['improvement_factor']:.2f}x")
            
            # Strategische Empfehlungen
            print(f"\n💡 STRATEGISCHE LOTTO-EMPFEHLUNGEN:")
            print("=" * 40)
            
            # Top Trend-Zahlen
            top_trend = sorted(generator.trend_predictions.items(), 
                              key=lambda x: x[1]['prediction_score'], reverse=True)[:8]
            print(f"🎯 TOP 8 TREND-ZAHLEN für kommende Ziehungen:")
            for i, (number, data) in enumerate(top_trend):
                status = generator.momentum_scores[number]['status']
                print(f"   {i+1}. Zahl {number:2}: {data['recommendation']} {status}")
            
            # Momentum-Verteilung
            very_hot_lotto = [n for n in generator.hot_numbers 
                             if generator.momentum_scores[n]['momentum_score'] > 0.3]
            if very_hot_lotto:
                print(f"\n🔥 MOMENTUM-ALERT für Lotto:")
                print(f"   Sehr heiße Zahlen: {very_hot_lotto}")
                print(f"   → Verwenden Sie 2-3 dieser Zahlen in Ihren Tipps!")
            
            # Superzahl-Empfehlung
            if generator.supernumber_frequencies:
                top_superzahl = generator.supernumber_frequencies.most_common(3)
                print(f"\n🎲 TOP SUPERZAHL-EMPFEHLUNGEN:")
                for sz, count in top_superzahl:
                    percentage = (count / len(generator.df)) * 100
                    print(f"   Superzahl {sz}: {count}x ({percentage:.1f}%)")
        
        else:
            print("❌ Keine Tipps generiert!")
    
    except Exception as e:
        print(f"❌ Fehler: {e}")
        print("💡 Stellen Sie sicher, dass die CSV-Datei korrekt formatiert ist:")
        print("   Spalten: Datum, Z1, Z2, Z3, Z4, Z5, Z6, SZ")

if __name__ == "__main__":
    # Reproduzierbarer Zufallsseed
    random.seed(42)
    np.random.seed(42)
    
    # Ultimate Lotto Generator starten
    main()