#!/usr/bin/env python3
"""
NHL Goalie Stats Scraper
Fetches goalie statistics from NHL API
Run: Weekly Monday 3:00 AM UTC
"""
import requests
import json
import os
from datetime import datetime, timezone

NHL_API_BASE = "https://api-web.nhle.com/v1"
DATA_DIR = "/var/www/html/eventheodds/data"

def fetch_goalie_stats(season="20242025"):
    """Fetch goalie stats from NHL API"""
    print(f"[{datetime.now()}] Fetching NHL goalie stats for season {season}...")

    url = f"{NHL_API_BASE}/goalie-stats-leaders/{season}/2"

    try:
        resp = requests.get(url, timeout=30)
        if resp.status_code != 200:
            print(f"  NHL API returned {resp.status_code}")
            return None

        data = resp.json()
        goalies = []

        # Process different stat categories
        for category in ['wins', 'savePctg', 'goalsAgainstAverage', 'shutouts']:
            if category in data:
                for goalie in data[category]:
                    goalies.append({
                        'playerId': goalie.get('playerId'),
                        'firstName': goalie.get('firstName', {}).get('default', ''),
                        'lastName': goalie.get('lastName', {}).get('default', ''),
                        'teamAbbrev': goalie.get('teamAbbrevs', ''),
                        'gamesPlayed': goalie.get('gamesPlayed'),
                        'wins': goalie.get('wins'),
                        'losses': goalie.get('losses'),
                        'otLosses': goalie.get('otLosses'),
                        'savePctg': goalie.get('savePctg'),
                        'goalsAgainstAvg': goalie.get('goalsAgainstAverage'),
                        'shutouts': goalie.get('shutouts'),
                        'category': category,
                    })

        # Dedupe by playerId, keeping most complete record
        seen = {}
        for g in goalies:
            pid = g['playerId']
            if pid not in seen:
                seen[pid] = g
            else:
                # Merge stats
                for k, v in g.items():
                    if v is not None and seen[pid].get(k) is None:
                        seen[pid][k] = v

        return list(seen.values())

    except Exception as e:
        print(f"  Error fetching goalie stats: {e}")
        return None


def save_goalie_stats(goalies):
    """Save goalie stats to JSON file"""
    os.makedirs(DATA_DIR, exist_ok=True)
    output_path = os.path.join(DATA_DIR, 'nhl_goalie_stats.json')

    with open(output_path, 'w') as f:
        json.dump({
            'goalies': goalies,
            'count': len(goalies),
            'timestamp': datetime.now(timezone.utc).isoformat(),
        }, f, indent=2)

    print(f"  Saved {len(goalies)} goalie records to {output_path}")


def main():
    print("=" * 60)
    print("NHL GOALIE STATS SCRAPER")
    print("=" * 60)

    goalies = fetch_goalie_stats()

    if goalies:
        save_goalie_stats(goalies)
        print(f"\n✅ Successfully fetched {len(goalies)} NHL goalies")
    else:
        print("\n❌ Failed to fetch goalie stats")


if __name__ == '__main__':
    main()
