import { ConfigManager, createAppConfig } from '@stock-bot/engine-config';
import * as path from 'path';
import { wcagAppConfigSchema, type WcagAppConfig } from './schemas/wcag-app.schema';

let configInstance: ConfigManager<WcagAppConfig> | null = null;

/**
 * Initialize the WCAG-ADA configuration
 * @param serviceName - Optional service name for service-specific overrides
 */
export function initializeWcagConfig(
  serviceName?: 'api' | 'dashboard' | 'worker'
): WcagAppConfig {
  if (!configInstance) {
    configInstance = createAppConfig(wcagAppConfigSchema, {
      configPath: path.join(__dirname, '../config'),
      envPrefix: 'WCAG_',
    });
  }

  const config = configInstance.initialize(wcagAppConfigSchema);

  // Apply service-specific overrides if provided
  if (serviceName && config.services[serviceName]) {
    const serviceConfig = config.services[serviceName];
    
    // Override port if specified for the service
    if (serviceConfig.port && process.env.PORT) {
      serviceConfig.port = parseInt(process.env.PORT, 10);
    }
  }

  return config;
}

/**
 * Get the current WCAG configuration instance
 * @throws Error if configuration hasn't been initialized
 */
export function getWcagConfig(): WcagAppConfig {
  if (!configInstance) {
    throw new Error('WCAG configuration not initialized. Call initializeWcagConfig() first.');
  }
  return configInstance.get();
}

/**
 * Get a specific configuration value by path
 * @param path - Dot-notation path to the configuration value
 */
export function getConfigValue<T = unknown>(path: string): T {
  if (!configInstance) {
    throw new Error('WCAG configuration not initialized. Call initializeWcagConfig() first.');
  }
  return configInstance.getValue<T>(path);
}

/**
 * Check if a configuration path exists
 * @param path - Dot-notation path to check
 */
export function hasConfigValue(path: string): boolean {
  if (!configInstance) {
    return false;
  }
  return configInstance.has(path);
}