#!/usr/bin/env npx tsx
/**
 * Remove duplicate games from SportsDB
 * Keeps games from TheSportsDB (tsdb_*) over TheOddsAPI when duplicates exist
 */
require('dotenv').config({ path: '.env.local' });
require('dotenv').config({ path: '.env' });

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

async function main() {
  const prisma = getSportsDb();
  const leagues = ['nba', 'nfl', 'nhl', 'mlb'];
  let totalDeleted = 0;

  for (const league of leagues) {
    console.log(`\n=== Processing ${league.toUpperCase()} ===`);

    // Get all games for this league
    const games = await prisma.sportsGame.findMany({
      where: { league },
      orderBy: { gameDate: 'asc' },
      select: {
        id: true,
        gameDate: true,
        homeTeam: true,
        awayTeam: true,
        externalGameId: true,
        homeScore: true,
        moneylineHome: true,
      },
    });

    console.log(`Total games: ${games.length}`);

    // Group by matchup + date
    const groups = new Map<string, typeof games>();
    for (const game of games) {
      const dateStr = game.gameDate.toISOString().split('T')[0];
      const key = `${game.awayTeam}-${game.homeTeam}-${dateStr}`;

      if (!groups.has(key)) {
        groups.set(key, []);
      }
      groups.get(key)!.push(game);
    }

    // Find duplicates and decide which to delete
    const toDelete: number[] = [];
    let duplicateCount = 0;

    for (const [key, dupes] of groups) {
      if (dupes.length > 1) {
        duplicateCount++;

        // Sort: prefer tsdb entries, then ones with more data
        dupes.sort((a, b) => {
          // Prefer tsdb_ sources
          const aIsTsdb = a.externalGameId?.startsWith('tsdb_') ? 1 : 0;
          const bIsTsdb = b.externalGameId?.startsWith('tsdb_') ? 1 : 0;
          if (aIsTsdb !== bIsTsdb) return bIsTsdb - aIsTsdb;

          // Prefer entries with scores
          const aHasScore = a.homeScore !== null ? 1 : 0;
          const bHasScore = b.homeScore !== null ? 1 : 0;
          if (aHasScore !== bHasScore) return bHasScore - aHasScore;

          // Prefer entries with odds
          const aHasOdds = a.moneylineHome !== null ? 1 : 0;
          const bHasOdds = b.moneylineHome !== null ? 1 : 0;
          return bHasOdds - aHasOdds;
        });

        // Keep the first, delete the rest
        for (let i = 1; i < dupes.length; i++) {
          toDelete.push(dupes[i].id);
        }
      }
    }

    console.log(`Duplicate groups: ${duplicateCount}`);
    console.log(`Games to delete: ${toDelete.length}`);

    if (toDelete.length > 0) {
      const result = await prisma.sportsGame.deleteMany({
        where: { id: { in: toDelete } },
      });
      console.log(`Deleted: ${result.count}`);
      totalDeleted += result.count;
    }
  }

  console.log(`\n=== Summary ===`);
  console.log(`Total deleted: ${totalDeleted}`);
}

main().catch(console.error);
