#!/usr/bin/env bash
# Sets up the Humand frontend sandbox environment on macOS.
# Usage: bash setup-env.sh
# Output: writes ~/.humand/sandbox-installed.json and prints a JSON summary to stdout.
#
# Brew path:  brew → nvm → node, then brew for git + gh
# Mise path:  mise → node (no nvm), curl for bun, git/gh warn user

set -uo pipefail

NODE_VERSION="24.11.1"
HUMAND_DIR="$HOME/.humand"
REGISTRY_FILE="$HUMAND_DIR/sandbox-installed.json"
MISE_BIN="$HOME/.local/bin/mise"
USING_MISE=false

# ── helpers ────────────────────────────────────────────────────────────────────

log()  { echo "▶ $*" >&2; }
ok()   { echo "✓ $*" >&2; }
fail() { echo "✗ $*" >&2; }
warn() { echo "⚠ $*" >&2; }

REGISTRY_TOOLS="{}"

registry_set() {
  local tool="$1" preexisting="$2"
  REGISTRY_TOOLS=$(echo "$REGISTRY_TOOLS" | \
    python3 -c "import sys,json; d=json.load(sys.stdin); d['$tool']={'preexisting':$preexisting}; print(json.dumps(d))")
  python3 -c "
import json, sys
data = {
  'installedAt': '$(date -u +"%Y-%m-%dT%H:%M:%SZ")',
  'nodeVersion': '$NODE_VERSION',
  'tools': $REGISTRY_TOOLS
}
print(json.dumps(data, indent=2))
" > "$REGISTRY_FILE"
}

# ── pre-flight ─────────────────────────────────────────────────────────────────

mkdir -p "$HUMAND_DIR"

if [[ -f "$REGISTRY_FILE" ]]; then
  REGISTRY_TOOLS=$(python3 -c "
import json
with open('$REGISTRY_FILE') as f:
  d = json.load(f)
print(json.dumps(d.get('tools', {})))
")
fi

# ── mise helpers ───────────────────────────────────────────────────────────────

install_mise() {
  if [[ -x "$MISE_BIN" ]] || command -v mise &>/dev/null; then
    ok "mise already installed"
    return 0
  fi
  log "Installing mise (user-space, no admin required)..."
  curl -fsSL https://mise.run | sh
  export PATH="$HOME/.local/bin:$PATH"
  ok "mise installed at $MISE_BIN"
}

activate_mise_in_shellrc() {
  local shell_name
  shell_name=$(basename "${SHELL:-bash}")
  local rc_file=""
  case "$shell_name" in
    zsh)  rc_file="$HOME/.zshrc" ;;
    bash) rc_file="$HOME/.bash_profile" ;;
  esac
  [[ -z "$rc_file" ]] && return
  if ! grep -q "mise activate" "$rc_file" 2>/dev/null; then
    {
      echo ''
      echo '# mise (added by humand setup-sandbox)'
      echo "eval \"\$(~/.local/bin/mise activate $shell_name)\""
    } >> "$rc_file"
    ok "mise activation added to $rc_file"
  fi
}

# ── Homebrew ───────────────────────────────────────────────────────────────────

log "Checking Homebrew..."
if command -v brew &>/dev/null; then
  ok "Homebrew already installed"
  registry_set homebrew true
else
  log "Installing Homebrew..."
  BREW_OUTPUT=$(NONINTERACTIVE=1 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" 2>&1) && BREW_OK=true || BREW_OK=false

  if $BREW_OK; then
    eval "$(/opt/homebrew/bin/brew shellenv)" 2>/dev/null || eval "$(/usr/local/bin/brew shellenv)" 2>/dev/null || true
  fi

  if command -v brew &>/dev/null; then
    ok "Homebrew installed"
    registry_set homebrew false
  else
    # Brew failed — check if it's a permissions issue
    if echo "$BREW_OUTPUT" | grep -qiE "permission denied|not permitted|sudo|admin|root"; then
      warn "Homebrew requires admin permissions. Switching to mise (no admin required)."
    else
      warn "Homebrew installation failed. Switching to mise as fallback."
      echo "$BREW_OUTPUT" >&2
    fi
    USING_MISE=true
    registry_set homebrew_skipped true
  fi
fi

# ── nvm + Node (brew path) — OR — mise + Node (mise path) ─────────────────────

if ! $USING_MISE; then
  # ── nvm ──────────────────────────────────────────────────────────────────────
  log "Checking nvm..."
  NVM_LOADED=false
  if command -v nvm &>/dev/null || [[ -s "$HOME/.nvm/nvm.sh" ]]; then
    ok "nvm already installed"
    registry_set nvm true
  else
    log "Installing nvm via Homebrew..."
    brew install nvm
    registry_set nvm false
  fi

  export NVM_DIR="${NVM_DIR:-$HOME/.nvm}"
  NVM_SH="$(brew --prefix)/opt/nvm/nvm.sh"
  if [[ -s "$NVM_SH" ]]; then
    # shellcheck source=/dev/null
    source "$NVM_SH"
    NVM_LOADED=true
  fi

  if ! $NVM_LOADED && ! command -v nvm &>/dev/null; then
    fail "nvm could not be loaded after installation. Re-open the terminal and re-run this script."
    exit 1
  fi

  # Ensure nvm init is in the shell profile (idempotent)
  PROFILE_FILE=""
  if [[ -f "$HOME/.zshrc" ]]; then PROFILE_FILE="$HOME/.zshrc"
  elif [[ -f "$HOME/.bash_profile" ]]; then PROFILE_FILE="$HOME/.bash_profile"
  fi

  NVM_INIT_LINE='[ -s "$(brew --prefix)/opt/nvm/nvm.sh" ] && \. "$(brew --prefix)/opt/nvm/nvm.sh"'
  if [[ -n "$PROFILE_FILE" ]] && ! grep -q "opt/nvm/nvm.sh" "$PROFILE_FILE"; then
    {
      echo ''
      echo '# nvm (added by humand setup-sandbox)'
      echo "export NVM_DIR=\"\$HOME/.nvm\""
      echo "$NVM_INIT_LINE"
    } >> "$PROFILE_FILE"
    ok "nvm init added to $PROFILE_FILE"
  fi

  # ── Node (via nvm) ────────────────────────────────────────────────────────────
  log "Checking Node $NODE_VERSION..."
  CURRENT_NODE=$(node --version 2>/dev/null || echo "none")
  if [[ "$CURRENT_NODE" == "v$NODE_VERSION" ]]; then
    ok "Node $NODE_VERSION already active"
    registry_set node true
  else
    log "Installing Node $NODE_VERSION via nvm..."
    nvm install "$NODE_VERSION"
    nvm use "$NODE_VERSION"
    nvm alias default "$NODE_VERSION"
    ok "Node $NODE_VERSION installed and set as default"
    registry_set node false
  fi

else
  # ── Node via mise (no brew, no nvm) ──────────────────────────────────────────
  log "Using mise to install Node $NODE_VERSION (no admin required)..."
  install_mise
  activate_mise_in_shellrc

  CURRENT_NODE=$(node --version 2>/dev/null || echo "none")
  if [[ "$CURRENT_NODE" == "v$NODE_VERSION" ]]; then
    ok "Node $NODE_VERSION already active"
    registry_set node true
  else
    "$MISE_BIN" use -g "node@$NODE_VERSION"
    export PATH="$HOME/.local/share/mise/shims:$PATH"
    ok "Node $NODE_VERSION installed via mise"
    registry_set node false
  fi

  registry_set nvm_skipped true
fi

# ── bun ────────────────────────────────────────────────────────────────────────

log "Checking bun..."
if command -v bun &>/dev/null; then
  ok "bun already installed"
  registry_set bun true
else
  log "Installing bun..."
  curl -fsSL https://bun.sh/install | bash
  export PATH="$HOME/.bun/bin:$PATH"
  ok "bun installed"
  registry_set bun false
fi

# ── git ────────────────────────────────────────────────────────────────────────

log "Checking git..."
if command -v git &>/dev/null; then
  ok "git already installed"
  registry_set git true
elif ! $USING_MISE; then
  log "Installing git via Homebrew..."
  brew install git
  ok "git installed"
  registry_set git false
else
  warn "git not found. Installation requires admin (brew). Ask IT to run: brew install git"
  registry_set git_missing true
fi

# ── GitHub CLI ─────────────────────────────────────────────────────────────────

log "Checking gh (GitHub CLI)..."
if command -v gh &>/dev/null; then
  ok "gh already installed"
  registry_set gh true
elif ! $USING_MISE; then
  log "Installing gh via Homebrew..."
  brew install gh
  ok "gh installed"
  registry_set gh false
else
  warn "gh (GitHub CLI) not found. Installation requires admin (brew). Ask IT to run: brew install gh"
  registry_set gh_missing true
fi

# ── done ───────────────────────────────────────────────────────────────────────

if $USING_MISE; then
  warn "Homebrew no estaba disponible. Se usó mise para instalar Node. git y gh pueden requerir permisos de admin — contactá a IT si los necesitás."
fi

ok "All done. Registry saved to $REGISTRY_FILE"
cat "$REGISTRY_FILE"
