#!/usr/bin/env python3
"""
NBA Dynamic Strategy with Time Period Filtering
Demonstrates strategies that filter by specific time periods
"""

import json
from datetime import datetime

def simulate_ai_time_period_response(user_query):
    """Simulate AI response for time period specific NBA strategies"""

    print("🤖 AI Processing Time-Period Strategy:")
    print(f"   User: '{user_query}'")
    print("\n" + "="*70)

    # AI generates strategy with time period filtering
    ai_generated_code = '''```python
def generate_bets(games, players, teams, params):
    """
    NBA Strategy: Bet on home teams only during December games
    Time period filtering demonstrates advanced strategy logic
    """
    bets = []
    stake = params.get('stake', 100)

    for game in games:
        # Parse game date to check if it's in December
        game_date_str = game.get('game_date', '')
        if not game_date_str:
            continue

        try:
            # Parse date and check if it's December
            game_date = datetime.fromisoformat(game_date_str.replace('Z', '+00:00'))
            is_december = game_date.month == 12

            # Only bet on December home games
            if is_december:
                bet = {
                    'game_id': game.get('game_id', game.get('id', 'unknown')),
                    'bet_type': 'moneyline',
                    'prediction': 'home',
                    'confidence': 0.62,  # Higher confidence for time-filtered bets
                    'stake': stake,
                    'time_period': 'December',
                    'reason': f'December home game: {game.get("home_team_name", "Unknown")}'
                }
                bets.append(bet)

        except Exception as e:
            # Skip games with invalid dates
            continue

    return bets
```'''

    print("🎯 AI Generated Time-Period Strategy Code:")
    print(ai_generated_code)

    return ai_generated_code.strip('```python').strip('```').strip()

def create_time_period_games_data():
    """Create NBA games data with different time periods"""

    return [
        # December games (should be included)
        {
            'game_id': '20231201_LAL_GSW',
            'game_date': '2023-12-01',
            'home_team_name': 'Los Angeles Lakers',
            'away_team_name': 'Golden State Warriors',
            'home_score': 115,
            'away_score': 108,
            'season': '2023-24',
            'month': 'December'
        },
        {
            'game_id': '20231215_BOS_NYK',
            'game_date': '2023-12-15',
            'home_team_name': 'New York Knicks',
            'away_team_name': 'Boston Celtics',
            'home_score': 118,
            'away_score': 112,
            'season': '2023-24',
            'month': 'December'
        },
        # January games (should be excluded)
        {
            'game_id': '20240105_PHO_DAL',
            'game_date': '2024-01-05',
            'home_team_name': 'Dallas Mavericks',
            'away_team_name': 'Phoenix Suns',
            'home_score': 120,
            'away_score': 115,
            'season': '2023-24',
            'month': 'January'
        },
        {
            'game_id': '20240120_LAL_PHO',
            'game_date': '2024-01-20',
            'home_team_name': 'Phoenix Suns',
            'away_team_name': 'Los Angeles Lakers',
            'home_score': 125,
            'away_score': 118,
            'season': '2023-24',
            'month': 'January'
        },
        # February games (should be excluded)
        {
            'game_id': '20240210_GSW_DAL',
            'game_date': '2024-02-10',
            'home_team_name': 'Dallas Mavericks',
            'away_team_name': 'Golden State Warriors',
            'home_score': 110,
            'away_score': 105,
            'season': '2023-24',
            'month': 'February'
        }
    ]

def simulate_time_period_backtesting(strategy_code):
    """Simulate backtesting with time period filtering"""

    print("\n" + "="*70)
    print("🏀 NBA Backtesting with Time Period Filtering...")
    print("="*70)

    # Use games with different time periods
    games_data = create_time_period_games_data()

    print(f"📊 Loaded {len(games_data)} NBA games across multiple months:")
    month_counts = {}
    for game in games_data:
        month = game.get('month', 'Unknown')
        month_counts[month] = month_counts.get(month, 0) + 1

    for month, count in month_counts.items():
        print(f"   • {month}: {count} games")

    print("\n🎲 Executing time-period filtered strategy...")

    # Execute the strategy
    try:
        local_scope = {}
        global_scope = {
            'games': games_data,
            'players': [],
            'teams': [],
            'len': len,
            'range': range,
            'int': int,
            'float': float,
            'str': str,
            'dict': dict,
            'list': list,
            'datetime': datetime
        }

        exec(strategy_code, global_scope, local_scope)

        if 'generate_bets' in local_scope:
            strategy_func = local_scope['generate_bets']
            bets = strategy_func(games_data, [], [], {'stake': 100})

            print(f"✅ Strategy filtered to {len(bets)} eligible bets (December only)")

            if len(bets) == 0:
                print("⚠️  No bets generated - time period filter might be too restrictive")
                return {'success': False, 'error': 'No bets generated'}

            # Evaluate bets
            print("\n📈 Evaluating time-filtered bets...")
            total_profit = 0
            winning_bets = 0

            for i, bet in enumerate(bets, 1):
                game = next((g for g in games_data if g['game_id'] == bet['game_id']), None)
                if game:
                    home_won = game['home_score'] > game['away_score']
                    prediction_correct = (bet['prediction'] == 'home' and home_won)

                    if prediction_correct:
                        winning_bets += 1
                        total_profit += bet['stake'] * 0.91  # Approximate payout
                        outcome = "✅ WIN"
                    else:
                        total_profit -= bet['stake']
                        outcome = "❌ LOSS"

                    print(f"   Bet {i}: {bet['prediction']} vs {game['away_team_name']} @ {game['home_team_name']}")
                    print(f"        Date: {game['game_date']} ({bet.get('time_period', 'Unknown')}) - {outcome}")
                    print(".2f")
            win_rate = winning_bets / len(bets) if bets else 0

            print("\n📊 TIME-PERIOD FILTERED BACKTESTING RESULTS:")
            print("="*50)
            print(f"   Total Games Analyzed: {len(games_data)}")
            print(f"   Eligible Bets (December): {len(bets)}")
            print(f"   Filtered Out: {len(games_data) - len(bets)} games")
            print(".1f")
            print(f"   Win Rate: {win_rate:.1%}")
            print(".2f")
            print(".2f")

            return {
                'success': True,
                'total_games': len(games_data),
                'eligible_bets': len(bets),
                'filtered_games': len(games_data) - len(bets),
                'winning_bets': winning_bets,
                'win_rate': win_rate,
                'total_profit': total_profit,
                'roi': (total_profit / (len(bets) * 100)) * 100 if bets else 0
            }

    except Exception as e:
        print(f"❌ Error executing time-period strategy: {e}")
        return {'success': False, 'error': str(e)}

def demonstrate_seasonal_patterns():
    """Show how time periods affect betting performance"""

    print("\n" + "="*70)
    print("📈 NBA Seasonal Pattern Analysis")
    print("="*70)

    # Analyze performance by month
    games_data = create_time_period_games_data()

    monthly_performance = {}
    for game in games_data:
        month = game.get('month', 'Unknown')
        home_won = game['home_score'] > game['away_score']

        if month not in monthly_performance:
            monthly_performance[month] = {'games': 0, 'home_wins': 0}

        monthly_performance[month]['games'] += 1
        if home_won:
            monthly_performance[month]['home_wins'] += 1

    print("🏠 Home Court Advantage by Month (2023-24):")
    print("-" * 45)

    for month, stats in monthly_performance.items():
        win_rate = stats['home_wins'] / stats['games']
        print("<12")
    print("\n💡 Time-period strategies can exploit seasonal patterns!")
    print("   • Higher home win rates in certain months")
    print("   • Holiday season effects (December)")
    print("   • Playoff push vs tanking seasons")
    print("   • Weather/injury patterns by time of year")

def main():
    """Demonstrate NBA strategies with time period filtering"""

    print("🏀 NBA Dynamic Strategy with Time Period Filtering")
    print("="*70)
    print("Demonstrating how strategies can filter by specific time periods")
    print("="*70)

    # Test case: December-only betting
    test_query = "Only bet on home teams during December NBA games"

    print(f"\n{'='*25} TIME PERIOD TEST {'='*25}")
    print(f"Strategy: '{test_query}'")

    # Step 1: AI generates time-aware code
    generated_code = simulate_ai_time_period_response(test_query)

    # Step 2: Backtesting with time filtering
    results = simulate_time_period_backtesting(generated_code)

    if results['success']:
        print("\n🎉 SUCCESS: Time-period strategy executed successfully!")
        print(".1f")
        print(f"   Games Filtered Out: {results['filtered_games']} (non-December)")
        print(".1f")
    else:
        print(f"\n❌ FAILED: {results.get('error', 'Unknown error')}")

    # Step 3: Show seasonal analysis
    demonstrate_seasonal_patterns()

    print("\n" + "="*70)
    print("🏀 TIME-PERIOD NBA STRATEGY SYSTEM SUMMARY")
    print("="*70)
    print("✅ AI Integration: Generates Python code with date/time filtering")
    print("✅ Time Period Logic: datetime parsing and month filtering")
    print("✅ Selective Betting: Only bets on games matching time criteria")
    print("✅ Performance Analysis: Measures effectiveness of time filters")
    print("✅ Seasonal Patterns: Can exploit month-to-month performance variations")
    print("\n🎯 Advanced NBA strategies can now filter by:")
    print("   • Specific months (December, playoffs, etc.)")
    print("   • Time ranges (holiday season, regular season)")
    print("   • Seasonal patterns (weather, motivation, injuries)")
    print("   • Historical performance by time period")

    print("\n🚀 The system supports sophisticated temporal betting strategies!")

if __name__ == "__main__":
    main()
