#!/usr/bin/env python3
"""
Test NBA Dynamic Strategy Generation and Execution
Tests the integration between chat system, AI code generation, and NBA backtesting engine
"""

import os
import sys
import json
import subprocess
from datetime import datetime

def test_nba_data_loading():
    """Test NBA data loading via API endpoints"""

    print("🏀 Testing NBA Dynamic Strategy System")
    print("=" * 60)

    # Test 1: Verify NBA data loading via API endpoints
    print("\n1️⃣ Testing NBA Data Loading...")
    try:
        # Test NBA API endpoints directly (these use mock data)
        import requests

        # Test games endpoint
        response = requests.get('http://localhost:3003/api/nba/games?limit=10')
        if response.status_code == 200:
            games_data = response.json()
            if games_data.get('success') and games_data.get('data'):
                games = games_data['data']
                print(f"✅ Loaded {len(games)} NBA games via API")
                if games:
                    sample_game = games[0]
                    print(f"   Sample: {sample_game.get('home_team', 'Home')} vs {sample_game.get('away_team', 'Away')}")
            else:
                print("❌ API returned success but no data")
                return False
        else:
            print(f"❌ Failed to load NBA games via API: {response.status_code}")
            return False

    except Exception as e:
        print(f"❌ Error testing NBA data loading: {e}")
        return False

    # Test 2: Test NBA dynamic strategy code structure
    print("\n2️⃣ Testing NBA Dynamic Strategy Code Structure...")

    # Sample NBA betting strategy code that should be generated
    nba_strategy_code = '''
def generate_bets(games, players, teams, params):
    """
    Sample NBA strategy: Bet on home teams with high confidence
    """
    bets = []
    stake = params.get('stake', 100)

    # Filter to recent games only (last 50 games for testing)
    recent_games = games[-50:] if len(games) > 50 else games

    for game in recent_games:
        # Simple strategy: Always bet on home team to win
        bet = {
            'game_id': game.get('game_id', game.get('id', 'unknown')),
            'bet_type': 'moneyline',
            'prediction': 'home',
            'confidence': 0.55,  # Slightly above 50% for realistic odds
            'stake': stake
        }
        bets.append(bet)

    return bets
'''

    # Test that the code structure is valid Python
    try:
        # Try to compile the code to check syntax
        compile(nba_strategy_code, '<string>', 'exec')
        print("✅ NBA strategy code syntax is valid")

        # Test that we can extract the function name
        if 'def generate_bets(' in nba_strategy_code:
            print("✅ NBA strategy code contains required generate_bets function")
            return True
        else:
            print("❌ NBA strategy code missing generate_bets function")
            return False

    except SyntaxError as e:
        print(f"❌ NBA strategy code has syntax error: {e}")
        return False
    except Exception as e:
        print(f"❌ Error testing NBA strategy code: {e}")
        return False

def test_nba_strategy_code():
    """Test NBA dynamic strategy code structure"""
    print("\n2️⃣ Testing NBA Dynamic Strategy Code Structure...")

    # Sample NBA betting strategy code that should be generated
    nba_strategy_code = '''
def generate_bets(games, players, teams, params):
    """
    Sample NBA strategy: Bet on home teams with high confidence
    """
    bets = []
    stake = params.get('stake', 100)

    # Filter to recent games only (last 50 games for testing)
    recent_games = games[-50:] if len(games) > 50 else games

    for game in recent_games:
        # Simple strategy: Always bet on home team to win
        bet = {
            'game_id': game.get('game_id', game.get('id', 'unknown')),
            'bet_type': 'moneyline',
            'prediction': 'home',
            'confidence': 0.55,  # Slightly above 50% for realistic odds
            'stake': stake
        }
        bets.append(bet)

    return bets
'''

    # Test that the code structure is valid Python
    try:
        # Try to compile the code to check syntax
        compile(nba_strategy_code, '<string>', 'exec')
        print("✅ NBA strategy code syntax is valid")

        # Test that we can extract the function name
        if 'def generate_bets(' in nba_strategy_code:
            print("✅ NBA strategy code contains required generate_bets function")
            return True
        else:
            print("❌ NBA strategy code missing generate_bets function")
            return False

    except SyntaxError as e:
        print(f"❌ NBA strategy code has syntax error: {e}")
        return False
    except Exception as e:
        print(f"❌ Error testing NBA strategy code: {e}")
        return False

def test_ai_code_generation():
    """Test that AI can generate NBA strategy code (mock test)"""
    print("\n3️⃣ Testing AI Code Generation Structure...")

    # Test that the system prompt includes NBA instructions
    try:
        with open('src/lib/chat.ts', 'r') as f:
            content = f.read()

        has_generate_bets = 'def generate_bets(games: list, players: list, teams: list, params: dict)' in content
        has_nba_sports = 'NBA/Sports betting strategies' in content

        print(f"   Checking for 'generate_bets(...)': {'✅ Found' if has_generate_bets else '❌ Not found'}")
        print(f"   Checking for 'NBA/Sports betting strategies': {'✅ Found' if has_nba_sports else '❌ Not found'}")

        if has_generate_bets and has_nba_sports:
            print("✅ NBA strategy generation instructions found in chat system")
            return True
        else:
            print("❌ NBA strategy generation instructions not found")
            print("   File content around NBA section:")
            lines = content.split('\n')
            for i, line in enumerate(lines):
                if 'NBA/Sports betting strategies' in line:
                    for j in range(max(0, i-2), min(len(lines), i+8)):
                        print(f"   {j+1}: {lines[j]}")
                    break
            return False

    except Exception as e:
        print(f"❌ Error checking AI code generation: {e}")
        return False

def main():
    """Run all NBA dynamic strategy tests"""

    print("🏀 NBA Dynamic Strategy Integration Test")
    print("=" * 60)
    print(f"Started at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"Python version: {sys.version}")
    print(f"Working directory: {os.getcwd()}")

    tests_passed = 0
    total_tests = 4

    # Test 1: NBA Data Loading
    if test_nba_data_loading():
        tests_passed += 1
        print("✅ Test 1 PASSED: NBA Data Loading")
    else:
        print("❌ Test 1 FAILED: NBA Data Loading")

    # Test 2: NBA Strategy Code Structure
    if test_nba_strategy_code():
        tests_passed += 1
        print("✅ Test 2 PASSED: NBA Strategy Code Structure")
    else:
        print("❌ Test 2 FAILED: NBA Strategy Code Structure")

    # Test 3: AI Code Generation Structure
    if test_ai_code_generation():
        tests_passed += 1
        print("✅ Test 3 PASSED: AI Code Generation Structure")
    else:
        print("❌ Test 3 FAILED: AI Code Generation Structure")

    # Test 4: Universal Backtesting Engine NBA Support
    print("\n5️⃣ Testing Universal Backtesting Engine NBA Integration...")
    try:
        # Check if NBA dynamic engine exists in the code
        with open('universal_backtesting.py', 'r') as f:
            content = f.read()

        if '_get_nba_dynamic_engine' in content and 'execute_nba_dynamic_strategy' in content:
            print("✅ NBA dynamic engine found in universal backtesting")
            tests_passed += 1
            print("✅ Test 4 PASSED: Universal Backtesting Engine NBA Integration")
        else:
            print("❌ NBA dynamic engine not found in universal backtesting")
            print("❌ Test 4 FAILED: Universal Backtesting Engine NBA Integration")

    except Exception as e:
        print(f"❌ Error testing universal backtesting: {e}")
        print("❌ Test 4 FAILED: Universal Backtesting Engine NBA Integration")

    # Final Results
    print("\n" + "=" * 60)
    print("🏀 NBA DYNAMIC STRATEGY TEST RESULTS")
    print("=" * 60)
    print(f"Tests Passed: {tests_passed}/{total_tests}")
    print(".1f")

    if tests_passed == total_tests:
        print("🎉 ALL TESTS PASSED! NBA Dynamic Strategy system is ready!")
        print("\nNext steps:")
        print("1. Test with real AI-generated code via chat interface")
        print("2. Add more complex NBA betting strategies")
        print("3. Implement player statistics integration")
        print("4. Add team performance metrics")
        return 0
    else:
        print(f"❌ {total_tests - tests_passed} test(s) failed. Please fix issues above.")
        return 1

if __name__ == "__main__":
    sys.exit(main())
