#!/usr/bin/env bash
set -euo pipefail

# One-line launcher:
# curl -fsSL https://www.lingyuncx.com/openclaw/install-openclaw-macos.sh | bash

OFFICIAL_INSTALL_URL="https://openclaw.ai/install.sh"
GUIDE_URL="https://www.lingyuncx.com/openclaw/"
OPENCLAW_STATE_DIR="${OPENCLAW_STATE_DIR:-$HOME/.openclaw}"
OPENCLAW_CONFIG="${OPENCLAW_CONFIG:-$OPENCLAW_STATE_DIR/openclaw.json}"
FORCE_ONBOARD="${FORCE_ONBOARD:-0}"

log() {
  printf '[INFO] %s\n' "$*"
}

warn() {
  printf '[WARN] %s\n' "$*" >&2
}

die() {
  printf '[ERROR] %s\n' "$*" >&2
  exit 1
}

command_exists() {
  command -v "$1" >/dev/null 2>&1
}

ensure_macos() {
  [[ "$(uname -s)" == "Darwin" ]] || die "This installer only supports macOS."
}

download_to_file() {
  local url="$1"
  local output="$2"

  if command_exists curl; then
    curl -fsSL --proto '=https' --tlsv1.2 "$url" -o "$output"
    return
  fi

  if command_exists wget; then
    wget -qO "$output" "$url"
    return
  fi

  die "curl or wget is required."
}

refresh_path() {
  local candidates=(
    "$HOME/.local/bin"
    "/opt/homebrew/bin"
    "/usr/local/bin"
  )
  local npm_prefix

  if command_exists npm; then
    npm_prefix="$(npm config get prefix 2>/dev/null || true)"
    if [[ -n "$npm_prefix" ]]; then
      candidates+=("${npm_prefix%/}/bin")
    fi
  fi

  for candidate in "${candidates[@]}"; do
    if [[ -d "$candidate" && ":$PATH:" != *":$candidate:"* ]]; then
      export PATH="$candidate:$PATH"
    fi
  done

  hash -r 2>/dev/null || true
}

find_openclaw() {
  local candidates=()
  local npm_prefix

  if command_exists openclaw; then
    command -v openclaw
    return 0
  fi

  if command_exists npm; then
    npm_prefix="$(npm config get prefix 2>/dev/null || true)"
    if [[ -n "$npm_prefix" ]]; then
      candidates+=("${npm_prefix%/}/bin/openclaw")
    fi
  fi

  candidates+=(
    "$HOME/.local/bin/openclaw"
    "/opt/homebrew/bin/openclaw"
    "/usr/local/bin/openclaw"
  )

  local candidate
  for candidate in "${candidates[@]}"; do
    if [[ -x "$candidate" ]]; then
      printf '%s\n' "$candidate"
      return 0
    fi
  done

  return 1
}

needs_onboard() {
  [[ "$FORCE_ONBOARD" == "1" || ! -s "$OPENCLAW_CONFIG" ]]
}

run_official_installer() {
  local tmp
  tmp="$(mktemp)"
  trap 'rm -f "$tmp"' EXIT

  log "Downloading official OpenClaw installer."
  download_to_file "$OFFICIAL_INSTALL_URL" "$tmp"

  log "Running official installer without onboarding; guide: $GUIDE_URL"
  /bin/bash "$tmp" --no-onboard
}

run_onboard() {
  local claw="$1"

  if ! needs_onboard; then
    log "Existing OpenClaw config found at $OPENCLAW_CONFIG; skipping onboarding."
    return
  fi

  [[ -t 0 ]] || die "Onboarding is interactive. Run this script in Terminal, not in a detached shell."

  log "Starting onboarding wizard."
  "$claw" onboard --install-daemon

  if [[ ! -s "$OPENCLAW_CONFIG" ]]; then
    die "Onboarding did not finish successfully. Missing config: $OPENCLAW_CONFIG"
  fi
}

verify_installation() {
  local claw="$1"

  log "OpenClaw path: $claw"
  "$claw" --version

  if ! "$claw" gateway status; then
    warn "Gateway status is not healthy yet. Trying repair."
    "$claw" doctor --repair || true
    "$claw" gateway status || die "Gateway verification failed."
  fi

  "$claw" status --deep || true
  "$claw" health --json || true

  if "$claw" dashboard; then
    return
  fi

  if command_exists open; then
    open "http://127.0.0.1:18789/" >/dev/null 2>&1 || true
  fi
}

main() {
  ensure_macos
  refresh_path
  run_official_installer
  refresh_path

  local claw
  claw="$(find_openclaw || true)"
  [[ -n "$claw" ]] || die "OpenClaw was installed, but the binary is still not on PATH. Open a new Terminal and re-run this script."

  run_onboard "$claw"
  verify_installation "$claw"

  cat <<EOF

OpenClaw 安装完成。

下一步：
  1. 浏览器打开控制台：http://127.0.0.1:18789/
  2. 教程页：$GUIDE_URL
  3. 健康检查：openclaw gateway status
EOF
}

main "$@"
