#!/bin/bash
# Daily Canonical Roster Sync
# Ensures player team assignments are current after trades/signings
# Run: Daily at 8 AM UTC (before game prep)
# Cron: 0 8 * * * /var/www/html/eventheodds/scripts/cron-sync-canonical-rosters.sh

set -e

LOG_FILE="/var/log/eventheodds/canonical-roster-sync.log"
SCRIPTS_DIR="/var/www/html/eventheodds/scripts"

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

mkdir -p /var/log/eventheodds

log "=========================================="
log "Starting canonical roster sync..."
log "=========================================="

cd /var/www/html/eventheodds

# Step 1: Sync rosters from ESPN (updates team assignments for traded players)
log "Step 1: Syncing team rosters from ESPN..."
npx tsx "$SCRIPTS_DIR/sync-rosters.ts" >> "$LOG_FILE" 2>&1 || log "WARNING: Roster sync had errors"

# Step 2: Run unified sync to link any new/unlinked data
log "Step 2: Running unified sync pipeline..."
npx tsx "$SCRIPTS_DIR/unified-sync.ts" --full >> "$LOG_FILE" 2>&1 || log "WARNING: Unified sync had errors"

# Step 3: Run name-based linking for any remaining unlinked metrics
log "Step 3: Running name-based linking..."
npx tsx "$SCRIPTS_DIR/link-by-name.ts" >> "$LOG_FILE" 2>&1 || log "WARNING: Name-based linking had errors"

# Step 4: Record sync timestamp for monitoring
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
echo "$TIMESTAMP" > /var/www/html/eventheodds/logs/last-canonical-sync.txt

# Step 5: Generate coverage report
log "Step 4: Generating coverage report..."
psql "$SPORTS_DATABASE_URL" -c "
SELECT
    'PlayerPropLine' as table_name,
    league,
    COUNT(*) as total,
    COUNT(CASE WHEN \"canonicalPlayerId\" IS NOT NULL THEN 1 END) as linked,
    ROUND(COUNT(CASE WHEN \"canonicalPlayerId\" IS NOT NULL THEN 1 END)::numeric / NULLIF(COUNT(*), 0) * 100, 1) as pct
FROM \"PlayerPropLine\"
GROUP BY league
UNION ALL
SELECT
    'PlayerGameMetric' as table_name,
    league,
    COUNT(*) as total,
    COUNT(CASE WHEN \"canonicalPlayerId\" IS NOT NULL THEN 1 END) as linked,
    ROUND(COUNT(CASE WHEN \"canonicalPlayerId\" IS NOT NULL THEN 1 END)::numeric / NULLIF(COUNT(*), 0) * 100, 1) as pct
FROM \"PlayerGameMetric\"
GROUP BY league
ORDER BY table_name, league;
" >> "$LOG_FILE" 2>&1

log "=========================================="
log "Canonical roster sync completed."
log "=========================================="
