#!/usr/bin/env bash

set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
ENV_FILE="${ROOT_DIR}/.env.local"
SECRET_KEY="${CLERK_SECRET_KEY:-}"
PUBLISHABLE_KEY="${NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY:-${CLERK_PUBLISHABLE_KEY:-}}"

usage() {
  cat <<'EOF'
Usage:
  scripts/setup-clerk-keys.sh --secret-key sk_test_xxx --publishable-key pk_test_xxx

Options:
  --secret-key VALUE        Clerk secret key to store as CLERK_SECRET_KEY
  --publishable-key VALUE   Clerk publishable key to store as NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY
  --env-file PATH           Target env file (default: .env.local)
  --help                    Show this message

Notes:
  - Real Clerk keys are created by Clerk, not generated offline by this script.
  - Find them in the Clerk Dashboard > API Keys.
EOF
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --secret-key)
      SECRET_KEY="${2:-}"
      shift 2
      ;;
    --publishable-key)
      PUBLISHABLE_KEY="${2:-}"
      shift 2
      ;;
    --env-file)
      ENV_FILE="${2:-}"
      shift 2
      ;;
    --help|-h)
      usage
      exit 0
      ;;
    *)
      echo "Unknown argument: $1" >&2
      usage >&2
      exit 1
      ;;
  esac
done

prompt_if_missing() {
  local var_name="$1"
  local label="$2"
  local current_value="$3"

  if [[ -n "$current_value" ]]; then
    printf '%s' "$current_value"
    return 0
  fi

  read -r -p "${label}: " current_value
  printf '%s' "$current_value"
}

SECRET_KEY="$(prompt_if_missing "CLERK_SECRET_KEY" "Enter your Clerk secret key (sk_test_... or sk_live_...)" "$SECRET_KEY")"
PUBLISHABLE_KEY="$(prompt_if_missing "NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY" "Enter your Clerk publishable key (pk_test_... or pk_live_...)" "$PUBLISHABLE_KEY")"

validate_prefix() {
  local value="$1"
  local name="$2"
  local prefix_a="$3"
  local prefix_b="$4"

  if [[ -z "$value" ]]; then
    echo "${name} is required." >&2
    exit 1
  fi

  if [[ "$value" != "${prefix_a}"* && "$value" != "${prefix_b}"* ]]; then
    echo "${name} must start with ${prefix_a} or ${prefix_b}." >&2
    exit 1
  fi
}

validate_prefix "$SECRET_KEY" "CLERK_SECRET_KEY" "sk_test_" "sk_live_"
validate_prefix "$PUBLISHABLE_KEY" "NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY" "pk_test_" "pk_live_"

mkdir -p "$(dirname "$ENV_FILE")"
touch "$ENV_FILE"

upsert_env_var() {
  local file="$1"
  local key="$2"
  local value="$3"
  local escaped_value
  escaped_value="$(printf '%s' "$value" | sed 's/[&|]/\\&/g')"

  if grep -q "^${key}=" "$file"; then
    sed -i "s|^${key}=.*|${key}=${escaped_value}|" "$file"
  else
    printf '\n%s=%s\n' "$key" "$value" >> "$file"
  fi
}

upsert_env_var "$ENV_FILE" "CLERK_SECRET_KEY" "$SECRET_KEY"
upsert_env_var "$ENV_FILE" "NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY" "$PUBLISHABLE_KEY"

echo "Updated ${ENV_FILE}"
echo "  CLERK_SECRET_KEY=${SECRET_KEY:0:10}..."
echo "  NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=${PUBLISHABLE_KEY:0:10}..."
