import os
import json

from typing import Any, List


def ENV(key: str, default: Any = None) -> Any:
  """
  Get an environment variable, attempting to JSON-parse it if it's a string.
  If the variable is not set and no default is provided, returns None.
  """
  raw = os.getenv(key)
  val = raw if raw is not None else default

  if isinstance(val, str):
    try:
      return json.loads(val)
    except json.JSONDecodeError:
      return val
  return val


def ENV_A(key: str, default: List[Any] | None = None) -> List[Any]:
  """
  Get a comma-separated environment variable as a list.
  Defaults to an empty list if not set and no default provided.
  Avoids Python's mutable default argument pitfall.
  """
  if default is None:
    default = []

  raw = os.getenv(key)
  if raw is not None:
    return raw.split(",")
  return default
