#!/bin/bash
set -e

ENVIRONMENT=${1:-dev}
IMAGE_TAG=${2:-latest}

echo "🚀 Manual deployment starting..."
echo "Environment: $ENVIRONMENT"
echo "Image Tag: $IMAGE_TAG"

# Check if kustomize is installed
if ! command -v kustomize &> /dev/null; then
    echo "Installing Kustomize..."
    curl -s "https://raw.githubusercontent.com/kubernetes-sigs/kustomize/master/hack/install_kustomize.sh" | bash
    sudo mv kustomize /usr/local/bin/
fi

# Load environment variables from .github/config
if [[ -f ".github/config/deploy_env_vars_${ENVIRONMENT}" ]]; then
    source ".github/config/deploy_env_vars_${ENVIRONMENT}"
    echo "✅ Environment variables loaded for $ENVIRONMENT"
else
    echo "❌ Environment configuration file not found: .github/config/deploy_env_vars_${ENVIRONMENT}"
    exit 1
fi

# Create namespace
echo "📝 Creating namespace hgzero..."
kubectl create namespace hgzero --dry-run=client -o yaml | kubectl apply -f -

# 환경별 이미지 태그 업데이트 (.github/kustomize 사용)
cd .github/kustomize/overlays/${ENVIRONMENT}

echo "🔄 Updating image tags..."
# 서비스 배열 정의
services=(user meeting stt ai notification)

# 각 서비스별 이미지 태그 업데이트
for service in "${services[@]}"; do
  kustomize edit set image acrdigitalgarage02.azurecr.io/hgzero/$service:${ENVIRONMENT}-${IMAGE_TAG}
done

echo "🚀 Deploying to Kubernetes..."
# 배포 실행
kubectl apply -k .

echo "⏳ Waiting for deployments to be ready..."
# 서비스별 배포 상태 확인
for service in "${services[@]}"; do
  kubectl rollout status deployment/$service -n hgzero --timeout=300s || echo "⚠️ $service deployment timeout"
done

echo "🔍 Health check..."
# 각 서비스의 Health Check
for service in "${services[@]}"; do
  POD=$(kubectl get pod -n hgzero -l app.kubernetes.io/name=$service -o jsonpath='{.items[0].metadata.name}' 2>/dev/null || echo "")
  if [[ -n "$POD" ]]; then
    kubectl -n hgzero exec $POD -- curl -f http://localhost:8080/actuator/health 2>/dev/null || echo "⚠️ $service health check failed"
  else
    echo "⚠️ $service pod not found"
  fi
done

echo "📋 Service Information:"
kubectl get pods -n hgzero
kubectl get services -n hgzero
kubectl get ingress -n hgzero

echo "✅ GitHub Actions deployment completed successfully!"
