#!/usr/bin/env bash
# Deploy resources that don't require additional vCPUs

set -e

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

# Color codes

echo "==================================================================="
echo "  DEPLOYING RESOURCES WITHOUT QUOTA INCREASE"
echo "==================================================================="

# Check Kubernetes access
if ! kubectl cluster-info &> /dev/null 2>&1; then
    log_warn "⚠️  Configuring Kubernetes access..."
    az aks get-credentials --resource-group az-p-we-rg-comp-001 --name az-p-we-aks-main --overwrite-existing
fi

# Step 1: Create Namespaces
log_info "Step 1: Creating Namespaces"
kubectl create namespace besu-network --dry-run=client -o yaml | kubectl apply -f -
kubectl create namespace monitoring --dry-run=client -o yaml | kubectl apply -f -
kubectl create namespace firefly --dry-run=client -o yaml | kubectl apply -f -
log_success "✅ Namespaces created"

# Step 2: Deploy Monitoring Stack
log_info "Step 2: Deploying Monitoring Stack"

# Add Helm repos
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts 2>/dev/null || true
helm repo add grafana https://grafana.github.io/helm-charts 2>/dev/null || true
helm repo update 2>/dev/null || true

# Deploy Prometheus
if ! helm list -n monitoring 2>/dev/null | grep -q prometheus; then
    echo "Deploying Prometheus..."
    helm install prometheus prometheus-community/kube-prometheus-stack \
        -n monitoring \
        --set prometheus.prometheusSpec.replicas=1 \
        --set prometheus.prometheusSpec.retention=7d \
        --set prometheus.prometheusSpec.resources.requests.cpu=500m \
        --set prometheus.prometheusSpec.resources.requests.memory=2Gi \
        --wait --timeout 5m 2>&1 | tail -10
    log_success "✅ Prometheus deployed"
else
    log_success "✅ Prometheus already deployed"
fi

# Deploy Grafana
if ! helm list -n monitoring 2>/dev/null | grep -q grafana; then
    echo "Deploying Grafana..."
    helm install grafana grafana/grafana \
        -n monitoring \
        --set persistence.enabled=false \
        --set adminPassword=admin \
        --set resources.requests.cpu=200m \
        --set resources.requests.memory=512Mi \
        --wait --timeout 5m 2>&1 | tail -10
    log_success "✅ Grafana deployed"
else
    log_success "✅ Grafana already deployed"
fi

# Step 3: Deploy Besu (Single Pod)
log_info "Step 3: Deploying Besu Validator (Single Pod)"

if ! kubectl get deployment besu-validator -n besu-network &> /dev/null 2>&1; then
    kubectl apply -f - <<EOF
apiVersion: apps/v1
kind: Deployment
metadata:
  name: besu-validator
  namespace: besu-network
spec:
  replicas: 1
  selector:
    matchLabels:
      app: besu-validator
  template:
    metadata:
      labels:
        app: besu-validator
    spec:
      containers:
      - name: besu
        image: hyperledger/besu:latest
        command: ["besu"]
        args: ["--network=dev", "--rpc-http-enabled", "--rpc-http-host=0.0.0.0"]
        resources:
          requests:
            cpu: 500m
            memory: 1Gi
          limits:
            cpu: 1000m
            memory: 2Gi
        ports:
        - containerPort: 8545
          name: http-rpc
        - containerPort: 8546
          name: ws-rpc
---
apiVersion: v1
kind: Service
metadata:
  name: besu-validator
  namespace: besu-network
spec:
  selector:
    app: besu-validator
  ports:
  - port: 8545
    targetPort: 8545
    name: http-rpc
  - port: 8546
    targetPort: 8546
    name: ws-rpc
  type: LoadBalancer
EOF
    log_success "✅ Besu validator deployed"
else
    log_success "✅ Besu validator already deployed"
fi

# Step 4: Deploy Kubernetes Base Resources
log_info "Step 4: Deploying Kubernetes Base Resources"
if [ -d k8s/base ]; then
    kubectl apply -k k8s/base 2>&1 | tail -10
    log_success "✅ Base resources deployed"
else
    log_warn "⚠️  k8s/base directory not found"
fi

# Step 5: Verify Deployments
log_info "Step 5: Verifying Deployments"
echo "📊 Pods:"
kubectl get pods --all-namespaces | grep -E "(NAME|besu|prometheus|grafana)" | head -10

echo "📊 Services:"
kubectl get svc --all-namespaces | grep -E "(NAME|besu|prometheus|grafana)" | head -10

log_success "✅ Deployment complete!"
echo "📋 Access Information:"
echo "  • Grafana: kubectl port-forward -n monitoring svc/grafana 3000:80"
echo "  • Prometheus: kubectl port-forward -n monitoring svc/prometheus-kube-prometheus-prometheus 9090:9090"
echo "  • Besu RPC: kubectl port-forward -n besu-network svc/besu-validator 8545:8545"
