#!/bin/bash
# deploy_cloudrun.sh - 一鍵部署到 Google Cloud Run
set -e

echo "=========================================="
echo "部署 Momo Pro System 到 Cloud Run"
echo "=========================================="

# 檢查是否已登入 gcloud
if ! gcloud auth list --filter=status:ACTIVE --format="value(account)" | grep -q .; then
    echo "❌ 請先登入 gcloud："
    echo "   gcloud auth login"
    exit 1
fi

# 取得或設定專案 ID
PROJECT_ID=$(gcloud config get-value project 2>/dev/null)
if [ -z "$PROJECT_ID" ]; then
    read -p "請輸入 GCP 專案 ID: " PROJECT_ID
    gcloud config set project $PROJECT_ID
fi

echo "📋 使用專案: $PROJECT_ID"

# 設定區域
REGION="asia-east1"
SERVICE_NAME="momo-pro-system"

# 詢問是否需要設定環境變數
echo ""
read -p "是否需要設定環境變數？(y/n): " SETUP_ENV
if [ "$SETUP_ENV" = "y" ]; then
    echo ""
    echo "請輸入環境變數（留空跳過）："
    read -p "EMAIL_USER: " EMAIL_USER
    read -sp "EMAIL_PASSWORD: " EMAIL_PASSWORD
    echo ""
    read -p "SMTP_SERVER (預設: smtp.gmail.com): " SMTP_SERVER
    SMTP_SERVER=${SMTP_SERVER:-smtp.gmail.com}
    read -p "SMTP_PORT (預設: 587): " SMTP_PORT
    SMTP_PORT=${SMTP_PORT:-587}
fi

# 啟用必要的 API
echo ""
echo "📡 啟用必要的 GCP API..."
gcloud services enable \
    run.googleapis.com \
    cloudbuild.googleapis.com \
    artifactregistry.googleapis.com

# 部署到 Cloud Run（直接從原始碼建立）
echo ""
echo "🚀 部署到 Cloud Run..."
echo "   這可能需要幾分鐘時間..."

DEPLOY_CMD="gcloud run deploy $SERVICE_NAME \
    --source . \
    --region=$REGION \
    --allow-unauthenticated \
    --port=5000 \
    --memory=2Gi \
    --cpu=2 \
    --min-instances=0 \
    --max-instances=10 \
    --timeout=300"

# 添加環境變數
if [ "$SETUP_ENV" = "y" ] && [ ! -z "$EMAIL_USER" ]; then
    DEPLOY_CMD="$DEPLOY_CMD --set-env-vars=EMAIL_USER=$EMAIL_USER,SMTP_SERVER=$SMTP_SERVER,SMTP_PORT=$SMTP_PORT"

    # 處理密碼（使用 Secret Manager）
    if [ ! -z "$EMAIL_PASSWORD" ]; then
        echo "🔐 設定 Email 密碼到 Secret Manager..."
        echo -n "$EMAIL_PASSWORD" | gcloud secrets create email-password --data-file=- || \
            echo -n "$EMAIL_PASSWORD" | gcloud secrets versions add email-password --data-file=-

        DEPLOY_CMD="$DEPLOY_CMD --set-secrets=EMAIL_PASSWORD=email-password:latest"
    fi
fi

# 執行部署
eval $DEPLOY_CMD

# 取得服務 URL
SERVICE_URL=$(gcloud run services describe $SERVICE_NAME \
    --region=$REGION \
    --format='value(status.url)')

echo ""
echo "=========================================="
echo "✅ 部署成功！"
echo "=========================================="
echo ""
echo "🌐 服務 URL: $SERVICE_URL"
echo ""
echo "📊 查看日誌："
echo "   gcloud logging read \"resource.type=cloud_run_revision AND resource.labels.service_name=$SERVICE_NAME\" --limit=50"
echo ""
echo "🔄 更新服務："
echo "   ./deploy_scripts/deploy_cloudrun.sh"
echo ""
echo "❌ 刪除服務："
echo "   gcloud run services delete $SERVICE_NAME --region=$REGION"
echo ""
echo "💰 查看費用："
echo "   https://console.cloud.google.com/billing"
echo ""
