#!/bin/bash

set -euo pipefail

# Configuration
PROJECT_ID="${PROJECT_ID:-accessible-video-platform}"
REGION="${REGION:-us-central1}"
SERVICE_ACCOUNT_API="accessible-video-api@${PROJECT_ID}.iam.gserviceaccount.com"
SERVICE_ACCOUNT_WORKER="accessible-video-worker@${PROJECT_ID}.iam.gserviceaccount.com"

echo "🚀 Deploying Accessible Video Platform to Cloud Run"
echo "Project: $PROJECT_ID"
echo "Region: $REGION"

# Validate environment
if ! command -v gcloud &> /dev/null; then
    echo "❌ gcloud CLI not found. Please install Google Cloud SDK."
    exit 1
fi

if ! gcloud auth list --filter=status:ACTIVE --format="value(account)" | head -n1 > /dev/null; then
    echo "❌ Please authenticate with Google Cloud: gcloud auth login"
    exit 1
fi

# Set project
echo "📋 Setting project to $PROJECT_ID"
gcloud config set project "$PROJECT_ID"

# Enable required APIs
echo "🔧 Enabling required Google Cloud APIs..."
gcloud services enable \
    cloudbuild.googleapis.com \
    run.googleapis.com \
    containerregistry.googleapis.com \
    secretmanager.googleapis.com \
    cloudtrace.googleapis.com \
    monitoring.googleapis.com \
    translate.googleapis.com \
    texttospeech.googleapis.com \
    storage.googleapis.com

# Create service accounts if they don't exist
echo "👤 Creating service accounts..."
gcloud iam service-accounts create accessible-video-api \
    --display-name="Accessible Video API Service Account" \
    --description="Service account for the API server" || true

gcloud iam service-accounts create accessible-video-worker \
    --display-name="Accessible Video Worker Service Account" \
    --description="Service account for Celery workers" || true

# Grant IAM roles
echo "🔐 Configuring IAM roles..."

# API service permissions
gcloud projects add-iam-policy-binding "$PROJECT_ID" \
    --member="serviceAccount:$SERVICE_ACCOUNT_API" \
    --role="roles/secretmanager.secretAccessor"

gcloud projects add-iam-policy-binding "$PROJECT_ID" \
    --member="serviceAccount:$SERVICE_ACCOUNT_API" \
    --role="roles/storage.objectAdmin"

gcloud projects add-iam-policy-binding "$PROJECT_ID" \
    --member="serviceAccount:$SERVICE_ACCOUNT_API" \
    --role="roles/cloudtrace.agent"

gcloud projects add-iam-policy-binding "$PROJECT_ID" \
    --member="serviceAccount:$SERVICE_ACCOUNT_API" \
    --role="roles/monitoring.metricWriter"

# Worker service permissions
gcloud projects add-iam-policy-binding "$PROJECT_ID" \
    --member="serviceAccount:$SERVICE_ACCOUNT_WORKER" \
    --role="roles/secretmanager.secretAccessor"

gcloud projects add-iam-policy-binding "$PROJECT_ID" \
    --member="serviceAccount:$SERVICE_ACCOUNT_WORKER" \
    --role="roles/storage.objectAdmin"

gcloud projects add-iam-policy-binding "$PROJECT_ID" \
    --member="serviceAccount:$SERVICE_ACCOUNT_WORKER" \
    --role="roles/cloudtrace.agent"

gcloud projects add-iam-policy-binding "$PROJECT_ID" \
    --member="serviceAccount:$SERVICE_ACCOUNT_WORKER" \
    --role="roles/monitoring.metricWriter"

gcloud projects add-iam-policy-binding "$PROJECT_ID" \
    --member="serviceAccount:$SERVICE_ACCOUNT_WORKER" \
    --role="roles/aiplatform.user"

# Create GCS bucket for video storage
echo "📦 Creating GCS bucket..."
gsutil mb -p "$PROJECT_ID" -c STANDARD -l "$REGION" "gs://accessible-video-${PROJECT_ID}" || true

# Set bucket CORS for frontend access
echo "🌐 Configuring bucket CORS..."
cat > /tmp/cors.json << EOF
[
  {
    "origin": ["https://your-frontend-domain.com", "http://localhost:5173"],
    "method": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
    "responseHeader": ["Content-Type", "Authorization", "Range"],
    "maxAgeSeconds": 3600
  }
]
EOF
gsutil cors set /tmp/cors.json "gs://accessible-video-${PROJECT_ID}"

# Submit Cloud Build
echo "🏗️ Starting Cloud Build deployment..."
cd "$(dirname "$0")/../.."

gcloud builds submit \
    --config=infra/cloud-run/cloudbuild.yaml \
    --substitutions=_REGION="$REGION" \
    .

echo "✅ Deployment completed successfully!"
echo ""
echo "📍 API Service URL:"
gcloud run services describe accessible-video-api \
    --region="$REGION" \
    --format="value(status.url)"
echo ""
echo "📍 Worker Service (internal only):"
gcloud run services describe accessible-video-worker \
    --region="$REGION" \
    --format="value(status.url)"

echo ""
echo "🔧 Next steps:"
echo "1. Configure your domain and SSL certificate"
echo "2. Set up monitoring dashboards"
echo "3. Configure alerting policies"
echo "4. Update frontend environment with API URL"