/**
 * Pilot Program Configuration
 *
 * Centralized configuration for pilot mode features.
 *
 * Works in two modes:
 * 1. Kubernetes/Docker: Reads from window.__RUNTIME_CONFIG__ (injected at container startup)
 * 2. Local Development: Reads from import.meta.env (build-time variables from .env)
 */

/**
 * Helper function to get environment variable value
 * Tries runtime config first (Kubernetes), falls back to build-time (local dev)
 */
const getEnvVar = (key: string): string | undefined => {
  // Try runtime config first (Kubernetes/Docker environment)
  if (typeof window !== 'undefined' && (window as any).__RUNTIME_CONFIG__) {
    const value = (window as any).__RUNTIME_CONFIG__[key];
    if (value !== undefined) {
      return value;
    }
  }

  // Fallback to build-time environment variables (local development)
  return import.meta.env[key];
};

/**
 * Create pilot config with getter functions to ensure we always read fresh values
 * This is important because runtime-config.js might load after this module
 */
const createPilotConfig = () => {
  return {
    /**
     * Master switch for pilot mode
     * When false, all pilot features are disabled globally
     */
    get enabled(): boolean {
      const value = getEnvVar('VITE_PILOT_MODE_ENABLED');
      return value === 'true';
    },

    /**
     * Coupon code for pilot participants
     */
    get couponCode(): string {
      return getEnvVar('VITE_PILOT_COUPON_CODE') || 'PILOT2025';
    },

    /**
     * Trial period in months for pilot participants
     */
    get trialMonths(): number {
      return parseInt(getEnvVar('VITE_PILOT_TRIAL_MONTHS') || '3');
    },

    /**
     * Trial period in days (calculated from months)
     */
    get trialDays(): number {
      return this.trialMonths * 30;
    },

    /**
     * Lifetime discount percentage for pilot participants
     */
    lifetimeDiscount: 20,
  };
};

export const PILOT_CONFIG = createPilotConfig();

// Debug logging
console.log('🔧 Pilot Config Loading:', {
  source: typeof window !== 'undefined' && (window as any).__RUNTIME_CONFIG__ ? 'runtime' : 'build-time',
  raw: getEnvVar('VITE_PILOT_MODE_ENABLED'),
  type: typeof getEnvVar('VITE_PILOT_MODE_ENABLED'),
  enabled: PILOT_CONFIG.enabled,
  runtimeConfigExists: typeof window !== 'undefined' && !!(window as any).__RUNTIME_CONFIG__,
  runtimeConfigKeys: typeof window !== 'undefined' && (window as any).__RUNTIME_CONFIG__
    ? Object.keys((window as any).__RUNTIME_CONFIG__)
    : []
});

console.log('✅ Pilot Config:', {
  enabled: PILOT_CONFIG.enabled,
  couponCode: PILOT_CONFIG.couponCode,
  trialMonths: PILOT_CONFIG.trialMonths,
  trialDays: PILOT_CONFIG.trialDays
});

export default PILOT_CONFIG;
