#!/bin/bash
# Run this script in Google Cloud Shell to set up AlloyDB
# Cloud Shell has VPC access, so it can connect to AlloyDB directly

set -e

echo "🚀 AlloyDB Setup via Cloud Shell"
echo "=================================="
echo ""

# Set project
PROJECT_ID="gen-lang-client-0980079410"
REGION="northamerica-northeast1"
CLUSTER="vibn"
INSTANCE="vibn-primary"
USER="mark@getacquired.com"

echo "Project: $PROJECT_ID"
echo "Cluster: $CLUSTER"
echo "Instance: $INSTANCE"
echo ""

# Get AlloyDB private IP
echo "📍 Getting AlloyDB private IP..."
ALLOYDB_IP=$(gcloud alloydb instances describe $INSTANCE \
  --cluster=$CLUSTER \
  --region=$REGION \
  --project=$PROJECT_ID \
  --format="value(ipAddress)")

echo "✅ AlloyDB IP: $ALLOYDB_IP"
echo ""

# Install psql if needed
if ! command -v psql &> /dev/null; then
  echo "📦 Installing PostgreSQL client..."
  sudo apt-get update && sudo apt-get install -y postgresql-client
fi

echo "✅ PostgreSQL client ready"
echo ""

# Connect and check databases
echo "🔍 Checking existing databases..."
psql "host=$ALLOYDB_IP port=5432 user=$USER dbname=postgres sslmode=disable" -c "\l"

echo ""
read -p "Create 'vibn' database? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
  echo "📝 Creating vibn database..."
  psql "host=$ALLOYDB_IP port=5432 user=$USER dbname=postgres sslmode=disable" \
    -c "CREATE DATABASE vibn;"
  echo "✅ Database created"
fi

echo ""
echo "🔌 Enabling extensions..."
psql "host=$ALLOYDB_IP port=5432 user=$USER dbname=vibn sslmode=disable" <<EOF
CREATE EXTENSION IF NOT EXISTS vector;
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
SELECT extname, extversion FROM pg_extension WHERE extname IN ('vector', 'uuid-ossp');
EOF

echo ""
echo "✅ Extensions installed!"
echo ""
echo "📋 Next: Upload and run the schema file"
echo ""
echo "1. Upload lib/db/knowledge-chunks-schema.sql to Cloud Shell"
echo "2. Run: psql \"host=$ALLOYDB_IP port=5432 user=$USER dbname=vibn sslmode=disable\" -f knowledge-chunks-schema.sql"
echo ""
echo "Or copy-paste the SQL manually into psql"

