// Import singleton automation manager
async function getAutomationInstance() {
  try {
    const { getAutomationInstance } = await import('../../../../lib/automation-singleton.js');
    return await getAutomationInstance();
  } catch (error) {
    console.error('❌ Could not get automation instance:', error);
    return null;
  }
}

export async function POST() {
  try {
    console.log('🛑 AUTOMATION STOP: Request received');
    
    const automation = await getAutomationInstance();
    let result = { success: false, message: 'No automation instance available' };
    
    if (automation) {
      result = await automation.stop();
      
      // Check if learning system was active
      if (typeof automation.getLearningStatus === 'function') {
        const learningStatus = await automation.getLearningStatus();
        console.log('🧠 LEARNING SYSTEM: Stopped with', learningStatus.activeDecisions, 'active decisions');
      }
    }
    
    // Additional cleanup
    try {
      const { execSync } = require('child_process');
      execSync('pkill -f "chrome|chromium" 2>/dev/null || true');
      console.log('✅ Additional cleanup completed');
    } catch (cleanupError) {
      console.error('Cleanup error:', cleanupError.message);
    }

    return Response.json(result);
  } catch (error) {
    console.error('❌ Stop automation error:', error);
    return Response.json({
      success: false,
      message: error.message
    }, { status: 500 });
  }
}
