#!/usr/bin/env bash

set -euo pipefail

ENV_FILE="${1:-}"
BATCH="${2:-all}"

if [[ -z "${ENV_FILE}" ]]; then
  echo "Usage: bash scripts/check_validation_env.sh <env-file> [batch]"
  exit 1
fi

if [[ ! -f "${ENV_FILE}" ]]; then
  echo "Env file not found: ${ENV_FILE}"
  exit 1
fi

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

check_vars() {
  local label="$1"
  shift
  local missing=()
  local var_name value

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

  if (( ${#missing[@]} > 0 )); then
    echo ""
    echo "[FAIL] ${label}"
    printf '  - missing: %s\n' "${missing[@]}"
    return 1
  fi

  echo ""
  echo "[PASS] ${label}"
  return 0
}

check_runtime_site() {
  if [[ -z "${SITE_ID:-}" && -z "${SITE_KEY:-}" ]]; then
    echo ""
    echo "[FAIL] runtime smoke"
    echo "  - missing: SITE_ID or SITE_KEY"
    return 1
  fi

  echo ""
  echo "[PASS] runtime smoke site scope"
  return 0
}

run_batch_check() {
  local batch_name="$1"
  local failed=0

  case "${batch_name}" in
    batch1|batch2)
      check_vars "validation smoke" API_BASE_URL ACCESS_TOKEN || failed=1
      ;;
    batch3)
      check_vars "editor smoke" API_BASE_URL ACCESS_TOKEN VARIANT_ID BASE_URL || failed=1
      ;;
    batch4)
      check_vars "runtime smoke" API_BASE_URL PAGE_URL EXPERIMENT_ID EXPERIMENT_KEY VARIANT_ID VARIANT_KEY || failed=1
      check_runtime_site || failed=1
      ;;
    batch1-3)
      run_batch_check batch1 || failed=1
      run_batch_check batch3 || failed=1
      ;;
    all)
      run_batch_check batch1 || failed=1
      run_batch_check batch3 || failed=1
      run_batch_check batch4 || failed=1
      ;;
    *)
      echo "Unknown batch: ${batch_name}"
      exit 1
      ;;
  esac

  return "${failed}"
}

if run_batch_check "${BATCH}"; then
  echo ""
  echo "Validation env check passed for '${BATCH}'."
else
  echo ""
  echo "Validation env check failed for '${BATCH}'."
  exit 1
fi
