const ENV_TYPE = {
  DEV: 'dev',
  TEST: 'test',
  PROD: 'prod'
}

const normalizeEnv = (value) => {
  if (!value) return ENV_TYPE.DEV
  if (value === 'development' || value === 'dev') return ENV_TYPE.DEV
  if (value === 'production' || value === 'prod') return ENV_TYPE.PROD
  if (value === 'test') return ENV_TYPE.TEST
  return ENV_TYPE.DEV
}

const currentEnv = normalizeEnv(import.meta.env.VITE_APP_ENV || import.meta.env.MODE)

const envConfig = {
  [ENV_TYPE.DEV]: {
    API_BASE_URL: 'http://localhost:19089',
    WS_URL: 'ws://localhost:19089',
    DEBUG: true
  },
  [ENV_TYPE.TEST]: {
    API_BASE_URL: 'https://lifescript.happylifeos.com/api',
    WS_URL: 'wss://lifescript.happylifeos.com/ws',
    DEBUG: true
  },
  [ENV_TYPE.PROD]: {
    API_BASE_URL: 'https://lifescript.happylifeos.com/api',
    WS_URL: 'wss://lifescript.happylifeos.com/ws',
    DEBUG: false
  }
}

const getConfig = () => {
  const base = envConfig[currentEnv] || envConfig[ENV_TYPE.DEV]
  const apiBaseUrl = import.meta.env.VITE_API_BASE_URL || base.API_BASE_URL
  const wsUrl = import.meta.env.VITE_WS_URL || base.WS_URL
  const debug = import.meta.env.VITE_DEBUG !== undefined
    ? import.meta.env.VITE_DEBUG === 'true'
    : base.DEBUG

  // 添加诊断日志
  if (debug) {
    console.log('[ENV] 环境配置:', {
      rawEnv: import.meta.env.VITE_APP_ENV,
      normalizedEnv: currentEnv,
      API_BASE_URL: apiBaseUrl,
      WS_URL: wsUrl,
      DEBUG: debug,
      isFromEnvFile: import.meta.env.VITE_API_BASE_URL ? 'yes' : 'fallback-to-config'
    })
  }

  return {
    API_BASE_URL: apiBaseUrl,
    WS_URL: wsUrl,
    DEBUG: debug
  }
}

const getEnvValue = (key) => {
  const config = getConfig()
  return config[key]
}

const isDev = () => {
  return currentEnv === ENV_TYPE.DEV
}

const isTest = () => {
  return currentEnv === ENV_TYPE.TEST
}

const isProd = () => {
  return currentEnv === ENV_TYPE.PROD
}

export {
  ENV_TYPE,
  currentEnv,
  getConfig,
  getEnvValue,
  isDev,
  isTest,
  isProd
}

export default {
  ENV_TYPE,
  currentEnv,
  getConfig,
  getEnvValue,
  isDev,
  isTest,
  isProd
}
