#!/usr/bin/env bash
# Deploy Chain-138 Infrastructure

set -e

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

# Color codes

echo "==================================================================="
echo "  CHAIN-138 INFRASTRUCTURE DEPLOYMENT"
echo "==================================================================="

# Load environment variables
if [ -f .env ]; then
    source .env 2>/dev/null || true
fi

ERRORS=0
WARNINGS=0
SUCCESS=0

check_prerequisite() {
    local tool=$1
    local install_cmd=$2
    
    if command -v "$tool" &> /dev/null; then
        log_success "✅ $tool installed"
        SUCCESS=$((SUCCESS + 1))
        return 0
    else
        log_error "❌ $tool not found"
        if [ -n "$install_cmd" ]; then
            echo "  Install with: $install_cmd"
        fi
        ERRORS=$((ERRORS + 1))
        return 1
    fi
}

log_info "Step 1: Checking Prerequisites"

check_prerequisite "terraform" "Install from https://www.terraform.io/downloads"
check_prerequisite "kubectl" "Install from https://kubernetes.io/docs/tasks/tools/"
check_prerequisite "helm" "Install from https://helm.sh/docs/intro/install/"
check_prerequisite "az" "Install from https://docs.microsoft.com/en-us/cli/azure/install-azure-cli"
check_prerequisite "besu" "Install from https://besu.hyperledger.org/en/stable/HowTo/Get-Started/Installation-Options/"


if [ $ERRORS -gt 0 ]; then
    log_error "❌ Missing prerequisites. Please install required tools."
    exit 1
fi

log_info "Step 2: Azure Authentication"

if az account show &> /dev/null; then
    ACCOUNT=$(az account show --query name -o tsv 2>/dev/null || echo "Unknown")
    log_success "✅ Azure CLI authenticated"
    echo "  Account: $ACCOUNT"
    SUCCESS=$((SUCCESS + 1))
else
    log_warn "⚠️  Azure CLI not authenticated"
    echo "  Run: az login"
    WARNINGS=$((WARNINGS + 1))
fi


log_info "Step 3: Terraform Configuration"

if [ -d "terraform" ]; then
    log_success "✅ Terraform directory exists"
    
    cd terraform
    
    # Check for terraform.tfvars
    if [ -f "terraform.tfvars" ]; then
        log_success "✅ terraform.tfvars exists"
    else
        if [ -f "terraform.tfvars.example" ]; then
            log_warn "⚠️  terraform.tfvars not found, copying from example..."
            cp terraform.tfvars.example terraform.tfvars
            log_warn "⚠️  Please edit terraform.tfvars with your values"
            WARNINGS=$((WARNINGS + 1))
        else
            log_error "❌ terraform.tfvars not found and no example available"
            ERRORS=$((ERRORS + 1))
        fi
    fi
    
    # Initialize Terraform
    log_info "Initializing Terraform..."
    if terraform init 2>&1 | tail -20; then
        log_success "✅ Terraform initialized"
        SUCCESS=$((SUCCESS + 1))
    else
        log_error "❌ Terraform initialization failed"
        ERRORS=$((ERRORS + 1))
    fi
    
    cd ..
else
    log_error "❌ Terraform directory not found"
    ERRORS=$((ERRORS + 1))
fi


log_info "Step 4: Kubernetes Configuration"

# Check for kubeconfig
if [ -n "$KUBECONFIG" ] || [ -f "$HOME/.kube/config" ]; then
    log_success "✅ Kubernetes config found"
    
    if kubectl cluster-info &> /dev/null 2>&1; then
        CLUSTER=$(kubectl config current-context 2>/dev/null || echo "Unknown")
        log_success "✅ Kubernetes cluster accessible"
        echo "  Context: $CLUSTER"
        SUCCESS=$((SUCCESS + 1))
    else
        log_warn "⚠️  Kubernetes cluster not accessible"
        echo "  May need to configure: az aks get-credentials"
        WARNINGS=$((WARNINGS + 1))
    fi
else
    log_warn "⚠️  Kubernetes config not found"
    echo "  Will be created after AKS deployment"
    WARNINGS=$((WARNINGS + 1))
fi


log_info "Step 5: Genesis File"

if [ -f "config/genesis.json" ] || [ -f "genesis.json" ]; then
    GENESIS_FILE=$(find . -name "genesis.json" -type f | head -1)
    log_success "✅ Genesis file found: $GENESIS_FILE"
    
    # Check for WETH9/WETH10 in genesis
    if grep -q "C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" "$GENESIS_FILE" 2>/dev/null; then
        log_success "✅ WETH9 found in genesis"
    else
        log_warn "⚠️  WETH9 not found in genesis"
    fi
    
    if grep -q "f4BB2e28688e89fCcE3c0580D37d36A7672E8A9f" "$GENESIS_FILE" 2>/dev/null; then
        log_success "✅ WETH10 found in genesis"
    else
        log_warn "⚠️  WETH10 not found in genesis"
    fi
    
    SUCCESS=$((SUCCESS + 1))
else
    log_error "❌ Genesis file not found"
    echo "  Generate with: ./scripts/generate-genesis-proper.sh 4"
    ERRORS=$((ERRORS + 1))
fi


log_info "Step 6: Deployment Plan"

echo "Infrastructure deployment will proceed in the following order:"
echo "  1. Azure Infrastructure (Terraform)"
echo "     - Resource Group"
echo "     - AKS Cluster"
echo "     - Key Vault"
echo "     - Storage Account"
echo "     - Network Resources"
echo "  2. Kubernetes Resources"
echo "     - Namespace: besu-network"
echo "     - Service Accounts"
echo "     - RBAC"
echo "  3. Besu Network"
echo "     - Validators (Helm)"
echo "     - Sentries (Helm)"
echo "     - RPC Nodes (Helm)"
echo "  4. Monitoring Stack"
echo "     - Prometheus"
echo "     - Grafana"
echo "     - Blockscout"

echo "==================================================================="
log_info "SUMMARY"
echo "==================================================================="
echo "  ✅ Prerequisites: $SUCCESS"
echo "  ⚠️  Warnings: $WARNINGS"
echo "  ❌ Errors: $ERRORS"

if [ $ERRORS -eq 0 ]; then
    log_success "✅ Ready to begin infrastructure deployment"
    echo "Next steps:"
    echo "  1. Review terraform.tfvars"
    echo "  2. Run: cd terraform && terraform plan"
    echo "  3. Run: terraform apply (when ready)"
    echo "  4. Get kubeconfig: az aks get-credentials"
    echo "  5. Deploy Kubernetes resources"
    exit 0
else
    log_error "❌ Prerequisites not met. Please resolve errors above."
    exit 1
fi
