import json
import base64
import brotli

from typing import Any, Dict, Optional


def base64_url_encode(data: bytes) -> str:
  """
  Base64 URL-safe encoding without padding.
  """
  encoded = base64.urlsafe_b64encode(data).decode("ascii")
  return encoded.rstrip("=")


def get_params(
  config: Optional[Any],
  brotli_cfg: Optional[Any],
  query_or_filter: Optional[Any] = None,
) -> Dict[str, Any]:
  config = dict(config or {})
  query_or_filter = query_or_filter or {}

  params = {}
  params.update(query_or_filter or {})
  params.update(config.get("params") or {})

  if brotli_cfg is not None and brotli_cfg is not False:
    quality = None
    if isinstance(brotli_cfg, dict):
      quality = dict(brotli_cfg).get("quality")
      quality = 8 if quality is None else int(quality)
    elif isinstance(brotli_cfg, int):
      quality = brotli_cfg
    else:
      quality = 8

    params = json.dumps(params).encode("utf-8")
    compressed = brotli.compress(params, quality=quality)
    return {"q": base64_url_encode(compressed)}
  else:
    return params
