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

set -e

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

# Color codes

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

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

# Step 1: Run prerequisite check
log_info "Step 1: Running Prerequisite Checks..."
./scripts/deployment/deploy-chain138-infrastructure.sh
PREREQ_STATUS=$?

if [ $PREREQ_STATUS -ne 0 ]; then
    log_error "❌ Prerequisites not met. Please resolve issues above."
    exit 1
fi

log_info "Step 2: Terraform Planning..."

cd terraform

# Check if already initialized
if [ ! -d ".terraform" ]; then
    echo "Initializing Terraform..."
    terraform init 2>&1 | tail -10
fi

# Create plan
echo "Creating Terraform plan..."
terraform plan -out=tfplan 2>&1 | tail -30

PLAN_STATUS=$?

cd ..

if [ $PLAN_STATUS -eq 0 ]; then
    log_success "✅ Terraform plan created successfully"
    log_warn "⚠️  REVIEW THE PLAN ABOVE BEFORE PROCEEDING"
    echo "To apply the plan:"
    echo "  cd terraform"
    echo "  terraform apply tfplan"
    echo "Or to apply directly:"
    echo "  cd terraform"
    echo "  terraform apply"
else
    log_error "❌ Terraform plan failed"
    exit 1
fi

log_info "Step 3: Preparing Kubernetes Resources..."

# Check Kubernetes manifests
if [ -d "k8s" ]; then
    MANIFEST_COUNT=$(find k8s -name "*.yaml" -o -name "*.yml" 2>/dev/null | wc -l)
    log_success "✅ Found $MANIFEST_COUNT Kubernetes manifest files"
    
    # Check for namespace
    if [ -f "k8s/base/namespace.yaml" ]; then
        log_success "✅ Namespace manifest found"
    else
        log_warn "⚠️  Namespace manifest not found"
    fi
else
    log_error "❌ k8s directory not found"
fi

log_info "Step 4: Preparing Helm Charts..."

if [ -d "helm" ]; then
    CHART_COUNT=$(find helm -name "Chart.yaml" 2>/dev/null | wc -l)
    log_success "✅ Found $CHART_COUNT Helm charts"
    
    # Check for besu-network chart
    if [ -f "helm/besu-network/Chart.yaml" ]; then
        log_success "✅ Besu network chart found"
    else
        log_warn "⚠️  Besu network chart not found"
    fi
else
    log_error "❌ helm directory not found"
fi

echo "==================================================================="
log_info "DEPLOYMENT READY"
echo "==================================================================="
log_success "✅ Infrastructure deployment preparation complete!"
echo "Next steps:"
echo "  1. Review Terraform plan (in terraform/tfplan)"
echo "  2. Apply Terraform: cd terraform && terraform apply tfplan"
echo "  3. Get kubeconfig: az aks get-credentials --resource-group <rg> --name <cluster>"
echo "  4. Deploy Kubernetes: kubectl apply -k k8s/base"
echo "  5. Deploy Besu: helm install besu-validators ./helm/besu-network -n besu-network"
