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

async function createLearningDashboard() {
  console.log('🎯 AI LEARNING SYSTEM - COMPREHENSIVE INTELLIGENCE REPORT');
  console.log('═'.repeat(80));
  
  const prisma = new PrismaClient();
  
  try {
    // Load learning system
    const SimplifiedStopLossLearner = require('./lib/simplified-stop-loss-learner.js');
    const learner = new SimplifiedStopLossLearner();
    
    console.log('\n📊 CURRENT LEARNING STATUS');
    console.log('─'.repeat(50));
    
    const totalRecords = await prisma.ai_learning_data.count();
    console.log(`📈 Total Learning Records: ${totalRecords.toLocaleString()}`);
    
    // Learning system status
    try {
      const report = await learner.generateLearningReport();
      console.log(`🧠 System Confidence: ${(report.summary?.systemConfidence || 0).toFixed(1)}%`);
      console.log(`🎯 Success Rate: ${report.summary?.successRate || 'No trades yet'}`);
      console.log(`📋 Decisions Made: ${report.summary?.totalDecisions || 0}`);
    } catch (e) {
      console.log('❌ Learning report unavailable');
    }
    
    // What symbols the AI knows best
    const symbolExpertise = await prisma.ai_learning_data.groupBy({
      by: ['symbol'],
      _count: { symbol: true },
      orderBy: { _count: { symbol: 'desc' } }
    });
    
    console.log('\n🎯 AI TRADING EXPERTISE BY SYMBOL');
    console.log('─'.repeat(50));
    symbolExpertise.slice(0, 5).forEach((sym, i) => {
      const expertise = sym._count.symbol > 1000 ? '🥇 Expert' : 
                       sym._count.symbol > 100 ? '🥈 Experienced' : 
                       '🥉 Learning';
      console.log(`${expertise} ${sym.symbol}: ${sym._count.symbol.toLocaleString()} analyses`);
    });
    
    // AI Decision Patterns
    console.log('\n🧠 AI DECISION INTELLIGENCE');
    console.log('─'.repeat(50));
    
    const recentDecisions = await prisma.ai_learning_data.findMany({
      where: {
        timeframe: 'DECISION',
        confidenceScore: { not: null }
      },
      select: {
        confidenceScore: true,
        analysisData: true,
        createdAt: true
      },
      orderBy: { createdAt: 'desc' },
      take: 20
    });
    
    const avgConfidence = recentDecisions.reduce((sum, d) => sum + d.confidenceScore, 0) / recentDecisions.length;
    console.log(`📊 Current Confidence Level: ${avgConfidence.toFixed(1)}%`);
    
    // Confidence distribution
    const high = recentDecisions.filter(d => d.confidenceScore >= 70).length;
    const medium = recentDecisions.filter(d => d.confidenceScore >= 40 && d.confidenceScore < 70).length;
    const low = recentDecisions.filter(d => d.confidenceScore < 40).length;
    
    console.log(`🔥 High Confidence (≥70%): ${high}/${recentDecisions.length} decisions`);
    console.log(`⚡ Medium Confidence (40-69%): ${medium}/${recentDecisions.length} decisions`);
    console.log(`⚠️  Low Confidence (<40%): ${low}/${recentDecisions.length} decisions`);
    
    // What makes the AI cautious vs confident
    console.log('\n🎭 WHAT INFLUENCES AI CONFIDENCE');
    console.log('─'.repeat(50));
    
    // Analyze decision reasoning patterns
    const reasoningPatterns = {};
    recentDecisions.forEach(decision => {
      try {
        const analysis = JSON.parse(decision.analysisData);
        if (analysis.reasoning) {
          const reasoning = analysis.reasoning.toLowerCase();
          
          // Extract key phrases that indicate learning
          const patterns = [
            'increased monitoring',
            'position is safe',
            'standard monitoring',
            'preparing contingency',
            'technical analysis',
            'emergency',
            'risk'
          ];
          
          patterns.forEach(pattern => {
            if (reasoning.includes(pattern)) {
              if (!reasoningPatterns[pattern]) reasoningPatterns[pattern] = [];
              reasoningPatterns[pattern].push(decision.confidenceScore);
            }
          });
        }
      } catch (e) {}
    });
    
    Object.entries(reasoningPatterns).forEach(([pattern, confidences]) => {
      const avgConf = confidences.reduce((a, b) => a + b, 0) / confidences.length;
      const emoji = avgConf >= 60 ? '🟢' : avgConf >= 40 ? '🟡' : '🔴';
      console.log(`${emoji} "${pattern}": Avg ${avgConf.toFixed(1)}% confidence (${confidences.length} times)`);
    });
    
    // Learning evolution over time
    console.log('\n📈 LEARNING EVOLUTION');
    console.log('─'.repeat(50));
    
    const oldDecisions = await prisma.ai_learning_data.findMany({
      where: { confidenceScore: { not: null } },
      orderBy: { createdAt: 'asc' },
      take: 50,
      select: { confidenceScore: true }
    });
    
    const newDecisions = await prisma.ai_learning_data.findMany({
      where: { confidenceScore: { not: null } },
      orderBy: { createdAt: 'desc' },
      take: 50,
      select: { confidenceScore: true }
    });
    
    const oldAvg = oldDecisions.reduce((sum, d) => sum + d.confidenceScore, 0) / oldDecisions.length;
    const newAvg = newDecisions.reduce((sum, d) => sum + d.confidenceScore, 0) / newDecisions.length;
    const evolution = newAvg - oldAvg;
    
    console.log(`📊 Early Period Confidence: ${oldAvg.toFixed(1)}%`);
    console.log(`📊 Recent Period Confidence: ${newAvg.toFixed(1)}%`);
    console.log(`📈 Evolution: ${evolution > 0 ? '+' : ''}${evolution.toFixed(1)}% ${evolution > 0 ? '(Learning & Improving)' : '(Becoming More Cautious)'}`);
    
    // Test AI recommendation system
    console.log('\n🤖 AI RECOMMENDATION ENGINE TEST');
    console.log('─'.repeat(50));
    
    try {
      const testScenarios = [
        { distanceFromSL: 0.01, desc: 'Very close to stop loss (1%)' },
        { distanceFromSL: 0.05, desc: 'Close to stop loss (5%)' },
        { distanceFromSL: 0.15, desc: 'Safe distance from stop loss (15%)' }
      ];
      
      for (const scenario of testScenarios) {
        const recommendation = await learner.getSmartRecommendation({
          distanceFromSL: scenario.distanceFromSL,
          symbol: 'SOL-PERP',
          marketConditions: 'VOLATILE'
        });
        
        console.log(`🎯 ${scenario.desc}:`);
        console.log(`   → Action: ${recommendation.action} (${recommendation.confidence.toFixed(1)}% confidence)`);
        console.log(`   → Reasoning: ${recommendation.reasoning}`);
      }
    } catch (e) {
      console.log('❌ Recommendation system test failed');
    }
    
    // Trading outcomes (actual learning validation)
    const outcomes = await prisma.ai_learning_data.findMany({
      where: { outcome: { not: null } },
      select: { outcome: true, confidenceScore: true }
    });
    
    console.log('\n🏆 REAL TRADING VALIDATION');
    console.log('─'.repeat(50));
    
    if (outcomes.length > 0) {
      const wins = outcomes.filter(o => o.outcome === 'WIN').length;
      const total = outcomes.length;
      console.log(`✅ Validated Trades: ${total}`);
      console.log(`🎯 Success Rate: ${wins}/${total} (${(wins/total*100).toFixed(1)}%)`);
      console.log(`🧠 AI is learning from REAL trading outcomes`);
    } else {
      console.log(`⚠️  No real trading outcomes recorded yet`);
      console.log(`📝 AI needs actual trade results to validate its learning`);
    }
    
    // Summary insights
    console.log('\n💡 KEY LEARNING INSIGHTS');
    console.log('─'.repeat(50));
    
    console.log(`🔹 The AI has analyzed ${totalRecords.toLocaleString()} market situations`);
    console.log(`🔹 Primary expertise: SOL-PERP trading (${symbolExpertise[0]?._count?.symbol || 0} analyses)`);
    console.log(`🔹 Current confidence level: ${avgConfidence.toFixed(1)}% (${evolution > 0 ? 'improving' : 'more cautious than before'})`);
    console.log(`🔹 Learning pattern: More analysis → ${evolution > 0 ? 'Higher' : 'Lower'} confidence`);
    
    if (outcomes.length > 0) {
      console.log(`🔹 Real trade validation: Active (${outcomes.length} outcomes recorded)`);
    } else {
      console.log(`🔹 Real trade validation: Pending (needs actual trading results)`);
    }
    
    console.log('\n🚀 NEXT STEPS FOR AI ENHANCEMENT');
    console.log('─'.repeat(50));
    console.log(`📊 Continue real trading to validate AI predictions`);
    console.log(`🎯 Monitor confidence evolution as more trades complete`);
    console.log(`🧠 AI will learn from win/loss patterns to improve accuracy`);
    console.log(`⚡ Current state: Analysis-heavy, validation-light`);
    
  } catch (error) {
    console.error('❌ Dashboard error:', error);
  } finally {
    await prisma.$disconnect();
  }
}

createLearningDashboard();
