// lib/ipconfig.ts
// export function getRuntimeEnv(key: string): string | undefined {
//   if (typeof window !== "undefined" && typeof window.RUNTIME_ENV !== "undefined") {
//     return window.RUNTIME_ENV[key];
//   }
//   return process.env[key];
// }




// let _env: Record<string, string> | null = null
// export function getRuntimeEnv(key: string): string | undefined {
//   console.log("============>>Getting Supabase API URL.")

//   if (typeof window !== "undefined") {
//     if (!_env && typeof window.RUNTIME_ENV !== "undefined") {
//       _env = window.RUNTIME_ENV
//       console.log("[browser-side] Retrieved API endpoint from window.RUNTIME_ENV:", _env);
//     }

//     if (_env) {
//       console.log("[browser-side]Returning cached API from _env:", _env)
//       return _env[key]
//     }

//     console.log("[browser-side]No window.RUNTIME_ENV found in browser")
//     return undefined
//   }

//   // 服务端始终动态读取 process.env
//   const val = process.env[key]
//   console.log("[server-side] Falling back to process.env for key:", key, "value:", val)
//   return val
// }






let _env: Record<string, string> | null = null

// 最大重试次数
const MAX_RETRIES = 5
// 每次重试的延时（毫秒）
const RETRY_DELAY = 1000

export function getRuntimeEnv(key: string): string | undefined {
  console.log("============>>Getting Supabase API URL.")

  if (typeof window !== "undefined") {
    if (!_env && typeof window.RUNTIME_ENV !== "undefined") {
      _env = window.RUNTIME_ENV
      console.log("[browser-side] Retrieved API endpoint from window.RUNTIME_ENV:", _env)
    }

    // 尝试读取缓存的 _env
    if (_env) {
      console.log("[browser-side] Returning cached API from _env:", _env)
      return _env[key]
    }

    console.log("[browser-side] No window.RUNTIME_ENV found in browser, _env=", _env)

    let retries = 0
    // 定义一个同步延时重试的函数
    const tryGetEnvSync = () => {
      if (typeof window.RUNTIME_ENV !== "undefined") {
        _env = window.RUNTIME_ENV
        console.log("[browser-side] Retrieved API endpoint from window.RUNTIME_ENV:", _env)
        return _env[key]  // 成功获取，返回结果
      } else {
        retries += 1
        if (retries <= MAX_RETRIES) {
          console.log(`[browser-side] Retry ${retries}/${MAX_RETRIES} - Retrying in ${RETRY_DELAY}ms...`)
          // 延时并重试
          setTimeout(tryGetEnvSync, RETRY_DELAY)
        } else {
          console.log("[browser-side] Failed to retrieve window.RUNTIME_ENV after retries.")
          return undefined  // 重试次数耗尽，返回 undefined
        }
      }
    }

    return tryGetEnvSync()  // 调用同步重试方法
  }

  // 服务端始终动态读取 process.env
  const val = process.env[key]
  console.log("[server-side] Falling back to process.env for key:", key, "value:", val)
  return val  // 服务端直接返回 process.env 的值
}
