#!/usr/bin/env bash
# Main deployment orchestration script for SMOM-DBIS-138 on Proxmox VE

set -euo pipefail

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

source "$PROJECT_ROOT/lib/common.sh"

# Parse command line arguments
SKIP_BESU="${SKIP_BESU:-false}"
SKIP_SERVICES="${SKIP_SERVICES:-false}"
SKIP_MONITORING="${SKIP_MONITORING:-false}"
SKIP_CONFIG="${SKIP_CONFIG:-false}"

while [[ $# -gt 0 ]]; do
    case $1 in
        --skip-besu)
            SKIP_BESU=true
            shift
            ;;
        --skip-services)
            SKIP_SERVICES=true
            shift
            ;;
        --skip-monitoring)
            SKIP_MONITORING=true
            shift
            ;;
        --skip-config)
            SKIP_CONFIG=true
            shift
            ;;
        --help)
            echo "Usage: $0 [OPTIONS]"
            echo ""
            echo "Options:"
            echo "  --skip-besu        Skip Besu nodes deployment"
            echo "  --skip-services    Skip services deployment"
            echo "  --skip-monitoring  Skip monitoring stack deployment"
            echo "  --skip-config      Skip configuration updates"
            echo "  --help             Show this help message"
            exit 0
            ;;
        *)
            log_error "Unknown option: $1"
            exit 1
            ;;
    esac
done

# Load configuration
load_config

# Initialize rollback tracking
if command_exists init_rollback 2>/dev/null; then
    init_rollback "$PROJECT_ROOT/logs/rollback-$(date +%Y%m%d-%H%M%S).log"
    set_rollback_trap
fi

log_info "========================================="
log_info "SMOM-DBIS-138 Proxmox Deployment"
log_info "========================================="
log_info ""

# Check prerequisites
log_info "Checking prerequisites..."
if ! command_exists pct; then
    error_exit "pct command not found. This script must be run on Proxmox host."
fi

if [[ $EUID -ne 0 ]]; then
    error_exit "This script must be run as root"
fi

# Ensure OS template exists before starting deployment
log_info "Checking OS template..."
ensure_os_template "${CONTAINER_OS_TEMPLATE:-local:vztmpl/ubuntu-22.04-standard_22.04-1_amd64.tar.zst}" || {
    error_exit "OS template not available. Please download it first: pveam download local ubuntu-22.04-standard_22.04-1_amd64.tar.zst"
}

# Create log directory
mkdir -p "$PROJECT_ROOT/logs"
LOG_FILE="$PROJECT_ROOT/logs/deployment-$(date +%Y%m%d-%H%M%S).log"

log_info "Deployment log: $LOG_FILE"
exec > >(tee -a "$LOG_FILE") 2>&1

log_success "Prerequisites checked"

# Deploy Besu nodes
if [[ "$SKIP_BESU" != "true" ]]; then
    log_info ""
    log_info "=== Deploying Besu Nodes ==="
    "$SCRIPT_DIR/deploy-besu-nodes.sh" || {
        log_error "Besu nodes deployment failed"
        exit 1
    }
else
    log_info "Skipping Besu nodes deployment (--skip-besu)"
fi

# Deploy services
if [[ "$SKIP_SERVICES" != "true" ]]; then
    log_info ""
    log_info "=== Deploying Services ==="
    if [[ -f "$SCRIPT_DIR/deploy-services.sh" ]]; then
        "$SCRIPT_DIR/deploy-services.sh" || {
            log_error "Services deployment failed"
            exit 1
        }
    else
        log_warn "Services deployment script not found, skipping"
    fi
    
    log_info ""
    log_info "=== Deploying Hyperledger Services ==="
    if [[ -f "$SCRIPT_DIR/deploy-hyperledger-services.sh" ]]; then
        "$SCRIPT_DIR/deploy-hyperledger-services.sh" || {
            log_warn "Hyperledger services deployment had issues, continuing..."
        }
    else
        log_warn "Hyperledger services deployment script not found, skipping"
    fi
else
    log_info "Skipping services deployment (--skip-services)"
fi

# Deploy monitoring
if [[ "$SKIP_MONITORING" != "true" ]]; then
    log_info ""
    log_info "=== Deploying Monitoring Stack ==="
    if [[ -f "$SCRIPT_DIR/deploy-monitoring.sh" ]]; then
        "$SCRIPT_DIR/deploy-monitoring.sh" || {
            log_error "Monitoring deployment failed"
            exit 1
        }
    else
        log_warn "Monitoring deployment script not found, skipping"
    fi
else
    log_info "Skipping monitoring deployment (--skip-monitoring)"
fi

# Update configurations
if [[ "$SKIP_CONFIG" != "true" ]]; then
    log_info ""
    log_info "=== Updating Configurations ==="
    if [[ -f "$SCRIPT_DIR/network/update-static-nodes.sh" ]]; then
        "$SCRIPT_DIR/network/update-static-nodes.sh" || {
            log_warn "Static nodes update failed, continuing..."
        }
    fi
else
    log_info "Skipping configuration updates (--skip-config)"
fi

log_info ""
log_success "========================================="
log_success "Deployment Completed Successfully!"
log_success "========================================="

# Clean up rollback file on successful completion
if command_exists cleanup_rollback 2>/dev/null; then
    clear_rollback_trap
    cleanup_rollback
fi
log_info ""
log_info "Next Steps:"
log_info "1. Review deployment inventory: $PROJECT_ROOT/config/inventory.conf"
log_info "2. Copy genesis.json and configuration files to containers"
log_info "3. Copy validator keys to validator containers"
log_info "4. Update static-nodes.json with all node IPs"
log_info "5. Start Besu services in containers"
log_info "6. Verify network connectivity between nodes"
log_info "7. Check logs: $LOG_FILE"
log_info ""

