const DEFAULT_API_BASE_URL = 'http://192.168.3.11:8000';

function trimTrailingSlash(value: string): string {
  return value.replace(/\/+$/, '');
}

function inferApiBaseUrl(): string {
  const envUrl = import.meta.env.VITE_API_BASE_URL;
  if (envUrl) return trimTrailingSlash(envUrl);

  if (typeof window !== 'undefined' && window.location.hostname) {
    return `${window.location.protocol}//${window.location.hostname}:8000`;
  }

  return DEFAULT_API_BASE_URL;
}

export const API_BASE_URL = inferApiBaseUrl();

function inferWsProgressUrl(): string {
  const envUrl = import.meta.env.VITE_WS_PROGRESS_URL;
  if (envUrl) return envUrl;

  const url = new URL('/ws/progress', API_BASE_URL);
  url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
  return url.toString();
}

export const WS_PROGRESS_URL = inferWsProgressUrl();
