# Flask uygulamasının ana dosyası
from flask import Flask, render_template, request, jsonify
import pandas as pd
from predictor import MatchPredictor
from gpt_comment import GPTCommentGenerator
from live_fixtures import LiveFixtureAPI
import requests
import json
import random
import hashlib

app = Flask(__name__)

# Tahminci, yorum oluşturucu ve fikstür API'sini başlat
predictor = MatchPredictor()
comment_generator = GPTCommentGenerator()
fixture_api = LiveFixtureAPI()

# Modeli başlangıçta eğit
print("🚀 AI Match başlatılıyor...")
accuracy = predictor.train_model()
print(f"📊 Model doğruluğu: {accuracy:.2%}")

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/predict', methods=['POST'])
def predict():
    """Gelişmiş tahmin sistemi"""
    try:
        # Form verilerini al
        if request.is_json:
            data = request.get_json()
            home_team = data.get('home_team')
            away_team = data.get('away_team')
        else:
            home_team = request.form.get('home_team')
            away_team = request.form.get('away_team')
        
        if not home_team or not away_team:
            return jsonify({'error': 'Takım isimleri eksik!'})
        
        # Gelişmiş analiz yap
        analysis_result = enhanced_team_analysis(home_team, away_team)
        
        return jsonify(analysis_result)
        
    except Exception as e:
        return jsonify({'error': f'Analiz hatası: {str(e)}'})

def enhanced_team_analysis(home_team, away_team):
    """Gelişmiş takım analizi ve tahmini"""
    try:
        print(f"🔍 Gelişmiş analiz: {home_team} vs {away_team}")
        
        # 1. Takım güçlerini hesapla (0-10 ölçeği)
        home_stats = calculate_enhanced_team_stats(home_team)
        away_stats = calculate_enhanced_team_stats(away_team)
        
        # 2. Gelişmiş ML modeli ile tahmin
        prediction_result = predictor.predict_match(
            home_team=home_team,
            away_team=away_team,
            home_form=home_stats['form'],
            away_form=away_stats['form'],
            home_possession=home_stats['possession'],
            away_possession=away_stats['possession'],
            home_shots=home_stats['shots'],
            away_shots=away_stats['shots']
        )
        
        # 3. Detaylı analiz oluştur
        detailed_analysis = generate_enhanced_analysis(
            home_team, away_team, home_stats, away_stats, prediction_result
        )
        
        # 4. GPT yorumu ekle
        gpt_analysis = comment_generator.generate_detailed_match_analysis(
            home_team, away_team, home_stats, away_stats, prediction_result
        )
        
        return {
            'home_team': home_team,
            'away_team': away_team,
            'home_stats': home_stats,
            'away_stats': away_stats,
            'prediction': prediction_result,
            'enhanced_analysis': detailed_analysis,
            'gpt_analysis': gpt_analysis,
            'model_confidence': f"{prediction_result['confidence']:.2%}",
            'algorithm_version': "Gelişmiş ML v2.0",
            'success': True
        }
        
    except Exception as e:
        print(f"❌ Gelişmiş analiz hatası: {e}")
        return fallback_analysis(home_team, away_team)

def calculate_enhanced_team_stats(team_name):
    """Gelişmiş takım istatistiklerini hesapla"""
    import random
    import hashlib
    
    # Takım isimden seed oluştur (tutarlı sonuçlar için)
    seed = int(hashlib.md5(team_name.encode()).hexdigest()[:8], 16)
    random.seed(seed)
    
    # Takım ligine göre temel değerler
    base_strength = get_team_base_strength(team_name)
    
    stats = {
        'form': min(10, max(1, base_strength + random.uniform(-2, 2))),
        'possession': min(70, max(30, 50 + random.uniform(-15, 15))),
        'shots': min(20, max(5, 12 + random.randint(-4, 6))),
        'attack_rating': min(10, max(1, base_strength + random.uniform(-1.5, 1.5))),
        'defense_rating': min(10, max(1, base_strength + random.uniform(-1.5, 1.5))),
        'last_form': [random.choice(['W', 'D', 'L']) for _ in range(5)],
        'league': detect_team_league(team_name),
        'home_advantage': 0.5 if 'home' in team_name.lower() else 0
    }
    
    # Form hesaplama (son 5 maç)
    form_points = {'W': 3, 'D': 1, 'L': 0}
    total_points = sum(form_points[result] for result in stats['last_form'])
    stats['form'] = min(10, (total_points / 15) * 10)
    
    return stats

def get_team_base_strength(team_name):
    """Takım ismine göre temel güç hesabı"""
    # Büyük takımlar
    top_teams = [
        'Barcelona', 'Real Madrid', 'Manchester City', 'Liverpool',
        'Bayern Munich', 'PSG', 'Chelsea', 'Arsenal', 'Manchester United',
        'Juventus', 'AC Milan', 'Inter Milan', 'Atletico Madrid',
        'Tottenham', 'Napoli', 'Borussia Dortmund'
    ]
    
    team_lower = team_name.lower()
    
    for top_team in top_teams:
        if top_team.lower() in team_lower or team_lower in top_team.lower():
            return random.uniform(7.5, 9.5)  # Üst seviye takımlar
    
    # Orta seviye takımlar
    if any(keyword in team_lower for keyword in ['fc', 'united', 'city', 'athletic']):
        return random.uniform(5.5, 7.5)
    
    # Diğer takımlar
    return random.uniform(3.0, 6.5)

def generate_enhanced_analysis(home_team, away_team, home_stats, away_stats, prediction):
    """Gelişmiş analiz raporu oluştur"""
    analysis = {
        'match_overview': f"{home_team} vs {away_team}",
        'prediction_summary': {
            'predicted_result': prediction['prediction'],
            'confidence': f"{prediction['confidence']:.2%}",
            'probabilities': prediction['probabilities']
        },
        'key_factors': [],
        'statistical_comparison': {},
        'tactical_insights': [],
        'risk_assessment': 'Düşük'
    }
    
    # Anahtar faktörler
    form_diff = home_stats['form'] - away_stats['form']
    if abs(form_diff) > 1.5:
        better_team = home_team if form_diff > 0 else away_team
        analysis['key_factors'].append(f"🔥 {better_team} form avantajında (+{abs(form_diff):.1f})")
    
    possession_diff = home_stats['possession'] - away_stats['possession']
    if abs(possession_diff) > 10:
        control_team = home_team if possession_diff > 0 else away_team
        analysis['key_factors'].append(f"⚽ {control_team} oyun kontrolü bekleniyor")
    
    # İstatistiksel karşılaştırma
    analysis['statistical_comparison'] = {
        'form_comparison': f"{home_stats['form']:.1f} vs {away_stats['form']:.1f}",
        'attack_vs_defense': f"Ev: {home_stats['attack_rating']:.1f} | Konuk: {away_stats['defense_rating']:.1f}",
        'possession_battle': f"{home_stats['possession']:.1f}% vs {away_stats['possession']:.1f}%"
    }
    
    # Risk analizi
    if prediction['confidence'] > 0.7:
        analysis['risk_assessment'] = 'Düşük'
    elif prediction['confidence'] > 0.5:
        analysis['risk_assessment'] = 'Orta'
    else:
        analysis['risk_assessment'] = 'Yüksek'
    
    # Taktiksel görüşler
    if home_stats['possession'] > 55:
        analysis['tactical_insights'].append("🎯 Ev sahibi takım hakimiyet kurabilir")
    if away_stats['attack_rating'] > home_stats['defense_rating']:
        analysis['tactical_insights'].append("⚡ Konuk takım atağında etkili olabilir")
    
    return analysis

def fallback_analysis(home_team, away_team):
    """Hata durumunda basit analiz"""
    return {
        'home_team': home_team,
        'away_team': away_team,
        'prediction': {
            'prediction': 'beraberlik',
            'confidence': 0.33,
            'probabilities': {'home_win': 0.33, 'draw': 0.34, 'away_win': 0.33}
        },
        'enhanced_analysis': {
            'match_overview': f"{home_team} vs {away_team}",
            'prediction_summary': {'predicted_result': 'beraberlik', 'confidence': '%33'}
        },
        'algorithm_version': "Yedek sürüm v1.0",
        'success': True,
        'note': 'Basit analiz yedeklendi'
    }

def detect_team_league(team_name):
    """Takım isminden ligini tespit et"""
    team_lower = team_name.lower()
    
    # Türk takımları
    turkish_teams = ['fenerbahce', 'galatasaray', 'besiktas', 'trabzonspor', 'basaksehir']
    if any(team in team_lower for team in turkish_teams):
        return 'Süper Lig'
    
    # İngiliz takımları
    english_teams = ['manchester', 'liverpool', 'chelsea', 'arsenal', 'tottenham']
    if any(team in team_lower for team in english_teams):
        return 'Premier League'
    
    # İspanyol takımları
    spanish_teams = ['barcelona', 'real madrid', 'atletico', 'sevilla', 'valencia']
    if any(team in team_lower for team in spanish_teams):
        return 'La Liga'
    
    return 'Bilinmeyen'

@app.route("/coin", methods=["GET", "POST"])
def coin():
    result = None
    if request.method == "POST":
        coin_name = request.form["coin"]
        result = analyze_coin(coin_name)
    return render_template("coin.html", result=result)

def analyze_coin(coin_name):
    """Kripto para analizi fonksiyonu"""
    try:
        # CoinGecko API'den veri çek (ücretsiz)
        url = f"https://api.coingecko.com/api/v3/simple/price?ids={coin_name.lower()}&vs_currencies=usd,try&include_24hr_change=true&include_market_cap=true"
        response = requests.get(url)
        
        if response.status_code == 200:
            data = response.json()
            if coin_name.lower() in data:
                coin_data = data[coin_name.lower()]
                
                # GPT ile analiz yorumu üret
                analysis_text = f"""
                Coin: {coin_name.upper()}
                Fiyat (USD): ${coin_data.get('usd', 'N/A')}
                Fiyat (TRY): ₺{coin_data.get('try', 'N/A')}
                24s Değişim: %{coin_data.get('usd_24h_change', 'N/A')}
                Piyasa Değeri: ${coin_data.get('usd_market_cap', 'N/A')}
                """
                
                gpt_analysis = comment_generator.generate_coin_comment(coin_name, coin_data)
                
                return {
                    'coin_name': coin_name.upper(),
                    'price_usd': coin_data.get('usd'),
                    'price_try': coin_data.get('try'),
                    'change_24h': coin_data.get('usd_24h_change'),
                    'market_cap': coin_data.get('usd_market_cap'),
                    'analysis': gpt_analysis,
                    'success': True
                }
            else:
                return {'error': 'Coin bulunamadı', 'success': False}
        else:
            return {'error': 'API hatası', 'success': False}
            
    except Exception as e:
        return {'error': f'Analiz hatası: {str(e)}', 'success': False}

@app.route("/basketball", methods=["GET", "POST"])
def basketball():
    result = None
    if request.method == "POST":
        home_team = request.form["home_team"]
        away_team = request.form["away_team"]
        # Basketbol analizi (demo veriler)
        result = {
            'home_team': home_team,
            'away_team': away_team,
            'prediction': f'{home_team} %65 kazanma şansına sahip',
            'analysis': f'GPT Analizi: {home_team} takımı ev sahibi avantajı ve son performansını düşündüğümüzde güçlü görünüyor.'
        }
    return render_template("basketball.html", result=result)

@app.route("/stocks", methods=["GET", "POST"])
def stocks():
    result = None
    if request.method == "POST":
        stock_symbol = request.form["stock"]
        # Hisse senedi analizi (demo)
        result = {
            'symbol': stock_symbol.upper(),
            'price': '245.50 TL',
            'change': '+%2.5',
            'analysis': f'{stock_symbol.upper()} hissesi teknik analizlere göre yükseliş trendi gösteriyor.'
        }
    return render_template("stocks.html", result=result)

@app.route("/weather", methods=["GET", "POST"])
def weather():
    result = None
    if request.method == "POST":
        city = request.form["city"]
        # Hava durumu API'si
        try:
            # OpenWeatherMap API (demo)
            result = {
                'city': city,
                'temperature': '24°C',
                'description': 'Parçalı bulutlu',
                'humidity': '%65',
                'forecast': 'Önümüzdeki 3 gün güneşli hava bekleniyor.'
            }
        except:
            result = {'error': 'Şehir bulunamadı'}
    return render_template("weather.html", result=result)

@app.route("/movies", methods=["GET", "POST"])
def movies():
    result = None
    if request.method == "POST":
        genre = request.form["genre"]
        # Film öneri sistemi
        movies_data = {
            'action': ['John Wick 4', 'Fast X', 'Mission Impossible'],
            'comedy': ['Guardians of Galaxy 3', 'The Menu', 'Glass Onion'],
            'drama': ['Everything Everywhere', 'The Whale', 'Tar']
        }
        result = {
            'genre': genre,
            'recommendations': movies_data.get(genre.lower(), ['Film bulunamadı']),
            'analysis': f'{genre} türü popüler filmler listelendi.'
        }
    return render_template("movies.html", result=result)

@app.route("/forex", methods=["GET", "POST"])
def forex():
    result = None
    if request.method == "POST":
        pair = request.form["pair"]
        # Forex analizi
        result = {
            'pair': pair.upper(),
            'rate': '18.45' if 'usd' in pair.lower() else '19.85',
            'change': '+%0.25',
            'analysis': f'{pair.upper()} paritesi güncel ekonomik verilere göre analiz edildi.'
        }
    return render_template("forex.html", result=result)

@app.route("/news", methods=["GET", "POST"])
def news():
    # Güncel haberler ve duygu analizi
    news_data = [
        {'title': 'Kripto Piyasalar Yükselişte', 'sentiment': 'Pozitif', 'impact': 'Yüksek'},
        {'title': 'Merkez Bankası Faiz Kararı', 'sentiment': 'Nötr', 'impact': 'Orta'},
        {'title': 'Teknoloji Hisseleri Düşüşte', 'sentiment': 'Negatif', 'impact': 'Yüksek'}
    ]
    return render_template("news.html", news=news_data)

@app.route("/dashboard")
def dashboard():
    # Ana kontrol paneli - tüm verilerin özeti
    dashboard_data = {
        'crypto_summary': 'Bitcoin: $45,230 (+%2.1)',
        'stock_summary': 'BIST100: 8,450 (+%0.8)',
        'weather_summary': 'İstanbul: 24°C, Güneşli',
        'sports_summary': 'Bugün 5 maç tahmini mevcut'
    }
    return render_template("dashboard.html", data=dashboard_data)

@app.route("/chat", methods=["GET", "POST"])
def chat():
    response = None
    if request.method == "POST":
        user_message = request.form["message"]
        # GPT sohbet botu
        response = f"AI Asistan: {user_message} konusunda size yardımcı olabilirim. Bu konuda daha detaylı bilgi almak ister misiniz?"
    return render_template("chat.html", response=response)

@app.route("/health", methods=["GET", "POST"])
def health():
    result = None
    if request.method == "POST":
        age = request.form["age"]
        weight = request.form["weight"]
        height = request.form["height"]
        # BMI hesaplama
        bmi = round(float(weight) / ((float(height)/100) ** 2), 1)
        result = {
            'bmi': bmi,
            'category': 'Normal' if 18.5 <= bmi <= 24.9 else 'Dikkat',
            'recommendation': 'Sağlıklı beslenme ve düzenli egzersiz önerilir.'
        }
    return render_template("health.html", result=result)

@app.route("/travel", methods=["GET", "POST"])
def travel():
    result = None
    if request.method == "POST":
        destination = request.form["destination"]
        budget = request.form["budget"]
        result = {
            'destination': destination,
            'budget': budget,
            'recommendations': f'{destination} için {budget} TL bütçe ile 3-4 gün kalabilirsiniz.',
            'best_time': 'En uygun seyahat zamanı: İlkbahar ve sonbahar'
        }
    return render_template("travel.html", result=result)

# ======================================
# CANLI FİKSTÜR SİSTEMİ
# ======================================

@app.route('/fixtures')
def fixtures():
    """Canlı fikstür sayfası"""
    return render_template('fixtures.html')

@app.route('/api/fixtures')
def api_fixtures():
    """Canlı fikstürleri JSON olarak döndür"""
    try:
        fixtures = fixture_api.get_today_fixtures()
        formatted_fixtures = fixture_api.format_for_prediction(fixtures)
        
        return jsonify({
            'success': True,
            'fixtures': formatted_fixtures,
            'total': len(formatted_fixtures),
            'last_update': '2025-07-30T' + str(pd.Timestamp.now().time())[:8]
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e),
            'fixtures': []
        })

@app.route('/api/fixtures/league/<league_name>')
def api_league_fixtures(league_name):
    """Belirli lig fikstürlerini getir"""
    try:
        all_fixtures = fixture_api.get_today_fixtures()
        league_fixtures = [f for f in all_fixtures if f.get('league') == league_name]
        
        return jsonify({
            'success': True,
            'fixtures': league_fixtures,
            'league': league_name,
            'total': len(league_fixtures)
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e),
            'fixtures': []
        })

@app.route('/api/predict-from-fixture', methods=['POST'])
def predict_from_fixture():
    """Fikstürden seçilen maç için tahmin yap"""
    try:
        data = request.get_json()
        home_team = data.get('home_team')
        away_team = data.get('away_team')
        
        if not home_team or not away_team:
            return jsonify({
                'success': False,
                'error': 'Takım isimleri eksik'
            })
        
        # Normal tahmin sistemini kullan
        prediction_result = predictor.predict_match(home_team, away_team)
        
        return jsonify({
            'success': True,
            'home_team': home_team,
            'away_team': away_team,
            'prediction': prediction_result,
            'source': 'live_fixture'
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        })

if __name__ == '__main__':
    import os
    # Production için port ve host ayarları
    port = int(os.environ.get('PORT', 5000))
    debug_mode = os.environ.get('FLASK_ENV') != 'production'
    
    print(f"🚀 AI Match başlatılıyor...")
    print(f"🌐 Port: {port}")
    print(f"🔧 Debug Modu: {debug_mode}")
    
    app.run(host='0.0.0.0', port=port, debug=debug_mode)
