#!/usr/bin/env python3
"""
Capture Live/In-Game Odds from The Odds API

Polls The Odds API for live games and captures in-play odds.
Falls back when SGO is unavailable.

Run: Every 5 minutes during game hours
"""
import requests
import psycopg2
import os
from datetime import datetime, timezone, timedelta

ODDS_API_BASE = 'https://api.the-odds-api.com/v4'


def load_db_url():
    env_path = '/var/www/html/eventheodds/.env'
    try:
        with open(env_path, 'r') as f:
            for line in f:
                if line.startswith('SPORTS_DATABASE_URL='):
                    return line.split('=', 1)[1].strip().strip('"').split('?')[0]
    except FileNotFoundError:
        pass
    return os.environ.get('SPORTS_DATABASE_URL', '').split('?')[0]


def load_odds_api_key():
    env_path = '/var/www/html/eventheodds/.env'
    try:
        with open(env_path, 'r') as f:
            for line in f:
                if line.startswith('THE_ODDS_API_KEY='):
                    return line.split('=', 1)[1].strip()
    except FileNotFoundError:
        pass
    return os.environ.get('THE_ODDS_API_KEY')


# League mapping for The Odds API
LEAGUE_MAP = {
    'nba': 'basketball_nba',
    'nfl': 'americanfootball_nfl',
    'nhl': 'icehockey_nhl',
    'mlb': 'baseball_mlb',
    'ncaab': 'basketball_ncaab',
    'ncaaf': 'americanfootball_ncaaf',
}


def get_live_odds(api_key, league):
    """Get live odds from The Odds API"""
    sport = LEAGUE_MAP.get(league)
    if not sport:
        return []

    params = {
        'apiKey': api_key,
        'regions': 'us',
        'markets': 'spreads,totals,h2h',
        'oddsFormat': 'american',
        'eventIds': '',  # Empty = all
    }

    try:
        # First get events to find in-progress ones
        resp = requests.get(
            f'{ODDS_API_BASE}/sports/{sport}/odds',
            params=params,
            timeout=30
        )

        if resp.status_code == 401:
            print(f"  Invalid API key for {league}")
            return []
        if resp.status_code == 422:
            print(f"  No events for {league}")
            return []
        if resp.status_code != 200:
            print(f"  API returned {resp.status_code} for {league}")
            return []

        events = resp.json()

        # Filter for live events (commence_time in past but not too far)
        now = datetime.now(timezone.utc)
        live_events = []

        for event in events:
            commence = event.get('commence_time')
            if commence:
                try:
                    commence_dt = datetime.fromisoformat(commence.replace('Z', '+00:00'))
                    # Game started within last 4 hours
                    if now - timedelta(hours=4) < commence_dt < now:
                        live_events.append(event)
                except:
                    pass

        return live_events, events  # Return both live and all

    except Exception as e:
        print(f"  Error fetching {league}: {e}")
        return [], []


def capture_odds():
    print("=" * 60)
    print("CAPTURE LIVE ODDS (The Odds API)")
    print(f"Time: {datetime.now(timezone.utc).isoformat()}")
    print("=" * 60)

    db_url = load_db_url()
    api_key = load_odds_api_key()

    if not api_key:
        print("ERROR: THE_ODDS_API_KEY not set")
        return

    conn = psycopg2.connect(db_url)
    cur = conn.cursor()

    # Ensure LiveOdds table exists
    cur.execute('''
        CREATE TABLE IF NOT EXISTS "LiveOdds" (
            id SERIAL PRIMARY KEY,
            league VARCHAR(20),
            "gameId" INTEGER,
            "externalGameId" VARCHAR(100),
            "gameDate" TIMESTAMP,
            "homeTeam" VARCHAR(100),
            "awayTeam" VARCHAR(100),
            "gameStatus" VARCHAR(20),
            "gameTime" VARCHAR(20),
            "homeScoreLive" INTEGER,
            "awayScoreLive" INTEGER,
            "liveSpreadHome" DOUBLE PRECISION,
            "liveSpreadAway" DOUBLE PRECISION,
            "liveSpreadHomeOdds" INTEGER,
            "liveSpreadAwayOdds" INTEGER,
            "liveTotal" DOUBLE PRECISION,
            "liveTotalOverOdds" INTEGER,
            "liveTotalUnderOdds" INTEGER,
            "liveMoneylineHome" INTEGER,
            "liveMoneylineAway" INTEGER,
            "capturedAt" TIMESTAMP DEFAULT NOW(),
            source VARCHAR(50),
            bookmaker VARCHAR(50),
            raw JSONB,
            "createdAt" TIMESTAMP DEFAULT NOW()
        )
    ''')
    cur.execute('''
        CREATE INDEX IF NOT EXISTS idx_live_odds_game
        ON "LiveOdds"(league, "externalGameId", "capturedAt")
    ''')
    conn.commit()

    leagues = ['nba', 'nfl', 'nhl']
    total_captured = 0
    total_live = 0

    for league in leagues:
        result = get_live_odds(api_key, league)
        if not result:
            continue

        live_events, all_events = result
        print(f"\n{league.upper()}: {len(live_events)} live, {len(all_events)} total events")
        total_live += len(live_events)

        # Capture all events (not just live) to populate LiveOdds
        for event in all_events:
            event_id = event.get('id')
            home = event.get('home_team', '')
            away = event.get('away_team', '')
            commence = event.get('commence_time')

            commence_dt = None
            if commence:
                try:
                    commence_dt = datetime.fromisoformat(commence.replace('Z', '+00:00'))
                except:
                    pass

            # Extract odds from bookmakers
            bookmakers = event.get('bookmakers', [])
            for book in bookmakers[:3]:  # Take first 3 bookmakers
                book_name = book.get('key', 'unknown')

                spread_home = spread_away = None
                spread_home_odds = spread_away_odds = None
                total_line = None
                total_over_odds = total_under_odds = None
                ml_home = ml_away = None

                for market in book.get('markets', []):
                    market_key = market.get('key')
                    outcomes = market.get('outcomes', [])

                    if market_key == 'spreads':
                        for outcome in outcomes:
                            if outcome.get('name') == home:
                                spread_home = outcome.get('point')
                                spread_home_odds = outcome.get('price')
                            elif outcome.get('name') == away:
                                spread_away = outcome.get('point')
                                spread_away_odds = outcome.get('price')

                    elif market_key == 'totals':
                        for outcome in outcomes:
                            if outcome.get('name') == 'Over':
                                total_line = outcome.get('point')
                                total_over_odds = outcome.get('price')
                            elif outcome.get('name') == 'Under':
                                total_under_odds = outcome.get('price')

                    elif market_key == 'h2h':
                        for outcome in outcomes:
                            if outcome.get('name') == home:
                                ml_home = outcome.get('price')
                            elif outcome.get('name') == away:
                                ml_away = outcome.get('price')

                # Insert into LiveOdds
                cur.execute('''
                    INSERT INTO "LiveOdds" (
                        league, "externalGameId", "gameDate", "homeTeam", "awayTeam",
                        "liveSpreadHome", "liveSpreadAway", "liveSpreadHomeOdds", "liveSpreadAwayOdds",
                        "liveTotal", "liveTotalOverOdds", "liveTotalUnderOdds",
                        "liveMoneylineHome", "liveMoneylineAway",
                        "capturedAt", source, bookmaker
                    )
                    VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, NOW(), 'theoddsapi', %s)
                ''', (
                    league, event_id, commence_dt, home, away,
                    spread_home, spread_away, spread_home_odds, spread_away_odds,
                    total_line, total_over_odds, total_under_odds,
                    ml_home, ml_away, book_name
                ))
                total_captured += 1

    conn.commit()

    # Report
    print(f"\n{'='*60}")
    print(f"RESULTS: {total_live} live games, {total_captured} odds captured")

    cur.execute('''
        SELECT league, COUNT(*)
        FROM "LiveOdds"
        WHERE "capturedAt" > NOW() - INTERVAL '1 hour'
        GROUP BY league
    ''')
    print("\nRecent captures by league:")
    for row in cur.fetchall():
        print(f"  {row[0]}: {row[1]}")

    print("=" * 60)

    cur.close()
    conn.close()


if __name__ == '__main__':
    capture_odds()
