#!/usr/bin/env bash
# Complete Chain-138 Infrastructure Deployment

set -e

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

# Color codes

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

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

# Step 1: Fix Kubernetes version if needed
log_info "Step 1: Checking Kubernetes version compatibility..."

cd terraform

# Get current cluster version if cluster exists
if az aks show --resource-group az-p-we-rg-comp-001 --name az-p-we-aks-main &> /dev/null 2>&1; then
    CURRENT_VERSION=$(az aks show --resource-group az-p-we-rg-comp-001 --name az-p-we-aks-main --query kubernetesVersion -o tsv 2>/dev/null || echo "")
    if [ -n "$CURRENT_VERSION" ]; then
        echo "Current cluster version: $CURRENT_VERSION"
        # Update terraform.tfvars to match
        sed -i "s/kubernetes_version = \".*\"/kubernetes_version = \"$CURRENT_VERSION\"/" terraform.tfvars
        log_success "✅ Updated terraform.tfvars to match cluster version"
    fi
fi

# Step 2: Apply Terraform
log_info "Step 2: Applying Terraform..."

terraform plan -out=tfplan 2>&1 | tail -30

read -p "Apply Terraform plan? (y/N): " -n 1 -r

if [[ $REPLY =~ ^[Yy]$ ]]; then
    terraform apply -auto-approve tfplan
    
    if [ $? -eq 0 ]; then
        log_success "✅ Terraform apply successful"
        
        # Get outputs
        RG_NAME=$(terraform output -raw resource_group_name 2>/dev/null || echo "az-p-we-rg-comp-001")
        CLUSTER_NAME=$(terraform output -raw cluster_name 2>/dev/null || echo "az-p-we-aks-main")
        
        echo "Resource Group: $RG_NAME"
        echo "Cluster Name: $CLUSTER_NAME"
    else
        log_error "❌ Terraform apply failed"
        exit 1
    fi
else
    log_warn "⚠️  Terraform apply skipped"
fi

cd ..

# Step 3: Get kubeconfig
log_info "Step 3: Configuring Kubernetes access..."

if [ -n "$RG_NAME" ] && [ -n "$CLUSTER_NAME" ]; then
    az aks get-credentials --resource-group "$RG_NAME" --name "$CLUSTER_NAME" --overwrite-existing
    
    if kubectl cluster-info &> /dev/null 2>&1; then
        log_success "✅ Kubernetes cluster accessible"
    else
        log_error "❌ Failed to access cluster"
        exit 1
    fi
fi

# Step 4: Deploy Kubernetes resources
log_info "Step 4: Deploying Kubernetes resources..."

if kubectl cluster-info &> /dev/null 2>&1; then
    ./scripts/deployment/deploy-infrastructure-phase2.sh
else
    log_error "❌ Kubernetes not accessible"
    exit 1
fi

# Step 5: Deploy Besu network
log_info "Step 5: Deploying Besu network..."

if kubectl get namespace besu-network &> /dev/null 2>&1; then
    ./scripts/deployment/deploy-infrastructure-phase3.sh
else
    log_error "❌ Namespace not ready"
    exit 1
fi

# Step 6: Deploy monitoring
log_info "Step 6: Deploying monitoring..."

if kubectl cluster-info &> /dev/null 2>&1; then
    ./scripts/deployment/deploy-infrastructure-phase4.sh
fi

# Step 7: Verification
log_info "Step 7: Running verification..."

./scripts/deployment/verify-chain138-complete.sh

log_success "✅ Infrastructure deployment complete!"
