const resolveApiUrl = () => {
  const mode = import.meta.env.MODE;
  const envApiUrl = import.meta.env.VITE_API_URL;

  if (mode === '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 mode = import.meta.env.MODE;
  const envAuthUrl = import.meta.env.VITE_AUTH_URL;

  if (mode === '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 mode = import.meta.env.MODE;
  const envAuthApiUrl = import.meta.env.VITE_AUTH_API_URL;

  if (mode === '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: import.meta.env.VITE_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 'VITE_API_URL': return ENV_CONFIG.API_URL;
    case 'VITE_AUTH_URL': return ENV_CONFIG.AUTH_URL;
    case 'VITE_AUTH_API_URL': return ENV_CONFIG.AUTH_API_URL;
    default: return defaultValue;
  }
};

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

export default ENV_CONFIG;
