import type { AwilixContainer } from 'awilix';
import type { AppConfig as StockBotAppConfig } from '@stock-bot/config';
import { ServiceContainerBuilder } from './builder';
import type { ServiceDefinitions, ServiceContainerOptions } from './types';

/**
 * Creates a service container from raw configuration
 * @deprecated Use ServiceContainerBuilder instead
 */
export function createServiceContainer(rawConfig: unknown): AwilixContainer<ServiceDefinitions> {
  // For backward compatibility, we need to create the container synchronously
  // This means we'll use the original implementation pattern
  const { createContainer, InjectionMode, asValue: _asValue, asFunction } = require('awilix');
  const { appConfigSchema } = require('../config/schemas');
  const config = appConfigSchema.parse(rawConfig);
  
  const container = createContainer({
    injectionMode: InjectionMode.PROXY,
    strict: true,
  });

  // Register all services synchronously
  const { 
    registerCoreServices,
    registerCacheServices,
    registerDatabaseServices,
    registerApplicationServices 
  } = require('../registrations');
  
  registerCoreServices(container, config);
  registerCacheServices(container, config);
  registerDatabaseServices(container, config);
  registerApplicationServices(container, config);
  
  // Register service container aggregate
  container.register({
    serviceContainer: asFunction((cradle: ServiceDefinitions) => ({
      logger: cradle.logger,
      cache: cradle.cache,
      proxy: cradle.proxyManager, // Map proxyManager to proxy
      browser: cradle.browser,
      queue: cradle.queueManager, // Map queueManager to queue
      mongodb: cradle.mongoClient, // Map mongoClient to mongodb
      postgres: cradle.postgresClient, // Map postgresClient to postgres
      questdb: cradle.questdbClient, // Map questdbClient to questdb
    })).singleton(),
  });

  return container;
}


/**
 * Creates a service container from StockBotAppConfig
 * @deprecated Use ServiceContainerBuilder instead
 */
export function createServiceContainerFromConfig(
  appConfig: StockBotAppConfig,
  options: ServiceContainerOptions = {}
): AwilixContainer<ServiceDefinitions> {
  const builder = new ServiceContainerBuilder();
  return builder
    .withConfig(appConfig)
    .withOptions({
      ...options,
      skipInitialization: true, // Legacy behavior
    })
    .build()
    .then(container => container)
    .catch(error => {
      throw error;
    }) as any; // Sync interface for backward compatibility
}

/**
 * Modern async factory for creating service containers
 */
export async function createServiceContainerAsync(
  config: StockBotAppConfig,
  options: ServiceContainerOptions = {}
): Promise<AwilixContainer<ServiceDefinitions>> {
  const builder = new ServiceContainerBuilder();
  return builder
    .withConfig(config)
    .withOptions(options)
    .build();
}

/**
 * Initialize services in an existing container
 * @deprecated Handled automatically by ServiceContainerBuilder
 */
export async function initializeServices(
  container: AwilixContainer<ServiceDefinitions>
): Promise<void> {
  const { ServiceLifecycleManager } = await import('../utils/lifecycle');
  const lifecycleManager = new ServiceLifecycleManager();
  await lifecycleManager.initializeServices(container);
}