import { NextResponse } from 'next/server';

// 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);
    throw error;
  }
}

export async function POST(request) {
  try {
    const config = await request.json();
    
    console.log('🚀 AUTOMATION START: Received config:', JSON.stringify(config, null, 2));
    console.log('🧠 LEARNING SYSTEM: Attempting to start with AI learning integration');
    
    const automation = await getAutomationInstance();
    const result = await automation.start(config);
    
    // Add learning system status to response
    const response = {
      ...result,
      learningSystem: {
        integrated: typeof automation.getLearningStatus === 'function',
        type: automation.constructor.name
      }
    };
    
    if (result.success) {
      console.log('✅ AUTOMATION STARTED:', response.learningSystem.integrated ? 'With AI Learning' : 'Basic Mode');
      return NextResponse.json(response);
    } else {
      return NextResponse.json(response, { status: 400 });
    }
    
  } catch (error) {
    console.error('❌ Start automation error:', error);
    return NextResponse.json({ 
      success: false, 
      error: 'Internal server error',
      message: error.message,
      learningSystem: {
        integrated: false,
        error: 'Failed to initialize'
      }
    }, { status: 500 });
  }
}
