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

async function analyzeLearningProgress() {
  const prisma = new PrismaClient();
  
  try {
    console.log('🧠 AI Learning System Analysis Report\n');
    
    // Basic statistics
    const totalRecords = await prisma.ai_learning_data.count();
    console.log(`📊 Total Learning Records: ${totalRecords}`);
    
    // Symbol distribution
    const symbolStats = await prisma.ai_learning_data.groupBy({
      by: ['symbol'],
      _count: { symbol: true },
      orderBy: { _count: { symbol: 'desc' } }
    });
    
    console.log('\n📈 Most Analyzed Symbols:');
    symbolStats.slice(0, 5).forEach(stat => {
      console.log(`  ${stat.symbol}: ${stat._count.symbol} analyses`);
    });
    
    // Timeframe distribution
    const timeframeStats = await prisma.ai_learning_data.groupBy({
      by: ['timeframe'],
      _count: { timeframe: true },
      orderBy: { _count: { timeframe: 'desc' } }
    });
    
    console.log('\n⏰ Most Used Timeframes:');
    timeframeStats.slice(0, 5).forEach(stat => {
      console.log(`  ${stat.timeframe}: ${stat._count.timeframe} analyses`);
    });
    
    // Confidence score analysis
    const records = await prisma.ai_learning_data.findMany({
      where: { confidenceScore: { not: null } },
      select: { confidenceScore: true, analysisData: true, outcome: true },
      orderBy: { createdAt: 'desc' },
      take: 100
    });
    
    if (records.length > 0) {
      const avgConfidence = records.reduce((sum, r) => sum + (r.confidenceScore || 0), 0) / records.length;
      console.log(`\n🎯 Average Confidence Score: ${avgConfidence.toFixed(1)}%`);
      
      const highConfidence = records.filter(r => (r.confidenceScore || 0) >= 80).length;
      console.log(`  High Confidence (≥80%): ${highConfidence}/${records.length} (${(highConfidence/records.length*100).toFixed(1)}%)`);
    }
    
    // Analysis data insights
    const recommendations = {};
    const marketSentiments = {};
    
    records.forEach(record => {
      try {
        const analysis = JSON.parse(record.analysisData);
        
        if (analysis.recommendation) {
          recommendations[analysis.recommendation] = (recommendations[analysis.recommendation] || 0) + 1;
        }
        
        if (analysis.marketSentiment) {
          marketSentiments[analysis.marketSentiment] = (marketSentiments[analysis.marketSentiment] || 0) + 1;
        }
      } catch (e) {
        // Skip invalid JSON
      }
    });
    
    console.log('\n📋 AI Recommendations Distribution:');
    Object.entries(recommendations)
      .sort(([,a], [,b]) => b - a)
      .forEach(([rec, count]) => {
        console.log(`  ${rec}: ${count} times`);
      });
    
    console.log('\n📊 Market Sentiment Analysis:');
    Object.entries(marketSentiments)
      .sort(([,a], [,b]) => b - a)
      .forEach(([sentiment, count]) => {
        console.log(`  ${sentiment}: ${count} times`);
      });
    
    // Learning outcomes
    const outcomes = await prisma.ai_learning_data.groupBy({
      by: ['outcome'],
      _count: { outcome: true },
      where: { outcome: { not: null } }
    });
    
    console.log('\n🏆 Learning Outcomes:');
    if (outcomes.length > 0) {
      outcomes.forEach(outcome => {
        console.log(`  ${outcome.outcome}: ${outcome._count.outcome} trades`);
      });
    } else {
      console.log('  No trading outcomes recorded yet');
    }
    
    // Recent activity
    const recentAnalyses = await prisma.ai_learning_data.findMany({
      select: { 
        symbol: true, 
        timeframe: true, 
        confidenceScore: true,
        analysisData: true,
        createdAt: true
      },
      orderBy: { createdAt: 'desc' },
      take: 5
    });
    
    console.log('\n🕐 Recent AI Analysis Activity:');
    recentAnalyses.forEach(analysis => {
      try {
        const data = JSON.parse(analysis.analysisData);
        const time = new Date(analysis.createdAt).toLocaleString();
        console.log(`  ${time}: ${analysis.symbol} (${analysis.timeframe}) - ${data.recommendation || 'NO_REC'} (${analysis.confidenceScore || 'N/A'}%)`);
      } catch (e) {
        console.log(`  ${new Date(analysis.createdAt).toLocaleString()}: ${analysis.symbol} (${analysis.timeframe}) - Parse Error`);
      }
    });
    
    // Key learning insights
    console.log('\n🎓 Key Learning Insights:');
    
    const totalWithOutcomes = await prisma.ai_learning_data.count({
      where: { outcome: { not: null } }
    });
    
    if (totalWithOutcomes > 0) {
      console.log(`  ✅ ${totalWithOutcomes} decisions have been validated with real outcomes`);
      
      const winCount = await prisma.ai_learning_data.count({
        where: { outcome: 'WIN' }
      });
      
      if (winCount > 0) {
        console.log(`  🎯 Success Rate: ${winCount}/${totalWithOutcomes} (${(winCount/totalWithOutcomes*100).toFixed(1)}%)`);
      }
    } else {
      console.log('  ⚠️  No trading outcomes recorded yet - system needs real trade validation');
    }
    
    const highConfidenceCount = await prisma.ai_learning_data.count({
      where: { confidenceScore: { gte: 85 } }
    });
    
    console.log(`  🔥 High confidence analyses (≥85%): ${highConfidenceCount}`);
    
    // Most active trading periods
    const recent30Days = new Date();
    recent30Days.setDate(recent30Days.getDate() - 30);
    
    const recentActivity = await prisma.ai_learning_data.count({
      where: { 
        createdAt: { gte: recent30Days }
      }
    });
    
    console.log(`  📅 Analyses in last 30 days: ${recentActivity}`);
    
    console.log('\n🚀 System Status:');
    console.log(`  Database: Connected (${totalRecords} records)`);
    console.log(`  Learning: ${totalWithOutcomes > 0 ? 'Active with validation' : 'Analysis only (no trade validation yet)'}`);
    console.log(`  Data Quality: ${records.length > 0 ? 'Good (structured analysis data)' : 'Limited'}`);
    
  } catch (error) {
    console.error('❌ Error analyzing learning data:', error);
  } finally {
    await prisma.$disconnect();
  }
}

analyzeLearningProgress();
