#!/bin/bash
# =============================================================================
# Shared .env loader for Aurora scripts
# =============================================================================
# Safely loads .env files without using `source`, which breaks on values
# containing special bash characters like ), (, !, etc.
#
# Usage: source shared/scripts/lib/load-env.sh
#        load_env              # loads .env from current directory
#        load_env .env.test    # loads a specific file
# =============================================================================

load_env() {
  local env_file="${1:-.env}"

  if [ ! -f "$env_file" ]; then
    return 0
  fi

  while IFS= read -r line || [ -n "$line" ]; do
    # Skip comments and empty lines
    [[ -z "$line" || "$line" =~ ^[[:space:]]*# ]] && continue

    # Skip lines without an = sign
    [[ "$line" != *"="* ]] && continue

    # Strip leading/trailing whitespace
    line="${line#"${line%%[![:space:]]*}"}"

    # Remove surrounding quotes from the value (KEY="value" → KEY=value)
    local key="${line%%=*}"
    local value="${line#*=}"
    value="${value#\"}" ; value="${value%\"}"
    value="${value#\'}" ; value="${value%\'}"

    export "$key=$value"
  done < "$env_file"
}
