interface Config {
  wrenApiKey: string;
  formspreeContactId: string;
  formspreeOffsetId: string;
  isProduction: boolean;
}

// Get environment variables either from window.env (for Docker) or import.meta.env (for development)
const getEnv = (key: string): string => {
  // Extract the name without VITE_ prefix
  const varName = key.replace('VITE_', '');
  
  // First check if window.env exists and has the variable
  if (typeof window !== 'undefined' && window.env) {
    // In Docker, the env.sh script has already removed the VITE_ prefix
    const envValue = window.env[varName];
    if (envValue) {
      console.log(`Using ${varName} from window.env`);
      return envValue;
    }
  }
  
  // Fall back to Vite's import.meta.env (for development)
  // Here we need the full name with VITE_ prefix
  const value = import.meta.env[key];
  return typeof value === 'string' ? value : '';
};

// Load environment variables
const wrenApiKey = getEnv('VITE_WREN_API_TOKEN');
const formspreeContactId = getEnv('VITE_FORMSPREE_CONTACT_ID');
const formspreeOffsetId = getEnv('VITE_FORMSPREE_OFFSET_ID');

// Initialize config
export const config: Config = {
  wrenApiKey: wrenApiKey || '',
  formspreeContactId: formspreeContactId || 'xkgovnby',
  formspreeOffsetId: formspreeOffsetId || 'xvgzbory',
  isProduction: import.meta.env.PROD === true
};

// Validate required environment variables
if (!config.wrenApiKey) {
  console.error('Missing required environment variable: WREN_API_TOKEN');
  console.error('Current environment:', window?.env ? JSON.stringify(window.env) : 'No window.env available');
}

// Log config in development
if (!config.isProduction) {
  console.log('Config:', {
    ...config,
    wrenApiKey: config.wrenApiKey ? '[REDACTED]' : 'MISSING'
  });
}
