import * as path from 'path';
import { fileURLToPath } from 'url';
import { ConfigManager, createAppConfig } from '@stock-bot/config';
import { getLogger } from '@stock-bot/logger';
import { stockAppSchema, type StockAppConfig } from './schemas';

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

// ESM-compatible __dirname
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

/**
 * Initialize the stock application configuration
 * @param serviceName - Optional service name to override port configuration
 */
export function initializeStockConfig(
  serviceName?: 'dataIngestion' | 'dataPipeline' | 'webApi' | 'orchestrator'
): StockAppConfig {
  try {
    if (!configInstance) {
      configInstance = createAppConfig(stockAppSchema, {
        configPath: path.join(__dirname, '../config'),
      });
    }

    const config = configInstance.initialize(stockAppSchema);

    // If a service name is provided, override the service port
    if (serviceName && config.services?.[serviceName]) {
      const kebabName = serviceName
        .replace(/([A-Z])/g, '-$1')
        .toLowerCase()
        .replace(/^-/, '');
      return {
        ...config,
        service: {
          ...config.service,
          port: config.services[serviceName].port,
          name: serviceName, // Keep original for backward compatibility
          serviceName: kebabName, // Standard kebab-case name
        },
      };
    }

    return config;
  } catch (error) {
    const logger = getLogger('stock-config');
    const errorMessage = error instanceof Error ? error.message : String(error);
    logger.error('Failed to initialize stock configuration:', errorMessage);
    if (error && typeof error === 'object' && 'errors' in error) {
      logger.error('Validation errors:', error.errors);
    }
    throw error;
  }
}

/**
 * Get the current stock configuration
 */
export function getStockConfig(): StockAppConfig {
  if (!configInstance) {
    // Auto-initialize if not already done
    return initializeStockConfig();
  }
  return configInstance.get();
}

/**
 * Get configuration for a specific service
 */
export function getServiceConfig(service: 'dataIngestion' | 'dataPipeline' | 'webApi') {
  const config = getStockConfig();
  return config.services?.[service];
}

/**
 * Get configuration for a specific provider
 */
export function getProviderConfig(provider: 'eod' | 'ib' | 'qm' | 'yahoo') {
  const config = getStockConfig();
  return config.providers[provider];
}

/**
 * Check if a feature is enabled
 */
export function isFeatureEnabled(feature: keyof StockAppConfig['features']): boolean {
  const config = getStockConfig();
  return config.features[feature];
}

/**
 * Reset configuration (useful for testing)
 */
export function resetStockConfig(): void {
  configInstance = null;
}
