#!/usr/bin/env node

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

async function showLastTradeResult() {
  console.log('🔍 FETCHING LAST REAL TRADE RESULT...');
  console.log('='.repeat(60));
  
  try {
    // Get the most recent real trade
    const lastTrade = await prisma.trade.findFirst({
      where: {
        tradingMode: 'REAL',
        driftTxId: { not: null }
      },
      orderBy: { createdAt: 'desc' }
    });
    
    if (!lastTrade) {
      console.log('❌ No real trades found');
      return;
    }
    
    console.log('📊 LAST REAL TRADE DETAILS:');
    console.log('──────────────────────────────────────────────────');
    console.log(`Trade ID: ${lastTrade.id}`);
    console.log(`Drift TX ID: ${lastTrade.driftTxId}`);
    console.log(`Symbol: ${lastTrade.symbol}`);
    console.log(`Side: ${lastTrade.side.toUpperCase()}`);
    console.log(`Amount: ${lastTrade.amount}`);
    console.log(`Entry Price: $${lastTrade.entryPrice}`);
    console.log(`Stop Loss: $${lastTrade.stopLoss}`);
    console.log(`Take Profit: $${lastTrade.takeProfit}`);
    console.log(`Status: ${lastTrade.status}`);
    console.log(`Created: ${lastTrade.createdAt}`);
    console.log(`Executed: ${lastTrade.executedAt || 'N/A'}`);
    
    console.log('\n🎯 OUTCOME DETAILS:');
    console.log('──────────────────────────────────────────────────');
    console.log(`Outcome: ${lastTrade.outcome || 'PENDING'}`);
    console.log(`Exit Price: $${lastTrade.exitPrice || 'N/A'}`);
    console.log(`P&L: ${lastTrade.pnlPercent ? (lastTrade.pnlPercent > 0 ? '+' : '') + lastTrade.pnlPercent.toFixed(2) + '%' : 'N/A'}`);
    console.log(`Risk/Reward: ${lastTrade.actualRR ? lastTrade.actualRR.toFixed(2) + ':1' : 'N/A'}`);
    console.log(`Closed At: ${lastTrade.closedAt || 'STILL OPEN'}`);
    
    if (lastTrade.learningData) {
      console.log('\n🧠 LEARNING DATA:');
      console.log('──────────────────────────────────────────────────');
      try {
        const learningData = JSON.parse(lastTrade.learningData);
        console.log(JSON.stringify(learningData, null, 2));
      } catch (e) {
        console.log(lastTrade.learningData);
      }
    }
    
    // Calculate percentages for verification
    if (lastTrade.entryPrice && lastTrade.stopLoss && lastTrade.takeProfit) {
      const slPercent = Math.abs((lastTrade.stopLoss - lastTrade.entryPrice) / lastTrade.entryPrice * 100);
      const tpPercent = Math.abs((lastTrade.takeProfit - lastTrade.entryPrice) / lastTrade.entryPrice * 100);
      
      console.log('\n📏 PERCENTAGE VERIFICATION:');
      console.log('──────────────────────────────────────────────────');
      console.log(`Stop Loss Distance: ${slPercent.toFixed(2)}%`);
      console.log(`Take Profit Distance: ${tpPercent.toFixed(2)}%`);
      console.log(`Risk/Reward Ratio: ${(tpPercent/slPercent).toFixed(2)}:1`);
    }
    
    // Show all real trades for comparison
    console.log('\n📈 ALL REAL TRADES SUMMARY:');
    console.log('──────────────────────────────────────────────────');
    
    const allRealTrades = await prisma.trade.findMany({
      where: {
        tradingMode: 'REAL',
        driftTxId: { not: null }
      },
      orderBy: { createdAt: 'desc' },
      take: 5
    });
    
    for (const trade of allRealTrades) {
      const outcomeIcon = trade.outcome === 'WIN' ? '✅' : trade.outcome === 'LOSS' ? '❌' : '🟡';
      const pnl = trade.pnlPercent ? `${trade.pnlPercent > 0 ? '+' : ''}${trade.pnlPercent.toFixed(2)}%` : 'PENDING';
      console.log(`${outcomeIcon} ${trade.driftTxId.substring(0, 8)}... | ${trade.symbol} ${trade.side.toUpperCase()} | ${pnl}`);
    }
    
  } catch (error) {
    console.error('❌ Error fetching trade:', error.message);
  } finally {
    await prisma.$disconnect();
  }
}

if (require.main === module) {
  showLastTradeResult();
}
