#!/usr/bin/env bash
# Check that .env has the VITE_* (and related) vars needed for frontend-dapp production build.
# Usage: ./scripts/deployment/check-dapp-env.sh [path-to-.env]
# Exit 0 if all required are set; exit 1 and list missing if not.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
# Load .env via dotenv (RPC CR/LF trim). Fallback: raw source.
if [[ -f "$SCRIPT_DIR/../lib/deployment/dotenv.sh" ]]; then
  # shellcheck disable=SC1090
  source "$SCRIPT_DIR/../lib/deployment/dotenv.sh"
  load_deployment_env --repo-root "${PROJECT_ROOT:-$REPO_ROOT}"
elif [[ -n "${PROJECT_ROOT:-}" && -f "$PROJECT_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/.env"
  set +a
elif [[ -n "${REPO_ROOT:-}" && -f "$REPO_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$REPO_ROOT/.env"
  set +a
fi
ENV_FILE="${1:-$REPO_ROOT/.env}"

get_var() {
  local name="$1"
  if [[ ! -f "$ENV_FILE" ]]; then
    echo ""
    return
  fi
  local line
  line="$(grep -E "^(export[[:space:]]+)?${name}=" "$ENV_FILE" 2>/dev/null | head -1)"
  if [[ -n "$line" ]]; then
    echo "$line" | sed -E 's/^(export[[:space:]]+)?[^=]+=//' | sed 's/^["'\'' ]//;s/["'\'' ]$//' | xargs
  else
    echo ""
  fi
}

REQUIRED_FOR_BUILD=(
  "VITE_RPC_URL_138"
)
OPTIONAL_BUT_RECOMMENDED=(
  "VITE_LOCKBOX_138"
  "VITE_INBOX_ETH_MAINNET"
  "VITE_LIQUIDITY_POOL_ETH_MAINNET"
  "VITE_DUAL_ROUTER_BRIDGE_SWAP_COORDINATOR"
  "VITE_CHALLENGE_MANAGER_MAINNET"
  "VITE_WALLETCONNECT_PROJECT_ID"
  "VITE_THIRDWEB_CLIENT_ID"
)

missing=()
for v in "${REQUIRED_FOR_BUILD[@]}"; do
  val="$(get_var "$v")"
  if [[ -z "$val" || "$val" == "0x..." || "$val" == "your-"* ]]; then
    missing+=("$v")
  fi
done

if [[ ${#missing[@]} -gt 0 ]]; then
  echo "Missing or placeholder required for DApp build: ${missing[*]}"
  echo "Set them in $ENV_FILE (or copy from .env.example and fill)."
  exit 1
fi

echo "Required VITE_* for DApp build are set."
for v in "${OPTIONAL_BUT_RECOMMENDED[@]}"; do
  val="$(get_var "$v")"
  if [[ -z "$val" || "$val" == "0x..." || "$val" == "your-"* ]]; then
    echo "Optional (recommended): $v"
  fi
done
exit 0
