#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
export KUBECONFIG="$SCRIPT_DIR/../env/frigo-dev.yaml"

TAG="${1:-latest}"

echo "=== dc-backend Update ==="
echo ""

# --- Build & Push ---
echo "→ [1/3] Build & Push Image (Tag: $TAG)..."
bash "$SCRIPT_DIR/build-and-push.sh" "$TAG"

# --- Apply Kubernetes Manifests ---
echo ""
echo "→ [2/3] Kubernetes Manifests anwenden..."
kubectl apply -f "$SCRIPT_DIR/k8s/deployment.yaml"

# --- Rolling Restart (zieht neues 'latest'-Image) ---
echo ""
echo "→ [3/3] Rolling Restart..."
kubectl rollout restart deployment/dc-backend -n ai-env

echo ""
echo "→ Warte auf Rollout..."
kubectl rollout status deployment/dc-backend -n ai-env --timeout=120s

echo ""
echo "✓ Deployment abgeschlossen."
echo ""
kubectl get pods -n ai-env -l app=dc-backend
