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);
    return null;
  }
}

export async function GET() {
  try {
    const automation = await getAutomationInstance();
    
    if (!automation) {
      return NextResponse.json({ 
        error: 'No automation instance available',
        isRunning: false,
        learningSystem: { enabled: false }
      }, { status: 503 });
    }
    
    const status = automation.getStatus();
    
    // Add learning system status if available
    if (typeof automation.getLearningStatus === 'function') {
      try {
        const learningStatus = await automation.getLearningStatus();
        status.learningSystem = learningStatus;
      } catch (learningError) {
        status.learningSystem = { 
          enabled: false, 
          error: learningError.message 
        };
      }
    } else {
      status.learningSystem = { 
        enabled: false, 
        message: 'Basic automation - learning not integrated' 
      };
    }
    
    return NextResponse.json(status);
  } catch (error) {
    console.error('❌ Status error:', error);
    return NextResponse.json({ 
      error: 'Failed to get status',
      message: error.message,
      isRunning: false,
      learningSystem: { enabled: false, error: 'Status check failed' }
    }, { status: 500 });
  }
}
