const resolveApiUrl = () => {
  const env = process.env.NODE_ENV;
  const envApiUrl = process.env.REACT_APP_API_URL;

  if (env === 'production') {
    if (envApiUrl && envApiUrl.trim() !== '') return envApiUrl;
    return 'https://infogenie.api.shumengya.top';
  }

  if (envApiUrl && envApiUrl.trim() !== '') return envApiUrl;
  return 'http://127.0.0.1:5002';
};

const resolveAuthUrl = () => {
  const env = process.env.NODE_ENV;
  const envAuthUrl = process.env.REACT_APP_AUTH_URL;

  if (env === 'production') {
    if (envAuthUrl && envAuthUrl.trim() !== '') return envAuthUrl;
    return 'https://auth.shumengya.top';
  }

  if (envAuthUrl && envAuthUrl.trim() !== '') return envAuthUrl;
  return 'https://auth.shumengya.top';
};

const resolveAuthApiUrl = () => {
  const env = process.env.NODE_ENV;
  const envAuthApiUrl = process.env.REACT_APP_AUTH_API_URL;

  if (env === 'production') {
    if (envAuthApiUrl && envAuthApiUrl.trim() !== '') return envAuthApiUrl;
    return 'https://auth.api.shumengya.top';
  }

  if (envAuthApiUrl && envAuthApiUrl.trim() !== '') return envAuthApiUrl;
  return 'https://auth.api.shumengya.top';
};

const config = {
  API_URL: resolveApiUrl(),
  AUTH_URL: resolveAuthUrl(),
  AUTH_API_URL: resolveAuthApiUrl(),
  DEBUG: process.env.REACT_APP_DEBUG === 'true',
  LOG_LEVEL: 'debug',
};

export const ENV_CONFIG = {
  API_URL: config.API_URL,
  AUTH_URL: config.AUTH_URL,
  AUTH_API_URL: config.AUTH_API_URL,
  DEBUG: config.DEBUG,
  LOG_LEVEL: config.LOG_LEVEL,
  APP_NAME: 'InfoGenie',
  APP_VERSION: '2.2.3',
  CLIENT_ID: 'infogenie',
  CLIENT_NAME: '万象口袋',
};

export const getEnvVar = (key, defaultValue = '') => {
  switch (key) {
    case 'REACT_APP_API_URL': return ENV_CONFIG.API_URL;
    case 'REACT_APP_AUTH_URL': return ENV_CONFIG.AUTH_URL;
    case 'REACT_APP_AUTH_API_URL': return ENV_CONFIG.AUTH_API_URL;
    default: return process.env[key] || defaultValue;
  }
};

if (typeof window !== 'undefined') {
  window.ENV_CONFIG = ENV_CONFIG;
}

export default ENV_CONFIG;
