#!/usr/bin/env bash
# Master deployment script for all ChainID 138 containers
# This script orchestrates the complete deployment process

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# Check prerequisites
check_prerequisites() {
    log_info "Checking prerequisites..."
    
    local missing=0
    
    # Check if scripts exist
    local required_scripts=(
        "configure-besu-chain138-nodes.sh"
        "verify-chain138-config.sh"
        "setup-jwt-auth-all-rpc-containers.sh"
    )
    
    for script in "${required_scripts[@]}"; do
        if [ ! -f "$SCRIPT_DIR/$script" ]; then
            log_error "Required script not found: $script"
            ((missing++))
        fi
    done
    
    if [ $missing -gt 0 ]; then
        log_error "Missing required scripts. Please ensure all scripts are present."
        return 1
    fi
    
    log_success "All prerequisites met"
    return 0
}

# Step 1: Configure Besu nodes
step1_configure_besu() {
    log_info "Step 1: Configuring Besu nodes..."
    echo ""
    
    if [ ! -f "$SCRIPT_DIR/configure-besu-chain138-nodes.sh" ]; then
        log_error "configure-besu-chain138-nodes.sh not found"
        return 1
    fi
    
    bash "$SCRIPT_DIR/configure-besu-chain138-nodes.sh"
    
    if [ $? -eq 0 ]; then
        log_success "Besu nodes configured successfully"
        return 0
    else
        log_error "Failed to configure Besu nodes"
        return 1
    fi
}

# Step 2: Verify configuration
step2_verify_config() {
    log_info "Step 2: Verifying configuration..."
    echo ""
    
    if [ ! -f "$SCRIPT_DIR/verify-chain138-config.sh" ]; then
        log_error "verify-chain138-config.sh not found"
        return 1
    fi
    
    bash "$SCRIPT_DIR/verify-chain138-config.sh"
    
    if [ $? -eq 0 ]; then
        log_success "Configuration verified successfully"
        return 0
    else
        log_warn "Some verification checks may have failed (this is OK if containers are not yet running)"
        return 0
    fi
}

# Step 3: Setup JWT authentication
step3_setup_jwt() {
    log_info "Step 3: Setting up JWT authentication for RPC containers..."
    echo ""
    
    if [ ! -f "$SCRIPT_DIR/setup-jwt-auth-all-rpc-containers.sh" ]; then
        log_error "setup-jwt-auth-all-rpc-containers.sh not found"
        return 1
    fi
    
    bash "$SCRIPT_DIR/setup-jwt-auth-all-rpc-containers.sh"
    
    if [ $? -eq 0 ]; then
        log_success "JWT authentication configured successfully"
        return 0
    else
        log_warn "JWT authentication setup may have failed for some containers (this is OK if containers are not yet running)"
        return 0
    fi
}

# Step 4: Generate JWT tokens
step4_generate_tokens() {
    log_info "Step 4: Generating JWT tokens for operators..."
    echo ""
    
    if [ ! -f "$SCRIPT_DIR/generate-jwt-token-for-container.sh" ]; then
        log_error "generate-jwt-token-for-container.sh not found"
        return 1
    fi
    
    # Generate tokens for Ali (full access)
    log_info "Generating tokens for Ali (full access)..."
    for vmid in 2503 2504; do
        log_info "  VMID $vmid:"
        bash "$SCRIPT_DIR/generate-jwt-token-for-container.sh" "$vmid" "ali-full-access" 365 || log_warn "  Failed to generate token for $vmid"
    done
    
    # Generate tokens for Luis (RPC-only)
    log_info "Generating tokens for Luis (RPC-only)..."
    for vmid in 2505 2506; do
        log_info "  VMID $vmid:"
        bash "$SCRIPT_DIR/generate-jwt-token-for-container.sh" "$vmid" "luis-rpc-access" 365 || log_warn "  Failed to generate token for $vmid"
    done
    
    # Generate tokens for Putu (RPC-only)
    log_info "Generating tokens for Putu (RPC-only)..."
    for vmid in 2507 2508; do
        log_info "  VMID $vmid:"
        bash "$SCRIPT_DIR/generate-jwt-token-for-container.sh" "$vmid" "putu-rpc-access" 365 || log_warn "  Failed to generate token for $vmid"
    done
    
    log_success "JWT token generation completed"
}

# Main execution
main() {
    echo ""
    log_info "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    log_info "ChainID 138 Complete Deployment Script"
    log_info "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo ""
    
    # Check prerequisites
    if ! check_prerequisites; then
        log_error "Prerequisites check failed. Please fix issues and try again."
        exit 1
    fi
    
    echo ""
    log_info "This script will:"
    log_info "  1. Configure all Besu nodes (static-nodes.json, permissioned-nodes.json)"
    log_info "  2. Verify configuration"
    log_info "  3. Setup JWT authentication for RPC containers"
    log_info "  4. Generate JWT tokens for operators"
    echo ""
    
    read -p "Continue? (y/N): " -n 1 -r
    echo ""
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        log_info "Deployment cancelled"
        exit 0
    fi
    
    local failed_steps=0
    
    # Step 1: Configure Besu
    if ! step1_configure_besu; then
        ((failed_steps++))
    fi
    echo ""
    
    # Step 2: Verify configuration
    if ! step2_verify_config; then
        ((failed_steps++))
    fi
    echo ""
    
    # Step 3: Setup JWT
    if ! step3_setup_jwt; then
        ((failed_steps++))
    fi
    echo ""
    
    # Step 4: Generate tokens
    step4_generate_tokens
    echo ""
    
    # Summary
    echo ""
    log_info "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    log_info "Deployment Summary"
    log_info "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    
    if [ $failed_steps -eq 0 ]; then
        log_success "All deployment steps completed successfully!"
    else
        log_warn "Deployment completed with $failed_steps failed step(s)"
        log_info "Some steps may have failed because containers are not yet running"
        log_info "Re-run this script after containers are created"
    fi
    
    echo ""
    log_info "Next steps:"
    log_info "  1. Create remaining containers (see docs/MISSING_CONTAINERS_LIST.md)"
    log_info "  2. Re-run this script to complete configuration"
    log_info "  3. Test JWT authentication on each RPC container"
    log_info "  4. Distribute JWT tokens to operators"
    echo ""
}

main "$@"

