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

async function checkLearningData() {
  try {
    console.log('🔍 Checking AI learning data in database...');
    
    const learningData = await prisma.aILearningData.findMany({
      orderBy: { createdAt: 'desc' },
      take: 5
    });
    
    console.log(`📊 Found ${learningData.length} learning records`);
    
    if (learningData.length > 0) {
      console.log('\n🧠 Recent learning data:');
      learningData.forEach((record, i) => {
        console.log(`${i + 1}. ${record.createdAt}: ${record.recommendation} (${record.confidence}% confidence)`);
        if (record.analysisData) {
          try {
            const analysis = JSON.parse(record.analysisData);
            console.log(`   Analysis: ${analysis.reasoning ? analysis.reasoning.substring(0, 100) : 'No reasoning'}...`);
          } catch (e) {
            console.log('   Analysis: [Could not parse]');
          }
        }
      });
    } else {
      console.log('❌ No learning data found - system hasn\'t started learning yet');
      
      // Let's create a sample learning record to show how it works
      console.log('\n📝 Creating sample learning data to demonstrate...');
      
      const sampleAnalysis = {
        recommendation: 'BUY',
        confidence: 75,
        reasoning: 'Multi-timeframe analysis shows RSI oversold on 15m while 1h trend remains bullish. MACD showing positive divergence with strong volume support at current levels.',
        marketSentiment: 'BULLISH',
        keyLevels: {
          support: 64250,
          resistance: 67800
        },
        indicators: {
          rsi: 28,
          macd: { signal: 'BUY', strength: 'STRONG' },
          ema: { trend: 'BULLISH' }
        }
      };
      
      const sampleRecord = await prisma.aILearningData.create({
        data: {
          userId: 'demo-user',
          analysis: sampleAnalysis.reasoning,
          recommendation: sampleAnalysis.recommendation,
          confidence: sampleAnalysis.confidence,
          timeframe: '15m',
          marketConditions: JSON.stringify({
            timestamp: new Date(),
            symbol: 'BTCUSD',
            price: 65500,
            volume: 'HIGH'
          }),
          analysisData: JSON.stringify(sampleAnalysis),
          accuracyScore: null // This gets updated later based on trade outcome
        }
      });
      
      console.log('✅ Sample learning record created:', {
        id: sampleRecord.id,
        recommendation: sampleRecord.recommendation,
        confidence: sampleRecord.confidence
      });
    }
    
    // Check for automation sessions
    const sessions = await prisma.automationSession.findMany({
      orderBy: { createdAt: 'desc' },
      take: 3
    });
    
    console.log(`\n📋 Found ${sessions.length} automation sessions`);
    sessions.forEach((session, i) => {
      console.log(`${i + 1}. ${session.createdAt}: ${session.status} (${session.mode})`);
    });
    
    // Check for actual trades
    const trades = await prisma.trade.findMany({
      orderBy: { createdAt: 'desc' },
      take: 3
    });
    
    console.log(`\n💰 Found ${trades.length} trade records`);
    trades.forEach((trade, i) => {
      console.log(`${i + 1}. ${trade.createdAt}: ${trade.type} ${trade.symbol} - ${trade.status}`);
    });
    
    await prisma.$disconnect();
  } catch (error) {
    console.error('❌ Error:', error);
  }
}

checkLearningData();
