/**
 * Data Integrity Test - 2026 Season Focus
 * Tests current season data accuracy across all leagues
 */

import { getSportsDb } from '../src/lib/sportsDb';
import * as directQuery from '../src/lib/directSportsQuery';

interface TestResult {
  id: number;
  query: string;
  status: 'PASS' | 'PARTIAL' | 'NO_DATA' | 'FAIL';
  expected: string;
  actual: string;
  source: string;
}

const results: TestResult[] = [];
let testId = 0;

async function test(query: string, expected: string, testFn: () => Promise<{ pass: boolean; actual: string; source: string }>): Promise<void> {
  testId++;
  try {
    const result = await testFn();
    results.push({
      id: testId,
      query,
      status: result.pass ? 'PASS' : 'NO_DATA',
      expected,
      actual: result.actual,
      source: result.source
    });
  } catch (error: any) {
    results.push({
      id: testId,
      query,
      status: 'FAIL',
      expected,
      actual: `Error: ${error.message?.slice(0, 80)}`,
      source: 'error'
    });
  }
}

async function main() {
  console.log('═'.repeat(70));
  console.log('        DATA INTEGRITY TEST - 2026 SEASON FOCUS');
  console.log('        Current Date: ' + new Date().toISOString().slice(0, 10));
  console.log('═'.repeat(70));
  console.log();

  const db = getSportsDb();

  // ════════════════════════════════════════════════════════════════════
  // NFL 2025-26 SEASON
  // ════════════════════════════════════════════════════════════════════
  console.log('🏈 NFL 2025-26 SEASON\n');

  await test(
    'Super Bowl LX matchup and odds',
    'Seahawks vs Patriots with betting lines',
    async () => {
      const sb = await db.sportsGame.findFirst({
        where: {
          league: 'nfl',
          gameDate: { gte: new Date('2026-02-08'), lte: new Date('2026-02-10') }
        }
      });
      if (sb) {
        return {
          pass: true,
          actual: `${sb.awayTeam} vs ${sb.homeTeam} | ML: ${sb.moneylineAway}/${sb.moneylineHome} | Spread: ${sb.spreadHome} | O/U: ${sb.total}`,
          source: 'Database'
        };
      }
      return { pass: false, actual: 'Not found', source: 'Database' };
    }
  );

  await test(
    'AFC Championship result',
    'Patriots beat Broncos',
    async () => {
      const game = await db.sportsGame.findFirst({
        where: {
          league: 'nfl',
          gameDate: { gte: new Date('2026-01-24'), lte: new Date('2026-01-26') },
          OR: [
            { homeTeam: { contains: 'Patriots', mode: 'insensitive' } },
            { awayTeam: { contains: 'Patriots', mode: 'insensitive' } }
          ],
          homeScore: { not: null }
        }
      });
      if (game) {
        const winner = (game.homeScore || 0) > (game.awayScore || 0) ? game.homeTeam : game.awayTeam;
        return {
          pass: true,
          actual: `${game.awayTeam} ${game.awayScore} - ${game.homeTeam} ${game.homeScore} | Winner: ${winner}`,
          source: 'Database'
        };
      }
      return { pass: false, actual: 'Not found', source: 'Database' };
    }
  );

  await test(
    'NFC Championship result',
    'Seahawks beat 49ers',
    async () => {
      const game = await db.sportsGame.findFirst({
        where: {
          league: 'nfl',
          gameDate: { gte: new Date('2026-01-17'), lte: new Date('2026-01-19') },
          OR: [
            { homeTeam: { contains: 'Seahawks', mode: 'insensitive' } },
            { awayTeam: { contains: 'Seahawks', mode: 'insensitive' } }
          ],
          homeScore: { not: null }
        }
      });
      if (game) {
        const winner = (game.homeScore || 0) > (game.awayScore || 0) ? game.homeTeam : game.awayTeam;
        return {
          pass: true,
          actual: `${game.awayTeam} ${game.awayScore} - ${game.homeTeam} ${game.homeScore} | Winner: ${winner}`,
          source: 'Database'
        };
      }
      return { pass: false, actual: 'Not found', source: 'Database' };
    }
  );

  await test(
    'NFL 2025-26 season game count',
    '250+ games with scores',
    async () => {
      const count = await db.sportsGame.count({
        where: { league: 'nfl', season: 2025, homeScore: { not: null } }
      });
      return {
        pass: count >= 200,
        actual: `${count} games with scores`,
        source: 'Database'
      };
    }
  );

  // ════════════════════════════════════════════════════════════════════
  // NBA 2025-26 SEASON
  // ════════════════════════════════════════════════════════════════════
  console.log('\n🏀 NBA 2025-26 SEASON\n');

  await test(
    'NBA games today/recent',
    'Current NBA games with scores',
    async () => {
      const today = new Date().toISOString().slice(0, 10);
      const games = await db.sportsGame.findMany({
        where: {
          league: 'nba',
          gameDate: { gte: new Date(today + 'T00:00:00Z'), lte: new Date(today + 'T23:59:59Z') }
        },
        take: 10
      });

      // Also try ESPN for live
      const espn = await directQuery.fetchLiveScoresFromApi('nba');

      if (games.length > 0 || (espn && espn.games.length > 0)) {
        const dbGames = games.map(g => `${g.awayTeam}@${g.homeTeam}`).join(', ');
        const liveGames = espn?.games.slice(0, 3).map(g => `${g.awayTeam} ${g.awayScore || ''}-${g.homeScore || ''} ${g.homeTeam}`).join(', ');
        return {
          pass: true,
          actual: `DB: ${games.length} games | ESPN Live: ${liveGames || 'none'}`,
          source: 'Database + ESPN'
        };
      }
      return { pass: false, actual: 'No games today', source: 'Database' };
    }
  );

  await test(
    'NBA 2025-26 season coverage',
    'Full season games and props',
    async () => {
      const [games, props, stats] = await Promise.all([
        db.sportsGame.count({ where: { league: 'nba', season: { gte: 2025 } } }),
        db.playerPropLine.count({ where: { league: 'nba' } }),
        db.playerGameMetric.count({ where: { league: 'nba', season: { gte: 2025 } } })
      ]);
      return {
        pass: games > 500 && props > 10000,
        actual: `${games} games | ${props} props | ${stats} player stats`,
        source: 'Database'
      };
    }
  );

  await test(
    'NBA standings leaders 2025-26',
    'Top teams with records',
    async () => {
      const standings = await db.$queryRaw<any[]>`
        SELECT team, wins, losses, "winPct"
        FROM "TeamStanding"
        WHERE league = 'nba' AND season = 2025
        ORDER BY wins DESC
        LIMIT 5
      `;
      if (standings.length > 0) {
        return {
          pass: true,
          actual: standings.map(s => `${s.team}: ${s.wins}-${s.losses}`).join(' | '),
          source: 'Database'
        };
      }

      // Fallback: calculate from games
      const records = await db.$queryRaw<any[]>`
        SELECT team, SUM(wins) as wins, SUM(losses) as losses FROM (
          SELECT "homeTeam" as team,
                 SUM(CASE WHEN "homeScore" > "awayScore" THEN 1 ELSE 0 END) as wins,
                 SUM(CASE WHEN "homeScore" < "awayScore" THEN 1 ELSE 0 END) as losses
          FROM "SportsGame" WHERE league = 'nba' AND season >= 2025 AND "homeScore" IS NOT NULL
          GROUP BY "homeTeam"
          UNION ALL
          SELECT "awayTeam" as team,
                 SUM(CASE WHEN "awayScore" > "homeScore" THEN 1 ELSE 0 END) as wins,
                 SUM(CASE WHEN "awayScore" < "homeScore" THEN 1 ELSE 0 END) as losses
          FROM "SportsGame" WHERE league = 'nba' AND season >= 2025 AND "homeScore" IS NOT NULL
          GROUP BY "awayTeam"
        ) t GROUP BY team ORDER BY wins DESC LIMIT 5
      `;
      if (records.length > 0) {
        return {
          pass: true,
          actual: records.map(r => `${r.team}: ${r.wins}-${r.losses}`).join(' | '),
          source: 'Calculated'
        };
      }
      return { pass: false, actual: 'No standings data', source: 'Database' };
    }
  );

  // ════════════════════════════════════════════════════════════════════
  // NHL 2025-26 SEASON
  // ════════════════════════════════════════════════════════════════════
  console.log('\n🏒 NHL 2025-26 SEASON\n');

  await test(
    'NHL 2025-26 game coverage',
    'Regular season games',
    async () => {
      const [games, props] = await Promise.all([
        db.sportsGame.count({ where: { league: 'nhl', season: { gte: 2025 } } }),
        db.playerPropLine.count({ where: { league: 'nhl' } })
      ]);
      return {
        pass: games > 500,
        actual: `${games} games | ${props} props`,
        source: 'Database'
      };
    }
  );

  await test(
    'NHL recent games with scores',
    'Last week of NHL results',
    async () => {
      const weekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
      const games = await db.sportsGame.findMany({
        where: {
          league: 'nhl',
          gameDate: { gte: weekAgo },
          homeScore: { not: null }
        },
        orderBy: { gameDate: 'desc' },
        take: 5
      });
      if (games.length > 0) {
        return {
          pass: true,
          actual: games.map(g => `${g.awayTeam} ${g.awayScore}-${g.homeScore} ${g.homeTeam}`).join(' | '),
          source: 'Database'
        };
      }
      return { pass: false, actual: 'No recent games', source: 'Database' };
    }
  );

  // ════════════════════════════════════════════════════════════════════
  // MLB 2025 SEASON (Offseason now)
  // ════════════════════════════════════════════════════════════════════
  console.log('\n⚾ MLB 2025 SEASON\n');

  await test(
    'MLB 2025 season coverage',
    '2000+ games from 2025 season',
    async () => {
      const [games, stats] = await Promise.all([
        db.sportsGame.count({ where: { league: 'mlb', season: 2025 } }),
        db.playerGameMetric.count({ where: { league: 'mlb', season: 2025 } })
      ]);
      return {
        pass: games > 2000,
        actual: `${games} games | ${stats} player stats`,
        source: 'Database'
      };
    }
  );

  await test(
    'MLB 2025 HR leaders',
    'Top home run hitters',
    async () => {
      const leaders = await db.$queryRaw<any[]>`
        SELECT "playerName", SUM(value) as hrs
        FROM "PlayerGameMetric"
        WHERE league = 'mlb' AND season = 2025 AND "statKey" IN ('HR', 'home_runs', 'homeRuns')
        GROUP BY "playerName"
        ORDER BY hrs DESC
        LIMIT 5
      `;
      if (leaders.length > 0) {
        return {
          pass: true,
          actual: leaders.map(l => `${l.playerName}: ${l.hrs}`).join(' | '),
          source: 'Database'
        };
      }
      return { pass: false, actual: 'No HR data', source: 'Database' };
    }
  );

  // ════════════════════════════════════════════════════════════════════
  // PLAYER PROPS 2026
  // ════════════════════════════════════════════════════════════════════
  console.log('\n📊 PLAYER PROPS (Current)\n');

  await test(
    'NBA player props available',
    'Props for upcoming games',
    async () => {
      const props = await db.playerPropLine.findMany({
        where: { league: 'nba' },
        orderBy: { createdAt: 'desc' },
        take: 10
      });
      if (props.length > 0) {
        const sample = props.slice(0, 3).map(p => `${p.playerExternalId}: ${p.propType} ${p.lineValue}`);
        return {
          pass: true,
          actual: `${props.length} recent props | Ex: ${sample.join(', ')}`,
          source: 'Database'
        };
      }
      return { pass: false, actual: 'No props', source: 'Database' };
    }
  );

  await test(
    'NFL Super Bowl player props',
    'Props for Super Bowl LX',
    async () => {
      const sbGame = await db.sportsGame.findFirst({
        where: {
          league: 'nfl',
          gameDate: { gte: new Date('2026-02-08'), lte: new Date('2026-02-10') }
        }
      });

      if (sbGame) {
        const props = await db.playerPropLine.findMany({
          where: { gameId: sbGame.id },
          take: 10
        });
        if (props.length > 0) {
          return {
            pass: true,
            actual: `${props.length} props for Super Bowl`,
            source: 'Database'
          };
        }
      }
      return { pass: false, actual: 'No Super Bowl props yet', source: 'Database' };
    }
  );

  // ════════════════════════════════════════════════════════════════════
  // LIVE API VERIFICATION
  // ════════════════════════════════════════════════════════════════════
  console.log('\n🌐 LIVE API VERIFICATION\n');

  await test(
    'ESPN API - NBA live scores',
    'Real-time NBA data',
    async () => {
      const scores = await directQuery.fetchLiveScoresFromApi('nba');
      if (scores && scores.games.length > 0) {
        const sample = scores.games.slice(0, 2).map(g =>
          `${g.awayTeam} ${g.awayScore || 'vs'} ${g.homeTeam} ${g.homeScore || ''} (${g.status})`
        );
        return {
          pass: true,
          actual: sample.join(' | '),
          source: 'ESPN API'
        };
      }
      return { pass: false, actual: 'No live games', source: 'ESPN API' };
    }
  );

  await test(
    'ESPN API - NHL live scores',
    'Real-time NHL data',
    async () => {
      const scores = await directQuery.fetchLiveScoresFromApi('nhl');
      if (scores && scores.games.length > 0) {
        const sample = scores.games.slice(0, 2).map(g =>
          `${g.awayTeam} ${g.awayScore || 'vs'} ${g.homeTeam} ${g.homeScore || ''}`
        );
        return {
          pass: true,
          actual: sample.join(' | '),
          source: 'ESPN API'
        };
      }
      return { pass: false, actual: 'No live games', source: 'ESPN API' };
    }
  );

  await test(
    'System health check',
    'All systems operational',
    async () => {
      const health = await directQuery.getSystemHealth();
      return {
        pass: health.status !== 'error',
        actual: `${health.status.toUpperCase()} - ${health.checks.map(c => `${c.name}:${c.status}`).join(', ')}`,
        source: 'System'
      };
    }
  );

  // ════════════════════════════════════════════════════════════════════
  // RESULTS SUMMARY
  // ════════════════════════════════════════════════════════════════════
  console.log('\n' + '═'.repeat(70));
  console.log('                    2026 DATA INTEGRITY RESULTS');
  console.log('═'.repeat(70) + '\n');

  const passed = results.filter(r => r.status === 'PASS').length;
  const noData = results.filter(r => r.status === 'NO_DATA').length;
  const failed = results.filter(r => r.status === 'FAIL').length;

  // Print each result
  for (const r of results) {
    const emoji = r.status === 'PASS' ? '✅' : r.status === 'NO_DATA' ? '📭' : '❌';
    console.log(`${emoji} #${r.id}: ${r.query}`);
    console.log(`   ${r.actual}`);
    console.log(`   [${r.source}]`);
    console.log();
  }

  console.log('═'.repeat(70));
  console.log(`  PASSED: ${passed}/${results.length} | NO DATA: ${noData} | FAILED: ${failed}`);
  console.log(`  ACCURACY: ${((passed / results.length) * 100).toFixed(1)}%`);
  console.log('═'.repeat(70));

  process.exit(0);
}

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