#!/var/www/html/eventheodds/.venv-scraper/bin/python
"""
Fetch Half-Line Odds (1H spreads/totals) from The Odds API
Unlocks: Q4 (half spreads vs full game efficiency)

Run: Every 6 hours during season

KNOWN ISSUE: The Odds API does NOT support h1 (first-half) markets.
The markets h2h_h1, spreads_h1, totals_h1 return INVALID_MARKET error.

ALTERNATIVES:
1. Use calculate_half_lines.py to estimate 1H lines from full-game lines
2. Use scrape_oddsportal_halflines.py for OddsPortal data
3. Use scrape_dk_halflines_playwright.py for DraftKings data
"""
import requests
import psycopg2
import os
from datetime import datetime, timezone
import time

def load_env():
    env_path = '/var/www/html/eventheodds/.env'
    env_vars = {}
    try:
        with open(env_path, 'r') as f:
            for line in f:
                if '=' in line and not line.startswith('#'):
                    key, val = line.strip().split('=', 1)
                    env_vars[key] = val
    except FileNotFoundError:
        pass
    return env_vars

env = load_env()
API_KEY = env.get('ODDS_API_KEY', os.environ.get('ODDS_API_KEY', ''))
DB_URL = env.get('SPORTS_DATABASE_URL', '').split('?')[0]

SPORTS_MAP = {
    'nba': 'basketball_nba',
    'nfl': 'americanfootball_nfl',
    'nhl': 'icehockey_nhl',
    'ncaab': 'basketball_ncaab',
    'ncaaf': 'americanfootball_ncaaf',
}

# Half-line markets
HALF_MARKETS = 'h2h_h1,spreads_h1,totals_h1'

def fetch_half_lines(sport_key):
    """Fetch half-line odds from The Odds API"""
    url = f'https://api.the-odds-api.com/v4/sports/{sport_key}/odds'
    params = {
        'apiKey': API_KEY,
        'regions': 'us',
        'markets': HALF_MARKETS,
        'oddsFormat': 'american',
    }

    try:
        resp = requests.get(url, params=params, timeout=30)
        if resp.status_code == 200:
            return resp.json()
        else:
            print(f"  API error {resp.status_code}: {resp.text[:100]}")
            return []
    except Exception as e:
        print(f"  Request error: {e}")
        return []


def store_half_lines(conn, league, events):
    """Store half-line odds in GameHalfLine table"""
    cur = conn.cursor()

    stored = 0
    for event in events:
        event_id = event.get('id')
        home_team = event.get('home_team', '')
        away_team = event.get('away_team', '')
        commence_time = event.get('commence_time')

        # Find matching game
        cur.execute('''
            SELECT id, "gameDate" FROM "SportsGame"
            WHERE league = %s
              AND "homeTeam" = %s AND "awayTeam" = %s
              AND "gameDate"::date = %s::date
            LIMIT 1
        ''', (league, home_team, away_team, commence_time[:10] if commence_time else None))

        game = cur.fetchone()
        game_id = game[0] if game else None
        game_date = game[1] if game else commence_time

        for bookmaker in event.get('bookmakers', []):
            book_name = bookmaker.get('key', '')

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

                # Map market to period
                if '_h1' in market_key:
                    period = '1h'
                elif '_h2' in market_key:
                    period = '2h'
                else:
                    continue

                # Determine market type
                if 'spread' in market_key:
                    market_type = 'spread'
                elif 'total' in market_key:
                    market_type = 'total'
                elif 'h2h' in market_key:
                    market_type = 'moneyline'
                else:
                    continue

                for outcome in market.get('outcomes', []):
                    side = outcome.get('name', '')
                    price = outcome.get('price')
                    point = outcome.get('point')

                    # Upsert into GameHalfLine
                    cur.execute('''
                        INSERT INTO "GameHalfLine"
                        (league, "gameId", "gameDate", "homeTeam", "awayTeam",
                         period, market, side, "lineValue", "bookOdds", bookmaker, "createdAt", "updatedAt")
                        VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, NOW(), NOW())
                        ON CONFLICT DO NOTHING
                    ''', (league, game_id, game_date, home_team, away_team,
                          period, market_type, side, point, price, book_name))
                    stored += 1

    conn.commit()
    cur.close()
    return stored


def main():
    print("=" * 60)
    print("FETCH HALF-LINE ODDS")
    print(f"Time: {datetime.now(timezone.utc).isoformat()}")
    print("=" * 60)

    if not API_KEY:
        print("ERROR: ODDS_API_KEY not set")
        return

    conn = psycopg2.connect(DB_URL)
    total_stored = 0

    for league, sport_key in SPORTS_MAP.items():
        print(f"\n{league.upper()}: Fetching half-lines...")
        events = fetch_half_lines(sport_key)

        if events:
            stored = store_half_lines(conn, league, events)
            print(f"  {league}: {len(events)} events, {stored} lines stored")
            total_stored += stored
        else:
            print(f"  {league}: No events or API error")

        time.sleep(1)  # Rate limiting

    conn.close()

    print("\n" + "=" * 60)
    print(f"Total: {total_stored} half-lines stored")
    print("=" * 60)


if __name__ == '__main__':
    main()
