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

REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
ENV_FILE="${1:-$REPO_ROOT/.env}"

if [[ ! -f "$ENV_FILE" ]]; then
  echo "Missing env file: $ENV_FILE"
  echo "Copy .env.example to .env and fill in the required values."
  exit 1
fi

required_vars=(
  COSMOS_ENDPOINT
  COSMOS_KEY
  JWT_SECRET
)

optional_vars=(
  GEMINI_API_KEY
)

missing_required=()
missing_optional=()

for var_name in "${required_vars[@]}"; do
  value="$(grep -E "^${var_name}=" "$ENV_FILE" | tail -n 1 | cut -d= -f2- || true)"
  if [[ -z "${value// }" ]] || [[ "$value" == your-* ]]; then
    missing_required+=("$var_name")
  fi
done

for var_name in "${optional_vars[@]}"; do
  value="$(grep -E "^${var_name}=" "$ENV_FILE" | tail -n 1 | cut -d= -f2- || true)"
  if [[ -z "${value// }" ]] || [[ "$value" == your-* ]]; then
    missing_optional+=("$var_name")
  fi
done

if ((${#missing_required[@]} > 0)); then
  echo "Missing required environment variables in $ENV_FILE:"
  printf '  - %s\n' "${missing_required[@]}"
  exit 1
fi

echo "Required environment variables look present in $ENV_FILE."

if ((${#missing_optional[@]} > 0)); then
  echo "Optional variables not set:"
  printf '  - %s\n' "${missing_optional[@]}"
  echo "Extraction features that call Gemini may not work until these are configured."
fi
