#!/bin/bash
#
# Phase 9: Infrastructure Services Deployment
# Deploy monitoring, logging, and infrastructure services
#

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/config.sh"

log_info "=========================================="
log_info "Phase 9: Infrastructure Services Deployment"
log_info "=========================================="

# Verify Kubernetes access
if ! kubectl cluster-info &> /dev/null; then
  az aks get-credentials --resource-group "${AKS_RESOURCE_GROUP}" \
                         --name "${AKS_NAME}" \
                         --overwrite-existing
fi

# 9.1 External Secrets Operator
log_step "9.1 Deploying External Secrets Operator..."

if ! kubectl get crd externalsecrets.external-secrets.io &> /dev/null; then
  log_info "Installing External Secrets Operator..."
  kubectl apply -f https://external-secrets.io/latest/deploy/ || error_exit "Failed to install"
  
  log_info "Waiting for operator to be ready..."
  kubectl wait --for=condition=ready pod \
    -l app.kubernetes.io/name=external-secrets \
    -n external-secrets-system \
    --timeout=300s || log_warning "Operator not ready yet"
else
  log_success "External Secrets Operator already installed"
fi

# 9.2 Monitoring Stack (Prometheus & Grafana)
log_step "9.2 Deploying monitoring stack..."

if ! command -v helm &> /dev/null; then
  log_warning "Helm not found. Install Helm to deploy monitoring stack."
  log_info "See: https://helm.sh/docs/intro/install/"
else
  if ! helm repo list | grep -q prometheus-community; then
    log_info "Adding Prometheus Helm repository..."
    helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
    helm repo update
  fi
  
  if ! helm list -n monitoring | grep -q prometheus; then
    log_info "Installing Prometheus stack..."
    kubectl create namespace monitoring --dry-run=client -o yaml | kubectl apply -f -
    helm install prometheus prometheus-community/kube-prometheus-stack \
      --namespace monitoring \
      --create-namespace \
      || log_warning "Prometheus installation failed or already exists"
  else
    log_success "Prometheus already installed"
  fi
fi

log_info "Monitoring stack deployment complete"
log_info "Access Grafana: kubectl port-forward svc/prometheus-grafana 3000:80 -n monitoring"

# Save state
save_state "phase9" "complete"

log_success "=========================================="
log_success "Phase 9: Infrastructure Services - COMPLETE"
log_success "=========================================="

