#!/usr/bin/env bash
#
# KRAY•SPACE — kray-pool-agent one-line installer
#
#   curl -fsSL https://www.kray.space/pool.sh | bash
#
# What this does (and nothing more):
#   1. Checks for git + Node.js 20+ (offers to install Node via nvm if missing)
#   2. Clones (or updates) https://github.com/tomkray/kray-pool-agent into ~/kray-pool-agent
#   3. Runs npm install + npm link so the `kray-pool-agent` command works anywhere
#   4. Tells you the next steps (setup → fund → start)
#
# It never asks for keys, passwords or funds. The daemon generates and
# encrypts your pool wallet locally during `kray-pool-agent setup`.

set -euo pipefail

REPO_URL="https://github.com/tomkray/kray-pool-agent"
INSTALL_DIR="$HOME/kray-pool-agent"
MIN_NODE_MAJOR=20

# ── pretty output ────────────────────────────────────────────────────────────
if [ -t 1 ]; then
    BOLD=$(printf '\033[1m'); DIM=$(printf '\033[2m'); GREEN=$(printf '\033[32m')
    YELLOW=$(printf '\033[33m'); RED=$(printf '\033[31m'); CYAN=$(printf '\033[36m')
    RESET=$(printf '\033[0m')
else
    BOLD=""; DIM=""; GREEN=""; YELLOW=""; RED=""; CYAN=""; RESET=""
fi

step()  { printf '\n%s▸ %s%s\n' "$BOLD" "$1" "$RESET"; }
ok()    { printf '%s  ✓ %s%s\n' "$GREEN" "$1" "$RESET"; }
warn()  { printf '%s  ! %s%s\n' "$YELLOW" "$1" "$RESET"; }
fail()  { printf '%s  ✗ %s%s\n' "$RED" "$1" "$RESET"; exit 1; }

printf '%s\n' "${BOLD}"
printf '  ╔═══════════════════════════════════════════════╗\n'
printf '  ║   KRAY•SPACE — Sovereign Pool Agent installer ║\n'
printf '  ║   Your keys. Your machine. Your pool.         ║\n'
printf '  ╚═══════════════════════════════════════════════╝\n'
printf '%s\n' "${RESET}"

# ── 0. OS sanity ─────────────────────────────────────────────────────────────
OS="$(uname -s)"
case "$OS" in
    Darwin|Linux) ;;
    *) fail "Unsupported OS: $OS. Use macOS, Linux, or Windows via WSL (https://learn.microsoft.com/windows/wsl/install)." ;;
esac

# ── 1. git ───────────────────────────────────────────────────────────────────
step "Checking requirements"
if command -v git >/dev/null 2>&1; then
    ok "git found"
else
    if [ "$OS" = "Darwin" ]; then
        fail "git is missing. Run: xcode-select --install   (then re-run this installer)"
    else
        fail "git is missing. Run: sudo apt install git   (Debian/Ubuntu) — then re-run this installer"
    fi
fi

# ── 2. Node.js 20+ ───────────────────────────────────────────────────────────
node_major() { node -v 2>/dev/null | sed 's/^v//' | cut -d. -f1; }

NEED_NODE=0
if ! command -v node >/dev/null 2>&1; then
    NEED_NODE=1
    warn "Node.js not found"
elif [ "$(node_major)" -lt "$MIN_NODE_MAJOR" ]; then
    NEED_NODE=1
    warn "Node.js $(node -v) is too old (need ${MIN_NODE_MAJOR}+)"
else
    ok "Node.js $(node -v)"
fi

if [ "$NEED_NODE" = "1" ]; then
    # Ask before touching the system — read from /dev/tty so it works with `curl | bash`.
    ANSWER="y"
    if [ -r /dev/tty ]; then
        printf '%s  Install Node.js %s via nvm (official installer, no sudo)? [Y/n] %s' "$CYAN" "$MIN_NODE_MAJOR" "$RESET"
        read -r ANSWER < /dev/tty || ANSWER="y"
    fi
    case "$ANSWER" in
        n|N|no|NO) fail "Node.js ${MIN_NODE_MAJOR}+ is required. Install it from https://nodejs.org and re-run." ;;
    esac
    step "Installing Node.js via nvm"
    export NVM_DIR="$HOME/.nvm"
    if [ ! -s "$NVM_DIR/nvm.sh" ]; then
        curl -fsSL https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash >/dev/null 2>&1
    fi
    # shellcheck disable=SC1091
    . "$NVM_DIR/nvm.sh"
    nvm install "$MIN_NODE_MAJOR" >/dev/null 2>&1
    nvm use "$MIN_NODE_MAJOR" >/dev/null 2>&1
    ok "Node.js $(node -v) installed"
fi

# ── 3. clone or update the agent ─────────────────────────────────────────────
if [ -d "$INSTALL_DIR/.git" ]; then
    step "Updating existing install at $INSTALL_DIR"
    git -C "$INSTALL_DIR" pull --ff-only || warn "Could not fast-forward — keeping your current version"
    ok "Repository up to date"
else
    step "Downloading kray-pool-agent to $INSTALL_DIR"
    git clone --depth 1 "$REPO_URL" "$INSTALL_DIR"
    ok "Repository cloned"
fi

# ── 4. install dependencies + link the CLI ───────────────────────────────────
step "Installing dependencies (this can take a minute)"
cd "$INSTALL_DIR"
npm install --no-fund --no-audit --loglevel=error
ok "Dependencies installed"

step "Linking the kray-pool-agent command"
if npm link --loglevel=error >/dev/null 2>&1; then
    ok "Command linked"
elif sudo -n true 2>/dev/null && sudo npm link --loglevel=error >/dev/null 2>&1; then
    ok "Command linked (with sudo)"
else
    warn "npm link needs permissions. You can still run the agent with:"
    printf '%s      node %s/bin/kray-pool-agent.js <command>%s\n' "$DIM" "$INSTALL_DIR" "$RESET"
fi

# ── 5. done — next steps ─────────────────────────────────────────────────────
printf '\n%s%s  Installed successfully.%s\n' "$GREEN" "$BOLD" "$RESET"
printf '\n%sNext steps:%s\n\n' "$BOLD" "$RESET"
printf '  %s1.%s Create your pool wallet (interactive, ~2 min):\n' "$CYAN" "$RESET"
printf '       %skray-pool-agent setup%s\n' "$BOLD" "$RESET"
printf '       %s→ choose a password, name your pool, WRITE DOWN the 12 words%s\n\n' "$DIM" "$RESET"
printf '  %s2.%s Send BTC + your Rune to the bc1p... pool address it prints\n' "$CYAN" "$RESET"
printf '       %s→ the BTC:Rune ratio you send sets the starting price%s\n\n' "$DIM" "$RESET"
printf '  %s3.%s Go live:\n' "$CYAN" "$RESET"
printf '       %skray-pool-agent start%s\n' "$BOLD" "$RESET"
printf '       %s→ your pool appears at https://www.kray.space/swap%s\n\n' "$DIM" "$RESET"
printf '  Manage everything at %shttps://www.kray.space/my-pool%s\n\n' "$CYAN" "$RESET"
