export type AMapRuntimeConfig = {
  webJsKey: string;
  securityJsCode: string;
  securityServiceHost: string;
};

export type AppRuntimeConfig = AMapRuntimeConfig & {
  apiBaseUrl: string;
  prototypeUseRealData: boolean;
};

function runtimeConfig() {
  return window.__LINGNIU_APP_CONFIG__ ?? {};
}

function boolFromConfig(value: unknown, defaultValue: boolean) {
  if (value == null || value === '') {
    return defaultValue;
  }
  if (typeof value === 'boolean') {
    return value;
  }
  return !['0', 'false', 'off', 'no'].includes(String(value).trim().toLowerCase());
}

export function getAMapConfig(): AMapRuntimeConfig {
  const runtime = runtimeConfig();
  return {
    webJsKey: String(runtime.amapWebJsKey || import.meta.env.VITE_AMAP_WEB_JS_KEY || '').trim(),
    securityJsCode: String(runtime.amapSecurityJsCode || import.meta.env.VITE_AMAP_SECURITY_JS_CODE || '').trim(),
    securityServiceHost: String(runtime.amapSecurityServiceHost || import.meta.env.VITE_AMAP_SECURITY_SERVICE_HOST || '').trim()
  };
}

export function isAMapConfigured(config = getAMapConfig()) {
  return Boolean(config.webJsKey);
}

export function getAppConfig(): AppRuntimeConfig {
  const runtime = runtimeConfig();
  const amap = getAMapConfig();
  return {
    ...amap,
    apiBaseUrl: String(runtime.apiBaseUrl || import.meta.env.VITE_API_BASE_URL || '').trim().replace(/\/$/, ''),
    prototypeUseRealData: boolFromConfig(
      runtime.prototypeUseRealData ?? import.meta.env.VITE_PROTOTYPE_REAL_DATA,
      true
    )
  };
}

export function getApiBaseUrl(config = getAppConfig()) {
  return config.apiBaseUrl;
}

export function shouldUsePrototypeRealData(config = getAppConfig()) {
  return config.prototypeUseRealData;
}
