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

# Canary deployment for a single workload region.
# - Applies Terraform only for one region's AKS + networking + storage
# - Uses lock timeouts (no -lock=false)
# - Runs basic health checks on the AKS cluster and Besu pods
#
# Usage:
#   scripts/deployment/canary-region.sh <region-name>
#   scripts/deployment/canary-region.sh northeurope

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
# Load .env via dotenv (RPC CR/LF trim). Fallback: raw source.
if [[ -f "$SCRIPT_DIR/../lib/deployment/dotenv.sh" ]]; then
  # shellcheck disable=SC1090
  source "$SCRIPT_DIR/../lib/deployment/dotenv.sh"
  load_deployment_env --repo-root "${PROJECT_ROOT:-$REPO_ROOT}"
elif [[ -n "${PROJECT_ROOT:-}" && -f "$PROJECT_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/.env"
  set +a
elif [[ -n "${REPO_ROOT:-}" && -f "$REPO_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$REPO_ROOT/.env"
  set +a
fi
TERRAFORM_DIR="$PROJECT_ROOT/terraform"

REGION="${1:-northeurope}"

echo "=== Canary deployment for region: ${REGION} ==="

cd "$TERRAFORM_DIR"

echo "Running Terraform plan for canary region (AKS + networking + storage)..."
terraform plan \
  -lock-timeout=5m \
  -compact-warnings \
  -target="module.aks_global_multi_region[\"${REGION}\"]" \
  -target="module.networking_global_multi_region[\"${REGION}\"]" \
  -target="module.storage_global_multi_region[\"${REGION}\"]" \
  -out="tfplan.canary.${REGION}"

echo
echo "Applying Terraform canary plan for ${REGION}..."
terraform apply \
  -lock-timeout=5m \
  "tfplan.canary.${REGION}"

echo
echo "Fetching cluster info for ${REGION} from Terraform outputs..."

CLUSTERS_JSON="$(terraform output -json global_multi_region_clusters || echo '{}')"

if [[ "$CLUSTERS_JSON" == "null" || -z "$CLUSTERS_JSON" ]]; then
  echo "ERROR: global_multi_region_clusters output is empty or null."
  exit 1
fi

CLUSTER_NAME="$(echo "$CLUSTERS_JSON" | jq -r --arg R "$REGION" '.[$R].cluster_name')"
CLUSTER_LOCATION="$(echo "$CLUSTERS_JSON" | jq -r --arg R "$REGION" '.[$R].location')"

if [[ -z "$CLUSTER_NAME" || "$CLUSTER_NAME" == "null" ]]; then
  echo "ERROR: could not resolve cluster_name for region ${REGION} from Terraform outputs."
  exit 1
fi

echo "Cluster name: ${CLUSTER_NAME}"
echo "Cluster location: ${CLUSTER_LOCATION}"

echo
echo "Getting AKS credentials..."
az aks get-credentials \
  --resource-group "$(terraform output -raw resource_group_name)" \
  --name "${CLUSTER_NAME}" \
  --overwrite-existing

echo
echo "=== Health checks for canary region: ${REGION} ==="

echo "- AKS provisioning state:"
az aks show \
  --resource-group "$(terraform output -raw resource_group_name)" \
  --name "${CLUSTER_NAME}" \
  --query "provisioningState" \
  -o tsv

echo
echo "- Nodes summary:"
kubectl get nodes -o wide

echo
echo "- Besu pods (if deployed) in namespace besu-network:"
kubectl get pods -n besu-network || echo "Namespace besu-network not yet deployed."

echo
echo "Canary deployment for ${REGION} completed. Review the above health checks before rolling out to all regions."


