type RuntimeConfig = {
  API_BASE_URL?: string;
  STORAGE_BASE_URL?: string;
};

declare global {
  interface Window {
    __DMT_MODEL_LIBRARY_CONFIG__?: RuntimeConfig;
  }
}

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

function cleanBaseUrl(value?: string) {
  return value?.trim().replace(/\/+$/g, "") ?? "";
}

function isAbsoluteUrl(url: string) {
  return /^https?:\/\//i.test(url);
}

function joinUrl(baseUrl: string, path: string) {
  if (!baseUrl || isAbsoluteUrl(path)) return path;
  return `${baseUrl}${path.startsWith("/") ? "" : "/"}${path}`;
}

function joinApiUrl(baseUrl: string, path: string) {
  if (!baseUrl || isAbsoluteUrl(path)) return path;

  try {
    const base = new URL(baseUrl);
    if (base.pathname.replace(/\/+$/g, "") === "/api" && path.startsWith("/api/")) {
      return joinUrl(baseUrl, path.slice(4));
    }
  } catch {
    // 非完整 URL 时按普通路径拼接。
  }

  return joinUrl(baseUrl, path);
}

export function resolveApiUrl(path: string) {
  return joinApiUrl(cleanBaseUrl(runtimeConfig().API_BASE_URL), path);
}

export function resolveStorageUrl(path: string) {
  const storageBaseUrl = cleanBaseUrl(runtimeConfig().STORAGE_BASE_URL);
  const apiBaseUrl = cleanBaseUrl(runtimeConfig().API_BASE_URL);
  return joinUrl(storageBaseUrl || apiBaseUrl, path);
}
