const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

async function findUpcomingMatch() {
  // 1 gün sonraki maçları bul (4-5 Mart 2026)
  const tomorrow = new Date();
  tomorrow.setDate(tomorrow.getDate() + 1);
  tomorrow.setHours(0, 0, 0, 0);

  const dayAfter = new Date(tomorrow);
  dayAfter.setDate(dayAfter.getDate() + 1);

  console.log('\n========================================');
  console.log('📅 1 GÜN SONRAKİ MAÇLAR');
  console.log('========================================\n');

  // Timestamp'e çevir
  const startTs = BigInt(tomorrow.getTime());
  const endTs = BigInt(dayAfter.getTime());

  const matches = await prisma.match.findMany({
    where: {
      sport: 'football',
      mstUtc: {
        gte: startTs,
        lt: endTs,
      },
    },
    include: {
      homeTeam: true,
      awayTeam: true,
      league: true,
      oddCategories: {
        include: {
          selections: true,
        },
      },
      prediction: true,
      aiFeatures: true,
    },
    take: 5,
    orderBy: { mstUtc: 'asc' },
  });

  console.log(`Bulunan maç sayısı: ${matches.length}`);

  for (const match of matches) {
    console.log('\n----------------------------------------');
    console.log(
      `⚽ ${match.homeTeam?.name || 'N/A'} vs ${match.awayTeam?.name || 'N/A'}`,
    );
    console.log(`🏆 Lig: ${match.league?.name || 'N/A'}`);
    console.log(`📅 Tarih: ${new Date(Number(match.mstUtc)).toISOString()}`);
    console.log(`🔢 İddaa Kodu: ${match.iddaaCode || 'N/A'}`);
    console.log(`🏟️ Durum: ${match.state} / ${match.status}`);

    // Oranlar
    console.log('\n📊 ORANLAR:');
    for (const cat of match.oddCategories.slice(0, 5)) {
      console.log(`  ${cat.name}:`);
      for (const sel of cat.selections.slice(0, 5)) {
        console.log(`    - ${sel.name}: ${sel.oddValue}`);
      }
    }

    // AI Features
    if (match.aiFeatures) {
      console.log('\n🤖 AI ÖZELLİKLER:');
      console.log(`  Home ELO: ${match.aiFeatures.homeElo}`);
      console.log(`  Away ELO: ${match.aiFeatures.awayElo}`);
      console.log(`  Home Form: ${match.aiFeatures.homeFormScore}`);
      console.log(`  Away Form: ${match.aiFeatures.awayFormScore}`);
    }

    // Tahmin
    if (match.prediction) {
      console.log('\n🔮 MEVCUT TAHMİN:');
      console.log(
        JSON.stringify(match.prediction.predictionJson, null, 2).substring(
          0,
          500,
        ),
      );
    }
  }

  // Detaylı analiz için ilk maçı seç
  if (matches.length > 0) {
    const selectedMatch = matches[0];
    console.log('\n\n========================================');
    console.log('🎯 SEÇİLEN MAÇ DETAY ANALİZİ');
    console.log('========================================');
    console.log(`Maç ID: ${selectedMatch.id}`);

    // Bu maç için ne kadar verimiz var?
    console.log('\n📈 VERİ KALİTESİ ANALİZİ:');
    console.log(
      `  - Oran Kategorisi: ${selectedMatch.oddCategories.length} adet`,
    );

    let totalSelections = 0;
    for (const cat of selectedMatch.oddCategories) {
      totalSelections += cat.selections.length;
    }
    console.log(`  - Toplam Oran Seçeneği: ${totalSelections} adet`);
    console.log(`  - AI Features: ${selectedMatch.aiFeatures ? 'VAR' : 'YOK'}`);
    console.log(`  - Prediction: ${selectedMatch.prediction ? 'VAR' : 'YOK'}`);

    // Bu takımların geçmiş maçları
    console.log('\n📚 TAKIM GEÇMİŞİ:');

    // Ev sahibi takımın son maçları
    const homeTeamMatches = await prisma.match.findMany({
      where: {
        OR: [
          { homeTeamId: selectedMatch.homeTeamId },
          { awayTeamId: selectedMatch.homeTeamId },
        ],
        sport: 'football',
        state: 'postGame',
      },
      include: {
        homeTeam: true,
        awayTeam: true,
      },
      take: 5,
      orderBy: { mstUtc: 'desc' },
    });

    console.log(`\n  ${selectedMatch.homeTeam?.name} Son 5 Maç:`);
    for (const m of homeTeamMatches) {
      const isHome = m.homeTeamId === selectedMatch.homeTeamId;
      const goalsFor = isHome ? m.scoreHome : m.scoreAway;
      const goalsAgainst = isHome ? m.scoreAway : m.scoreHome;
      const result =
        goalsFor > goalsAgainst ? 'W' : goalsFor < goalsAgainst ? 'L' : 'D';
      console.log(
        `    ${result} ${m.homeTeam?.name} ${m.scoreHome}-${m.scoreAway} ${m.awayTeam?.name}`,
      );
    }

    // Deplasman takımının son maçları
    const awayTeamMatches = await prisma.match.findMany({
      where: {
        OR: [
          { homeTeamId: selectedMatch.awayTeamId },
          { awayTeamId: selectedMatch.awayTeamId },
        ],
        sport: 'football',
        state: 'postGame',
      },
      include: {
        homeTeam: true,
        awayTeam: true,
      },
      take: 5,
      orderBy: { mstUtc: 'desc' },
    });

    console.log(`\n  ${selectedMatch.awayTeam?.name} Son 5 Maç:`);
    for (const m of awayTeamMatches) {
      const isHome = m.homeTeamId === selectedMatch.awayTeamId;
      const goalsFor = isHome ? m.scoreHome : m.scoreAway;
      const goalsAgainst = isHome ? m.scoreAway : m.scoreHome;
      const result =
        goalsFor > goalsAgainst ? 'W' : goalsFor < goalsAgainst ? 'L' : 'D';
      console.log(
        `    ${result} ${m.homeTeam?.name} ${m.scoreHome}-${m.scoreAway} ${m.awayTeam?.name}`,
      );
    }

    // Head-to-Head
    console.log('\n🔄 HEAD-TO-HEAD (Karşılıklı):');
    const h2hMatches = await prisma.match.findMany({
      where: {
        OR: [
          {
            homeTeamId: selectedMatch.homeTeamId,
            awayTeamId: selectedMatch.awayTeamId,
          },
          {
            homeTeamId: selectedMatch.awayTeamId,
            awayTeamId: selectedMatch.homeTeamId,
          },
        ],
        sport: 'football',
        state: 'postGame',
      },
      include: {
        homeTeam: true,
        awayTeam: true,
      },
      take: 5,
      orderBy: { mstUtc: 'desc' },
    });

    if (h2hMatches.length > 0) {
      for (const m of h2hMatches) {
        console.log(
          `  ${m.homeTeam?.name} ${m.scoreHome}-${m.scoreAway} ${m.awayTeam?.name}`,
        );
      }
    } else {
      console.log('  Karşılıklı maç bulunamadı');
    }
  }

  await prisma.$disconnect();
}

findUpcomingMatch().catch((e) => {
  console.error('Hata:', e);
  process.exit(1);
});
