#!/bin/bash
set -e

###############################################################################
# Backend Services Deployment Script for AKS
#
# Usage:
#   ./deploy.sh <environment> [service-name]
#
# Arguments:
#   environment  - Target environment (dev, staging, prod)
#   service-name - Specific service to deploy (optional, deploys all if not specified)
#
# Examples:
#   ./deploy.sh dev                    # Deploy all services to dev
#   ./deploy.sh prod user-service      # Deploy only user-service to prod
###############################################################################

# Color output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Functions
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Validate arguments
if [ $# -lt 1 ]; then
    log_error "Usage: $0 <environment> [service-name]"
    log_error "Environment must be one of: dev, staging, prod"
    exit 1
fi

ENVIRONMENT=$1
SERVICE=${2:-all}

# Validate environment
if [[ ! "$ENVIRONMENT" =~ ^(dev|staging|prod)$ ]]; then
    log_error "Invalid environment: $ENVIRONMENT"
    log_error "Must be one of: dev, staging, prod"
    exit 1
fi

# Load environment variables
ENV_FILE=".github/config/deploy_env_vars_${ENVIRONMENT}"
if [ ! -f "$ENV_FILE" ]; then
    log_error "Environment file not found: $ENV_FILE"
    exit 1
fi

source "$ENV_FILE"
log_info "Loaded environment configuration: $ENVIRONMENT"

# Service list
SERVICES=(
    "user-service"
    "event-service"
    "ai-service"
    "content-service"
    "distribution-service"
    "participation-service"
    "analytics-service"
)

# Validate service if specified
if [ "$SERVICE" != "all" ]; then
    if [[ ! " ${SERVICES[@]} " =~ " ${SERVICE} " ]]; then
        log_error "Invalid service: $SERVICE"
        log_error "Must be one of: ${SERVICES[*]}"
        exit 1
    fi
    SERVICES=("$SERVICE")
fi

log_info "Services to deploy: ${SERVICES[*]}"

# Check prerequisites
log_info "Checking prerequisites..."

if ! command -v az &> /dev/null; then
    log_error "Azure CLI not found. Please install Azure CLI."
    exit 1
fi

if ! command -v kubectl &> /dev/null; then
    log_error "kubectl not found. Please install kubectl."
    exit 1
fi

if ! command -v kustomize &> /dev/null; then
    log_error "kustomize not found. Please install kustomize."
    exit 1
fi

# Azure login check
log_info "Checking Azure authentication..."
if ! az account show &> /dev/null; then
    log_error "Not logged in to Azure. Please run 'az login'"
    exit 1
fi

# Get AKS credentials
log_info "Getting AKS credentials..."
az aks get-credentials \
    --resource-group "$RESOURCE_GROUP" \
    --name "$AKS_CLUSTER" \
    --overwrite-existing

# Check namespace
log_info "Checking namespace: $NAMESPACE"
if ! kubectl get namespace "$NAMESPACE" &> /dev/null; then
    log_warn "Namespace $NAMESPACE does not exist. Creating..."
    kubectl create namespace "$NAMESPACE"
fi

# Build and deploy with Kustomize
OVERLAY_DIR=".github/kustomize/overlays/${ENVIRONMENT}"
if [ ! -d "$OVERLAY_DIR" ]; then
    log_error "Kustomize overlay directory not found: $OVERLAY_DIR"
    exit 1
fi

log_info "Building Kustomize manifests for $ENVIRONMENT..."
cd "$OVERLAY_DIR"

# Update image tags
log_info "Updating image tags to: $ENVIRONMENT"
kustomize edit set image \
    ${ACR_NAME}.azurecr.io/kt-event-marketing/user-service:${ENVIRONMENT} \
    ${ACR_NAME}.azurecr.io/kt-event-marketing/event-service:${ENVIRONMENT} \
    ${ACR_NAME}.azurecr.io/kt-event-marketing/ai-service:${ENVIRONMENT} \
    ${ACR_NAME}.azurecr.io/kt-event-marketing/content-service:${ENVIRONMENT} \
    ${ACR_NAME}.azurecr.io/kt-event-marketing/distribution-service:${ENVIRONMENT} \
    ${ACR_NAME}.azurecr.io/kt-event-marketing/participation-service:${ENVIRONMENT} \
    ${ACR_NAME}.azurecr.io/kt-event-marketing/analytics-service:${ENVIRONMENT}

# Apply manifests
log_info "Applying manifests to AKS..."
kustomize build . | kubectl apply -f -

cd - > /dev/null

# Wait for deployments
log_info "Waiting for deployments to be ready..."
for service in "${SERVICES[@]}"; do
    log_info "Waiting for $service deployment..."
    if ! kubectl rollout status deployment/"$service" -n "$NAMESPACE" --timeout=5m; then
        log_error "Deployment of $service failed!"
        exit 1
    fi
    log_info "✓ $service is ready"
done

# Verify deployment
log_info "Verifying deployment..."
echo ""
echo "=== Pods Status ==="
kubectl get pods -n "$NAMESPACE" -l app.kubernetes.io/part-of=kt-event-marketing

echo ""
echo "=== Services ==="
kubectl get svc -n "$NAMESPACE"

echo ""
echo "=== Ingress ==="
kubectl get ingress -n "$NAMESPACE"

log_info "Deployment completed successfully!"
log_info "Environment: $ENVIRONMENT"
log_info "Services: ${SERVICES[*]}"
