"""
VQWEN v3 Model - Manual Prediction Script
Match ID: 558o1fq1vbfsi3m5gm4ekpyc4
Match: Kaiserslautern vs F. Düsseldorf
League: 2. Bundesliga
"""

import requests
import json
from datetime import datetime

# AI Engine base URL
AI_ENGINE_URL = "http://127.0.0.1:8000"
MATCH_ID = "558o1fq1vbfsi3m5gm4ekpyc4"

def check_engine_health():
    """Check if AI Engine is running"""
    try:
        response = requests.get(f"{AI_ENGINE_URL}/health", timeout=5)
        return response.status_code == 200
    except:
        return False

def run_prediction():
    """Run VQWEN v3 prediction for the match"""
    
    print("=" * 80)
    print("🤖 VQWEN v3 MODEL - MANUEL TAHMİN SİSTEMİ")
    print("=" * 80)
    print(f"\n📊 Maç Bilgileri:")
    print(f"   ID: {MATCH_ID}")
    print(f"   Ev Sahibi: Kaiserslautern")
    print(f"   Deplasman: F. Düsseldorf")
    print(f"   Lig: 2. Bundesliga")
    print(f"   Maç Zamanı: 2026-04-01 (MS: 1775300400000)")
    print(f"   Hakem: D. Schlager")
    print()
    
    # Check engine health
    print("🔍 AI Engine kontrol ediliyor...")
    if not check_engine_health():
        print("❌ AI Engine (Python FastAPI) çalışmıyor!")
        print()
        print("ℹ️  Lütfen AI Engine'i başlatın:")
        print("   cd ai-engine")
        print("   uvicorn main:app --host 0.0.0.0 --port 8000 --reload")
        print()
        print("📋 Alternatif olarak, maç verilerini hazırlayabilirim:")
        print()
        
        # Prepare match data for analysis
        match_data = {
            "match_id": MATCH_ID,
            "home_team": "Kaiserslautern",
            "away_team": "F. Düsseldorf",
            "league": "2. Bundesliga",
            "match_date_ms": "1775300400000",
            "referee": "D. Schlager",
            "odds": {
                "MS_1": 2.13,
                "MS_X": 3.23,
                "MS_2": 2.34,
                "Alt_2.5": 2.09,
                "Ust_2.5": 1.38,
                "KG_Var": 1.32,
                "KG_Yok": 2.25
            },
            "lineups_available": True,
            "sidelined_count": 0
        }
        
        print("✅ Maç verileri hazırlandı:")
        print(json.dumps(match_data, indent=2, ensure_ascii=False))
        print()
        print("⚠️  Tahmin almak için AI Engine'in çalışması gerekiyor.")
        print()
        return
    
    # If engine is running, call the analysis endpoint
    print("✅ AI Engine çalışıyor!")
    print()
    print("🎯 Tahmin yapılıyor...")
    
    try:
        response = requests.post(
            f"{AI_ENGINE_URL}/v20plus/analyze/{MATCH_ID}",
            json={},
            timeout=60
        )
        
        if response.status_code == 200:
            result = response.json()
            
            print("\n" + "=" * 80)
            print("📊 TAHMİN SONUÇLARI")
            print("=" * 80)
            
            # Main Pick
            if 'main_pick' in result:
                main = result['main_pick']
                print(f"\n🎯 ANA TAHMİN:")
                print(f"   Market: {main.get('market', 'N/A')}")
                print(f"   Tahmin: {main.get('pick', 'N/A')}")
                print(f"   Oran: {main.get('odds', 'N/A')}")
                print(f"   Güven: {main.get('confidence', 0):.1f}%")
                print(f"   Olasılık: {main.get('probability', 0):.1f}%")
                print(f"   Bahis Derecesi: {main.get('bet_grade', 'N/A')}")
            
            # Value Pick
            if 'value_pick' in result:
                value = result['value_pick']
                print(f"\n💎 DEĞER TAHMİNİ:")
                print(f"   Market: {value.get('market', 'N/A')}")
                print(f"   Tahmin: {value.get('pick', 'N/A')}")
                print(f"   Oran: {value.get('odds', 'N/A')}")
                print(f"   Güven: {value.get('confidence', 0):.1f}%")
                print(f"   Edge: {value.get('edge', 0):.2f}")
            
            # Score Prediction
            if 'score_prediction' in result:
                score = result['score_prediction']
                print(f"\n⚽ SKOR TAHMİNİ:")
                print(f"   İlk Yarı: {score.get('ht', 'N/A')}")
                print(f"   Maç Sonu: {score.get('ft', 'N/A')}")
                print(f"   xG (Ev): {score.get('xg_home', 0):.2f}")
                print(f"   xG (Dep): {score.get('xg_away', 0):.2f}")
                print(f"   Toplam xG: {score.get('xg_total', 0):.2f}")
            
            # Bet Summary
            if 'bet_summary' in result:
                print(f"\n📋 TÜM TAHMİNLER:")
                for bet in result['bet_summary']:
                    print(f"   • {bet.get('market', 'N/A')}: {bet.get('pick', 'N/A')} "
                          f"(Güven: {bet.get('calibrated_confidence', 0):.1f}%, "
                          f"Derece: {bet.get('bet_grade', 'N/A')})")
            
            # AI Commentary
            if 'ai_commentary' in result:
                print(f"\n💬 AI YORUMU:")
                print(f"   {result['ai_commentary']}")
            
            # Risk Assessment
            if 'risk' in result:
                risk = result['risk']
                print(f"\n⚠️  RİSK DEĞERLENDİRMESİ:")
                print(f"   Seviye: {risk.get('level', 'N/A')}")
                print(f"   Skor: {risk.get('score', 0):.1f}")
                if risk.get('warnings'):
                    print(f"   Uyarılar: {', '.join(risk['warnings'][:3])}")
            
            # Data Quality
            if 'data_quality' in result:
                quality = result['data_quality']
                print(f"\n📊 VERİ KALİTESİ:")
                print(f"   Seviye: {quality.get('label', 'N/A')}")
                print(f"   Skor: {quality.get('score', 0):.1f}")
            
            print("\n" + "=" * 80)
            
        else:
            print(f"❌ Hata: HTTP {response.status_code}")
            print(f"   {response.text}")
            
    except requests.exceptions.Timeout:
        print("❌ Zaman aşımı! AI Engine yanıt vermiyor.")
    except Exception as e:
        print(f"❌ Hata: {str(e)}")

if __name__ == "__main__":
    run_prediction()
