#!/bin/bash
# Deploy Streamlit MCP Chat STUDENT APP to GCP Cloud Run
# This app has safety guardrails enabled

set -e

# Configuration
PROJECT_ID="precision-medicine-poc"
REGION="us-central1"
SERVICE_NAME="streamlit-mcp-chat-students"  # Different service name

# Check if GEMINI_API_KEY is set (required for student app)
if [ -z "$GEMINI_API_KEY" ]; then
    echo "Error: GEMINI_API_KEY environment variable not set"
    echo "Usage: export GEMINI_API_KEY=your_key_here && ./deploy.sh"
    exit 1
fi

echo "=========================================="
echo "Deploying STUDENT MCP Chat to Cloud Run"
echo "=========================================="
echo "⚠️  STUDENT MODE ENABLED - Safety limits active"
echo "Project: $PROJECT_ID"
echo "Region: $REGION"
echo "Service: $SERVICE_NAME"
echo ""

# Deploy to Cloud Run
echo "Building and deploying..."
gcloud run deploy "$SERVICE_NAME" \
    --source . \
    --platform managed \
    --region "$REGION" \
    --project "$PROJECT_ID" \
    --allow-unauthenticated \
    --memory 1Gi \
    --cpu 1 \
    --min-instances 0 \
    --max-instances 8 \
    --timeout 300 \
    --set-env-vars GEMINI_API_KEY="$GEMINI_API_KEY",ENVIRONMENT=development,STUDENT_MODE=true,USE_MOCK_MCP=false \
    --port 8501 \
    --quiet

echo ""
echo "=========================================="
echo "✅ Deployment Complete!"
echo "=========================================="
echo ""

# Get the service URL
SERVICE_URL=$(gcloud run services describe "$SERVICE_NAME" \
    --region "$REGION" \
    --project "$PROJECT_ID" \
    --format 'value(status.url)')

echo "🌐 Your Streamlit app is live at:"
echo "   $SERVICE_URL"
echo ""
echo "📊 View logs:"
echo "   gcloud logging read \"resource.type=cloud_run_revision AND resource.labels.service_name=$SERVICE_NAME\" --limit=50 --project=$PROJECT_ID"
echo ""
echo "🔧 Manage service:"
echo "   https://console.cloud.google.com/run/detail/$REGION/$SERVICE_NAME?project=$PROJECT_ID"
echo ""
