#!/usr/bin/env bash
# Check smom-dbis-138/.env for required and optional variable names (no values printed).
# Usage: ./scripts/deployment/check-env-required.sh

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_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="${PROJECT_ROOT}/.env"

echo "=== .env check (keys only, no values) ==="
echo ""

if [ ! -f "$ENV_FILE" ]; then
  echo "  .env: MISSING"
  exit 1
fi

# Build list of key names (strip values; never print values)
keys_file=$(mktemp)
trap 'rm -f "$keys_file"' EXIT
grep -E '^[A-Za-z_][A-Za-z0-9_]*=' "$ENV_FILE" 2>/dev/null | sed 's/=.*//' > "$keys_file" || true
grep -E '^export [A-Za-z_][A-Za-z0-9_]*=' "$ENV_FILE" 2>/dev/null | sed 's/^export //; s/=.*//' >> "$keys_file" || true
sort -u "$keys_file" -o "$keys_file"

check() { grep -qx "$1" "$keys_file" 2>/dev/null; }
total=$(wc -l < "$keys_file")
echo "  .env: EXISTS ($total keys)"
echo ""

# Required for deploy-contracts-unified.sh and most Chain 138 scripts
echo "--- Required (deploy / Chain 138) ---"
for k in PRIVATE_KEY RPC_URL RPC_URL_138; do
  check "$k" && echo "  OK   $k" || echo "  MISS $k"
done

# PRIVATE_KEY format: 64 hex chars (no value printed). Use last assignment (dotenv override). Full value after first '='.
if check "PRIVATE_KEY"; then
  v="$(awk '
    /^PRIVATE_KEY=/ { v=$0; sub(/^PRIVATE_KEY=/, "", v); last=v }
    /^export[ \t]+PRIVATE_KEY=/ { v=$0; sub(/^export[ \t]+PRIVATE_KEY=/, "", v); last=v }
    END { print last }
  ' "$ENV_FILE" 2>/dev/null || true)"
  v="${v//$'\r'/}"
  v="${v#\"}"
  v="${v%\"}"
  v="${v#\'}"
  v="${v%\'}"
  v="$(printf '%s' "$v" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')"
  v="${v#0x}"
  len=${#v}
  if printf '%s' "$v" | grep -q '\${'; then
    echo "       PRIVATE_KEY format: SKIP (value references another var in file; length=$len — check resolved key after source)"
  elif [ "$len" = "64" ] && printf '%s' "$v" | grep -qE '^[0-9a-fA-F]{64}$'; then
    echo "       PRIVATE_KEY format: 64-char hex"
  else
    echo "       PRIVATE_KEY format: WARN (length=$len, expected 64 hex chars after optional 0x)"
  fi
fi
echo ""

# Optional for PMM pool script (create-all-dodo-pools-from-token-api.sh)
echo "--- Optional (PMM pools: DODO_PMM_INTEGRATION or DODO_PMM_INTEGRATION_ADDRESS, QUOTE_TOKEN or QUOTE_TOKEN_ADDRESS) ---"
for k in DODO_PMM_INTEGRATION DODO_PMM_INTEGRATION_ADDRESS QUOTE_TOKEN QUOTE_TOKEN_ADDRESS; do
  check "$k" && echo "  OK   $k" || echo "  --   $k"
done
echo ""

# Optional for mainnet dry-run
echo "--- Optional (mainnet dry-run) ---"
for k in ETHEREUM_MAINNET_RPC; do
  check "$k" && echo "  OK   $k" || echo "  --   $k"
done
echo ""

# Common CCIP / bridge
echo "--- Optional (CCIP / bridge) ---"
for k in CCIP_ROUTER LINK_TOKEN CCIPWETH9_BRIDGE_CHAIN138 CCIPWETH10_BRIDGE_CHAIN138; do
  check "$k" && echo "  OK   $k" || echo "  --   $k"
done
echo ""

echo "Done. Fix any MISS above; -- means optional and can be set when needed."
