/**
 * Handler initialization for data-ingestion service
 * Uses explicit imports for bundling compatibility
 */

import { getLogger } from '@stock-bot/logger';
import type { IServiceContainer } from '@stock-bot/types';
// Import handlers explicitly for bundling (ensures they're included in the build)
// These imports trigger the decorator metadata to be set
import { CeoHandler } from './ceo/ceo.handler';
import { IbHandler } from './ib/ib.handler';
import { QMHandler } from './qm/qm.handler';
import { WebShareHandler } from './webshare/webshare.handler';
import { TradingViewHandler } from './tradingview/tradingview.handler';
import { TeHandler } from './te/te.handler';
import { EodHandler } from './eod/eod.handler';
import { createEODOperationRegistry } from './eod/shared';
import { createQMOperationRegistry } from './qm/shared/operation-provider';

// Add more handler imports as needed

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

// Global operation registries that handlers will reference
let eodOperationRegistry: any;
let qmOperationRegistry: any;

/**
 * Initialize and register all handlers
 * Note: The actual registration is now handled by the HandlerScanner in the DI container
 * This function is kept for backward compatibility and explicit handler imports
 */
export async function initializeAllHandlers(serviceContainer: IServiceContainer): Promise<void> {
  try {
    // Initialize operation registries first
    logger.info('Initializing operation registries');
    
    const mongodb = serviceContainer.mongodb;
    const operationLogger = serviceContainer.logger;
    
    // Create operation registries
    try {
      eodOperationRegistry = await createEODOperationRegistry(mongodb, operationLogger);
      logger.info('EOD operation registry created');
      
      // Attach to handler class so instances can access it
      (EodHandler as any).operationRegistry = eodOperationRegistry;
    } catch (error) {
      logger.error('Failed to create EOD operation registry', { error });
    }
    
    try {
      qmOperationRegistry = await createQMOperationRegistry(mongodb, operationLogger);
      logger.info('QM operation registry created');
      
      // Attach to handler class so instances can access it
      (QMHandler as any).operationRegistry = qmOperationRegistry;
    } catch (error) {
      logger.error('Failed to create QM operation registry', { error });
    }
    
    // The HandlerScanner in the DI container will handle the actual registration
    // We just need to ensure handlers are imported so their decorators run

    const handlers = [CeoHandler, IbHandler, QMHandler, WebShareHandler, TradingViewHandler, TeHandler, EodHandler];

    logger.info('Handler imports loaded', {
      count: handlers.length,
      handlers: handlers.map(h => (h as any).__handlerName || h.name),
    });

    // Log what metadata the handlers have
    for (const HandlerClass of handlers) {
      const metadata = (HandlerClass as any).__handlerMetadata;
      logger.info(`Handler ${HandlerClass.name} metadata`, {
        hasMetadata: !!metadata,
        handlerName: metadata?.name,
        operationCount: metadata?.operations?.length || 0,
        scheduledJobCount: metadata?.scheduledJobs?.length || 0,
      });
    }

    // Get the DI container from the service container
    const diContainer = (serviceContainer as any)._diContainer;

    if (diContainer?.resolve) {
      // Get handler scanner from DI container
      const scanner = diContainer.resolve('handlerScanner');
      if (scanner?.registerHandlerClass) {
        for (const HandlerClass of handlers) {
          scanner.registerHandlerClass(HandlerClass, { serviceName: 'data-ingestion' });
        }
        logger.info('Handlers registered with scanner');
      } else {
        logger.warn('Handler scanner not found or missing registerHandlerClass method');
      }

      // Also check the handler registry directly
      const handlerRegistry = diContainer.resolve('handlerRegistry');
      if (handlerRegistry) {
        logger.info('Handler registry state after registration', {
          registeredHandlers: handlerRegistry.getHandlerNames(),
          handlersWithSchedule: handlerRegistry.getAllHandlersWithSchedule().size,
        });
        
      }
    } else {
      logger.error('Could not access DI container from service container');
    }
  } catch (error) {
    logger.error('Handler initialization failed', { error });
    throw error;
  }
}
