"""Fetch MLB odds from The Odds API (real-time during season).

Note: BallDontLie does NOT have MLB betting odds endpoint.
We use The Odds API for MLB during the season (April-October).
"""
import json
import os
from datetime import datetime
from pathlib import Path
import urllib.request

API_KEY = '909eb71127b7d150ce59828cb97d4992'
BASE_URL = 'https://api.the-odds-api.com/v4'
DATA_DIR = Path('/var/www/html/eventheodds/data/betting')

def fetch_mlb_odds():
    """Fetch MLB odds from The Odds API."""
    data_file = DATA_DIR / 'mlb_historical.json'
    
    # Check if MLB is in season
    month = datetime.now().month
    if month < 3 or month > 10:
        print(f'MLB is off-season (current month: {month}). Skipping.')
        return 0
    
    # Load existing data
    existing = []
    if data_file.exists():
        with open(data_file) as f:
            existing = json.load(f)
    existing_ids = {d.get('game_id') for d in existing}
    
    # Fetch from The Odds API
    url = f'{BASE_URL}/sports/baseball_mlb/odds?apiKey={API_KEY}&regions=us&markets=h2h,spreads,totals&oddsFormat=american'
    
    print('Fetching MLB odds from The Odds API...')
    try:
        with urllib.request.urlopen(url, timeout=30) as resp:
            games = json.loads(resp.read().decode())
    except Exception as e:
        print(f'Error fetching: {e}')
        return 0
    
    print(f'Found {len(games)} games')
    
    new_games = []
    for game in games:
        game_id = game['id']
        if game_id in existing_ids:
            continue
        
        # Parse bookmaker odds
        sportsbooks = {}
        spread = None
        total = None
        home_ml = None
        away_ml = None
        
        for bookmaker in game.get('bookmakers', []):
            book_name = bookmaker['key']
            book_odds = {}
            
            for market in bookmaker.get('markets', []):
                if market['key'] == 'h2h':
                    for outcome in market['outcomes']:
                        if outcome['name'] == game['home_team']:
                            book_odds['home_ml'] = outcome['price']
                            if home_ml is None:
                                home_ml = outcome['price']
                        else:
                            book_odds['away_ml'] = outcome['price']
                            if away_ml is None:
                                away_ml = outcome['price']
                                
                elif market['key'] == 'spreads':
                    for outcome in market['outcomes']:
                        if outcome['name'] == game['home_team']:
                            book_odds['spread'] = outcome.get('point')
                            if spread is None:
                                spread = outcome.get('point')
                                
                elif market['key'] == 'totals':
                    for outcome in market['outcomes']:
                        if outcome['name'] == 'Over':
                            book_odds['total'] = outcome.get('point')
                            if total is None:
                                total = outcome.get('point')
            
            if book_odds:
                sportsbooks[book_name] = book_odds
        
        record = {
            'game_id': game_id,
            'sport': 'MLB',
            'date': game['commence_time'][:10],
            'home_team': game['home_team'],
            'away_team': game['away_team'],
            'spread': spread,
            'total': total,
            'home_ml': home_ml,
            'away_ml': away_ml,
            'odds': {
                'source': 'the-odds-api',
                'sportsbooks': sportsbooks
            }
        }
        new_games.append(record)
    
    # Merge and save
    all_data = existing + new_games
    with open(data_file, 'w') as f:
        json.dump(all_data, f, indent=2)
    
    print(f'=== MLB SUMMARY ===')
    print(f'Existing: {len(existing)}')
    print(f'New: {len(new_games)}')
    print(f'Total: {len(all_data)}')
    return len(new_games)

if __name__ == '__main__':
    DATA_DIR.mkdir(parents=True, exist_ok=True)
    fetch_mlb_odds()
