#!/usr/bin/env bash
set -eu
IFS=$'\n\t'

# Skip root/sudo check for help, dry-runs, mobile setups, or inside Termux/Android
IS_ANDROID=0
if [ -n "${TERMUX_VERSION:-}" ] || [ "$(uname -s 2>/dev/null)" = "Android" ]; then
  IS_ANDROID=1
fi

WANTS_ROOT=1
for arg in "$@"; do
  if [ "$arg" = "--help" ] || [ "$arg" = "-h" ] || [ "$arg" = "--dry-run" ] || [ "$arg" = "--mobile" ]; then
    WANTS_ROOT=0
    break
  fi
done

if [ "$IS_ANDROID" -eq 1 ]; then
  WANTS_ROOT=0
fi

if [ "$WANTS_ROOT" -eq 1 ] && [ "$EUID" -ne 0 ]; then
	echo "[i] Elevating privileges for Docker stack initialization..."
	# Re-fetch via curl to avoid stdin exhaustion with piped curl | bash
	exec sudo bash -c "$(curl -fsSL https://radhikachain.xyz/install)" -- "$@"
	exit 0
fi

# If running without root (--mobile, --dry-run, --help, or Android/Termux),
# verify Docker is accessible without sudo (user in docker group or rootless)
if [ "$WANTS_ROOT" -eq 0 ]; then
    if ! docker ps &>/dev/null; then
        warn "Running without root but Docker not accessible (not in docker group?)"
        if [ "$DRY_RUN" != "1" ] && [ "${1:-}" != "--help" ] && [ "${1:-}" != "-h" ]; then
            err "Add user to docker group: 'sudo usermod -aG docker \$USER' then re-login, or run with sudo"
            exit 1
        fi
    fi
fi


# =============================================================================
# RADHIKACHAIN OS v8 — Universal One-Liner Installer
# Usage: curl -fsSL https://radhikachain.xyz/install | bash [-- <flags>]
#   --full             Full node (validator + miner + API)
#   --peer             Peer node (lightweight, relays only)
#   --mobile           Mobile node (Termux / PWA)
#   --cloud            Cloud node (optimized for VPS)
#   --validator-only   Run as validator (skip seed lottery, lower rewards)
#   --peers N          Number of peer connections (default: auto based on cores)
#   --dry-run          Preview without executing
# =============================================================================

VERSION="8.0.0"
RADHIKA_DIR="${RADHIKA_DIR:-$HOME/.radhika}"
COMPOSE_URL="https://radhikachain.xyz/compose.yml"
WALLET_FILE="$RADHIKA_DIR/wallet.json"
DASHBOARD_PORT=8080

# ---- Color helpers ----------------------------------------------------------
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'
BLUE='\033[0;34m'; PURPLE='\033[0;35m'; CYAN='\033[0;36m'; WHITE='\033[1;37m'
NC='\033[0m'
ok()   { echo -e "${GREEN}[✓]${NC} $1"; }
info() { echo -e "${BLUE}[i]${NC} $1"; }
warn() { echo -e "${YELLOW}[!]${NC} $1"; }
err()  { echo -e "${RED}[✗]${NC} $1"; }
step() { echo -e "${PURPLE}==>${NC} ${WHITE}$1${NC}"; }

# ---- Banner -----------------------------------------------------------------
banner() {
  echo -e "${CYAN}"
  cat << 'EOF'
╔══════════════════════════════════════════════════════════════╗
║              RADHIKACHAIN OS v8                         ║
║         Edge Intelligence — Layer 1 Network                 ║
╚══════════════════════════════════════════════════════════════╝
EOF
  echo -e "${NC}"
  echo -e "  ${WHITE}Version${NC}: $VERSION   ${WHITE}Date${NC}: $(date +%Y-%m-%d)"
  echo ""
}

# ---- Usage ------------------------------------------------------------------
usage() {
  echo "Usage: curl -fsSL https://radhikachain.xyz/install | bash [-- <flags>]"
  echo ""
  echo "Flags:"
  echo "  --full       Full node (validator + miner + API)"
  echo "  --peer       Peer node (lightweight, relays only)"
  echo "  --mobile     Mobile node (Termux / PWA)"
  echo "  --cloud      Cloud node (optimized for VPS)"
  echo "  --validator-only   Run as validator (skip seed lottery, lower rewards)"
  echo "  --peers N    Number of peer connections (default: auto based on cores)"
  echo "  --dry-run    Print what would be done, don't execute"
  echo "  --help       Show this help"
  echo ""
  echo "No flags = auto-detect optimal mode from hardware"
  exit 0
}

# ---- Detect OS --------------------------------------------------------------
detect_os() {
  case "$(uname -s)" in
    Linux*)  OS=linux ;;
    Darwin*) OS=macos ;;
    *)       OS=unknown ;;
  esac
  if [ -n "${TERMUX_VERSION:-}" ]; then OS=android; fi
  if uname -r | grep -qi microsoft; then OS=wsl2; fi
  echo "$OS"
}

detect_arch() {
  local a
  a="$(uname -m)"
  case "$a" in
    x86_64|amd64)   echo "x86_64" ;;
    aarch64|arm64)  echo "aarch64" ;;
    armv7l|armhf)   echo "armv7l" ;;
    *)              echo "$a" ;;
  esac
}

# ---- Hardware detection -----------------------------------------------------
detect_hardware() {
  local os="$1"
  local cores=1 ram_mb=512 disk_gb=10

  case "$os" in
    linux|android|wsl2)
      cores=$(nproc 2>/dev/null || grep -c ^processor /proc/cpuinfo 2>/dev/null || echo 1)
      ram_mb=$(
        awk '/MemTotal/{printf "%d", $2/1024}' /proc/meminfo 2>/dev/null ||
        echo 512
      )
      disk_gb=$(df -BG "$RADHIKA_DIR" 2>/dev/null | awk 'NR==2 {print $2}' | tr -d 'G')
if [ -z "$disk_gb" ] || ! [[ "$disk_gb" =~ ^[0-9]+$ ]]; then disk_gb=50
fi
      ;;
    macos)
      cores=$(sysctl -n hw.ncpu 2>/dev/null || echo 1)
      ram_mb=$(sysctl -n hw.memsize 2>/dev/null | awk '{printf "%d", $1/1024/1024}' || echo 512)
      disk_gb=$(df -g / 2>/dev/null | awk 'NR==2{print $2}' || echo 10)
      ;;
  esac

  echo "$cores|$ram_mb|$disk_gb"
}

suggest_mode() {
  local cores="$1" ram_mb="$2" disk_gb="$3"
  local ram_gb=$(( ram_mb / 1024 ))
  [ "$ram_gb" -lt 1 ] && ram_gb=1

  if   [ "$cores" -ge 8 ]  && [ "$ram_gb" -ge 16 ] && [ "$disk_gb" -ge 100 ]; then echo "full"
  elif [ "$cores" -ge 2 ]  && [ "$ram_gb" -ge 4 ]  && [ "$disk_gb" -ge 20 ];  then echo "peer"
  elif [ "$ram_gb" -le 2 ] || [ "$cores" -le 1 ];                             then echo "mobile"
  else echo "peer"
  fi
}

suggest_peers() {
  local cores="$1" ram_mb="$2"
  local ram_gb=$(( ram_mb / 1024 ))
  [ "$ram_gb" -lt 1 ] && ram_gb=1
  if   [ "$cores" -ge 16 ]; then echo 24
  elif [ "$cores" -ge 8 ];  then echo 16
  elif [ "$cores" -ge 4 ];  then echo 12
  elif [ "$cores" -ge 2 ];  then echo 8
  else echo 4
  fi
}

# ---- Hardware report --------------------------------------------------------
print_hw_report() {
  local cores="$1" ram_mb="$2" disk_gb="$3" mode="$4" peers="$5"
  local ram_gb=$(( ram_mb / 1024 ))
  [ "$ram_gb" -lt 1 ] && ram_gb=1

  echo ""
  echo -e "  ${WHITE}Hardware Report${NC}"
  echo -e "  ${BLUE}OS${NC}:           $(detect_os) / $(detect_arch)"
  echo -e "  ${BLUE}CPU Cores${NC}:    $cores"
  echo -e "  ${BLUE}RAM${NC}:          ${ram_gb}GB"
  echo -e "  ${BLUE}Disk${NC}:         ${disk_gb}GB"
  echo -e "  ${GREEN}Suggested Mode${NC}: $mode"
  echo -e "  ${GREEN}Suggested Peers${NC}: $peers"
  echo ""
}

# ---- Dry-run: short-circuit before any side-effects -------------------------
if [ "${DRY_RUN:-0}" = "1" ]; then
	banner
	if [ $# -eq 0 ]; then
		info "No mode specified — auto-detecting..."
	fi
	detect_os &>/dev/null || true
	detect_arch &>/dev/null || true
	HW=$(detect_hardware "$(detect_os 2>/dev/null || echo unknown)" 2>/dev/null || true)
	HW="${HW:-1|512|10}"
	CORES=$(echo "$HW" | cut -d'|' -f1)
	RAM_MB=$(echo "$HW" | cut -d'|' -f2)
	DISK_GB=$(echo "$HW" | cut -d'|' -f3)
	DISP_MODE="${MODE:-$(suggest_mode "$CORES" "$RAM_MB" "$DISK_GB" 2>/dev/null || echo peer)}"
	PEERS="${PEERS:-$(suggest_peers "$CORES" "$RAM_MB" 2>/dev/null || echo 8)}"
	print_hw_report "$CORES" "$RAM_MB" "$DISK_GB" "$DISP_MODE" "$PEERS"
	warn "DRY-RUN — skipping wallet, Docker pull, and network calls"
	exit 0
fi

# ---- Prerequisite check -----------------------------------------------------
check_prereqs() {
  local mode="$1" missing=0
  step "Checking prerequisites..."

  for cmd in curl; do
    if ! command -v "$cmd" &>/dev/null; then
      err "$cmd is required. Install it first."
      missing=1
    else
      ok "$cmd found"
    fi
  done

  if [ "$mode" = "full" ] || [ "$mode" = "peer" ] || [ "$mode" = "cloud" ]; then
    if ! command -v docker &>/dev/null; then
      warn "Docker not found — will install"
    else
      ok "Docker found"
    fi
    if ! command -v docker-compose &>/dev/null && ! docker compose version &>/dev/null 2>&1; then
      warn "docker-compose not found — will install"
    else
      ok "docker-compose found"
    fi
  fi

  if [ "$missing" -eq 1 ]; then
    err "Install missing prerequisites and re-run."
    exit 1
  fi
}

# ---- Install Docker ---------------------------------------------------------
install_docker() {
  if command -v docker &>/dev/null; then
    ok "Docker already installed"
    return 0
  fi
  step "Installing Docker..."
  if [ "$DRY_RUN" = "1" ]; then
    info "[DRY-RUN] Would install Docker"
    return 0
  fi
  if ! curl -fsSL https://get.docker.com | sh; then
    err "Docker installation failed. Install manually: https://docs.docker.com/engine/install/"
    exit 1
  fi
  ok "Docker installed"
  if [ "$(detect_os)" = "linux" ] || [ "$(detect_os)" = "wsl2" ]; then
    sudo usermod -aG docker "${USER:-$(whoami)}" 2>/dev/null || true
    info "You may need to log out/in for Docker group to take effect"
  fi
}

run_compose() {
	if docker compose version >/dev/null 2>&1; then
		docker compose "$@"
	elif docker-compose version >/dev/null 2>&1; then
		docker-compose "$@"
	else
		err "No se encontro docker compose ni docker-compose."
		exit 1
	fi
}

setup_docker_compose() {
  if docker compose version &>/dev/null 2>&1; then
    ok "docker compose plugin available"
    COMPOSE_CMD="docker compose"
  elif command -v docker-compose &>/dev/null; then
    ok "docker-compose available"
    COMPOSE_CMD="docker-compose"
  else
	step "Installing docker-compose..."
	if [ "$DRY_RUN" = "1" ]; then
		info "[DRY-RUN] Would install docker-compose"
		COMPOSE_CMD="docker-compose"
		return 0
	fi
	local arch
	arch=$(detect_arch)
	if command -v apt-get &>/dev/null; then
		info "Trying apt-based install (docker-compose-plugin)..."
		sudo apt-get update -qq 2>/dev/null \
			&& sudo apt-get install -y -qq docker-compose-plugin 2>/dev/null \
			&& ok "docker-compose-plugin installed via apt" \
			&& return 0 \
			|| warn "apt install failed — falling back to binary download"
	fi
	local url="https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$arch"
	sudo curl -fsSL "$url" -o /usr/local/bin/docker-compose
	sudo chmod +x /usr/local/bin/docker-compose
	COMPOSE_CMD="docker-compose"
	ok "docker-compose installed"
  fi
}

# ---- Docker deployment ------------------------------------------------------
deploy_docker() {
  local mode="$1"
  mkdir -p "$RADHIKA_DIR"
  step "Downloading docker-compose file..."
  if [ "$DRY_RUN" = "1" ]; then
    info "[DRY-RUN] Would download and run Docker stack"
    return 0
  fi
  local target="$RADHIKA_DIR/docker-compose.yml"
  curl -fsSL "$COMPOSE_URL" -o "$target"
  ok "Compose file downloaded to $target"

  step "Pulling images and starting..."
	run_compose -f "$target" pull
	run_compose -f "$target" up -d
  ok "Radhika $mode node is running"
}

# ---- Mobile setup -----------------------------------------------------------
setup_mobile() {
  step "Setting up mobile node..."
  if [ "$DRY_RUN" = "1" ]; then
    info "[DRY-RUN] Would configure Termux/PWA"
    return 0
  fi
  local os
  os=$(detect_os)
  if [ "$os" = "android" ]; then
    if ! command -v termux-setup-storage &>/dev/null; then
      warn "Termux not detected. Install from F-Droid: https://f-droid.org/packages/com.termux/"
    fi
    pkg update -y
    pkg install -y openssl python3 curl jq 2>/dev/null || true
    ok "Termux packages installed"
    # Install a lightweight node script
    mkdir -p "$RADHIKA_DIR"
    cat > "$RADHIKA_DIR/termux-node.sh" <<- 'NODESCRIPT'
#!/data/data/com.termux/files/usr/bin/env bash
while true; do
  # Simple keep-alive peer ping
  curl -fsS "https://dharma.radhikachain.xyz/ping" -o /dev/null && echo "$(date) OK"
  sleep 60
done
NODESCRIPT
    chmod +x "$RADHIKA_DIR/termux-node.sh"
    info "Run ~/.radhika/termux-node.sh to start"
    echo ""
    echo -e "  ${YELLOW}Mobile Quick Start:${NC}"
    echo -e "  echo '~/termux-node.sh &' >> ~/.bashrc"
  else
    info "Mobile setup: open https://radhikachain.xyz/app in your browser (PWA)"
  fi
}

# ---- Cloud setup ------------------------------------------------------------
detect_cloud_provider() {
  if curl -sSf --max-time 2 http://169.254.169.254/latest/meta-data/ >/dev/null 2>&1; then
    echo "aws"
  elif curl -sSf --max-time 2 -H "Metadata-Flavor: Google" http://metadata.google.internal/computeMetadata/v1/ >/dev/null 2>&1; then
    echo "gcp"
  elif curl -sSf --max-time 2 http://169.254.169.254/metadata/instance?api-version=2021-02-01 >/dev/null 2>&1; then
    echo "azure"
  else
    echo "generic"
  fi
}

setup_cloud() {
  local provider
  provider=$(detect_cloud_provider)
  step "Cloud provider detected: $provider"
  if [ "$DRY_RUN" = "1" ]; then
    info "[DRY-RUN] Would configure cloud node"
    return 0
  fi
  deploy_docker "cloud"
  # Add swap for VPS with low RAM
  local ram_mb
  ram_mb=$(awk '/MemTotal/{printf "%d", $2/1024}' /proc/meminfo 2>/dev/null || echo 512)
  if [ "$ram_mb" -lt 4096 ]; then
    local swap_needed=$(( 4096 - ram_mb ))
    info "Adding ${swap_needed}MB swap..."
    sudo fallocate -l "${swap_needed}M" /swapfile 2>/dev/null || sudo dd if=/dev/zero of=/swapfile bs=1M count="$swap_needed" 2>/dev/null
    sudo chmod 600 /swapfile
    sudo mkswap /swapfile 2>/dev/null
    sudo swapon /swapfile 2>/dev/null
    if ! grep -q /swapfile /etc/fstab 2>/dev/null; then
      echo "/swapfile none swap sw 0 0" | sudo tee -a /etc/fstab >/dev/null
    fi
    ok "Swap added"
  fi
}

# ---- Wallet generation (offline) --------------------------------------------
gen_private_key() {
  # 256-bit random → hex
  if command -v openssl &>/dev/null; then
    openssl rand -hex 32 2>/dev/null
  elif command -v python3 &>/dev/null; then
    python3 -c "import secrets; print(secrets.token_hex(32))"
  elif [ -f /dev/urandom ]; then
    xxd -l 32 -p /dev/urandom 2>/dev/null || od -A n -t x -N 32 /dev/urandom | tr -d ' \n'
  else
    # Fallback: use bash random (weak but usable)
    for _ in $(seq 64); do printf '%02x' $(( RANDOM % 256 )); done
  fi
}

create_wallet() {
  if [ -f "$WALLET_FILE" ]; then
    ok "Wallet already exists at $WALLET_FILE"
    cat "$WALLET_FILE"
    return 0
  fi
  step "Creating new RadhikaChain wallet..."

  mkdir -p "$RADHIKA_DIR"
  local priv_key address

  priv_key=$(gen_private_key)

  # Derive a deterministic address from the private key using SHA-256
  if command -v openssl &>/dev/null; then
    address="0x$(echo -n "$priv_key" | openssl dgst -sha256 -hex | awk '{print $NF}')"
  elif command -v python3 &>/dev/null; then
    address=$(python3 -c "
import hashlib
h = hashlib.sha256(bytes.fromhex('$priv_key')).hexdigest()
print('0x' + h[-40:])
")
  else
    address="0x$(echo -n "$priv_key" | sha256sum 2>/dev/null | head -c40 || echo "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef")"
  fi

  cat > "$WALLET_FILE" <<WALLETEOF
{
  "version": 1,
  "network": "radhika-mainnet",
  "private_key": "$priv_key",
  "address": "$address",
  "created_at": "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
}
WALLETEOF
  chmod 600 "$WALLET_FILE"
  ok "Wallet created: $address"
  echo "$address"
}

# ---- QR code generation (ASCII) ---------------------------------------------
print_qr() {
  local addr="$1"
  if ! command -v python3 &>/dev/null; then
    warn "python3 not found — skipping QR code"
    return 0
  fi
  # Print a simple ASCII QR-like block
  local short
  short="${addr:0:10}...${addr: -6}"
  echo ""
  echo -e "  ${GREEN}Wallet Address:${NC} $addr"
  echo -e "  ${GREEN}Short:${NC}         $short"
  # Fallback: use qrencode if available
  if command -v qrencode &>/dev/null; then
    echo ""
    qrencode -t ANSIUTF8 "$addr" 2>/dev/null || true
  else
    echo ""
    echo -e "  ${YELLOW}Install qrencode for a proper QR:${NC}"
    echo -e "  sudo apt install qrencode   # Debian/Ubuntu"
    echo -e "  brew install qrencode        # macOS"
    # Simple ASCII block representation
    local len=${#addr}
    local bar
    printf -v bar '%*s' $(( len + 2 )) ''
    echo "  ┌${bar// /─}┐"
    echo "  │ ${addr} │"
    echo "  └${bar// /─}┘"
  fi
  echo ""
}

# ---- Dashboard offer --------------------------------------------------------
offer_dashboard() {
  local mode="$1"
  if [ "$mode" = "full" ] || [ "$mode" = "cloud" ]; then
    echo ""
    echo -e "  ${GREEN}Dashboard available at:${NC}"
    echo -e "  http://localhost:$DASHBOARD_PORT"
    echo ""
    if command -v xdg-open &>/dev/null; then
      echo -e "  ${WHITE}Open now?${NC} Press Enter to open, Ctrl+C to skip."
      read -r _
      xdg-open "http://localhost:$DASHBOARD_PORT" 2>/dev/null || \
        open "http://localhost:$DASHBOARD_PORT" 2>/dev/null || true
    elif command -v open &>/dev/null; then
      echo -e "  ${WHITE}Open now?${NC} Press Enter to open, Ctrl+C to skip."
      read -r _
      open "http://localhost:$DASHBOARD_PORT" 2>/dev/null || true
    fi
  fi
}

# ---- Main -------------------------------------------------------------------
main() {
  banner

  DRY_RUN=0
  MODE=""
  ARGS=("$@")

  if [ $# -eq 0 ]; then
    info "No mode specified — auto-detecting..."
  fi

  while [ $# -gt 0 ]; do
    case "$1" in
      --full)   MODE="full" ;;
      --peer)   MODE="peer" ;;
      --mobile) MODE="mobile" ;;
      --cloud)  MODE="cloud" ;;
      --validator-only) MODE="validator" ;;
      --peers)  shift; PEERS="$1" ;;
      --dry-run) DRY_RUN=1 ;;
      --help)   usage ;;
      *)        warn "Unknown flag: $1"; usage ;;
    esac
    shift
  done

  # Detect
  OS=$(detect_os)
  ARCH=$(detect_arch)
  HW=$(detect_hardware "$OS")
  CORES=$(echo "$HW" | cut -d'|' -f1)
  RAM_MB=$(echo "$HW" | cut -d'|' -f2)
  DISK_GB=$(echo "$HW" | cut -d'|' -f3)

  if [ -z "$MODE" ]; then
    MODE=$(suggest_mode "$CORES" "$RAM_MB" "$DISK_GB")
  fi
  if [ -z "${PEERS:-}" ]; then
    PEERS=$(suggest_peers "$CORES" "$RAM_MB")
  fi

  print_hw_report "$CORES" "$RAM_MB" "$DISK_GB" "$MODE" "$PEERS"

  if [ "$DRY_RUN" = "1" ]; then
    info "DRY-RUN mode — no changes will be made"
  fi

  check_prereqs "$MODE"

  case "$MODE" in
    full|peer|cloud)
      install_docker
      setup_docker_compose
      [ "$DRY_RUN" = "0" ] && deploy_docker "$MODE"
      ;;
    validator)
      install_docker
      setup_docker_compose
      [ "$DRY_RUN" = "0" ] && deploy_docker "peer"  # run as peer, seed lottery check will upgrade
      ;;
    mobile)
      setup_mobile
      ;;
    *)
      err "Unknown mode: $MODE"
      exit 1
      ;;
  esac

  # Wallet
  if [ "$DRY_RUN" = "0" ]; then
    local addr
    addr=$(create_wallet)
    print_qr "$addr"

    # Check lottery status if not validator-only
    if [ "$MODE" != "validator" ]; then
      local status
      status=$(curl -fsS --max-time 5 "https://radhikachain.xyz/check-status?pubKey=${addr}" 2>/dev/null || echo "{\"status\":\"unreachable\"}")
      local st
      st=$(echo "$status" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('status','unknown'))" 2>/dev/null || echo "unknown")
      if [ "$st" = "seed" ]; then
        local vn
        vn=$(echo "$status" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('vishnu_name',''))" 2>/dev/null || echo "")
        echo -e "  ${GREEN}🌟 FORTUNE 108 — SEED NODE ELECTED!${NC}"
        echo -e "  ${GREEN}   Your Sanskrit name: ${WHITE}$vn${NC}"
        echo -e "  ${GREEN}   Run 'karma-mine.py' to start mining as a seed node.${NC}"
      elif [ "$st" = "pending_lottery" ]; then
        echo -e "  ${YELLOW}🎲 Registered in Fortune 108 lottery — check back later.${NC}"
        echo -e "  ${YELLOW}   curl https://radhikachain.xyz/check-status?pubKey=${addr:0:16}...${NC}"
      else
        echo -e "  ${YELLOW}Register for Fortune 108 seed lottery:${NC}"
        echo -e "  ${YELLOW}   curl -X POST https://radhikachain.xyz/register-seed \\${NC}"
        echo -e "  ${YELLOW}     -H 'X-Dharma-Signature: <hmac>' \\${NC}"
        echo -e "  ${YELLOW}     -d '{\"pubKey\":\"${addr}\"}'${NC}"
      fi
    fi
  else
    info "[DRY-RUN] Would create wallet"
  fi

  # Summary
  echo ""
  echo -e "${GREEN}╔══════════════════════════════════════════════════════════════╗${NC}"
  echo -e "${GREEN}║           RADHIKACHAIN OS v8 INSTALL COMPLETE          ║${NC}"
  echo -e "${GREEN}╚══════════════════════════════════════════════════════════════╝${NC}"
  echo ""
  echo -e "  ${WHITE}RADHIKA_DIR${NC}:   $RADHIKA_DIR"
  echo -e "  ${WHITE}Mode${NC}:          $MODE"
  echo -e "  ${WHITE}Peers${NC}:         ${PEERS:-auto}"
  echo -e "  ${WHITE}OS${NC}:            $OS / $ARCH"
  echo ""
  echo -e "  ${YELLOW}Next steps:${NC}"
  echo -e "  • Check status:    ${CYAN}curl http://localhost:$DASHBOARD_PORT/health${NC}"
  echo -e "  • View logs:       ${CYAN}docker logs radhika-node${NC}"
  echo -e "  • Re-run:          ${CYAN}curl -fsSL https://radhikachain.xyz/install | bash${NC}"
  echo -e "  • Uninstall:       ${CYAN}rm -rf $RADHIKA_DIR${NC}"
  echo ""

  offer_dashboard "$MODE"
}

main "$@"
