#!/usr/bin/env python3
"""
Create Venue Table with Altitude Data
Enables Q17: Altitude effects on performance
"""
import psycopg2
from datetime import datetime, timezone

# NBA/NHL/NFL venue data with altitude
VENUES = [
    # NBA - High Altitude
    {'name': 'Ball Arena', 'city': 'Denver', 'state': 'CO', 'team': 'DEN', 'league': 'nba', 'altitude_ft': 5280, 'timezone': 'America/Denver', 'capacity': 19520},
    {'name': 'Vivint Arena', 'city': 'Salt Lake City', 'state': 'UT', 'team': 'UTA', 'league': 'nba', 'altitude_ft': 4226, 'timezone': 'America/Denver', 'capacity': 18306},
    {'name': 'Footprint Center', 'city': 'Phoenix', 'state': 'AZ', 'team': 'PHX', 'league': 'nba', 'altitude_ft': 1086, 'timezone': 'America/Phoenix', 'capacity': 18055},
    # NBA - Sea Level / Low
    {'name': 'Chase Center', 'city': 'San Francisco', 'state': 'CA', 'team': 'GSW', 'league': 'nba', 'altitude_ft': 52, 'timezone': 'America/Los_Angeles', 'capacity': 18064},
    {'name': 'Crypto.com Arena', 'city': 'Los Angeles', 'state': 'CA', 'team': 'LAL', 'league': 'nba', 'altitude_ft': 285, 'timezone': 'America/Los_Angeles', 'capacity': 19068},
    {'name': 'Crypto.com Arena', 'city': 'Los Angeles', 'state': 'CA', 'team': 'LAC', 'league': 'nba', 'altitude_ft': 285, 'timezone': 'America/Los_Angeles', 'capacity': 19068},
    {'name': 'Madison Square Garden', 'city': 'New York', 'state': 'NY', 'team': 'NYK', 'league': 'nba', 'altitude_ft': 33, 'timezone': 'America/New_York', 'capacity': 19812},
    {'name': 'Barclays Center', 'city': 'Brooklyn', 'state': 'NY', 'team': 'BKN', 'league': 'nba', 'altitude_ft': 33, 'timezone': 'America/New_York', 'capacity': 17732},
    {'name': 'TD Garden', 'city': 'Boston', 'state': 'MA', 'team': 'BOS', 'league': 'nba', 'altitude_ft': 20, 'timezone': 'America/New_York', 'capacity': 19156},
    {'name': 'Wells Fargo Center', 'city': 'Philadelphia', 'state': 'PA', 'team': 'PHI', 'league': 'nba', 'altitude_ft': 39, 'timezone': 'America/New_York', 'capacity': 20478},
    {'name': 'Capital One Arena', 'city': 'Washington', 'state': 'DC', 'team': 'WAS', 'league': 'nba', 'altitude_ft': 25, 'timezone': 'America/New_York', 'capacity': 20356},
    {'name': 'United Center', 'city': 'Chicago', 'state': 'IL', 'team': 'CHI', 'league': 'nba', 'altitude_ft': 594, 'timezone': 'America/Chicago', 'capacity': 20917},
    {'name': 'Little Caesars Arena', 'city': 'Detroit', 'state': 'MI', 'team': 'DET', 'league': 'nba', 'altitude_ft': 600, 'timezone': 'America/Detroit', 'capacity': 20332},
    {'name': 'Rocket Mortgage FieldHouse', 'city': 'Cleveland', 'state': 'OH', 'team': 'CLE', 'league': 'nba', 'altitude_ft': 653, 'timezone': 'America/New_York', 'capacity': 19432},
    {'name': 'Gainbridge Fieldhouse', 'city': 'Indianapolis', 'state': 'IN', 'team': 'IND', 'league': 'nba', 'altitude_ft': 715, 'timezone': 'America/Indiana/Indianapolis', 'capacity': 17923},
    {'name': 'Fiserv Forum', 'city': 'Milwaukee', 'state': 'WI', 'team': 'MIL', 'league': 'nba', 'altitude_ft': 617, 'timezone': 'America/Chicago', 'capacity': 17341},
    {'name': 'Target Center', 'city': 'Minneapolis', 'state': 'MN', 'team': 'MIN', 'league': 'nba', 'altitude_ft': 830, 'timezone': 'America/Chicago', 'capacity': 18978},
    {'name': 'FedExForum', 'city': 'Memphis', 'state': 'TN', 'team': 'MEM', 'league': 'nba', 'altitude_ft': 337, 'timezone': 'America/Chicago', 'capacity': 18119},
    {'name': 'Smoothie King Center', 'city': 'New Orleans', 'state': 'LA', 'team': 'NOP', 'league': 'nba', 'altitude_ft': 3, 'timezone': 'America/Chicago', 'capacity': 16867},
    {'name': 'Toyota Center', 'city': 'Houston', 'state': 'TX', 'team': 'HOU', 'league': 'nba', 'altitude_ft': 80, 'timezone': 'America/Chicago', 'capacity': 18055},
    {'name': 'American Airlines Center', 'city': 'Dallas', 'state': 'TX', 'team': 'DAL', 'league': 'nba', 'altitude_ft': 430, 'timezone': 'America/Chicago', 'capacity': 19200},
    {'name': 'Frost Bank Center', 'city': 'San Antonio', 'state': 'TX', 'team': 'SAS', 'league': 'nba', 'altitude_ft': 650, 'timezone': 'America/Chicago', 'capacity': 18418},
    {'name': 'Kaseya Center', 'city': 'Miami', 'state': 'FL', 'team': 'MIA', 'league': 'nba', 'altitude_ft': 6, 'timezone': 'America/New_York', 'capacity': 19600},
    {'name': 'Amway Center', 'city': 'Orlando', 'state': 'FL', 'team': 'ORL', 'league': 'nba', 'altitude_ft': 82, 'timezone': 'America/New_York', 'capacity': 18846},
    {'name': 'State Farm Arena', 'city': 'Atlanta', 'state': 'GA', 'team': 'ATL', 'league': 'nba', 'altitude_ft': 1050, 'timezone': 'America/New_York', 'capacity': 18118},
    {'name': 'Spectrum Center', 'city': 'Charlotte', 'state': 'NC', 'team': 'CHA', 'league': 'nba', 'altitude_ft': 751, 'timezone': 'America/New_York', 'capacity': 19077},
    {'name': 'Scotiabank Arena', 'city': 'Toronto', 'state': 'ON', 'team': 'TOR', 'league': 'nba', 'altitude_ft': 249, 'timezone': 'America/Toronto', 'capacity': 19800},
    {'name': 'Moda Center', 'city': 'Portland', 'state': 'OR', 'team': 'POR', 'league': 'nba', 'altitude_ft': 50, 'timezone': 'America/Los_Angeles', 'capacity': 19441},
    {'name': 'Golden 1 Center', 'city': 'Sacramento', 'state': 'CA', 'team': 'SAC', 'league': 'nba', 'altitude_ft': 30, 'timezone': 'America/Los_Angeles', 'capacity': 17608},
    {'name': 'Climate Pledge Arena', 'city': 'Seattle', 'state': 'WA', 'team': 'OKC', 'league': 'nba', 'altitude_ft': 1201, 'timezone': 'America/Chicago', 'capacity': 18203},  # OKC uses Paycom

    # NFL - High Altitude
    {'name': 'Empower Field at Mile High', 'city': 'Denver', 'state': 'CO', 'team': 'DEN', 'league': 'nfl', 'altitude_ft': 5280, 'timezone': 'America/Denver', 'capacity': 76125},
    {'name': 'State Farm Stadium', 'city': 'Glendale', 'state': 'AZ', 'team': 'ARI', 'league': 'nfl', 'altitude_ft': 1071, 'timezone': 'America/Phoenix', 'capacity': 63400},
    {'name': 'Allegiant Stadium', 'city': 'Las Vegas', 'state': 'NV', 'team': 'LV', 'league': 'nfl', 'altitude_ft': 2001, 'timezone': 'America/Los_Angeles', 'capacity': 65000},
    # NFL - Sea Level
    {'name': 'MetLife Stadium', 'city': 'East Rutherford', 'state': 'NJ', 'team': 'NYG', 'league': 'nfl', 'altitude_ft': 10, 'timezone': 'America/New_York', 'capacity': 82500},
    {'name': 'MetLife Stadium', 'city': 'East Rutherford', 'state': 'NJ', 'team': 'NYJ', 'league': 'nfl', 'altitude_ft': 10, 'timezone': 'America/New_York', 'capacity': 82500},
    {'name': 'Gillette Stadium', 'city': 'Foxborough', 'state': 'MA', 'team': 'NE', 'league': 'nfl', 'altitude_ft': 256, 'timezone': 'America/New_York', 'capacity': 65878},
    {'name': 'Hard Rock Stadium', 'city': 'Miami Gardens', 'state': 'FL', 'team': 'MIA', 'league': 'nfl', 'altitude_ft': 10, 'timezone': 'America/New_York', 'capacity': 64767},

    # NHL - High Altitude
    {'name': 'Ball Arena', 'city': 'Denver', 'state': 'CO', 'team': 'COL', 'league': 'nhl', 'altitude_ft': 5280, 'timezone': 'America/Denver', 'capacity': 18007},
    {'name': 'Delta Center', 'city': 'Salt Lake City', 'state': 'UT', 'team': 'UTA', 'league': 'nhl', 'altitude_ft': 4226, 'timezone': 'America/Denver', 'capacity': 18306},
    {'name': 'Mullett Arena', 'city': 'Tempe', 'state': 'AZ', 'team': 'ARI', 'league': 'nhl', 'altitude_ft': 1150, 'timezone': 'America/Phoenix', 'capacity': 5000},
    # NHL - Sea Level
    {'name': 'TD Garden', 'city': 'Boston', 'state': 'MA', 'team': 'BOS', 'league': 'nhl', 'altitude_ft': 20, 'timezone': 'America/New_York', 'capacity': 17850},
    {'name': 'Madison Square Garden', 'city': 'New York', 'state': 'NY', 'team': 'NYR', 'league': 'nhl', 'altitude_ft': 33, 'timezone': 'America/New_York', 'capacity': 18006},
    {'name': 'UBS Arena', 'city': 'Elmont', 'state': 'NY', 'team': 'NYI', 'league': 'nhl', 'altitude_ft': 62, 'timezone': 'America/New_York', 'capacity': 17255},
]

def load_db_url():
    with open('/var/www/html/eventheodds/.env', 'r') as f:
        for line in f:
            if line.startswith('SPORTS_DATABASE_URL='):
                return line.split('=', 1)[1].strip().split('?')[0]
    return ''

def create_venue_data():
    db_url = load_db_url()
    conn = psycopg2.connect(db_url)
    cur = conn.cursor()

    print("=" * 60)
    print("CREATE VENUE DATA WITH ALTITUDE")
    print(f"Time: {datetime.now(timezone.utc).isoformat()}")
    print("=" * 60)

    # Create table
    cur.execute('''
        CREATE TABLE IF NOT EXISTS "Venue" (
            id BIGSERIAL PRIMARY KEY,
            name VARCHAR(200),
            city VARCHAR(100),
            state VARCHAR(50),
            team VARCHAR(20),
            league VARCHAR(20),
            altitude_ft INT,
            timezone VARCHAR(50),
            capacity INT,
            latitude FLOAT,
            longitude FLOAT,
            "isOutdoor" BOOLEAN DEFAULT false,
            "surfaceType" VARCHAR(50),
            "createdAt" TIMESTAMP DEFAULT NOW(),
            UNIQUE(team, league)
        )
    ''')
    cur.execute('CREATE INDEX IF NOT EXISTS "Venue_altitude" ON "Venue" (altitude_ft DESC)')
    cur.execute('CREATE INDEX IF NOT EXISTS "Venue_league" ON "Venue" (league)')

    total = 0
    for v in VENUES:
        cur.execute('''
            INSERT INTO "Venue" (name, city, state, team, league, altitude_ft, timezone, capacity)
            VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
            ON CONFLICT (team, league) DO UPDATE SET
                name = EXCLUDED.name,
                altitude_ft = EXCLUDED.altitude_ft,
                timezone = EXCLUDED.timezone
        ''', (v['name'], v['city'], v['state'], v['team'], v['league'],
              v['altitude_ft'], v['timezone'], v['capacity']))
        total += 1

    conn.commit()

    # Summary
    print("\nVenues by Altitude:")
    cur.execute('''
        SELECT league, team, city, altitude_ft
        FROM "Venue"
        WHERE altitude_ft > 3000
        ORDER BY altitude_ft DESC
    ''')
    for r in cur.fetchall():
        print(f"  {r[0].upper()} {r[1]} ({r[2]}): {r[3]} ft")

    print("\nVenue Count by League:")
    cur.execute('''
        SELECT league, COUNT(*) FROM "Venue" GROUP BY league ORDER BY COUNT(*) DESC
    ''')
    for r in cur.fetchall():
        print(f"  {r[0].upper()}: {r[1]} venues")

    cur.close()
    conn.close()
    print(f"\nTotal venues created: {total}")
    return total

if __name__ == '__main__':
    create_venue_data()
