/**
 * Handler auto-registration
 * Automatically discovers and registers all handlers
 */

import type { IServiceContainer } from '@stock-bot/handlers';
import { autoRegisterHandlers } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger';
// Import handlers for bundling (ensures they're included in the build)
import './ceo/ceo.handler';
import './ib/ib.handler';
import './proxy/proxy.handler';
import './qm/qm.handler';
import './webshare/webshare.handler';

// Add more handler imports as needed

const logger = getLogger('handler-init');

/**
 * Initialize and register all handlers automatically
 */
export async function initializeAllHandlers(serviceContainer: IServiceContainer): Promise<void> {
  try {
    // Auto-register all handlers in this directory
    const result = await autoRegisterHandlers(__dirname, serviceContainer, {
      pattern: '.handler.',
      exclude: ['test', 'spec'],
      dryRun: false,
    });

    logger.info('Handler auto-registration complete', {
      registered: result.registered,
      failed: result.failed,
    });

    if (result.failed.length > 0) {
      logger.error('Some handlers failed to register', { failed: result.failed });
    }
  } catch (error) {
    logger.error('Handler auto-registration failed', { error });
    // Fall back to manual registration
    await manualHandlerRegistration(serviceContainer);
  }
}

/**
 * Manual fallback registration
 */
async function manualHandlerRegistration(_serviceContainer: any): Promise<void> {
  logger.warn('Falling back to manual handler registration');

  try {

    logger.info('Manual handler registration complete');
  } catch (error) {
    logger.error('Manual handler registration failed', { error });
    throw error;
  }
}
