/**
 * Integration patch for main trading system
 * Adds automated Drift order cleanup to trading workflow
 */

const { driftOrderCleanupService } = require('./lib/drift-order-cleanup-service.js')

class TradingSystemIntegration {
  static initialized = false

  /**
   * Initialize the cleanup service with the trading system
   */
  static async initializeCleanupService() {
    if (this.initialized) {
      console.log('🔄 Drift cleanup service already initialized')
      return
    }

    console.log('🚀 Initializing Drift order cleanup service...')

    try {
      // Start the automated monitoring
      driftOrderCleanupService.start(45000) // Check every 45 seconds

      // Set up cleanup triggers for position changes
      this.setupPositionMonitoring()

      this.initialized = true
      console.log('✅ Drift order cleanup service initialized successfully')

    } catch (error) {
      console.error('❌ Failed to initialize cleanup service:', error)
      throw error
    }
  }

  /**
   * Set up monitoring for position changes that might require cleanup
   */
  static setupPositionMonitoring() {
    // Monitor for position closures that might leave orphaned orders
    const originalMonitorPosition = global.monitorPosition || (() => {})
    
    global.monitorPosition = async (...args) => {
      const result = await originalMonitorPosition(...args)
      
      // Trigger cleanup after position monitoring
      setTimeout(async () => {
        try {
          console.log('🧹 Triggering cleanup after position monitoring...')
          await driftOrderCleanupService.checkAndCleanupOrders()
        } catch (error) {
          console.error('❌ Cleanup after position monitoring failed:', error)
        }
      }, 5000) // Wait 5 seconds after position monitoring
      
      return result
    }

    console.log('📊 Position monitoring integration set up')
  }

  /**
   * Cleanup orders after a specific trade action
   */
  static async cleanupAfterTrade(tradeInfo = {}) {
    console.log('🧹 Cleaning up orders after trade action:', tradeInfo)
    
    try {
      // Wait a moment for the trade to settle
      await new Promise(resolve => setTimeout(resolve, 3000))
      
      // Force cleanup
      const result = await driftOrderCleanupService.forceCleanup()
      
      console.log(`✅ Post-trade cleanup completed: ${result.summary.totalCanceled} orders canceled`)
      return result
      
    } catch (error) {
      console.error('❌ Post-trade cleanup failed:', error)
      return { success: false, error: error.message }
    }
  }

  /**
   * Enhanced position monitoring with automatic cleanup
   */
  static async monitorPositionWithCleanup(marketSymbol, maxChecks = 30) {
    console.log(`📊 Monitoring position for ${marketSymbol} with automatic cleanup...`)
    
    let lastPositionState = null
    
    for (let i = 0; i < maxChecks; i++) {
      try {
        // Check current position
        const response = await fetch('http://localhost:9001/api/drift/positions')
        
        if (response.ok) {
          const data = await response.json()
          const position = data.positions?.find(p => p.symbol === marketSymbol)
          
          // Detect position closure
          if (lastPositionState && lastPositionState.size !== 0 && (!position || position.size === 0)) {
            console.log(`🎯 Position closure detected for ${marketSymbol} - triggering cleanup`)
            
            // Wait a moment then cleanup
            setTimeout(async () => {
              try {
                await this.cleanupAfterTrade({ symbol: marketSymbol, action: 'position_closed' })
              } catch (error) {
                console.error('❌ Cleanup after position closure failed:', error)
              }
            }, 5000)
          }
          
          lastPositionState = position
        }
        
        // Wait before next check
        await new Promise(resolve => setTimeout(resolve, 10000))
        
      } catch (error) {
        console.error(`❌ Error monitoring position ${marketSymbol}:`, error)
      }
    }
    
    console.log(`📊 Position monitoring completed for ${marketSymbol}`)
  }

  /**
   * Get cleanup service status
   */
  static getCleanupStatus() {
    return {
      initialized: this.initialized,
      serviceStatus: driftOrderCleanupService.getStatus()
    }
  }

  /**
   * Stop the cleanup service
   */
  static stopCleanupService() {
    if (!this.initialized) {
      console.log('⚠️ Cleanup service not initialized')
      return
    }

    driftOrderCleanupService.stop()
    this.initialized = false
    console.log('🛑 Drift order cleanup service stopped')
  }
}

// Auto-initialize if running in main trading environment
if (typeof global !== 'undefined' && global.process?.title?.includes('node')) {
  // Wait a moment to let other systems initialize
  setTimeout(() => {
    TradingSystemIntegration.initializeCleanupService().catch(error => {
      console.error('❌ Auto-initialization failed:', error)
    })
  }, 10000) // Wait 10 seconds
}

module.exports = { TradingSystemIntegration, driftOrderCleanupService }
