#!/usr/bin/env bash

# Setup Firefly-Cacti Integration
# This script sets up the integration between Firefly and Cacti

set -e

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

# Configuration
FIREFLY_NAMESPACE="${FIREFLY_NAMESPACE:-firefly}"
CACTI_NAMESPACE="${CACTI_NAMESPACE:-cacti}"
FIREFLY_API_URL="${FIREFLY_API_URL:-http://firefly-api.firefly.svc.cluster.local:5000}"
CACTUS_API_URL="${CACTUS_API_URL:-http://cactus-api.cacti.svc.cluster.local:4000}"


log_success "Setting up Firefly-Cacti Integration..."

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

# Apply integration configuration
log_warn "Applying integration configuration..."
kubectl apply -f "$PROJECT_ROOT/connectors/firefly-cacti/integration.yaml"

# Wait for Firefly to be ready
log_warn "Waiting for Firefly to be ready..."
kubectl wait --for=condition=ready pod -l app=firefly-core -n "$FIREFLY_NAMESPACE" --timeout=300s

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

# Register Besu ledger with Cacti
log_warn "Registering Besu ledger with Cacti..."
curl -X POST "$CACTUS_API_URL/api/v1/plugins/ledger-connector/besu" \
  -H "Content-Type: application/json" \
  -d '{
    "ledgerId": "besu-chain-138",
    "chainId": 138,
    "rpc": {
      "http": "http://besu-rpc-service.besu-network.svc.cluster.local:8545",
      "ws": "ws://besu-rpc-service.besu-network.svc.cluster.local:8546"
    }
  }' || log_warn "Note: Cacti API may not be accessible from this context"

# Register Besu network with Firefly
log_warn "Registering Besu network with Firefly..."
curl -X POST "$FIREFLY_API_URL/api/v1/networks" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "besu-chain-138",
    "type": "ethereum",
    "chainId": 138,
    "rpc": {
      "http": "http://besu-rpc-service.besu-network.svc.cluster.local:8545",
      "ws": "ws://besu-rpc-service.besu-network.svc.cluster.local:8546"
    }
  }' || log_warn "Note: Firefly API may not be accessible from this context"

log_success "Firefly-Cacti integration setup complete!"
log_warn "Firefly API: $FIREFLY_API_URL"
log_warn "Cactus API: $CACTUS_API_URL"

