#!/usr/bin/env bash
# One-Command Deployment Script for SMOM-DBIS-138 on Proxmox VE LXC
# This script deploys all containers with a single command

set -euo pipefail

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

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

# Banner
echo -e "${CYAN}"
cat << "EOF"
   _____ __  __ ____  ____   ____  ____ ___  _____ 
  / ____|  \/  |  _ \|  _ \ / __ \|  _ \|__ \|__  |
 | (___ | \  / | |_) | |_) | |  | | |_) | ) |  / / 
  \___ \| |\/| |  _ <|  _ <| |  | |  _ < / /  / /_ 
  ____) | |  | | |_) | |_) | |__| | |_) / /_ |____|
 |_____/|_|  |_|____/|____/ \____/|____/____|      
                                                    
     Proxmox VE LXC Deployment Script
     Complete Deployment in One Command
EOF
echo -e "${NC}\n"

# Check if running on Proxmox host
if ! command -v pct >/dev/null 2>&1; then
    echo -e "${RED}ERROR: This script must be run on a Proxmox host${NC}"
    echo -e "${YELLOW}Install Proxmox VE and run this script on the Proxmox host${NC}"
    exit 1
fi

# Check if running as root
if [[ $EUID -ne 0 ]]; then
    echo -e "${RED}ERROR: This script must be run as root${NC}"
    echo -e "${YELLOW}Use: sudo $0${NC}"
    exit 1
fi

# Load configuration
if [[ ! -f "config/proxmox.conf" ]]; then
    if [[ -f "config/proxmox.conf.example" ]]; then
        echo -e "${YELLOW}Configuration file not found. Copying from example...${NC}"
        cp config/proxmox.conf.example config/proxmox.conf
        echo -e "${GREEN}✓ Created config/proxmox.conf${NC}"
        echo -e "${YELLOW}Please edit config/proxmox.conf with your settings before continuing${NC}"
        exit 1
    else
        echo -e "${RED}ERROR: Configuration file not found${NC}"
        exit 1
    fi
fi

source config/proxmox.conf
source config/network.conf 2>/dev/null || true

# Deployment options
DEPLOY_BESU="${DEPLOY_BESU:-true}"
DEPLOY_BESU_TEMP_VM="${DEPLOY_BESU_TEMP_VM:-false}"  # Use temporary VM instead of LXC
DEPLOY_HYPERLEDGER="${DEPLOY_HYPERLEDGER:-true}"
DEPLOY_SERVICES="${DEPLOY_SERVICES:-true}"
DEPLOY_MONITORING="${DEPLOY_MONITORING:-true}"
DEPLOY_EXPLORER="${DEPLOY_EXPLORER:-true}"

# Summary
echo -e "${BLUE}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║              Deployment Configuration Summary                ║${NC}"
echo -e "${BLUE}╠══════════════════════════════════════════════════════════════╣${NC}"
echo -e "${BLUE}║${NC} ${CYAN}Blockchain Core (Besu):${NC} ${DEPLOY_BESU}${NC}"
if [[ "$DEPLOY_BESU_TEMP_VM" == "true" ]]; then
    echo -e "${BLUE}║${NC}   - Deployment: ${YELLOW}Temporary VM (VMID 9000)${NC}"
    echo -e "${BLUE}║${NC}   - All 12 nodes in single VM with Docker${NC}"
else
    echo -e "${BLUE}║${NC}   - Validators: VMID ${VMID_VALIDATORS_START:-1000}-$((VMID_VALIDATORS_START + 4))${NC}"
    echo -e "${BLUE}║${NC}   - Sentries: VMID ${VMID_SENTRIES_START:-1500}-$((VMID_SENTRIES_START + 3))${NC}"
    echo -e "${BLUE}║${NC}   - RPC Nodes: VMID ${VMID_RPC_START:-2500}-$((VMID_RPC_START + 2))${NC}"
fi
echo -e "${BLUE}║${NC}"
echo -e "${BLUE}║${NC} ${CYAN}Hyperledger Services:${NC} ${DEPLOY_HYPERLEDGER}${NC}"
echo -e "${BLUE}║${NC}   - Firefly: VMID ${VMID_FIREFLY_START:-150}${NC}"
echo -e "${BLUE}║${NC}   - Cacti: VMID ${VMID_CACTI_START:-151}${NC}"
echo -e "${BLUE}║${NC}   - Fabric: VMID ${VMID_FABRIC_START:-152}${NC}"
echo -e "${BLUE}║${NC}   - Indy: VMID ${VMID_INDY_START:-153}${NC}"
echo -e "${BLUE}║${NC}"
echo -e "${BLUE}║${NC} ${CYAN}Services:${NC} ${DEPLOY_SERVICES}${NC}"
echo -e "${BLUE}║${NC}   - Oracle Publisher, CCIP Monitor, Keeper, Tokenization${NC}"
echo -e "${BLUE}║${NC}"
echo -e "${BLUE}║${NC} ${CYAN}Monitoring Stack:${NC} ${DEPLOY_MONITORING}${NC}"
echo -e "${BLUE}║${NC}   - Prometheus, Grafana, Loki, Alertmanager${NC}"
echo -e "${BLUE}║${NC}"
echo -e "${BLUE}║${NC} ${CYAN}Blockscout Explorer:${NC} ${DEPLOY_EXPLORER}${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════════════════════════╝${NC}\n"

# Confirmation
read -p "$(echo -e ${YELLOW}Continue with deployment? [y/N]: ${NC})" -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo -e "${YELLOW}Deployment cancelled${NC}"
    exit 0
fi

# Track deployment status
DEPLOYMENT_STATUS=0

# Function to run deployment script
run_deployment() {
    local script_name="$1"
    local description="$2"
    
    echo -e "\n${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${CYAN}Deploying: ${description}${NC}"
    echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}\n"
    
    if [[ -f "scripts/deployment/${script_name}" ]]; then
        if bash "scripts/deployment/${script_name}"; then
            echo -e "${GREEN}✓ Successfully deployed: ${description}${NC}\n"
            return 0
        else
            echo -e "${RED}✗ Failed to deploy: ${description}${NC}\n"
            DEPLOYMENT_STATUS=1
            return 1
        fi
    else
        echo -e "${YELLOW}⚠ Script not found: scripts/deployment/${script_name}${NC}\n"
        return 0
    fi
}

# Phase 1: Besu Network
if [[ "$DEPLOY_BESU" == "true" ]]; then
    if [[ "$DEPLOY_BESU_TEMP_VM" == "true" ]]; then
        echo -e "${YELLOW}Using temporary VM deployment for Besu nodes${NC}"
        run_deployment "deploy-besu-temp-vm-complete.sh" "Besu Blockchain Network (Temporary VM)"
    else
        run_deployment "deploy-besu-nodes.sh" "Besu Blockchain Network"
    fi
fi

# Phase 2: Hyperledger Services
if [[ "$DEPLOY_HYPERLEDGER" == "true" ]]; then
    run_deployment "deploy-hyperledger-services.sh" "Hyperledger Services"
fi

# Phase 3: Additional Services
if [[ "$DEPLOY_SERVICES" == "true" ]]; then
    if [[ -f "scripts/deployment/deploy-services.sh" ]]; then
        run_deployment "deploy-services.sh" "Oracle, CCIP Monitor, Keeper Services"
    else
        echo -e "${YELLOW}⚠ Services deployment script not yet implemented${NC}\n"
    fi
fi

# Phase 4: Monitoring Stack
if [[ "$DEPLOY_MONITORING" == "true" ]]; then
    if [[ -f "scripts/deployment/deploy-monitoring.sh" ]]; then
        run_deployment "deploy-monitoring.sh" "Monitoring Stack"
    else
        echo -e "${YELLOW}⚠ Monitoring deployment script not yet implemented${NC}\n"
    fi
fi

# Phase 5: Blockscout Explorer
if [[ "$DEPLOY_EXPLORER" == "true" ]]; then
    if [[ -f "scripts/deployment/deploy-explorer.sh" ]]; then
        run_deployment "deploy-explorer.sh" "Blockscout Explorer"
    else
        echo -e "${YELLOW}⚠ Explorer deployment script not yet implemented${NC}\n"
    fi
fi

# Final Summary
echo -e "\n${BLUE}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║                  Deployment Summary                          ║${NC}"
echo -e "${BLUE}╠══════════════════════════════════════════════════════════════╣${NC}"

if [[ $DEPLOYMENT_STATUS -eq 0 ]]; then
    echo -e "${BLUE}║${NC} ${GREEN}Status: ✓ Deployment completed successfully${NC}"
    echo -e "${BLUE}╠══════════════════════════════════════════════════════════════╣${NC}"
    echo -e "${BLUE}║${NC} ${CYAN}Next Steps:${NC}"
    echo -e "${BLUE}║${NC}   1. Configure service connections (Besu RPC, etc.)"
    echo -e "${BLUE}║${NC}   2. Update .env files in containers"
    echo -e "${BLUE}║${NC}   3. Start services: systemctl start <service>"
    echo -e "${BLUE}║${NC}   4. Verify deployment: scripts/verify-deployment.sh"
    echo -e "${BLUE}║${NC}"
    echo -e "${BLUE}║${NC} ${CYAN}Documentation:${NC}"
    echo -e "${BLUE}║${NC}   - README.md - Overview"
    echo -e "${BLUE}║${NC}   - docs/DEPLOYMENT.md - Full guide"
    echo -e "${BLUE}║${NC}   - docs/SERVICES_LIST.md - Service details"
else
    echo -e "${BLUE}║${NC} ${RED}Status: ✗ Deployment had errors${NC}"
    echo -e "${BLUE}║${NC} ${YELLOW}Check logs above for details${NC}"
fi

echo -e "${BLUE}╚══════════════════════════════════════════════════════════════╝${NC}\n"

exit $DEPLOYMENT_STATUS

