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

set -e

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

# Color codes

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

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

# Phase 1: Terraform
log_info "=== PHASE 1: AZURE INFRASTRUCTURE ==="

cd terraform

# Check if plan exists
if [ -f "tfplan" ]; then
    log_success "✅ Terraform plan found"
    log_warn "⚠️  This will create Azure resources and incur costs"
    read -p "Apply Terraform plan? (y/N): " -n 1 -r
    
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        echo "Applying Terraform plan..."
        terraform apply tfplan
        
        if [ $? -eq 0 ]; then
            log_success "✅ Phase 1 complete!"
            
            # Get outputs
            echo "Terraform outputs:"
            terraform output
            
            # Get resource group and cluster name
            RG_NAME=$(terraform output -raw resource_group_name 2>/dev/null || echo "")
            CLUSTER_NAME=$(terraform output -raw cluster_name 2>/dev/null || echo "")
            
            if [ -n "$RG_NAME" ] && [ -n "$CLUSTER_NAME" ]; then
                log_info "Getting kubeconfig..."
                az aks get-credentials --resource-group "$RG_NAME" --name "$CLUSTER_NAME" --overwrite-existing
                
                if [ $? -eq 0 ]; then
                    log_success "✅ Kubeconfig configured"
                else
                    log_warn "⚠️  Failed to get kubeconfig"
                fi
            fi
        else
            log_error "❌ Terraform apply failed"
            exit 1
        fi
    else
        log_warn "⚠️  Terraform apply skipped"
        echo "  Run manually: cd terraform && terraform apply tfplan"
    fi
else
    log_warn "⚠️  Terraform plan not found"
    echo "  Creating plan..."
    terraform plan -out=tfplan
    echo "Review the plan above, then run: terraform apply tfplan"
fi

cd ..

# Phase 2: Kubernetes (if cluster is accessible)
log_info "=== PHASE 2: KUBERNETES RESOURCES ==="

if kubectl cluster-info &> /dev/null 2>&1; then
    log_success "✅ Kubernetes cluster accessible"
    ./scripts/deployment/deploy-infrastructure-phase2.sh
else
    log_warn "⚠️  Kubernetes cluster not accessible"
    echo "  Complete Phase 1 first, then get kubeconfig:"
    echo "    az aks get-credentials --resource-group <rg> --name <cluster>"
fi

# Phase 3: Besu Network (if namespace exists)
log_info "=== PHASE 3: BESU NETWORK ==="

if kubectl cluster-info &> /dev/null 2>&1 && kubectl get namespace besu-network &> /dev/null 2>&1; then
    log_success "✅ Ready for Besu deployment"
    ./scripts/deployment/deploy-infrastructure-phase3.sh
else
    log_warn "⚠️  Not ready for Besu deployment"
    echo "  Complete Phases 1 and 2 first"
fi

# Phase 4: Monitoring (if namespace exists)
log_info "=== PHASE 4: MONITORING ==="

if kubectl cluster-info &> /dev/null 2>&1; then
    log_success "✅ Ready for monitoring deployment"
    ./scripts/deployment/deploy-infrastructure-phase4.sh
else
    log_warn "⚠️  Not ready for monitoring deployment"
    echo "  Complete previous phases first"
fi

# Final verification
echo "==================================================================="
log_info "FINAL VERIFICATION"
echo "==================================================================="

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

log_success "✅ Infrastructure deployment process complete!"
