#!/usr/bin/env bash
# Phase 1: Prerequisites & Setup - Complete automation
# This script completes all Phase 1 tasks

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 "Phase 1: Prerequisites & Setup"

# 1.1 Azure Authentication
section "1.1 Azure Authentication"
if command -v az &> /dev/null; then
    log "Azure CLI is installed"
    if az account show &> /dev/null; then
        log "Azure authentication verified"
        az account show --query "{Subscription:name, ID:id, Tenant:tenantId}" -o table
    else
        error "Not logged in to Azure. Run: az login"
    fi
else
    error "Azure CLI not installed"
fi

# 1.2 Environment Configuration
section "1.2 Environment Configuration"
if [ -f "$PROJECT_ROOT/.env" ]; then
    log ".env file exists"
    source "$PROJECT_ROOT/.env"
    
    # Verify required variables
    required_vars=("AZURE_SUBSCRIPTION_ID" "AZURE_LOCATION" "CLOUDFLARE_ZONE_ID" "CLOUDFLARE_API_TOKEN")
    missing=0
    for var in "${required_vars[@]}"; do
        if [ -z "${!var:-}" ]; then
            warn "$var is not set"
            missing=1
        else
            log "$var is set"
        fi
    done
    
    if [ $missing -eq 1 ]; then
        warn "Some environment variables are missing. Run: ./scripts/deployment/populate-env.sh"
    fi
else
    warn ".env file not found. Run: ./scripts/deployment/populate-env.sh"
fi

# 1.3 Prerequisites Verification
section "1.3 Prerequisites Verification"
if [ -f "$PROJECT_ROOT/scripts/azure/check-azure-prerequisites.sh" ]; then
    info "Running prerequisites check..."
    "$PROJECT_ROOT/scripts/azure/check-azure-prerequisites.sh" || warn "Some prerequisites may need attention"
else
    warn "Prerequisites check script not found"
fi

# 1.4 Key Generation
section "1.4 Key Generation"
KEYS_DIR="$PROJECT_ROOT/keys"

# Generate validator keys
if [ -f "$PROJECT_ROOT/scripts/key-management/generate-validator-keys.sh" ]; then
    if [ ! -d "$KEYS_DIR/validators" ] || [ -z "$(ls -A $KEYS_DIR/validators 2>/dev/null)" ]; then
        info "Generating validator keys..."
        "$PROJECT_ROOT/scripts/key-management/generate-validator-keys.sh" 4
        log "Validator keys generated"
    else
        log "Validator keys already exist"
    fi
else
    warn "Validator key generation script not found"
fi

# Generate oracle keys
if [ -f "$PROJECT_ROOT/scripts/key-management/generate-oracle-keys.sh" ]; then
    if [ ! -d "$KEYS_DIR/oracle" ] || [ -z "$(ls -A $KEYS_DIR/oracle 2>/dev/null)" ]; then
        info "Generating oracle keys..."
        "$PROJECT_ROOT/scripts/key-management/generate-oracle-keys.sh"
        log "Oracle keys generated"
    else
        log "Oracle keys already exist"
    fi
else
    warn "Oracle key generation script not found"
fi

# Generate genesis file
if [ -f "$PROJECT_ROOT/scripts/generate-genesis.sh" ]; then
    if [ ! -f "$PROJECT_ROOT/config/genesis.json" ]; then
        info "Generating genesis file..."
        if "$PROJECT_ROOT/scripts/generate-genesis.sh" 2>/dev/null; then
            log "Genesis file generated"
        else
            warn "Genesis generation failed (Besu may not be installed). Creating basic genesis..."
            # Create basic genesis if Besu is not available
            mkdir -p "$PROJECT_ROOT/config"
            cat > "$PROJECT_ROOT/config/genesis.json" <<'EOF'
{
  "config": {
    "chainId": 138,
    "berlinBlock": 0,
    "londonBlock": 0,
    "istanbulBlock": 0,
    "ibft2": {
      "blockperiodseconds": 2,
      "epochlength": 30000,
      "requesttimeoutseconds": 10
    },
    "ethash": {}
  },
  "nonce": "0x0",
  "timestamp": "0x0",
  "gasLimit": "0x1c9c380",
  "difficulty": "0x1",
  "mixHash": "0x63746963616c2062797a616e74696e65206661756c7420746f6c6572616e6365",
  "coinbase": "0x0000000000000000000000000000000000000000",
  "alloc": {},
  "extraData": "0x",
  "number": "0x0",
  "gasUsed": "0x0",
  "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000"
}
EOF
            warn "Basic genesis.json created. Update with proper validator addresses before deployment."
        fi
    else
        log "Genesis file already exists"
    fi
else
    warn "Genesis generation script not found"
fi

section "Phase 1 Complete"
log "All Phase 1 tasks completed"
info "Next: Phase 2 - Foundation Infrastructure"
info "Run: cd terraform && terraform init"

