#!/usr/bin/env bash
# ============================================================
#  DSEL Orbital SDK — Installer Script
#  https://get.dsel.ae/dseld
#  Usage: curl -sSL https://get.dsel.ae/dseld | bash
# ============================================================

set -euo pipefail

DSEL_BASE_URL="https://get.dsel.ae/bin"
DSEL_INSTALL_DIR="/usr/local/bin"
DSEL_BINARY="dseld"
DSEL_DOCS="https://sdk.dsel.ae"

# ──────────────────────────────────────────────
# Colors
# ──────────────────────────────────────────────
RESET='\033[0m'
BOLD='\033[1m'
DIM='\033[2m'
CYAN='\033[0;36m'
BLUE='\033[0;34m'
BRIGHT_CYAN='\033[0;96m'
GOLD='\033[0;33m'
BRIGHT_GOLD='\033[1;33m'
GREEN='\033[0;32m'
RED='\033[0;31m'
WHITE='\033[1;37m'
GRAY='\033[0;37m'

# ──────────────────────────────────────────────
# Banner
# ──────────────────────────────────────────────
print_banner() {
  echo ""
  echo -e "${BRIGHT_CYAN}${BOLD}"
  echo "  ██████╗ ███████╗███████╗██╗"
  echo "  ██╔══██╗██╔════╝██╔════╝██║"
  echo "  ██║  ██║███████╗█████╗  ██║"
  echo "  ██║  ██║╚════██║██╔══╝  ██║"
  echo "  ██████╔╝███████║███████╗███████╗"
  echo "  ╚═════╝ ╚══════╝╚══════╝╚══════╝"
  echo -e "${RESET}"
  echo -e "  ${GOLD}${BOLD}Orbital SDK Installer${RESET}   ${DIM}v1.0 · https://dsel.ae${RESET}"
  echo -e "  ${DIM}─────────────────────────────────────────────${RESET}"
  echo ""
}

# ──────────────────────────────────────────────
# Logging helpers
# ──────────────────────────────────────────────
info()    { echo -e "  ${CYAN}→${RESET}  $*"; }
success() { echo -e "  ${GREEN}✓${RESET}  $*"; }
warn()    { echo -e "  ${BRIGHT_GOLD}⚠${RESET}  $*"; }
error()   { echo -e "  ${RED}✗${RESET}  $*" >&2; }
step()    { echo -e "\n  ${BRIGHT_CYAN}${BOLD}[$1]${RESET} $2"; }

# ──────────────────────────────────────────────
# OS / Arch detection
# ──────────────────────────────────────────────
detect_platform() {
  OS="$(uname -s)"
  ARCH="$(uname -m)"

  case "$OS" in
    Linux)  OS_TAG="linux" ;;
    Darwin) OS_TAG="darwin" ;;
    *)
      error "Unsupported operating system: $OS"
      echo ""
      echo -e "  ${GRAY}DSEL Orbital SDK currently supports Linux and macOS.${RESET}"
      echo -e "  ${GRAY}Visit ${BRIGHT_CYAN}${DSEL_DOCS}${GRAY} for manual installation and other platforms.${RESET}"
      echo ""
      exit 1
      ;;
  esac

  case "$ARCH" in
    x86_64)          ARCH_TAG="amd64" ;;
    amd64)           ARCH_TAG="amd64" ;;
    aarch64 | arm64) ARCH_TAG="arm64" ;;
    *)
      error "Unsupported architecture: $ARCH"
      echo -e "  ${GRAY}Visit ${BRIGHT_CYAN}${DSEL_DOCS}${GRAY} for manual installation options.${RESET}"
      echo ""
      exit 1
      ;;
  esac

  PLATFORM="${OS_TAG}-${ARCH_TAG}"
  BINARY_URL="${DSEL_BASE_URL}/dseld-${PLATFORM}"
}

# ──────────────────────────────────────────────
# Dependency checks
# ──────────────────────────────────────────────
check_deps() {
  step "1/4" "Checking system requirements"

  local missing=()

  for cmd in curl chmod; do
    if ! command -v "$cmd" &>/dev/null; then
      missing+=("$cmd")
    fi
  done

  if [[ ${#missing[@]} -gt 0 ]]; then
    error "Missing required tools: ${missing[*]}"
    echo -e "  ${GRAY}Please install the missing tools and re-run the installer.${RESET}"
    exit 1
  fi

  success "System check passed (${OS_TAG}/${ARCH_TAG})"
}

# ──────────────────────────────────────────────
# Permission helper
# ──────────────────────────────────────────────
check_write_permission() {
  if [[ ! -w "$DSEL_INSTALL_DIR" ]]; then
    warn "Install directory ${DSEL_INSTALL_DIR} is not writable by current user."
    echo -e "  ${GRAY}Re-running with sudo...${RESET}"
    echo ""
    exec sudo bash "$0" "$@"
  fi
}

# ──────────────────────────────────────────────
# Download binary
# ──────────────────────────────────────────────
download_binary() {
  step "2/4" "Downloading dseld binary"
  info "Platform : ${BOLD}${PLATFORM}${RESET}"
  info "Source   : ${BRIGHT_CYAN}${BINARY_URL}${RESET}"
  info "Target   : ${BOLD}${DSEL_INSTALL_DIR}/dseld${RESET}"
  echo ""

  TMP_FILE="$(mktemp /tmp/dseld.XXXXXX)"

  if ! curl -sSL --progress-bar --fail \
      --connect-timeout 15 \
      --retry 3 \
      -o "$TMP_FILE" \
      "$BINARY_URL"; then
    rm -f "$TMP_FILE"
    error "Download failed. Please check your internet connection."
    echo -e "  ${GRAY}Binary URL: ${BINARY_URL}${RESET}"
    echo -e "  ${GRAY}Manual downloads available at: ${BRIGHT_CYAN}${DSEL_DOCS}${RESET}"
    echo ""
    exit 1
  fi

  success "Download complete"
}

# ──────────────────────────────────────────────
# Install binary
# ──────────────────────────────────────────────
install_binary() {
  step "3/4" "Installing dseld"

  chmod +x "$TMP_FILE"

  if mv "$TMP_FILE" "${DSEL_INSTALL_DIR}/${DSEL_BINARY}"; then
    success "Installed to ${BOLD}${DSEL_INSTALL_DIR}/${DSEL_BINARY}${RESET}"
  else
    rm -f "$TMP_FILE"
    error "Failed to move binary to ${DSEL_INSTALL_DIR}/${DSEL_BINARY}"
    echo -e "  ${GRAY}Try running with sudo or install manually.${RESET}"
    exit 1
  fi
}

# ──────────────────────────────────────────────
# Verify installation
# ──────────────────────────────────────────────
verify_install() {
  step "4/4" "Verifying installation"

  if command -v dseld &>/dev/null; then
    local version
    version="$(dseld version 2>/dev/null || echo 'unknown')"
    success "dseld is ready  ${DIM}(${version})${RESET}"
  else
    warn "dseld was installed but is not yet in PATH."
    echo ""
    echo -e "  ${GRAY}Add the following to your shell profile (.bashrc / .zshrc):${RESET}"
    echo -e "  ${BRIGHT_CYAN}  export PATH=\"\$PATH:/usr/local/bin\"${RESET}"
    echo ""
  fi
}

# ──────────────────────────────────────────────
# Print next steps
# ──────────────────────────────────────────────
print_next_steps() {
  echo ""
  echo -e "  ${BRIGHT_GOLD}${BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${RESET}"
  echo -e "  ${WHITE}${BOLD}  🚀  Orbital SDK installed successfully!${RESET}"
  echo -e "  ${BRIGHT_GOLD}${BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${RESET}"
  echo ""
  echo -e "  ${BOLD}Quick Start${RESET}"
  echo ""
  echo -e "  ${DIM}# Check version${RESET}"
  echo -e "  ${BRIGHT_CYAN}  dseld version${RESET}"
  echo ""
  echo -e "  ${DIM}# Create a new key${RESET}"
  echo -e "  ${BRIGHT_CYAN}  dseld keys add mykey${RESET}"
  echo ""
  echo -e "  ${DIM}# Query balances (testnet)${RESET}"
  echo -e "  ${BRIGHT_CYAN}  dseld query bank balances <dsel1...address>${RESET}"
  echo ""
  echo -e "  ${DIM}# Send tokens${RESET}"
  echo -e "  ${BRIGHT_CYAN}  dseld tx bank send mykey <recipient> 1000000utdsel --chain-id dsel-testnet-1${RESET}"
  echo ""
  echo -e "  ${BOLD}Resources${RESET}"
  echo ""
  echo -e "  ${GRAY}  Documentation  ${RESET}${BRIGHT_CYAN}https://sdk.dsel.ae${RESET}"
  echo -e "  ${GRAY}  RPC Endpoint   ${RESET}${BRIGHT_CYAN}https://rpc.dsel.ae${RESET}"
  echo -e "  ${GRAY}  Testnet Chain  ${RESET}${BRIGHT_CYAN}dsel-testnet-1${RESET}"
  echo ""
  echo -e "  ${DIM}© 2026 DSEL Ltd (ADGM) · https://dsel.ae${RESET}"
  echo ""
}

# ──────────────────────────────────────────────
# Cleanup on exit
# ──────────────────────────────────────────────
cleanup() {
  rm -f "${TMP_FILE:-}" 2>/dev/null || true
}
trap cleanup EXIT

# ──────────────────────────────────────────────
# Main
# ──────────────────────────────────────────────
main() {
  print_banner
  detect_platform
  check_deps
  check_write_permission "$@"
  download_binary
  install_binary
  verify_install
  print_next_steps
}

main "$@"
