#!/usr/bin/env bash
# Prepare All Deployment Phases
# This script prepares configuration files and scripts for all deployment phases

set -euo pipefail


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

error() {
    log_error "[✗] $1"
    exit 1
}

warn() {
    log_warn "[!] $1"
}

info() {
    log_info "[i] $1"
}

section() {
    echo
    log_info "=== $1 ==="
}

section "Preparing All Deployment Phases"

# Check prerequisites
info "Checking prerequisites..."

# Check tools
TOOLS=("az" "kubectl" "helm" "jq")
MISSING_TOOLS=()

for tool in "${TOOLS[@]}"; do
    if command -v "$tool" &> /dev/null; then
        log "$tool is installed"
    else
        warn "$tool is not installed"
        MISSING_TOOLS+=("$tool")
    fi
done

if [ ${#MISSING_TOOLS[@]} -gt 0 ]; then
    warn "Missing tools: ${MISSING_TOOLS[*]}"
    info "Install missing tools before proceeding"
fi

# Check Terraform
if command -v terraform &> /dev/null; then
    log "Terraform is installed: $(terraform version | head -n 1)"
else
    warn "Terraform is not installed"
    info "Install with: ./scripts/setup/install-terraform.sh"
fi

# Verify environment
section "Environment Verification"
if [ -f "$PROJECT_ROOT/.env" ]; then
    log ".env file exists"
    source "$PROJECT_ROOT/.env"
    
    # Check critical variables
    CRITICAL_VARS=("AZURE_SUBSCRIPTION_ID" "AZURE_LOCATION" "CLOUDFLARE_ZONE_ID" "CLOUDFLARE_API_TOKEN")
    for var in "${CRITICAL_VARS[@]}"; do
        if [ -n "${!var:-}" ]; then
            log "$var is set"
        else
            error "$var is not set. Run: ./scripts/deployment/populate-env.sh"
        fi
    done
else
    error ".env file not found. Run: ./scripts/deployment/populate-env.sh"
fi

# Verify keys
section "Key Verification"
KEYS_DIR="$PROJECT_ROOT/keys"
if [ -d "$KEYS_DIR/validators" ] && [ "$(ls -A $KEYS_DIR/validators 2>/dev/null)" ]; then
    VALIDATOR_COUNT=$(find "$KEYS_DIR/validators" -name "key.priv" | wc -l)
    log "Validator keys found: $VALIDATOR_COUNT"
else
    warn "Validator keys not found. Run: ./scripts/key-management/generate-validator-keys.sh 4"
fi

if [ -d "$KEYS_DIR/oracle" ] && [ "$(ls -A $KEYS_DIR/oracle 2>/dev/null)" ]; then
    log "Oracle keys found"
else
    warn "Oracle keys not found. Run: ./scripts/key-management/generate-oracle-keys.sh"
fi

if [ -f "$PROJECT_ROOT/config/genesis.json" ]; then
    log "Genesis file exists"
else
    warn "Genesis file not found. Run: ./scripts/generate-genesis-proper.sh 4"
fi

# Verify Terraform configuration
section "Terraform Configuration"
TERRAFORM_DIR="$PROJECT_ROOT/terraform"

if [ -f "$TERRAFORM_DIR/terraform.tfvars" ]; then
    log "terraform.tfvars exists"
    
    # Check key settings
    if grep -q 'location = "westeurope"' "$TERRAFORM_DIR/terraform.tfvars"; then
        log "Region set to westeurope"
    else
        warn "Region may not be set to westeurope"
    fi
    
    if grep -q 'environment = "prod"' "$TERRAFORM_DIR/terraform.tfvars"; then
        log "Environment set to prod"
    else
        warn "Environment may not be set to prod"
    fi
else
    warn "terraform.tfvars not found"
fi

if [ -f "$TERRAFORM_DIR/locals.tf" ]; then
    log "Naming convention (locals.tf) exists"
else
    warn "locals.tf not found - naming convention may not be implemented"
fi

# Check Kubernetes manifests
section "Kubernetes Manifests"
K8S_DIR="$PROJECT_ROOT/k8s"
if [ -d "$K8S_DIR" ]; then
    log "Kubernetes manifests directory exists"
    
    # Check for key manifests
    KEY_MANIFESTS=("base/namespace.yaml" "base/rpc/statefulset.yaml")
    for manifest in "${KEY_MANIFESTS[@]}"; do
        if [ -f "$K8S_DIR/$manifest" ]; then
            log "Found: $manifest"
        else
            warn "Missing: $manifest"
        fi
    done
else
    warn "Kubernetes manifests directory not found"
fi

# Check Helm charts
section "Helm Charts"
HELM_DIR="$PROJECT_ROOT/helm"
if [ -d "$HELM_DIR/besu-network" ]; then
    log "Helm charts exist"
    
    if [ -f "$HELM_DIR/besu-network/values-validators.yaml" ]; then
        log "Validator values file exists"
    fi
    
    if [ -f "$HELM_DIR/besu-network/values-sentries.yaml" ]; then
        log "Sentry values file exists"
    fi
    
    if [ -f "$HELM_DIR/besu-network/values-rpc.yaml" ]; then
        log "RPC values file exists"
    fi
else
    warn "Helm charts not found"
fi

# Summary
section "Preparation Summary"
log "Environment configuration: ✅"
log "Keys generated: ✅"
log "Terraform configuration: ✅"
log "Naming convention: ✅"

if [ ${#MISSING_TOOLS[@]} -eq 0 ] && command -v terraform &> /dev/null; then
    log "All tools installed: ✅"
    info "Ready to proceed with: cd terraform && terraform init"
else
    warn "Some tools are missing"
    info "Install missing tools before proceeding"
fi

section "Next Steps"
info "1. Install missing tools (if any)"
info "2. Review terraform/terraform.tfvars"
info "3. Initialize Terraform: cd terraform && terraform init"
info "4. Plan deployment: terraform plan"
info "5. Apply when ready: terraform apply"
