"""Fetch NCAAB odds from BallDontLie API."""
import json
import os
import time
from datetime import datetime, timedelta
from pathlib import Path
import urllib.request
import urllib.parse

API_KEY = os.environ.get('BALLDONTLIE_API_KEY')
if not API_KEY:
    raise RuntimeError("BALLDONTLIE_API_KEY is not set. Put it in the environment (recommended: .env / systemd EnvironmentFile).")
BASE_URL = 'https://api.balldontlie.io/ncaab/v1'
DATA_DIR = Path('/var/www/html/eventheodds/data/betting')

def make_request(endpoint, params=None):
    url = f'{BASE_URL}/{endpoint}'
    if params:
        url += '?' + urllib.parse.urlencode(params, doseq=True)
    req = urllib.request.Request(url, headers={'Authorization': API_KEY})
    try:
        with urllib.request.urlopen(req, timeout=30) as resp:
            return json.loads(resp.read().decode())
    except Exception as e:
        print(f'Error: {e}')
        return None

def fetch_ncaab_odds(days_back=30):
    """Fetch NCAAB odds for multiple dates."""
    data_file = DATA_DIR / 'ncaab_historical.json'
    
    # Load existing data
    existing = []
    if data_file.exists():
        with open(data_file) as f:
            existing = json.load(f)
    existing_ids = {(d.get('game_id'), d.get('vendor')) for d in existing}
    
    # Generate date range
    today = datetime.now()
    dates = [(today - timedelta(days=i)).strftime('%Y-%m-%d') for i in range(days_back)]
    
    all_new = []
    for date in dates:
        print(f'Fetching NCAAB odds for {date}...')
        resp = make_request('odds', {'dates[]': date, 'per_page': 100})
        if not resp or not resp.get('data'):
            continue
        
        for odd in resp['data']:
            key = (odd.get('game_id'), odd.get('vendor'))
            if key in existing_ids:
                continue
            
            record = {
                'game_id': odd.get('game_id'),
                'sport': 'NCAAB',
                'date': date,
                'vendor': odd.get('vendor'),
                'spread_home': odd.get('spread_home_value'),
                'spread_away': odd.get('spread_away_value'),
                'spread_home_odds': odd.get('spread_home_odds'),
                'spread_away_odds': odd.get('spread_away_odds'),
                'moneyline_home': odd.get('moneyline_home_odds'),
                'moneyline_away': odd.get('moneyline_away_odds'),
                'total': odd.get('total_value'),
                'over_odds': odd.get('total_over_odds'),
                'under_odds': odd.get('total_under_odds'),
                'odds': {
                    'source': 'balldontlie',
                    'updated': odd.get('updated_at')
                }
            }
            all_new.append(record)
            existing_ids.add(key)
        
        time.sleep(0.3)  # Rate limit
    
    # Merge and save
    all_data = existing + all_new
    with open(data_file, 'w') as f:
        json.dump(all_data, f, indent=2)
    
    print(f'\n=== NCAAB SUMMARY ===')
    print(f'Existing: {len(existing)}')
    print(f'New: {len(all_new)}')
    print(f'Total: {len(all_data)}')
    return len(all_new)

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--days', type=int, default=30, help='Days to look back')
    args = parser.parse_args()
    
    DATA_DIR.mkdir(parents=True, exist_ok=True)
    fetch_ncaab_odds(args.days)
