#!/usr/bin/env bash
set -euo pipefail

ENV_FILE="${1:?Usage: $0 <env-file>}"

if [[ ! -f "$ENV_FILE" ]]; then
  echo "Environment file not found: $ENV_FILE" >&2
  exit 1
fi

set -a
# shellcheck disable=SC1090
source "$ENV_FILE"
set +a

DJANGO_ENV="${DJANGO_ENV:-prod}"

required_vars=(
  DJANGO_SECRET_KEY
  DJANGO_ALLOWED_HOSTS
  DB_PASSWORD
  DB_NAME
  DB_USER
  DATABASE_URL
)

if [[ "$DJANGO_ENV" == "prod" || "$DJANGO_ENV" == "beta" ]]; then
  required_vars+=(
    RECAPTCHA_PUBLIC_KEY
    RECAPTCHA_PRIVATE_KEY
    EMAIL_HOST_USER
    EMAIL_HOST_PASSWORD
  )
fi

if [[ "$DJANGO_ENV" == "prod" ]]; then
  required_vars+=(TIANJI_WEBSITE_ID)
fi

missing=()
for var in "${required_vars[@]}"; do
  if [[ -z "${!var:-}" ]]; then
    missing+=("$var")
  fi
done

if ((${#missing[@]} > 0)); then
  echo "Missing required environment variables in $ENV_FILE:" >&2
  printf '  - %s\n' "${missing[@]}" >&2
  echo "Copy .env.prod.example to .env on the server and set production values." >&2
  exit 1
fi

if [[ "$DJANGO_ENV" == "prod" && "$DJANGO_SECRET_KEY" == change-me* ]]; then
  echo "DJANGO_SECRET_KEY must be changed from the example value for production." >&2
  exit 1
fi

echo "Environment validation passed (DJANGO_ENV=$DJANGO_ENV)."
