/* eslint-disable @typescript-eslint/no-explicit-any */

type EnvOptions = {
  required?: boolean;
  secure?: boolean;
  trimTrailingSlash?: boolean;
  stripDocsSuffix?: boolean;
};

const URL_FALLBACKS: Record<string, string> = {
  // Only public/third-party service URLs with reasonable defaults
  // All internal infrastructure URLs MUST come from .env file
};

function readEnvValue(name: string): string {
  // Static references to help Vite's static replacement engine during production builds.
  // Vite replaces these with literal strings at build time.
  const staticMap: Record<string, string | undefined> = {
    VITE_API_URL: import.meta.env.VITE_API_URL,
    VITE_RECORD_API_URL: import.meta.env.VITE_RECORD_API_URL,
    VITE_PERFORMANCE_API_URL: import.meta.env.VITE_PERFORMANCE_API_URL,
    VITE_OBJECTIVE_API_URL: import.meta.env.VITE_OBJECTIVE_API_URL,
    VITE_DMS_API_URL: import.meta.env.VITE_DMS_API_URL,
    VITE_API_BASE_URL: import.meta.env.VITE_API_BASE_URL,
    VITE_TIME_API_URL: import.meta.env.VITE_TIME_API_URL,
    VITE_TIME_FALLBACK_API_URL: import.meta.env.VITE_TIME_FALLBACK_API_URL,
    VITE_CHRONICLE_URL: import.meta.env.VITE_CHRONICLE_URL,
    VITE_AUDITLOG_API_URL: import.meta.env.VITE_AUDITLOG_API_URL,
  };

  const value = staticMap[name] || (import.meta as any)?.env?.[name];
  return typeof value === "string" ? value.trim() : "";
}

function ensureSecureProtocol(value: string): string {
  if (
    !value ||
    typeof window === "undefined" ||
    window.location.protocol !== "https:"
  ) {
    return value;
  }

  if (value.startsWith("http://")) {
    return `https://${value.slice("http://".length)}`;
  }

  if (value.startsWith("ws://")) {
    return `wss://${value.slice("ws://".length)}`;
  }

  return value;
}

export function normalizeSecureUrl(value: string): string {
  return ensureSecureProtocol((value || "").trim());
}

export function getEnv(name: string, options: EnvOptions = {}): string {
  const {
    required = false,
    secure = false,
    trimTrailingSlash = false,
    stripDocsSuffix = false,
  } = options;

  let value = readEnvValue(name);

  if (!value && Object.prototype.hasOwnProperty.call(URL_FALLBACKS, name)) {
    value = URL_FALLBACKS[name];
  }

  if (!value) {
    if (required) {
      console.warn(`Missing ${name}`);
    }
    return "";
  }

  if (secure) {
    value = normalizeSecureUrl(value);
  }

  if (trimTrailingSlash) {
    value = value.replace(/\/+$/, "");
  }

  if (stripDocsSuffix) {
    value = value.replace(/\/docs$/, "");
  }

  return value;
}

export function getEnvUrl(name: string, required = true): string {
  return getEnv(name, {
    required,
    secure: true,
    trimTrailingSlash: true,
    stripDocsSuffix: true,
  });
}

/**
 * Read a URL from env WITHOUT using hardcoded fallbacks.
 * This enforces that the value MUST be provided in .env file.
 * Throws an error if the env var is not set.
 */
export function getEnvUrlStrict(name: string): string {
  const value = readEnvValue(name);

  if (!value) {
    throw new Error(
      `Missing required env variable: ${name}. Must be defined in .env file (no fallback allowed).`,
    );
  }

  // Apply standard URL transformations
  const normalized = normalizeSecureUrl(value);
  const trimmed = normalized.replace(/\/+$/, "");
  const cleaned = trimmed.replace(/\/docs$/, "");

  return cleaned;
}
