#!/usr/bin/env python3
"""
Calculate Half-Lines from Full Game Lines
Generates approximate 1H/2H lines when direct sources unavailable.

Formulas based on historical correlation analysis:
- NBA: 1H spread ≈ full_spread * 0.52, 1H total ≈ full_total * 0.50
- NFL: 1H spread ≈ full_spread * 0.48, 1H total ≈ full_total * 0.50
- NHL: 1P total ≈ full_total * 0.33 (spread stays at ±1.5)

Run: Daily or after odds refresh
"""
import psycopg2
import os
from datetime import datetime, timezone, timedelta
from dotenv import load_dotenv

# Half-line multipliers by league
HALF_LINE_FACTORS = {
    'nba': {
        'spread': 0.52,
        'total': 0.50,
        'periods': ['1h', '2h'],
    },
    'nfl': {
        'spread': 0.48,
        'total': 0.50,
        'periods': ['1h', '2h'],
    },
    'nhl': {
        'spread': 1.0,  # NHL uses ±1.5 puck line regardless
        'total': 0.33,  # ~2 goals per period
        'periods': ['p1', 'p2', 'p3'],
    },
    'ncaab': {
        'spread': 0.52,
        'total': 0.50,
        'periods': ['1h', '2h'],
    },
}


def load_db_url():
    load_dotenv('/var/www/html/eventheodds/.env')
    url = os.environ.get('SPORTS_DATABASE_URL', '')
    return url.split('?')[0] if '?' in url else url


def calculate_half_lines():
    print("=" * 60)
    print("CALCULATE HALF-LINES FROM FULL GAME LINES")
    print(f"Time: {datetime.now(timezone.utc).isoformat()}")
    print("=" * 60)

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

    total_created = 0

    for league, factors in HALF_LINE_FACTORS.items():
        print(f"\n{league.upper()}: Processing...")

        # Get upcoming games with full-game lines but no half-lines
        cur.execute('''
            SELECT g.id, g.league, g."homeTeam", g."awayTeam", g."gameDate",
                   g."spreadHome" as full_spread, g.total as full_total
            FROM "SportsGame" g
            WHERE g.league = %s
              AND g."gameDate" > NOW()
              AND g."gameDate" < NOW() + INTERVAL '7 days'
              AND g."spreadHome" IS NOT NULL
              AND g.total IS NOT NULL
              AND NOT EXISTS (
                  SELECT 1 FROM "GameHalfLine" h
                  WHERE h."gameId" = g.id
                    AND h."lineValue" IS NOT NULL
              )
            LIMIT 100
        ''', (league,))

        games = cur.fetchall()
        print(f"  Found {len(games)} games needing half-lines")

        for game in games:
            game_id, league, home, away, game_date, full_spread, full_total = game

            # Calculate half-lines
            for period in factors['periods']:
                # Spread
                if period in ['1h', 'p1']:  # Only 1st half/period spread
                    if league == 'nhl':
                        half_spread = 0.5 if full_spread and full_spread > 0 else -0.5
                    else:
                        half_spread = round(full_spread * factors['spread'], 1) if full_spread else None

                    if half_spread is not None:
                        cur.execute('''
                            INSERT INTO "GameHalfLine"
                            (league, "gameId", "gameDate", "homeTeam", "awayTeam",
                             period, market, "lineValue", "bookOdds", bookmaker,
                             "createdAt", "updatedAt")
                            VALUES (%s, %s, %s, %s, %s, %s, 'spread', %s, -110, 'calculated', NOW(), NOW())
                            ON CONFLICT DO NOTHING
                        ''', (league, game_id, game_date, home, away, period, half_spread))
                        total_created += 1

                # Total
                if league == 'nhl':
                    half_total = round(full_total * 0.33, 1) if full_total else None
                else:
                    half_total = round(full_total * factors['total'], 1) if full_total else None

                if half_total is not None:
                    cur.execute('''
                        INSERT INTO "GameHalfLine"
                        (league, "gameId", "gameDate", "homeTeam", "awayTeam",
                         period, market, "lineValue", "bookOdds", bookmaker,
                         "createdAt", "updatedAt")
                        VALUES (%s, %s, %s, %s, %s, %s, 'total', %s, -110, 'calculated', NOW(), NOW())
                        ON CONFLICT DO NOTHING
                    ''', (league, game_id, game_date, home, away, period, half_total))
                    total_created += 1

        conn.commit()

    # Report
    cur.execute('''
        SELECT league, COUNT(*), COUNT(CASE WHEN "lineValue" IS NOT NULL THEN 1 END)
        FROM "GameHalfLine"
        GROUP BY league
        ORDER BY league
    ''')

    print("\n" + "=" * 60)
    print("HALF-LINE COVERAGE:")
    for row in cur.fetchall():
        print(f"  {row[0].upper()}: {row[2]}/{row[1]} with values")

    cur.close()
    conn.close()

    print(f"\nTotal half-lines created: {total_created}")
    print("=" * 60)


if __name__ == '__main__':
    calculate_half_lines()
