#!/usr/bin/env npx tsx
/**
 * Daily Roster Sync - Run via cron to keep 2026 rosters current
 *
 * Cron example (run daily at 6 AM):
 *   0 6 * * * cd /var/www/html/eventheodds && npx tsx src/scripts/dailyRosterSync.ts >> /var/log/roster-sync.log 2>&1
 */

require('dotenv').config({ path: '.env.local' });
require('dotenv').config({ path: '.env' });

import { getSportsDb, isSportsDbEnabled } from '../lib/sportsDb';

const NBA_TEAMS: Record<string, { id: string; abbrev: string }> = {
  'ATL': { id: '1', abbrev: 'ATL' }, 'BOS': { id: '2', abbrev: 'BOS' },
  'BKN': { id: '17', abbrev: 'BKN' }, 'CHA': { id: '30', abbrev: 'CHA' },
  'CHI': { id: '4', abbrev: 'CHI' }, 'CLE': { id: '5', abbrev: 'CLE' },
  'DAL': { id: '6', abbrev: 'DAL' }, 'DEN': { id: '7', abbrev: 'DEN' },
  'DET': { id: '8', abbrev: 'DET' }, 'GSW': { id: '9', abbrev: 'GSW' },
  'HOU': { id: '10', abbrev: 'HOU' }, 'IND': { id: '11', abbrev: 'IND' },
  'LAC': { id: '12', abbrev: 'LAC' }, 'LAL': { id: '13', abbrev: 'LAL' },
  'MEM': { id: '29', abbrev: 'MEM' }, 'MIA': { id: '14', abbrev: 'MIA' },
  'MIL': { id: '15', abbrev: 'MIL' }, 'MIN': { id: '16', abbrev: 'MIN' },
  'NOP': { id: '3', abbrev: 'NOP' }, 'NYK': { id: '18', abbrev: 'NYK' },
  'OKC': { id: '25', abbrev: 'OKC' }, 'ORL': { id: '19', abbrev: 'ORL' },
  'PHI': { id: '20', abbrev: 'PHI' }, 'PHX': { id: '21', abbrev: 'PHX' },
  'POR': { id: '22', abbrev: 'POR' }, 'SAC': { id: '23', abbrev: 'SAC' },
  'SAS': { id: '24', abbrev: 'SAS' }, 'TOR': { id: '28', abbrev: 'TOR' },
  'UTA': { id: '26', abbrev: 'UTA' }, 'WAS': { id: '27', abbrev: 'WAS' },
};

const NFL_TEAMS: Record<string, { id: string; abbrev: string }> = {
  'ARI': { id: '22', abbrev: 'ARI' }, 'ATL': { id: '1', abbrev: 'ATL' },
  'BAL': { id: '33', abbrev: 'BAL' }, 'BUF': { id: '2', abbrev: 'BUF' },
  'CAR': { id: '29', abbrev: 'CAR' }, 'CHI': { id: '3', abbrev: 'CHI' },
  'CIN': { id: '4', abbrev: 'CIN' }, 'CLE': { id: '5', abbrev: 'CLE' },
  'DAL': { id: '6', abbrev: 'DAL' }, 'DEN': { id: '7', abbrev: 'DEN' },
  'DET': { id: '8', abbrev: 'DET' }, 'GB': { id: '9', abbrev: 'GB' },
  'HOU': { id: '34', abbrev: 'HOU' }, 'IND': { id: '11', abbrev: 'IND' },
  'JAX': { id: '30', abbrev: 'JAX' }, 'KC': { id: '12', abbrev: 'KC' },
  'LV': { id: '13', abbrev: 'LV' }, 'LAC': { id: '24', abbrev: 'LAC' },
  'LAR': { id: '14', abbrev: 'LAR' }, 'MIA': { id: '15', abbrev: 'MIA' },
  'MIN': { id: '16', abbrev: 'MIN' }, 'NE': { id: '17', abbrev: 'NE' },
  'NO': { id: '18', abbrev: 'NO' }, 'NYG': { id: '19', abbrev: 'NYG' },
  'NYJ': { id: '20', abbrev: 'NYJ' }, 'PHI': { id: '21', abbrev: 'PHI' },
  'PIT': { id: '23', abbrev: 'PIT' }, 'SF': { id: '25', abbrev: 'SF' },
  'SEA': { id: '26', abbrev: 'SEA' }, 'TB': { id: '27', abbrev: 'TB' },
  'TEN': { id: '10', abbrev: 'TEN' }, 'WAS': { id: '28', abbrev: 'WAS' },
};

interface RosterPlayer {
  espnId: string;
  name: string;
  position: string;
  team: string;
}

async function fetchESPNRoster(league: string, teamAbbrev: string, teamId: string): Promise<RosterPlayer[]> {
  const sport = league === 'nba' ? 'basketball/nba' : 'football/nfl';
  const url = `https://site.api.espn.com/apis/site/v2/sports/${sport}/teams/${teamId}/roster`;

  try {
    const response = await fetch(url);
    if (!response.ok) return [];

    const data = await response.json();
    const players: RosterPlayer[] = [];
    const athletes = data.athletes || [];

    for (const item of athletes) {
      if (item.items) {
        for (const player of item.items) {
          if (player.fullName) {
            players.push({
              espnId: player.id,
              name: player.fullName,
              position: player.position?.abbreviation || '',
              team: teamAbbrev,
            });
          }
        }
      } else if (item.fullName) {
        players.push({
          espnId: item.id,
          name: item.fullName,
          position: item.position?.abbreviation || '',
          team: teamAbbrev,
        });
      }
    }

    return players;
  } catch {
    return [];
  }
}

async function syncLeague(league: string, prisma: any): Promise<number> {
  const teams = league === 'nba' ? NBA_TEAMS : NFL_TEAMS;
  let movements = 0;
  const currentSeason = new Date().getMonth() >= 9 ? new Date().getFullYear() + 1 : new Date().getFullYear();

  for (const [abbrev, team] of Object.entries(teams)) {
    const roster = await fetchESPNRoster(league, abbrev, team.id);

    for (const rosterPlayer of roster) {
      const dbPlayer = await prisma.player.findFirst({
        where: {
          name: { equals: rosterPlayer.name, mode: 'insensitive' },
          league: league,
        },
      });

      if (dbPlayer && dbPlayer.team) {
        const dbTeam = dbPlayer.team.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 3);
        const newTeam = rosterPlayer.team.toUpperCase();

        if (dbTeam !== newTeam && dbTeam !== newTeam.slice(0, 3)) {
          // Log transaction
          await prisma.playerTransaction.upsert({
            where: {
              league_externalPlayerId_transactionDate_toTeam: {
                league: league,
                externalPlayerId: rosterPlayer.espnId || '',
                transactionDate: new Date(),
                toTeam: rosterPlayer.team,
              },
            },
            create: {
              league: league,
              externalPlayerId: rosterPlayer.espnId,
              playerName: rosterPlayer.name,
              fromTeam: dbPlayer.team,
              toTeam: rosterPlayer.team,
              transactionType: 'roster_move',
              transactionDate: new Date(),
              season: currentSeason,
              source: 'espn_daily',
              verified: false,
            },
            update: {},
          });

          // Update player
          await prisma.player.update({
            where: { id: dbPlayer.id },
            data: {
              team: rosterPlayer.team,
              position: rosterPlayer.position || dbPlayer.position,
              updatedAt: new Date(),
            },
          });

          movements++;
          console.log(`  ${rosterPlayer.name}: ${dbPlayer.team} → ${rosterPlayer.team}`);
        }
      }
    }

    await new Promise(r => setTimeout(r, 100));
  }

  return movements;
}

async function main() {
  const timestamp = new Date().toISOString();
  console.log(`\n[${timestamp}] Daily Roster Sync Starting`);

  if (!isSportsDbEnabled()) {
    console.error('SportsDB not enabled');
    process.exit(1);
  }

  const prisma = getSportsDb();

  const nbaMovements = await syncLeague('nba', prisma);
  const nflMovements = await syncLeague('nfl', prisma);

  const total = nbaMovements + nflMovements;
  console.log(`[${timestamp}] Complete: ${total} movements (NBA: ${nbaMovements}, NFL: ${nflMovements})`);

  if (total > 0) {
    // Show recent transactions
    const recent = await prisma.playerTransaction.findMany({
      where: { source: 'espn_daily' },
      orderBy: { createdAt: 'desc' },
      take: 5,
    });
    console.log('Recent transactions:', recent.map(t => `${t.playerName}: ${t.fromTeam}→${t.toTeam}`).join(', '));
  }
}

main().catch(console.error);
