import { safeParallelAutomation } from '@/lib/safe-parallel-automation'

export async function POST(request) {
  try {
    const config = await request.json()
    
    console.log('SAFE START: Received config:', JSON.stringify(config, null, 2))
    
    // Validate timeframes
      return Response.json({
        success: false,
        message: 'At least one timeframe is required'
      }, { status: 400 })
    }
    
    // Detect trading strategy based on timeframes
    const timeframes = config.selectedTimeframes
    let strategyType = 'General'
    
    const isScalping = timeframes.includes('5') || timeframes.includes('15') || timeframes.includes('30')
    const isDayTrading = timeframes.includes('60') || timeframes.includes('120')
    const isSwingTrading = timeframes.includes('240') || timeframes.includes('D')
    
    if (isScalping) {
      strategyType = 'Scalping'
    } else if (isDayTrading) {
      strategyType = 'Day Trading'
    } else if (isSwingTrading) {
      strategyType = 'Swing Trading'
    }
    
    console.log('STRATEGY: Detected', strategyType, 'strategy')
    console.log('TIMEFRAMES:', timeframes)
    
    // Create safe automation config
    const automationConfig = {
      symbol: config.symbol || 'SOLUSD',
      timeframes: timeframes,
      mode: config.mode || 'SIMULATION',
      tradingAmount: config.tradingAmount || 1.0,
      leverage: config.leverage || 1,
      stopLoss: config.stopLoss || 2.0,
      takeProfit: config.takeProfit || 3.0,
      strategyType: strategyType,
      userId: 'default-user'
    }
    
    const result = await safeParallelAutomation.startSafeAutomation(automationConfig)
    
    if (result.success) {
      return Response.json({ 
        success: true, 
        message: 'Safe ' + strategyType + ' automation started successfully',
        strategy: strategyType,
        timeframes: timeframes
      })
    } else {
      return Response.json({ 
        success: false, 
        error: result.message || 'Failed to start automation'
      }, { status: 400 })
    }
  } catch (error) {
    console.error('Start automation error:', error)
    return Response.json({ 
      success: false, 
      error: 'Internal server error',
      message: error.message
    }, { status: 500 })
  }
}
