#!/usr/bin/env python3
"""
Capture Live/In-Game Odds from SportsGameOdds
Polls SGO API for live games and captures in-play odds snapshots.

Key features:
- Detects games currently in progress
- Captures odds every 5 minutes during live games
- Stores in OddsSnapshot with snapshotType='live'

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

SGO_BASE = 'https://api.sportsgameodds.com/v2'


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().split('?')[0]
    except FileNotFoundError:
        pass
    return os.environ.get('SPORTS_DATABASE_URL', '').split('?')[0]


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


def get_live_events(api_key, league):
    """Get currently live events from SGO"""
    headers = {'x-api-key': api_key}

    # SGO league mapping
    sgo_leagues = {
        'nba': 'NBA',
        'nfl': 'NFL',
        'nhl': 'NHL',
        'mlb': 'MLB',
        'ncaab': 'NCAAB',
        'ncaaf': 'NCAAF',
    }

    sgo_league = sgo_leagues.get(league)
    if not sgo_league:
        return []

    # Get events happening now (started but not finished)
    now = datetime.now(timezone.utc)
    params = {
        'league': sgo_league,
        'startsAfter': (now - timedelta(hours=6)).isoformat(),  # Started up to 6 hours ago
        'startsBefore': now.isoformat(),  # Started before now
    }

    try:
        resp = requests.get(f'{SGO_BASE}/events', headers=headers, params=params, timeout=30)

        if resp.status_code == 401:
            print(f"  Invalid API key")
            return []
        if resp.status_code != 200:
            print(f"  SGO returned {resp.status_code}")
            return []

        data = resp.json()
        events = data.get('events', [])

        # Filter for live (started but not ended)
        live_events = []
        for event in events:
            status = event.get('status', '')
            # SGO statuses: scheduled, in_progress, finished, postponed, cancelled
            if status in ['in_progress', 'live']:
                live_events.append(event)

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


def capture_live_snapshot(cur, event, league, api_key):
    """Capture odds snapshot for a live event"""
    event_id = event.get('eventID')
    if not event_id:
        return False

    # Get detailed odds for this event
    headers = {'x-api-key': api_key}

    try:
        resp = requests.get(f'{SGO_BASE}/events/{event_id}', headers=headers, timeout=30)
        if resp.status_code != 200:
            return False

        data = resp.json()
        odds = data.get('odds', {})

        # Extract key odds
        spread_home = None
        spread_away = None
        total = None
        ml_home = None
        ml_away = None

        for odd_key, odd_data in odds.items():
            stat_entity = odd_data.get('statEntityID', 'all')
            if stat_entity not in ['all', 'home', 'away']:
                continue  # Skip player props

            bet_type = odd_data.get('betTypeID', '')
            period = odd_data.get('periodID', 'game')
            side = odd_data.get('sideID', '')

            if period != 'game':
                continue

            # Get line value
            line = odd_data.get('bookOverUnder') or odd_data.get('fairOverUnder')
            odds_val = odd_data.get('bookOdds') or odd_data.get('fairOdds')

            if bet_type == 'spread':
                if side == 'home':
                    spread_home = float(line) if line else None
                elif side == 'away':
                    spread_away = float(line) if line else None
            elif bet_type == 'ou':
                if side == 'over':
                    total = float(line) if line else None
            elif bet_type == 'ml':
                try:
                    odds_int = int(str(odds_val).replace('+', '')) if odds_val else None
                    if side == 'home':
                        ml_home = odds_int
                    elif side == 'away':
                        ml_away = odds_int
                except:
                    pass

        # Insert snapshot
        now = datetime.now(timezone.utc)
        game_date = event.get('startsAt')
        if game_date:
            game_date = datetime.fromisoformat(game_date.replace('Z', '+00:00'))

        home_team = event.get('homeTeamID', '').split('_')[0] if event.get('homeTeamID') else ''
        away_team = event.get('awayTeamID', '').split('_')[0] if event.get('awayTeamID') else ''

        cur.execute('''
            INSERT INTO "OddsSnapshot" (
                league, "externalGameId", "gameDate", "homeTeam", "awayTeam",
                "snapshotType", "snapshotAt", "hoursToGame",
                "spreadHome", "spreadAway", "moneylineHome", "moneylineAway",
                total, source
            )
            VALUES (%s, %s, %s, %s, %s, 'live', %s, 0, %s, %s, %s, %s, %s, 'sgo-live')
            ON CONFLICT (league, "externalGameId", "snapshotAt", source, bookmaker)
            DO NOTHING
        ''', (
            league, event_id, game_date, home_team, away_team,
            now, spread_home, spread_away, ml_home, ml_away, total
        ))

        return True
    except Exception as e:
        return False


def capture_live_odds():
    """Main function to capture live odds"""
    db_url = load_db_url()
    if not db_url:
        raise RuntimeError('SPORTS_DATABASE_URL not set')

    api_key = load_sgo_key()
    if not api_key:
        raise RuntimeError('SPORTSGAMEODDS_API_KEY not set')

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

    print("=" * 60)
    print("CAPTURE LIVE ODDS FROM SGO")
    print(f"Time: {datetime.now(timezone.utc).isoformat()}")
    print("=" * 60)

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

    for league in leagues:
        live_events = get_live_events(api_key, league)

        if live_events:
            print(f"\n{league.upper()}: {len(live_events)} live games")
            total_live += len(live_events)

            for event in live_events:
                time.sleep(0.5)  # Rate limiting
                if capture_live_snapshot(cur, event, league, api_key):
                    total_captured += 1

    conn.commit()
    cur.close()
    conn.close()

    print(f"\n{'='*60}")
    print(f"TOTAL: {total_live} live games, {total_captured} snapshots captured")
    print("=" * 60)

    return {'live': total_live, 'captured': total_captured}


def main():
    try:
        result = capture_live_odds()
        print(f"\nCapture complete: {result['live']} live, {result['captured']} captured")
    except Exception as e:
        print(f"ERROR: {e}")
        import traceback
        traceback.print_exc()


if __name__ == '__main__':
    main()
