#!/bin/bash
# Clear stale BallDontLie cache files
# Run daily to prevent stale player/roster data

CACHE_DIR="/var/www/html/eventheodds/data/balldontlie_cache"
LOCAL_DATA_DIR="/var/www/html/eventheodds/data"
MAX_AGE_HOURS=12

echo "=== Clearing Stale Cache - $(date) ==="

# Clear BDL cache files older than 12 hours
if [ -d "$CACHE_DIR" ]; then
  count=$(find "$CACHE_DIR" -type f -name "*.json" -mmin +$((MAX_AGE_HOURS * 60)) | wc -l)
  find "$CACHE_DIR" -type f -name "*.json" -mmin +$((MAX_AGE_HOURS * 60)) -delete
  echo "Cleared $count stale cache files from $CACHE_DIR"
fi

# Clear stale local NBA/NFL/etc data files (older than 24 hours)
for league in nba nfl nhl mlb; do
  if [ -d "$LOCAL_DATA_DIR/$league" ]; then
    for file in standings.json games.json players.json; do
      filepath="$LOCAL_DATA_DIR/$league/$file"
      if [ -f "$filepath" ]; then
        age_hours=$(( ($(date +%s) - $(stat -c %Y "$filepath")) / 3600 ))
        if [ $age_hours -gt 24 ]; then
          rm -f "$filepath"
          echo "Removed stale $filepath (${age_hours}h old)"
        fi
      fi
    done
  fi
done

echo "=== Cache clear complete ==="
