#!/usr/bin/env npx tsx
/**
 * Sync all players from saved ESPN roster JSON
 */

import { PrismaClient } from '../prisma_sports/generated/sports-client';
import * as fs from 'fs';

const prisma = new PrismaClient();

function normalizePlayerName(name: string): string {
  if (!name) return '';
  return name
    .toLowerCase()
    .normalize('NFD')
    .replace(/[\u0300-\u036f]/g, '')
    .replace(/\s+(jr\.?|sr\.?|iii|ii|iv|v)$/i, '')
    .replace(/\./g, '')
    .replace(/\s+/g, ' ')
    .trim();
}

async function main() {
  console.log('='.repeat(60));
  console.log('SYNC ALL PLAYERS FROM ESPN ROSTER JSON');
  console.log('='.repeat(60));

  // Load roster JSON
  const rosterPath = '/var/www/html/eventheodds/data/nba_current_rosters.json';
  const rosterData = JSON.parse(fs.readFileSync(rosterPath, 'utf-8'));

  console.log(`Roster data from: ${rosterData.lastUpdated}`);
  console.log(`Source: ${rosterData.source}\n`);

  // Get all canonical teams
  const teams = await prisma.canonicalTeam.findMany({
    where: { league: 'nba' },
    select: { id: true, abbr: true, fullName: true },
  });
  const teamByAbbr = new Map(teams.map(t => [t.abbr, t]));

  let totalUpdated = 0;
  let totalNotFound = 0;
  const changes: Array<{ player: string; from: string; to: string }> = [];

  for (const [teamAbbr, players] of Object.entries(rosterData.rosters)) {
    const team = teamByAbbr.get(teamAbbr);
    if (!team) {
      console.log(`[WARN] No canonical team for ${teamAbbr}`);
      continue;
    }

    for (const playerName of players as string[]) {
      const normalized = normalizePlayerName(playerName);
      if (!normalized) continue;

      const existingPlayer = await prisma.canonicalPlayer.findFirst({
        where: { league: 'nba', normalizedName: normalized },
        include: { team: true },
      });

      if (existingPlayer) {
        if (existingPlayer.teamId !== team.id) {
          const oldTeam = existingPlayer.team?.abbr || 'NONE';
          changes.push({ player: playerName, from: oldTeam, to: teamAbbr });

          await prisma.canonicalPlayer.update({
            where: { id: existingPlayer.id },
            data: { teamId: team.id },
          });
          totalUpdated++;
        }
      } else {
        totalNotFound++;
      }
    }
  }

  console.log('='.repeat(60));
  console.log('SUMMARY');
  console.log('='.repeat(60));
  console.log(`Total players updated: ${totalUpdated}`);
  console.log(`Players not in canonical table: ${totalNotFound}`);

  if (changes.length > 0) {
    console.log('\n' + '='.repeat(60));
    console.log('ALL TEAM CHANGES');
    console.log('='.repeat(60) + '\n');

    changes.forEach(c => {
      console.log(`${c.player}: ${c.from} → ${c.to}`);
    });
  }

  await prisma.$disconnect();
}

main().catch((e) => {
  console.error('Sync failed:', e);
  process.exit(1);
});
