#!/usr/bin/env node

/**
 * AI Learning System Demo
 * 
 * Demonstrates the complete stop loss decision learning system
 */

const EnhancedAutonomousRiskManager = require('./lib/enhanced-autonomous-risk-manager.js');
const StopLossDecisionLearner = require('./lib/stop-loss-decision-learner.js');

async function demonstrateAILearning() {
  console.log('🧠 AI LEARNING SYSTEM DEMONSTRATION');
  console.log('='.repeat(80));
  
  console.log(`
🎯 WHAT THIS SYSTEM DOES:

1. 📊 Records every AI decision made near stop loss
2. 🔍 Tracks what happens after each decision
3. 🧠 Learns from outcomes to improve future decisions
4. 🚀 Gets smarter with every trade and decision
5. 🏖️ Enables true autonomous beach mode trading

🔄 LEARNING CYCLE:
Decision Made → Outcome Tracked → Pattern Analysis → Improved Decisions
`);

  const riskManager = new EnhancedAutonomousRiskManager();
  const learner = new StopLossDecisionLearner();

  console.log('\n🎬 DEMO SCENARIO: Simulating Decision Learning Process\n');

  // Simulate a series of decisions and outcomes
  const demoDecisions = [
    {
      scenario: 'SOL-PERP position 1.5% from stop loss',
      decision: 'EMERGENCY_EXIT',
      distanceFromSL: 1.5,
      outcome: 'AVOIDED_MAJOR_LOSS',
      pnlImpact: 5.2
    },
    {
      scenario: 'SOL-PERP position 2.8% from stop loss',
      decision: 'TIGHTEN_STOP_LOSS',
      distanceFromSL: 2.8,
      outcome: 'IMPROVED_PROFIT',
      pnlImpact: 2.1
    },
    {
      scenario: 'SOL-PERP position 4.2% from stop loss',
      decision: 'HOLD',
      distanceFromSL: 4.2,
      outcome: 'CORRECT_HOLD',
      pnlImpact: 1.8
    },
    {
      scenario: 'BTC-PERP position 1.2% from stop loss',
      decision: 'PARTIAL_EXIT',
      distanceFromSL: 1.2,
      outcome: 'REDUCED_RISK',
      pnlImpact: 0.8
    }
  ];

  console.log('📝 RECORDING DECISIONS FOR LEARNING:\n');

  const decisionIds = [];

  for (const demo of demoDecisions) {
    console.log(`🎯 Scenario: ${demo.scenario}`);
    console.log(`   Decision: ${demo.decision}`);
    
    // Record the decision
    const decisionId = await learner.recordDecision({
      tradeId: `demo_${Date.now()}_${Math.random().toString(36).substr(2, 5)}`,
      symbol: demo.scenario.split(' ')[0],
      decision: demo.decision,
      distanceFromSL: demo.distanceFromSL,
      reasoning: `Demo decision at ${demo.distanceFromSL}% distance`,
      currentPrice: 180 + Math.random() * 10,
      confidenceScore: 0.7 + Math.random() * 0.2,
      expectedOutcome: 'BETTER_RESULT'
    });

    if (decisionId) {
      decisionIds.push({ id: decisionId, demo });
      console.log(`   ✅ Recorded decision ${decisionId}`);
    }
    
    console.log('');
  }

  console.log('⏱️  Simulating time passage and outcome assessment...\n');
  
  // Wait a moment to simulate time passage
  await new Promise(resolve => setTimeout(resolve, 2000));

  console.log('🔍 ASSESSING DECISION OUTCOMES:\n');

  for (const { id, demo } of decisionIds) {
    console.log(`📊 Assessing decision ${id}:`);
    console.log(`   Outcome: ${demo.outcome}`);
    console.log(`   P&L Impact: +$${demo.pnlImpact}`);
    
    // Assess the outcome
    const assessment = await learner.assessDecisionOutcome({
      decisionId: id,
      actualOutcome: demo.outcome,
      timeToOutcome: 5 + Math.floor(Math.random() * 10), // 5-15 minutes
      pnlImpact: demo.pnlImpact,
      additionalContext: {
        scenario: demo.scenario,
        marketConditions: 'Demo simulation'
      }
    });

    if (assessment) {
      console.log(`   ✅ Assessment: ${assessment.wasCorrect ? 'CORRECT' : 'INCORRECT'} (Score: ${assessment.learningScore.toFixed(2)})`);
    }
    
    console.log('');
  }

  console.log('🧠 ANALYZING LEARNING PATTERNS:\n');

  const patterns = await learner.analyzeDecisionPatterns();
  
  if (patterns) {
    console.log('📈 SUCCESSFUL DECISION PATTERNS:');
    patterns.successfulPatterns.forEach(pattern => {
      console.log(`   ${pattern.decisionType}: ${pattern.successRate.toFixed(1)}% success rate (${pattern.sampleSize} samples)`);
    });
    
    if (patterns.failurePatterns.length > 0) {
      console.log('\n📉 AREAS FOR IMPROVEMENT:');
      patterns.failurePatterns.forEach(pattern => {
        console.log(`   ${pattern.decisionType}: ${pattern.successRate.toFixed(1)}% success rate (${pattern.sampleSize} samples)`);
      });
    }
    
    console.log('\n🎯 DISTANCE OPTIMIZATION:');
    Object.entries(patterns.distanceOptimization).forEach(([range, data]) => {
      console.log(`   ${range}: ${data.successRate.toFixed(1)}% success, optimal threshold: ${data.optimalThreshold.toFixed(2)}%`);
    });
  }

  console.log('\n🚀 GENERATING SMART RECOMMENDATION:\n');

  // Test smart recommendation system
  const recommendation = await learner.getSmartRecommendation({
    distanceFromSL: 2.5,
    symbol: 'SOL-PERP',
    marketConditions: {
      trend: 'BULLISH',
      volatility: 0.05,
      timeOfDay: new Date().getHours()
    }
  });

  console.log(`🎯 Smart Recommendation for 2.5% distance from SL:`);
  console.log(`   Suggested Action: ${recommendation.suggestedAction}`);
  console.log(`   Confidence: ${(recommendation.confidence * 100).toFixed(1)}%`);
  console.log(`   Reasoning: ${recommendation.reasoning}`);
  console.log(`   Learning-Based: ${recommendation.learningBased ? 'YES' : 'NO'}`);

  if (recommendation.supportingData) {
    console.log(`   Supporting Data: ${recommendation.supportingData.historicalSamples} similar situations`);
  }

  console.log('\n📊 GENERATING COMPREHENSIVE LEARNING REPORT:\n');

  const report = await learner.generateLearningReport();
  
  if (report) {
    console.log('📋 LEARNING SYSTEM STATUS:');
    console.log(`   Total Decisions: ${report.summary.totalDecisions}`);
    console.log(`   System Confidence: ${(report.summary.systemConfidence * 100).toFixed(1)}%`);
    console.log(`   Successful Patterns: ${report.summary.successfulPatterns}`);
    
    if (report.recommendations.length > 0) {
      console.log('\n💡 AI RECOMMENDATIONS:');
      report.recommendations.forEach(rec => {
        console.log(`   ${rec.type} (${rec.priority}): ${rec.message}`);
      });
    }
  }

  console.log('\n🏖️ BEACH MODE DEMONSTRATION:\n');

  console.log(`
🌊 ENHANCED BEACH MODE WITH AI LEARNING:

✅ System now records every decision made near stop loss
✅ Tracks outcomes and learns from what works/doesn't work  
✅ Adjusts decision thresholds based on historical success
✅ Provides smart recommendations based on learned patterns
✅ Continuously improves decision-making quality
✅ Builds confidence through validated success patterns

🎯 RESULT: Your AI doesn't just make autonomous decisions...
          It LEARNS from every decision to become smarter!

🚀 NEXT STEPS:
1. Start automation with enhanced learning system
2. Let it run and make decisions autonomously  
3. Check learning dashboard for insights
4. Watch confidence and success rates improve over time
5. Enjoy the beach knowing your AI is getting smarter! 🏖️
`);

  console.log('\n✨ DEMO COMPLETE! Your AI is ready to learn and improve! ✨\n');
}

// Run the demonstration
if (require.main === module) {
  demonstrateAILearning().catch(console.error);
}
