#!/usr/bin/env npx tsx
/**
 * Normalize Data - Fix team names and stat keys across all leagues
 * 
 * Usage:
 *   npx tsx src/scripts/normalizeData.ts --league=nba --dry-run
 *   npx tsx src/scripts/normalizeData.ts --league=nba --apply
 *   npx tsx src/scripts/normalizeData.ts --all --apply
 */

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

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

interface NormalizationResult {
  league: string;
  teamsNormalized: number;
  statsNormalized: number;
  errors: string[];
}

async function normalizeTeamNames(
  prisma: any,
  league: string,
  dryRun: boolean
): Promise<{ count: number; changes: string[] }> {
  const teams = league === 'nba' ? NBA_TEAMS : NFL_TEAMS;
  let totalCount = 0;
  const changes: string[] = [];

  for (const team of teams) {
    for (const alias of team.aliases) {
      // Skip if alias is same as canonical
      if (alias.toLowerCase() === team.canonical.toLowerCase()) continue;

      // Count affected rows
      const homeCount = await prisma.sportsGame.count({
        where: { league, homeTeam: alias }
      });
      const awayCount = await prisma.sportsGame.count({
        where: { league, awayTeam: alias }
      });

      if (homeCount > 0 || awayCount > 0) {
        changes.push(`${alias} → ${team.canonical} (${homeCount} home, ${awayCount} away)`);
        totalCount += homeCount + awayCount;

        if (!dryRun) {
          // Update home teams
          if (homeCount > 0) {
            await prisma.sportsGame.updateMany({
              where: { league, homeTeam: alias },
              data: { homeTeam: team.canonical }
            });
          }
          // Update away teams
          if (awayCount > 0) {
            await prisma.sportsGame.updateMany({
              where: { league, awayTeam: alias },
              data: { awayTeam: team.canonical }
            });
          }
        }
      }
    }
  }

  return { count: totalCount, changes };
}

async function normalizeStatKeys(
  prisma: any, 
  league: string,
  dryRun: boolean
): Promise<{ count: number; changes: string[] }> {
  // Map of alias → canonical for this league
  const statMappings: Record<string, string> = {
    // NBA
    threes: 'threePointersMade',
    '3PM': 'threePointersMade',
    fg3m: 'threePointersMade',
    pts: 'points',
    reb: 'rebounds',
    ast: 'assists',
    stl: 'steals',
    blk: 'blocks',
    // Add more as needed
  };

  let totalCount = 0;
  const changes: string[] = [];

  for (const [alias, canonical] of Object.entries(statMappings)) {
    const count = await prisma.playerGameMetric.count({
      where: { league, statKey: alias }
    });

    if (count > 0) {
      changes.push(`${alias} → ${canonical} (${count} records)`);
      totalCount += count;

      if (!dryRun) {
        await prisma.playerGameMetric.updateMany({
          where: { league, statKey: alias },
          data: { statKey: canonical }
        });
      }
    }
  }

  return { count: totalCount, changes };
}

async function runNormalization(league: string, dryRun: boolean): Promise<NormalizationResult> {
  const prisma = getSportsDb();
  const result: NormalizationResult = {
    league,
    teamsNormalized: 0,
    statsNormalized: 0,
    errors: []
  };

  console.log(`\n📊 Normalizing ${league.toUpperCase()} data${dryRun ? ' (DRY RUN)' : ''}...`);

  // Normalize team names
  console.log('\n  🏟️  Team name normalization:');
  try {
    const teamResult = await normalizeTeamNames(prisma, league, dryRun);
    result.teamsNormalized = teamResult.count;
    if (teamResult.changes.length > 0) {
      teamResult.changes.forEach(c => console.log(`     ${c}`));
    } else {
      console.log('     No changes needed');
    }
  } catch (err: any) {
    result.errors.push(`Team normalization error: ${err.message}`);
    console.log(`     ❌ Error: ${err.message}`);
  }

  // Normalize stat keys (only for NBA/NFL for now)
  if (['nba', 'nfl'].includes(league)) {
    console.log('\n  📈 Stat key normalization:');
    try {
      const statResult = await normalizeStatKeys(prisma, league, dryRun);
      result.statsNormalized = statResult.count;
      if (statResult.changes.length > 0) {
        statResult.changes.forEach(c => console.log(`     ${c}`));
      } else {
        console.log('     No changes needed');
      }
    } catch (err: any) {
      result.errors.push(`Stat normalization error: ${err.message}`);
      console.log(`     ❌ Error: ${err.message}`);
    }
  }

  return result;
}

async function main() {
  const args = process.argv.slice(2);
  const dryRun = !args.includes('--apply');
  const allLeagues = args.includes('--all');
  const leagueArg = args.find(a => a.startsWith('--league='));
  const league = leagueArg?.split('=')[1]?.toLowerCase();

  console.log('🔧 Data Normalization Tool');
  console.log('='.repeat(50));

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

  const leagues = allLeagues ? ['nba', 'nfl', 'nhl', 'mlb'] : (league ? [league] : []);

  if (leagues.length === 0) {
    console.log('\nUsage:');
    console.log('  npx tsx src/scripts/normalizeData.ts --league=nba --dry-run');
    console.log('  npx tsx src/scripts/normalizeData.ts --league=nba --apply');
    console.log('  npx tsx src/scripts/normalizeData.ts --all --apply');
    process.exit(0);
  }

  if (dryRun) {
    console.log('\n⚠️  DRY RUN MODE - No changes will be made');
    console.log('   Add --apply to actually update the database');
  }

  const results: NormalizationResult[] = [];

  for (const l of leagues) {
    const result = await runNormalization(l, dryRun);
    results.push(result);
  }

  // Summary
  console.log('\n' + '='.repeat(50));
  console.log('📋 NORMALIZATION SUMMARY');
  console.log('='.repeat(50));

  let totalTeams = 0;
  let totalStats = 0;

  for (const r of results) {
    console.log(`\n  ${r.league.toUpperCase()}:`);
    console.log(`    Teams: ${r.teamsNormalized} records`);
    console.log(`    Stats: ${r.statsNormalized} records`);
    if (r.errors.length > 0) {
      console.log(`    Errors: ${r.errors.length}`);
    }
    totalTeams += r.teamsNormalized;
    totalStats += r.statsNormalized;
  }

  console.log(`\n  TOTAL: ${totalTeams} team records, ${totalStats} stat records`);

  if (dryRun && (totalTeams > 0 || totalStats > 0)) {
    console.log('\n  💡 Run with --apply to execute these changes');
  }

  console.log('\n✅ Done!');
}

main().catch(console.error);
