#!/usr/bin/env python3
import requests
import json
import time
from datetime import datetime, timedelta
from pathlib import Path

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).")
HEADERS = {'Authorization': API_KEY}
BASE = 'https://api.balldontlie.io'
DATA_DIR = Path('/var/www/html/eventheodds/data/odds')
DATA_DIR.mkdir(parents=True, exist_ok=True)

def fetch(url):
    try:
        r = requests.get(url, headers=HEADERS, timeout=30)
        if r.ok:
            return r.json().get('data', [])
    except:
        pass
    return []

print('=== Fetching ALL Real Odds ===')
print(f'Started: {datetime.now()}')

# NBA - last 60 days
print('\n1. NBA Odds...')
nba = []
for i in range(60):
    date = (datetime.now() - timedelta(days=i)).strftime('%Y-%m-%d')
    items = fetch(f'{BASE}/v1/odds?date={date}&per_page=100')
    if items:
        for x in items: x['date'] = date
        nba.extend(items)
        print(f'  {date}: {len(items)}')
    time.sleep(0.3)
print(f'  NBA Total: {len(nba)}')

# NFL - 2025 season
print('\n2. NFL Odds...')
nfl = []
for week in range(1, 23):
    items = fetch(f'{BASE}/nfl/v1/odds?season=2025&week={week}&per_page=100')
    if items:
        for x in items: x['week'] = week
        nfl.extend(items)
        print(f'  Week {week}: {len(items)}')
    time.sleep(0.3)
print(f'  NFL Total: {len(nfl)}')

# NHL - last 60 days
print('\n3. NHL Odds...')
nhl = []
for i in range(60):
    date = (datetime.now() - timedelta(days=i)).strftime('%Y-%m-%d')
    items = fetch(f'{BASE}/nhl/v1/odds?dates[]={date}&per_page=100')
    if items:
        for x in items: x['date'] = date
        nhl.extend(items)
        print(f'  {date}: {len(items)}')
    time.sleep(0.3)
print(f'  NHL Total: {len(nhl)}')

# Save files
print('\n4. Saving data...')
if nba:
    with open(DATA_DIR / 'nba_odds.json', 'w') as f:
        json.dump(nba, f)
    print(f'  Saved {len(nba)} NBA odds')

if nfl:
    with open(DATA_DIR / 'nfl_odds.json', 'w') as f:
        json.dump(nfl, f)
    print(f'  Saved {len(nfl)} NFL odds')

if nhl:
    with open(DATA_DIR / 'nhl_odds.json', 'w') as f:
        json.dump(nhl, f)
    print(f'  Saved {len(nhl)} NHL odds')

# Summary
summary = {
    'fetched_at': datetime.now().isoformat(),
    'source': 'BallDontLie API - REAL SPORTSBOOK DATA',
    'nba_odds': len(nba),
    'nfl_odds': len(nfl),
    'nhl_odds': len(nhl),
    'total': len(nba) + len(nfl) + len(nhl)
}
with open(DATA_DIR / 'summary.json', 'w') as f:
    json.dump(summary, f, indent=2)

print('\n=== DONE ===')
print(f'Total: {summary["total"]} real odds entries')
print(f'Finished: {datetime.now()}')
