#!/bin/bash

# Deploy all Kubernetes manifests for Developer Portfolio Tracker
# Usage: ./deploy-all.sh [environment]
# Environment: dev, staging, prod (default: prod)

set -e

ENVIRONMENT=${1:-prod}
NAMESPACE="portfolio-${ENVIRONMENT}"

echo "🚀 Deploying Developer Portfolio Tracker to ${ENVIRONMENT} environment..."

# Check if kubectl is available
if ! command -v kubectl &> /dev/null; then
    echo "❌ kubectl is not installed or not in PATH"
    exit 1
fi

# Check if cluster is accessible
if ! kubectl cluster-info &> /dev/null; then
    echo "❌ Cannot connect to Kubernetes cluster"
    exit 1
fi

echo "✅ Kubernetes cluster is accessible"

# Function to wait for deployment to be ready
wait_for_deployment() {
    local deployment=$1
    local namespace=$2
    echo "⏳ Waiting for deployment ${deployment} to be ready..."
    kubectl wait --for=condition=available --timeout=300s deployment/${deployment} -n ${namespace}
    echo "✅ Deployment ${deployment} is ready"
}

# Function to wait for pods to be ready
wait_for_pods() {
    local label=$1
    local namespace=$2
    echo "⏳ Waiting for pods with label ${label} to be ready..."
    kubectl wait --for=condition=ready --timeout=300s pod -l ${label} -n ${namespace}
    echo "✅ Pods with label ${label} are ready"
}

# 1. Create namespaces
echo "📁 Creating namespaces..."
kubectl apply -f ../namespaces/namespaces.yaml
echo "✅ Namespaces created"

# 2. Apply ConfigMaps and Secrets
echo "⚙️  Applying ConfigMaps and Secrets..."
kubectl apply -f ../configmaps/app-config.yaml
echo "⚠️  Please ensure secrets are properly configured before proceeding"
echo "   You can apply secrets with: kubectl apply -f ../secrets/app-secrets.yaml"
echo "   Make sure to replace placeholder values with actual base64 encoded secrets"

# 3. Deploy infrastructure services
echo "🏗️  Deploying infrastructure services..."
kubectl apply -f ../deployments/infrastructure/mysql.yaml
kubectl apply -f ../deployments/infrastructure/mongodb.yaml
kubectl apply -f ../deployments/infrastructure/redis.yaml
kubectl apply -f ../deployments/infrastructure/kafka.yaml

# Apply infrastructure services
kubectl apply -f ../services/infrastructure-services.yaml

echo "⏳ Waiting for infrastructure services to be ready..."
wait_for_deployment "mysql" ${NAMESPACE}
wait_for_deployment "mongodb" ${NAMESPACE}
wait_for_deployment "redis" ${NAMESPACE}
wait_for_deployment "zookeeper" ${NAMESPACE}
wait_for_deployment "kafka" ${NAMESPACE}

# 4. Deploy application services
echo "🚀 Deploying application services..."
kubectl apply -f ../deployments/services/user-service.yaml
kubectl apply -f ../deployments/services/task-service.yaml
kubectl apply -f ../deployments/services/analytics-service.yaml
kubectl apply -f ../deployments/services/diagram-service.yaml
kubectl apply -f ../deployments/services/api-gateway.yaml
kubectl apply -f ../deployments/services/frontend.yaml

# Apply application services
kubectl apply -f ../services/application-services.yaml

echo "⏳ Waiting for application services to be ready..."
wait_for_deployment "user-service" ${NAMESPACE}
wait_for_deployment "task-service" ${NAMESPACE}
wait_for_deployment "analytics-service" ${NAMESPACE}
wait_for_deployment "diagram-service" ${NAMESPACE}
wait_for_deployment "api-gateway" ${NAMESPACE}
wait_for_deployment "frontend" ${NAMESPACE}

# 5. Apply Ingress
echo "🌐 Applying Ingress configuration..."
kubectl apply -f ../ingress/ingress.yaml

# 6. Apply HPA (only for production and staging)
if [[ "${ENVIRONMENT}" == "prod" || "${ENVIRONMENT}" == "staging" ]]; then
    echo "📈 Applying Horizontal Pod Autoscalers..."
    kubectl apply -f ../hpa/hpa.yaml
fi

# 7. Apply monitoring (if Prometheus is available)
if kubectl get crd servicemonitors.monitoring.coreos.com &> /dev/null; then
    echo "📊 Applying monitoring configuration..."
    kubectl apply -f ../monitoring/service-monitors.yaml
    kubectl apply -f ../monitoring/pod-monitors.yaml
else
    echo "⚠️  Prometheus CRDs not found, skipping monitoring setup"
fi

# 8. Display deployment status
echo "📋 Deployment Status:"
kubectl get pods -n ${NAMESPACE}
echo ""
kubectl get services -n ${NAMESPACE}
echo ""
kubectl get ingress -n ${NAMESPACE}

echo ""
echo "🎉 Deployment completed successfully!"
echo ""
echo "📝 Next steps:"
echo "   1. Ensure secrets are properly configured"
echo "   2. Update DNS records to point to your ingress controller"
echo "   3. Configure SSL certificates if using cert-manager"
echo "   4. Monitor application logs: kubectl logs -f deployment/api-gateway -n ${NAMESPACE}"
echo "   5. Check application health: kubectl get pods -n ${NAMESPACE}"
echo ""
echo "🔗 Access URLs (update with your actual domain):"
echo "   Frontend: https://${ENVIRONMENT}.portfolio.example.com"
echo "   API: https://api-${ENVIRONMENT}.portfolio.example.com"