#!/bin/bash
# AlloyDB Setup Script for Vibn
# This script helps you configure AlloyDB with a service account

set -e  # Exit on error

echo "🚀 AlloyDB Setup for Vibn"
echo "=========================="
echo ""

# Get project ID
PROJECT_ID=$(gcloud config get-value project 2>/dev/null)
if [ -z "$PROJECT_ID" ]; then
  echo "❌ No GCP project configured. Run: gcloud config set project YOUR_PROJECT_ID"
  exit 1
fi

echo "📋 Project: $PROJECT_ID"
echo ""

# Prompt for cluster details
read -p "Enter your AlloyDB cluster name: " CLUSTER_NAME
read -p "Enter your AlloyDB region [us-central1]: " REGION
REGION=${REGION:-us-central1}
read -p "Enter your AlloyDB instance name [${CLUSTER_NAME}-primary]: " INSTANCE_NAME
INSTANCE_NAME=${INSTANCE_NAME:-${CLUSTER_NAME}-primary}

echo ""
echo "Configuration:"
echo "  Cluster: $CLUSTER_NAME"
echo "  Region: $REGION"
echo "  Instance: $INSTANCE_NAME"
echo ""

read -p "Continue? (y/n) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
  exit 1
fi

# Create service account
echo ""
echo "📝 Step 1: Creating service account..."
SA_NAME="vibn-alloydb-client"
SA_EMAIL="${SA_NAME}@${PROJECT_ID}.iam.gserviceaccount.com"

if gcloud iam service-accounts describe $SA_EMAIL &>/dev/null; then
  echo "✅ Service account already exists: $SA_EMAIL"
else
  gcloud iam service-accounts create $SA_NAME \
    --display-name="Vibn AlloyDB Client" \
    --description="Service account for Vibn app to access AlloyDB"
  echo "✅ Created service account: $SA_EMAIL"
fi

# Grant permissions
echo ""
echo "🔑 Step 2: Granting permissions..."

gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:${SA_EMAIL}" \
  --role="roles/alloydb.client" \
  --condition=None \
  --quiet

gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:${SA_EMAIL}" \
  --role="roles/compute.networkUser" \
  --condition=None \
  --quiet

echo "✅ Granted AlloyDB client and network user roles"

# Create IAM database user
echo ""
echo "👤 Step 3: Creating IAM database user..."

if gcloud alloydb users list \
  --cluster=$CLUSTER_NAME \
  --instance=$INSTANCE_NAME \
  --region=$REGION \
  --filter="name:${SA_EMAIL}" \
  --format="value(name)" 2>/dev/null | grep -q "${SA_EMAIL}"; then
  echo "✅ IAM user already exists"
else
  gcloud alloydb users create $SA_EMAIL \
    --instance=$INSTANCE_NAME \
    --cluster=$CLUSTER_NAME \
    --region=$REGION \
    --type=IAM_BASED
  echo "✅ Created IAM database user"
fi

# Download service account key
echo ""
echo "🔐 Step 4: Downloading service account key..."
KEY_FILE="$HOME/vibn-alloydb-key.json"

if [ -f "$KEY_FILE" ]; then
  read -p "Key file already exists. Overwrite? (y/n) " -n 1 -r
  echo
  if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Skipping key download"
  else
    gcloud iam service-accounts keys create $KEY_FILE \
      --iam-account=$SA_EMAIL
    chmod 600 $KEY_FILE
    echo "✅ Key saved to: $KEY_FILE"
  fi
else
  gcloud iam service-accounts keys create $KEY_FILE \
    --iam-account=$SA_EMAIL
  chmod 600 $KEY_FILE
  echo "✅ Key saved to: $KEY_FILE"
fi

# Get AlloyDB instance URI
INSTANCE_URI="projects/${PROJECT_ID}/locations/${REGION}/clusters/${CLUSTER_NAME}/instances/${INSTANCE_NAME}"

echo ""
echo "🎉 Setup Complete!"
echo "=================="
echo ""
echo "Next steps:"
echo ""
echo "1. Add to your .env.local:"
echo "   ALLOYDB_HOST=127.0.0.1"
echo "   ALLOYDB_PORT=5432"
echo "   ALLOYDB_USER=${SA_EMAIL}"
echo "   ALLOYDB_PASSWORD="
echo "   ALLOYDB_DATABASE=vibn"
echo "   ALLOYDB_SSL=false"
echo "   GOOGLE_APPLICATION_CREDENTIALS=${KEY_FILE}"
echo ""
echo "2. Start AlloyDB Auth Proxy (in a separate terminal):"
echo "   alloydb-auth-proxy \\"
echo "     --credentials-file=${KEY_FILE} \\"
echo "     --port=5432 \\"
echo "     ${INSTANCE_URI}"
echo ""
echo "3. Create database and run schema:"
echo "   psql \"host=127.0.0.1 port=5432 user=${SA_EMAIL}\" -c 'CREATE DATABASE vibn;'"
echo "   psql \"host=127.0.0.1 port=5432 dbname=vibn user=${SA_EMAIL}\" \\"
echo "     -f lib/db/knowledge-chunks-schema.sql"
echo ""
echo "4. Test connection:"
echo "   npm run test:db"
echo ""

# Optionally create .env.local entry
read -p "Add these to .env.local now? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
  ENV_FILE=".env.local"
  
  # Backup existing .env.local
  if [ -f "$ENV_FILE" ]; then
    cp $ENV_FILE "${ENV_FILE}.backup"
    echo "📦 Backed up existing .env.local"
  fi
  
  # Append AlloyDB config
  cat >> $ENV_FILE << EOF

# AlloyDB Configuration (added by setup script)
ALLOYDB_HOST=127.0.0.1
ALLOYDB_PORT=5432
ALLOYDB_USER=${SA_EMAIL}
ALLOYDB_PASSWORD=
ALLOYDB_DATABASE=vibn
ALLOYDB_SSL=false
GOOGLE_APPLICATION_CREDENTIALS=${KEY_FILE}
EOF

  echo "✅ Added AlloyDB config to .env.local"
fi

echo ""
echo "📚 For full guide, see: SETUP_ALLOYDB_SERVICE_ACCOUNT.md"

