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

async function showDetailedLearningData() {
  try {
    console.log('🔍 Detailed AI Learning Data Analysis...\n');
    
    const learningData = await prisma.aILearningData.findMany({
      orderBy: { createdAt: 'desc' },
      take: 3
    });
    
    console.log(`📊 Analyzing ${learningData.length} most recent learning records:\n`);
    
    learningData.forEach((record, i) => {
      console.log(`\n🧠 LEARNING RECORD #${i + 1}`);
      console.log('═'.repeat(50));
      console.log(`📅 Date: ${record.createdAt}`);
      console.log(`👤 User: ${record.userId}`);
      console.log(`⏰ Timeframe: ${record.timeframe}`);
      console.log(`🎯 Recommendation: ${record.recommendation || 'PENDING'}`);
      console.log(`📊 Confidence: ${record.confidence || 'CALCULATING'}%`);
      console.log(`🎯 Accuracy Score: ${record.accuracyScore || 'NOT YET MEASURED'}`);
      
      if (record.analysisData) {
        try {
          const analysis = JSON.parse(record.analysisData);
          console.log('\n📈 TECHNICAL ANALYSIS:');
          console.log(`📝 Reasoning: ${analysis.reasoning || 'Multi-timeframe analysis'}`);
          
          if (analysis.multiTimeframeResults) {
            console.log('\n⏱️ MULTI-TIMEFRAME BREAKDOWN:');
            analysis.multiTimeframeResults.forEach((tf, idx) => {
              console.log(`  ${idx + 1}. ${tf.timeframe}: ${tf.analysis?.recommendation || 'ANALYZING'} (${tf.analysis?.confidence || 0}% confidence)`);
            });
          }
          
          if (analysis.confidence) {
            console.log(`\n🎯 Final Combined Confidence: ${analysis.confidence}%`);
          }
          
          if (analysis.marketSentiment) {
            console.log(`📊 Market Sentiment: ${analysis.marketSentiment}`);
          }
          
        } catch (e) {
          console.log('📝 Analysis: [Complex multi-timeframe data - parsing limited]');
        }
      }
      
      if (record.marketConditions) {
        try {
          const conditions = JSON.parse(record.marketConditions);
          console.log('\n🌍 MARKET CONDITIONS:');
          console.log(`📊 Symbol: ${conditions.symbol || 'UNKNOWN'}`);
          console.log(`⏰ Timestamp: ${conditions.timestamp}`);
          console.log(`🔗 Session: ${conditions.session}`);
        } catch (e) {
          console.log('🌍 Market Conditions: [Data available]');
        }
      }
      
      console.log('\n' + '─'.repeat(50));
    });
    
    // Show learning progression
    const totalAnalyses = await prisma.aILearningData.count();
    const accurateAnalyses = await prisma.aILearningData.count({
      where: {
        accuracyScore: { gt: 0.6 }
      }
    });
    
    console.log(`\n📊 LEARNING PROGRESSION SUMMARY:`);
    console.log('═'.repeat(50));
    console.log(`📈 Total Analyses: ${totalAnalyses}`);
    console.log(`✅ Accurate Predictions: ${accurateAnalyses}`);
    console.log(`🎯 Accuracy Rate: ${totalAnalyses > 0 ? ((accurateAnalyses / totalAnalyses) * 100).toFixed(1) : 0}%`);
    
    // Determine learning phase
    let phase = 'INITIAL';
    let phaseDescription = 'Learning market basics';
    
    if (totalAnalyses >= 100) {
      phase = 'EXPERT';
      phaseDescription = 'Advanced pattern recognition and risk management';
    } else if (totalAnalyses >= 50) {
      phase = 'ADVANCED';
      phaseDescription = 'Developing sophisticated trading strategies';
    } else if (totalAnalyses >= 20) {
      phase = 'PATTERN_RECOGNITION';
      phaseDescription = 'Learning to identify market patterns';
    }
    
    console.log(`🧠 Current Learning Phase: ${phase}`);
    console.log(`📝 Phase Description: ${phaseDescription}`);
    
    // Show recent automation activity
    const recentSessions = await prisma.automationSession.findMany({
      orderBy: { createdAt: 'desc' },
      take: 1
    });
    
    if (recentSessions.length > 0) {
      const session = recentSessions[0];
      console.log(`\n🤖 CURRENT AUTOMATION STATUS:`);
      console.log('═'.repeat(50));
      console.log(`📊 Status: ${session.status}`);
      console.log(`⚙️ Mode: ${session.mode}`);
      console.log(`📅 Started: ${session.createdAt}`);
      console.log(`📈 Trades Count: ${session.tradesCount || 0}`);
    }
    
    await prisma.$disconnect();
  } catch (error) {
    console.error('❌ Error:', error);
  }
}

showDetailedLearningData();
