/**
 * Update NBA Player Teams from BallDontLie API
 * This fetches current roster data and updates player team assignments
 */
import { PrismaClient } from '../prisma_sports/generated/sports-client';

const BDL_API = 'https://api.balldontlie.io/v1';
const BDL_KEY = process.env.BALLDONTLIE_API_KEY || '';

interface BdlPlayer {
  id: number;
  first_name: string;
  last_name: string;
  position: string;
  team: {
    id: number;
    abbreviation: string;
    full_name: string;
  };
}

async function fetchAllPlayers(): Promise<BdlPlayer[]> {
  const players: BdlPlayer[] = [];
  let cursor: number | null = null;

  console.log('Fetching players from BallDontLie API...');

  for (let page = 0; page < 20; page++) { // Max 20 pages
    const url = new URL(`${BDL_API}/players`);
    url.searchParams.set('per_page', '100');
    if (cursor) url.searchParams.set('cursor', String(cursor));

    const res = await fetch(url.toString(), {
      headers: BDL_KEY ? { 'Authorization': BDL_KEY } : {},
    });

    if (!res.ok) {
      console.error(`BDL API error: ${res.status}`);
      break;
    }

    const data = await res.json();
    if (!data.data?.length) break;

    players.push(...data.data);
    console.log(`  Fetched ${players.length} players...`);

    cursor = data.meta?.next_cursor;
    if (!cursor) break;

    await new Promise(r => setTimeout(r, 200)); // Rate limit
  }

  return players;
}

async function main() {
  const prisma = new PrismaClient();

  try {
    // Fetch current player data from BDL
    const bdlPlayers = await fetchAllPlayers();
    console.log(`\nFetched ${bdlPlayers.length} players from BallDontLie`);

    // Build a map of player name -> team abbreviation
    const playerTeams = new Map<string, string>();
    for (const p of bdlPlayers) {
      const name = `${p.first_name} ${p.last_name}`;
      if (p.team?.abbreviation) {
        playerTeams.set(name.toLowerCase(), p.team.abbreviation);
      }
    }
    console.log(`Built team map with ${playerTeams.size} entries`);

    // Update players in database
    let updated = 0;
    let notFound = 0;

    const dbPlayers = await prisma.player.findMany({
      where: { league: 'nba' },
      select: { id: true, name: true, team: true },
    });

    console.log(`\nUpdating ${dbPlayers.length} NBA players in database...`);

    for (const player of dbPlayers) {
      const currentTeam = playerTeams.get(player.name.toLowerCase());
      const oldTeam = player.team || 'NULL';
      if (currentTeam && currentTeam !== player.team) {
        await prisma.player.update({
          where: { id: player.id },
          data: { team: currentTeam, updatedAt: new Date() },
        });
        updated++;
        if (updated <= 30) {
          console.log(`  Updated: ${player.name}: ${oldTeam} -> ${currentTeam}`);
        }
      } else if (!currentTeam) {
        notFound++;
      }
    }

    console.log(`\n=== COMPLETE ===`);
    console.log(`Updated: ${updated} players`);
    console.log(`Not found in BDL: ${notFound} players`);

  } finally {
    await prisma.$disconnect();
  }
}

main().catch(console.error);
