#!/bin/bash
set -e

# Script to deploy to Kubernetes

NAMESPACE=${NAMESPACE:-"wcag-ada"}
ENVIRONMENT=${ENVIRONMENT:-"staging"}

echo "Deploying WCAG-ADA to Kubernetes..."
echo "Namespace: $NAMESPACE"
echo "Environment: $ENVIRONMENT"

# Get the script directory
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
K8S_DIR="$SCRIPT_DIR/../k8s"

# Create namespace if it doesn't exist
kubectl create namespace $NAMESPACE --dry-run=client -o yaml | kubectl apply -f -

# Apply configurations
echo "Applying configurations..."
kubectl apply -f "$K8S_DIR/configmap.yaml" -n $NAMESPACE

# Apply secrets (only if file exists)
if [ -f "$K8S_DIR/secrets-$ENVIRONMENT.yaml" ]; then
  echo "Applying environment-specific secrets..."
  kubectl apply -f "$K8S_DIR/secrets-$ENVIRONMENT.yaml" -n $NAMESPACE
else
  echo "Warning: No environment-specific secrets found. Using default secrets."
  kubectl apply -f "$K8S_DIR/secrets.yaml" -n $NAMESPACE
fi

# Deploy services
echo "Deploying PostgreSQL..."
kubectl apply -f "$K8S_DIR/postgres.yaml" -n $NAMESPACE

echo "Deploying Redis..."
kubectl apply -f "$K8S_DIR/redis.yaml" -n $NAMESPACE

# Wait for databases to be ready
echo "Waiting for databases to be ready..."
kubectl wait --for=condition=ready pod -l app=postgres -n $NAMESPACE --timeout=300s
kubectl wait --for=condition=ready pod -l app=redis -n $NAMESPACE --timeout=300s

# Deploy applications
echo "Deploying API..."
kubectl apply -f "$K8S_DIR/api.yaml" -n $NAMESPACE

echo "Deploying Worker..."
kubectl apply -f "$K8S_DIR/worker.yaml" -n $NAMESPACE

echo "Deploying Dashboard..."
kubectl apply -f "$K8S_DIR/dashboard.yaml" -n $NAMESPACE

# Apply ingress
echo "Applying Ingress rules..."
kubectl apply -f "$K8S_DIR/ingress.yaml" -n $NAMESPACE

# Wait for deployments
echo "Waiting for deployments to be ready..."
kubectl rollout status deployment/wcag-ada-api -n $NAMESPACE
kubectl rollout status deployment/wcag-ada-worker -n $NAMESPACE
kubectl rollout status deployment/wcag-ada-dashboard -n $NAMESPACE

echo "Deployment complete!"
echo ""
echo "Services deployed:"
kubectl get services -n $NAMESPACE
echo ""
echo "Pods status:"
kubectl get pods -n $NAMESPACE