#!/bin/bash
# deploy.sh — Build Theia locally then push to Cloud Run
#
# Usage:
#   ./deploy.sh                          # full build + push + deploy
#   ./deploy.sh --skip-compile           # just repackage + push (if already compiled)
#   ./deploy.sh --service theia-my-proj  # target a specific Cloud Run service

set -e

IMAGE="northamerica-northeast1-docker.pkg.dev/master-ai-484822/vibn-ide/theia:latest"
PROJECT="master-ai-484822"
REGION="northamerica-northeast1"
SERVICE="${SERVICE:-}"  # optional: set via --service flag or env var

SKIP_COMPILE=false

for arg in "$@"; do
  case $arg in
    --skip-compile) SKIP_COMPILE=true ;;
    --service=*) SERVICE="${arg#*=}" ;;
    --service) shift; SERVICE="$1" ;;
  esac
done

echo "🔧 Vibn IDE Deploy"
echo "   Image:   $IMAGE"
echo "   Project: $PROJECT"
echo ""

# ── Step 1: Compile Theia on the Mac ──────────────────────────────────────────
if [ "$SKIP_COMPILE" = false ]; then
  echo "▶ Step 1/3: Compiling Theia (TypeScript + webpack)..."
  npm install --legacy-peer-deps
  npm run compile
  npm run build:browser
  echo "✓ Compile done"
else
  echo "⏭  Skipping compile (--skip-compile)"
fi

# ── Step 2: Build runtime Docker image (no compile, just COPY) ─────────────
echo "▶ Step 2/3: Building runtime Docker image..."
docker build \
  --platform linux/amd64 \
  -f Dockerfile.runtime \
  -t "$IMAGE" \
  .
echo "✓ Docker image built"

# ── Step 3: Push to Artifact Registry ─────────────────────────────────────────
echo "▶ Step 3/3: Pushing to Artifact Registry..."
docker push "$IMAGE"
echo "✓ Pushed: $IMAGE"

# ── Optional: Update a specific Cloud Run service ──────────────────────────────
if [ -n "$SERVICE" ]; then
  echo "▶ Updating Cloud Run service: $SERVICE"
  gcloud run services update "$SERVICE" \
    --project="$PROJECT" \
    --region="$REGION" \
    --image="$IMAGE"
  echo "✓ Service updated"
fi

echo ""
echo "✅ Done! New image is live."
echo ""
echo "To update a specific Cloud Run service:"
echo "  gcloud run services update <service-name> \\"
echo "    --project=$PROJECT --region=$REGION \\"
echo "    --image=$IMAGE"
