#!/usr/bin/env bash
# deploy/lib/update.sh — 更新
set -e
set -u
if [ -n "${BASH_VERSION:-}" ]; then
  set -o pipefail
fi

LIB_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=common.sh
source "${LIB_DIR}/common.sh"

require_installed() {
  if ! repo_ready "${REPO_ROOT}"; then
    die "未找到安装,请先执行「1) 一键部署」"
  fi
}

update_quick() {
  step "快速更新"
  bash "${REPO_ROOT}/deploy/pull_and_restart.sh"
  verify_deployment "$(detect_server_ip)" || true
}

update_deps() {
  step "依赖更新"
  local dir
  for dir in crypto_monitor_binance crypto_monitor_gate crypto_monitor_okx; do
    local proj="${REPO_ROOT}/${dir}"
    if [[ -x "${proj}/.venv/bin/pip" ]]; then
      step "${dir}"
      pip_install_requirements "${proj}/.venv/bin/pip" "${REPO_ROOT}/requirements.txt" "交易所共用依赖"
    fi
  done
  local hub="${REPO_ROOT}/manual_trading_hub"
  if [[ -x "${hub}/.venv/bin/pip" && -f "${hub}/requirements.txt" ]]; then
    step "manual_trading_hub"
    pip_install_requirements "${hub}/.venv/bin/pip" "${hub}/requirements.txt" "中控依赖"
  fi
  update_quick
}

update_deep() {
  step "深度重装"
  if ! confirm_yes "深度重装将清库并保留 .env,确认继续?"; then
    log "已取消"
    return 0
  fi
  bash "${REPO_ROOT}/deploy/reinstall.sh" --yes
  verify_deployment "$(detect_server_ip)" || true
}

show_update_menu() {
  while true; do
    echo ""
    echo "  更新选项:"
    echo "  3-1) 快速更新(git pull + pm2 restart)"
    echo "  3-2) 依赖更新(含 pip install)"
    echo "  3-3) 深度重装(保留 .env,清库)"
    echo "  0)   返回主菜单"
    local choice=""
    cm_read choice "请选择 [0/3-1/3-2/3-3]: "
    case "${choice}" in
      3-1|31|1) update_quick; break ;;
      3-2|32|2) update_deps; break ;;
      3-3|33|3) update_deep; break ;;
      0) break ;;
      *) echo "无效选项" ;;
    esac
  done
}

main_update() {
  require_root
  if ! REPO_ROOT="$(resolve_repo_root)"; then
    die "未找到安装目录 ${INSTALL_ROOT},请先执行「1) 一键部署」"
  fi
  require_installed
  show_update_menu
}

main_update "$@"
