import json
from pathlib import Path
from datetime import datetime

DATA_DIR = Path("/var/www/html/eventheodds/data/betting")
metadata_file = DATA_DIR / "metadata.json"

print("="*60)
print("SYNCHRONIZING DATABASE METADATA")
print("="*60)

stats = []
total_games = 0
total_with_odds = 0

for f in sorted(DATA_DIR.glob("*_historical.json")):
    sport = f.stem.replace("_historical", "").lower()
    try:
        with open(f) as fh:
            data = json.load(fh)
        
        count = len(data)
        # Check for odds (moneylineHome or spreadHome)
        with_odds = sum(1 for g in data if (
            (g.get("odds", {}).get("moneylineHome") is not None) or 
            (g.get("home_ml") is not None) or
            (g.get("spread") is not None)
        ))
        
        stats.append({
            "sport": sport,
            "games": count,
            "hasOdds": with_odds > 0,
            "gamesWithOdds": with_odds
        })
        
        total_games += count
        total_with_odds += with_odds
        print(f"{sport:12} {count:6,} games ({with_odds:6,} with odds)")
    except Exception as e:
        print(f"Error processing {sport}: {e}")

metadata = {
    "importedAt": datetime.now().isoformat(),
    "source": "Unified Multi-Source (BallDontLie, The Odds API, Kaggle, Football-Data)",
    "totalGames": total_games,
    "gamesWithRealOdds": total_with_odds,
    "sports": stats,
    "seasons": "Multiple (varies by sport)",
    "dateRange": "1966-2025"
}

with open(metadata_file, "w") as f:
    json.dump(metadata, f, indent=2)

print("\n" + "="*60)
print(f"TOTAL RECORDS: {total_games:,}")
print(f"TOTAL W/ ODDS: {total_with_odds:,}")
print(f"Metadata updated in {metadata_file}")
print("="*60)
