#!/bin/bash
# Deploy a preview environment for a PR.
# Usage: ./preview-deploy.sh <pr_number>
#
# This script runs ON the EC2 instance (invoked via SSH from GitHub Actions).
# Only one preview can exist at a time. If a different PR's preview is running,
# it is torn down first.
#
#   1. Stops any existing preview
#   2. Copies the pre-built UI from the staging area
#   3. Installs dependencies and generates the Prisma client
#   4. Starts the Next.js server on the preview port (4001)
#   5. Records the PR number and PID for tracking

set -euo pipefail

PREVIEW_DIR="/opt/gemmbot/preview"
STAGING_DIR="/opt/gemmbot/preview-staging"
PREVIEW_PORT=4001
PREVIEW_DOMAIN="preview.gemmbot.gemmaanalytics.com"

if [ $# -ne 1 ]; then
    echo "ERROR: Usage: $0 <pr_number>"
    exit 1
fi

PR_NUMBER="$1"

if ! [[ "$PR_NUMBER" =~ ^[0-9]+$ ]]; then
    echo "ERROR: PR number must be a positive integer, got: '$PR_NUMBER'"
    exit 1
fi

if [ ! -d "$STAGING_DIR" ]; then
    echo "ERROR: Staging directory not found: $STAGING_DIR"
    exit 1
fi

# --- Check if a different PR's preview is already running ---
if [ -f "${PREVIEW_DIR}/.pr-number" ]; then
    EXISTING_PR=$(cat "${PREVIEW_DIR}/.pr-number")
    if [ "$EXISTING_PR" = "$PR_NUMBER" ]; then
        echo "### PR #${PR_NUMBER} already deployed — redeploying ###"
    else
        echo "### Replacing preview for PR #${EXISTING_PR} with PR #${PR_NUMBER} ###"
    fi
fi

echo "### Preview deploy for PR #${PR_NUMBER} ###"
echo "Domain: ${PREVIEW_DOMAIN}"
echo "Port: ${PREVIEW_PORT}"

# --- Stop existing preview ---
PID_FILE="${PREVIEW_DIR}/.pid"
if [ -f "$PID_FILE" ]; then
    OLD_PID=$(cat "$PID_FILE")
    if kill -0 "$OLD_PID" 2>/dev/null; then
        echo "### Stopping existing preview (PID ${OLD_PID}) ###"
        kill "$OLD_PID" 2>/dev/null || true
        sleep 2
        kill -9 "$OLD_PID" 2>/dev/null || true
    fi
fi

# --- Copy built UI to preview directory ---
echo "### Copying UI to preview directory ###"
mkdir -p "$PREVIEW_DIR"
rsync -a --delete \
    --exclude .env \
    --exclude .env.local \
    --exclude .pid \
    --exclude .pr-number \
    --exclude preview.log \
    "$STAGING_DIR/" "$PREVIEW_DIR/"

# --- Install dependencies ---
echo "### Installing dependencies ###"
cd "$PREVIEW_DIR"
npm ci --production

echo "### Generating Prisma client ###"
npx prisma generate

# --- Create preview env file ---
# Copy the production env and override NEXTAUTH_URL
if [ -f /opt/gemmbot/ui/.env ]; then
    cp /opt/gemmbot/ui/.env "$PREVIEW_DIR/.env.local"
    # Override NextAuth URL for preview domain
    sed -i "s|^NEXTAUTH_URL=.*|NEXTAUTH_URL=https://${PREVIEW_DOMAIN}|" "$PREVIEW_DIR/.env.local"
fi

# --- Start the preview ---
echo "### Starting preview on port ${PREVIEW_PORT} ###"
PORT=$PREVIEW_PORT nohup npx next start -p $PREVIEW_PORT > "${PREVIEW_DIR}/preview.log" 2>&1 &
NEW_PID=$!
echo "$NEW_PID" > "$PID_FILE"

# Record PR number for tracking
echo "$PR_NUMBER" > "${PREVIEW_DIR}/.pr-number"

# Wait for it to be ready
sleep 3
if kill -0 "$NEW_PID" 2>/dev/null; then
    echo "### Preview started (PID ${NEW_PID}) ###"
else
    echo "ERROR: Preview process died immediately"
    cat "${PREVIEW_DIR}/preview.log"
    exit 1
fi

echo "### Preview environment ready ###"
echo "URL: https://${PREVIEW_DOMAIN}"
