#!/usr/bin/env bash
# Phase 4: Deploy Monitoring and Explorer

set -e

cd "$(dirname "$0")/../.."

# Color codes

echo "==================================================================="
echo "  PHASE 4: MONITORING AND EXPLORER DEPLOYMENT"
echo "==================================================================="

# Check kubectl access
if ! kubectl cluster-info &> /dev/null; then
    log_error "❌ Kubernetes cluster not accessible"
    exit 1
fi

# Create monitoring namespace
log_info "Creating monitoring namespace..."
if kubectl get namespace monitoring &> /dev/null; then
    log_success "✅ Namespace 'monitoring' already exists"
else
    kubectl create namespace monitoring
    log_success "✅ Namespace 'monitoring' created"
fi

# Deploy Prometheus
log_info "Deploying Prometheus..."
if [ -f "monitoring/k8s/prometheus.yaml" ]; then
    kubectl apply -f monitoring/k8s/prometheus.yaml -n monitoring
    log_success "✅ Prometheus deployed"
else
    log_warn "⚠️  Prometheus manifest not found"
fi

# Deploy Grafana (optional)
log_info "Deploying Grafana (optional)..."
if command -v helm &> /dev/null; then
    if helm list -n monitoring | grep -q grafana; then
        log_success "✅ Grafana already deployed"
    else
        helm repo add grafana https://grafana.github.io/helm-charts 2>/dev/null || true
        helm install grafana grafana/grafana -n monitoring 2>/dev/null || echo "Grafana deployment skipped"
    fi
else
    log_warn "⚠️  Helm not available, skipping Grafana"
fi

# Deploy Blockscout
log_info "Deploying Blockscout..."
if [ -f "k8s/blockscout/deployment.yaml" ]; then
    kubectl apply -f k8s/blockscout/deployment.yaml -n besu-network
    log_success "✅ Blockscout deployed"
else
    log_warn "⚠️  Blockscout manifest not found"
fi

# Wait for services
log_info "Waiting for services to be ready..."
kubectl wait --for=condition=ready pod -l app=prometheus -n monitoring --timeout=300s 2>/dev/null || echo "Prometheus not ready yet"
kubectl wait --for=condition=ready pod -l app=blockscout -n besu-network --timeout=300s 2>/dev/null || echo "Blockscout not ready yet"

# Show status
log_info "Service Status:"
echo "Monitoring:"
kubectl get pods -n monitoring
echo "Blockscout:"
kubectl get pods -n besu-network -l app=blockscout

log_success "✅ Phase 4 complete!"
echo "Infrastructure deployment complete!"
