#!/usr/bin/env bash

# Fix Configuration Issues
# This script fixes identified configuration issues

set -e


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

log_info "=== Fixing Configuration Issues ==="

# Issue 1: Fix Terraform node counts
log_warn "1. Fixing Terraform node counts..."
if [ -f "terraform/terraform.tfvars" ]; then
    # Backup original
    cp terraform/terraform.tfvars terraform/terraform.tfvars.backup
    
    # Update node counts (comment out the reduced values, add proper values)
    sed -i 's/^node_count = {/node_count = {\n  # Production values (uncomment when quota allows):\n  # system     = 3\n  # validators = 4\n  # sentries   = 3\n  # rpc        = 3\n  #\n  # Current values (reduced for quota):/' terraform/terraform.tfvars
    
    # Add comment explaining the issue
    if ! grep -q "# CRITICAL: sentries and rpc are set to 0" terraform/terraform.tfvars; then
        sed -i '/sentries.*=.*0/a\  # CRITICAL: sentries and rpc are set to 0 - RPC endpoints will not be available!' terraform/terraform.tfvars
        sed -i '/rpc.*=.*0/a\  # CRITICAL: RPC nodes are disabled - external access will not work!' terraform/terraform.tfvars
    fi
    
    log_success "✅ Terraform node counts annotated"
    log_warn "   ⚠️  Manual fix required: Update node_count values in terraform.tfvars"
else
    log_error "❌ terraform.tfvars not found"
fi

# Issue 2: Fix Kubernetes version
log_warn "2. Fixing Kubernetes version..."
if [ -f "terraform/terraform.tfvars" ]; then
    # Check current version
    CURRENT_VERSION=$(grep "kubernetes_version" terraform/terraform.tfvars | cut -d'"' -f2)
    if [ "$CURRENT_VERSION" = "1.33" ]; then
        # Update to a more reasonable version (user should verify)
        sed -i 's/kubernetes_version = "1.33"/kubernetes_version = "1.28"  # FIXME: Verify latest supported version/' terraform/terraform.tfvars
        log_success "✅ Kubernetes version updated to 1.28"
        log_warn "   ⚠️  Please verify: az aks get-versions --location westeurope"
    else
        log_success "✅ Kubernetes version: ${CURRENT_VERSION}"
    fi
fi

# Issue 3: Check and fix genesis file
log_warn "3. Checking genesis file..."
if [ -f "config/genesis.json" ]; then
    EXTRADATA=$(grep -oE '"extraData"[[:space:]]*:[[:space:]]*"[^"]*"' config/genesis.json | cut -d'"' -f4)
    if [ "$EXTRADATA" = "0x" ] || [ -z "$EXTRADATA" ]; then
        log_error "❌ Genesis extraData is empty (no validators configured)"
        log_warn "   Fix: Run ./scripts/generate-genesis-proper.sh 4 to regenerate with validators"
        
        # Check if validator keys exist
        VALIDATOR_KEY_COUNT=$(find keys/validators -name "key.pub" 2>/dev/null | wc -l)
        if [ "$VALIDATOR_KEY_COUNT" -gt 0 ]; then
            log_success "   ✅ Validator keys found: ${VALIDATOR_KEY_COUNT}"
            log_warn "   Run: ./scripts/generate-genesis-proper.sh 4"
        else
            log_error "   ❌ No validator keys found"
            log_warn "   Run: ./scripts/key-management/generate-validator-keys.sh 4"
        fi
    else
        # Check if extraData looks valid (should be longer than "0x")
        if [ ${#EXTRADATA} -gt 4 ]; then
            log_success "✅ Genesis extraData appears to have validators"
        else
            log_warn "⚠️  Genesis extraData may be incomplete"
        fi
    fi
else
    log_error "❌ Genesis file not found"
fi

# Issue 4: Fix RPC storage size inconsistency
log_warn "4. Checking storage size consistency..."
RPC_STORAGE_K8S=$(grep -A 3 "storage:" k8s/base/rpc/statefulset.yaml | grep "storage:" | grep -oE '[0-9]+Gi' || echo "")
RPC_STORAGE_HELM=$(grep "size:" helm/besu-network/values-rpc.yaml | grep -oE '[0-9]+Gi' || echo "")

if [ -n "$RPC_STORAGE_K8S" ] && [ -n "$RPC_STORAGE_HELM" ]; then
    if [ "$RPC_STORAGE_K8S" != "$RPC_STORAGE_HELM" ]; then
        log_warn "⚠️  Storage size mismatch:"
        log_warn "   k8s/base/rpc/statefulset.yaml: ${RPC_STORAGE_K8S}"
        log_warn "   helm/besu-network/values-rpc.yaml: ${RPC_STORAGE_HELM}"
        log_warn "   Recommendation: Update k8s/base/rpc/statefulset.yaml to match Helm values"
    else
        log_success "✅ Storage sizes are consistent"
    fi
fi

# Issue 5: Check RPC CORS/host allowlist security
log_warn "5. Checking RPC security configuration..."
if grep -q 'corsOrigins: \["\*"\]' helm/besu-network/values-rpc.yaml; then
    log_warn "⚠️  RPC CORS is set to wildcard (security risk)"
    log_warn "   Recommendation: Restrict to specific domains in production"
fi

if grep -q 'hostAllowlist: \["\*"\]' helm/besu-network/values-rpc.yaml; then
    log_warn "⚠️  RPC host allowlist is set to wildcard (security risk)"
    log_warn "   Recommendation: Restrict to specific hosts in production"
fi

# Issue 6: Check Terraform backend
log_warn "6. Checking Terraform backend configuration..."
if [ -f "terraform/backend.tf" ]; then
    log_success "✅ backend.tf exists"
else
    log_warn "⚠️  backend.tf not found"
    if [ -f "terraform/backend.tf.example" ]; then
        log_warn "   Copy backend.tf.example to backend.tf and configure"
    fi
fi

# Issue 7: Check static-nodes.json
log_warn "7. Checking static-nodes.json..."
if [ -f "config/static-nodes.json" ]; then
    NODE_COUNT=$(grep -c "enode://" config/static-nodes.json 2>/dev/null || echo "0")
    if [ "$NODE_COUNT" -gt 0 ]; then
        log_success "✅ Static nodes configured: ${NODE_COUNT}"
    else
        log_warn "⚠️  No static nodes configured"
        log_warn "   Nodes may have trouble peering"
    fi
else
    log_warn "⚠️  static-nodes.json not found"
fi

log_info "=== Summary ==="
log_success "Configuration issues checked"
log_warn "Critical fixes needed:"
echo "  1. Update terraform.tfvars node_count (set sentries=3, rpc=3)"
echo "  2. Regenerate genesis.json with validators (./scripts/generate-genesis-proper.sh 4)"
echo "  3. Verify Kubernetes version is supported"
echo "  4. Configure Terraform backend"
log_warn "Security recommendations:"
echo "  1. Restrict RPC CORS origins"
echo "  2. Restrict RPC host allowlist"
echo "  3. Review network security groups"
