// Sync successful Drift trades to AI learning system

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

async function syncSuccessfulTrade() {
  try {
    console.log('🔄 Syncing successful trade to AI learning system...');
    
    // Get the successful trade from Drift position history
    const response = await fetch('http://localhost:9001/api/drift/position-history');
    const data = await response.json();
    
    if (!data.success || !data.trades.length) {
      throw new Error('No trades found in Drift history');
    }
    
    const trade = data.trades[0]; // Most recent successful trade
    console.log('📊 Found successful trade:', {
      id: trade.id,
      symbol: trade.symbol,
      side: trade.side,
      pnl: trade.pnl,
      outcome: trade.outcome
    });
    
    // Check if this trade is already in our database
    const existingTrade = await prisma.trades.findUnique({
      where: { id: trade.id }
    });
    
    if (existingTrade) {
      console.log('✅ Trade already exists in database');
      return;
    }
    
    // Add the successful trade to our database
    const newTrade = await prisma.trades.create({
      data: {
        id: trade.id,
        userId: 'default-user',
        symbol: trade.symbol,
        side: trade.side,
        amount: trade.amount,
        price: trade.entryPrice,
        entryPrice: trade.entryPrice,
        exitPrice: trade.exitPrice,
        leverage: trade.leverage || 1,
        stopLoss: trade.stopLoss,
        takeProfit: trade.takeProfit,
        status: 'COMPLETED',
        profit: trade.pnl,
        createdAt: new Date(trade.entryTime),
        closedAt: new Date(trade.exitTime),
        confidence: trade.confidence || 85,
        txId: trade.txId,
        mode: 'LIVE' // This was a real trade
      }
    });
    
    console.log('✅ Successfully added trade to database:', newTrade.id);
    
    // Also record this as an AI learning decision outcome
    try {
      const { SimplifiedStopLossLearner } = await import('../lib/simplified-stop-loss-learner-fixed.js');
      const learner = new SimplifiedStopLossLearner();
      
      // Create a decision ID for this trade
      const decisionId = `sync_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
      
      // Record the decision first
      await learner.recordDecision({
        id: decisionId,
        symbol: trade.symbol,
        recommendation: trade.side,
        confidence: trade.confidence || 85,
        stopLoss: trade.stopLoss || (trade.side === 'BUY' ? trade.entryPrice * 0.98 : trade.entryPrice * 1.02),
        takeProfit: trade.takeProfit || (trade.side === 'BUY' ? trade.entryPrice * 1.04 : trade.entryPrice * 0.96),
        entryPrice: trade.entryPrice,
        marketConditions: {
          timeframe: ['1h', '4h'],
          analysis: `Successful ${trade.side} trade - ${trade.outcome}`
        },
        timestamp: trade.entryTime
      });
      
      // Then record the successful outcome
      await learner.assessDecisionOutcome({
        decisionId: decisionId,
        outcome: 'WIN',
        actualPnL: trade.pnl,
        timestamp: trade.exitTime,
        positionInfo: {
          entryPrice: trade.entryPrice,
          exitPrice: trade.exitPrice,
          side: trade.side,
          pnl: trade.pnl
        }
      });
      
      console.log('🧠 Successfully recorded in AI learning system:', decisionId);
      
      // Generate updated learning report
      const report = await learner.generateLearningReport();
      console.log('📊 Updated learning statistics:', report.summary);
      
    } catch (learningError) {
      console.warn('⚠️ Could not add to AI learning system:', learningError.message);
    }
    
    console.log('✅ Trade sync completed successfully!');
    
  } catch (error) {
    console.error('❌ Error syncing trade:', error);
  } finally {
    await prisma.$disconnect();
  }
}

// Run the sync
syncSuccessfulTrade();
