// Singleton automation instance manager with learning integration
let automationInstance = null;

async function createAutomationInstance() {
  try {
    // Try to import the learning-enhanced automation first
    const AutomationWithLearning = (await import('./automation-with-learning-v2.js')).default;
    console.log('✅ Creating automation instance with AI learning system');
    return new AutomationWithLearning();
  } catch (error) {
    console.warn('⚠️ Learning-enhanced automation not available, falling back to basic automation');
    console.warn('Error:', error.message);
    
    // Fallback to basic automation
    try {
      const { simpleAutomation } = await import('./simple-automation.js');
      console.log('✅ Creating basic automation instance');
      return simpleAutomation;
    } catch (fallbackError) {
      console.error('❌ Could not create any automation instance:', fallbackError);
      throw new Error('No automation system available');
    }
  }
}

async function getAutomationInstance() {
  if (!automationInstance) {
    automationInstance = await createAutomationInstance();
  }
  return automationInstance;
}

async function resetAutomationInstance() {
  if (automationInstance) {
    console.log('🔄 Resetting automation instance');
    if (typeof automationInstance.stop === 'function') {
      await automationInstance.stop();
    }
  }
  automationInstance = null;
}

export {
  getAutomationInstance,
  resetAutomationInstance
};
