#!/usr/bin/env bash

# Deploy Hyperledger Cacti
# This script deploys Cacti to Kubernetes

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
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

# Configuration
NAMESPACE="${NAMESPACE:-cacti}"
BESU_RPC_URL="${BESU_RPC_URL:-http://besu-rpc-service.besu-network.svc.cluster.local:8545}"
BESU_WS_URL="${BESU_WS_URL:-ws://besu-rpc-service.besu-network.svc.cluster.local:8546}"
CHAIN_ID="${CHAIN_ID:-138}"


log_success "Deploying Hyperledger Cacti..."

# Check prerequisites
if ! command -v kubectl &> /dev/null; then
    log_error "Error: kubectl not found"
    exit 1
fi

# Create namespace
log_warn "Creating namespace..."
kubectl apply -f "$PROJECT_ROOT/k8s/cacti/namespace.yaml"

# Update ConfigMap with Besu RPC URLs
log_warn "Updating ConfigMap..."
kubectl create configmap cactus-config \
    --from-file="$PROJECT_ROOT/k8s/cacti/configmap.yaml" \
    --namespace="$NAMESPACE" \
    --dry-run=client -o yaml | kubectl apply -f -

# Deploy Cactus API
log_warn "Deploying Cactus API..."
kubectl apply -f "$PROJECT_ROOT/k8s/cacti/cactus-api.yaml"

# Wait for Cactus API to be ready
log_warn "Waiting for Cactus API to be ready..."
kubectl wait --for=condition=ready pod -l app=cactus-api -n "$NAMESPACE" --timeout=300s

# Deploy Besu Connector
log_warn "Deploying Besu Connector..."
kubectl apply -f "$PROJECT_ROOT/k8s/cacti/besu-connector.yaml"

# Wait for Besu Connector to be ready
log_warn "Waiting for Besu Connector to be ready..."
kubectl wait --for=condition=ready pod -l app=cactus-besu-connector -n "$NAMESPACE" --timeout=300s

log_success "Cacti deployed successfully!"
log_warn "Cactus API: http://cactus-api.$NAMESPACE.svc.cluster.local:4000"

