#!/bin/bash
set -euo pipefail

# MyAgent Installer for macOS and Linux
# 一键安装脚本
#
# 用法:
#   curl -fsSL https://raw.githubusercontent.com/ctz168/myagent/main/install/install.sh | bash
#   curl -fsSL ... | bash -s -- --no-deps     # 跳过系统依赖检查（仅 npm install）

BOLD='\033[1m'
ACCENT='\033[36m'
INFO='\033[90m'
SUCCESS='\033[32m'
WARN='\033[33m'
ERROR='\033[31m'
NC='\033[0m'

NO_DEPS=false
PKG_NAME="myagent-ai"
PKG_VERSION=""

fetch_version() {
  PKG_VERSION=""
  local npm_ver
  npm_ver="$(npm view "$PKG_NAME" version 2>/dev/null)" || true
  if [ -n "$npm_ver" ]; then PKG_VERSION="$npm_ver"; fi
}

for arg in "$@"; do
  case "$arg" in
    --no-deps) NO_DEPS=true ;;
    --help|-h)
      fetch_version
      echo "MyAgent Installer${PKG_VERSION:+ v$PKG_VERSION}"
      echo ""
      echo "Usage: curl -fsSL <script-url> | bash [-s -- OPTIONS]"
      echo ""
      echo "Options:"
      echo "  --no-deps    跳过 Python/Node.js 依赖检查"
      echo ""
      echo "安装完成后运行 myagent-ai 启动"
      exit 0
      ;;
    *) echo "Unknown option: $arg (use --help)"; exit 2 ;;
  esac
done

info()    { echo -e "${INFO}[i]${NC} $*"; }
success() { echo -e "${SUCCESS}[✓]${NC} $*"; }
warn()    { echo -e "${WARN}[!]${NC} $*"; }
err()     { echo -e "${ERROR}[✗]${NC} $*" >&2; }
step()    { echo -e "${ACCENT}[*]${NC} $*"; }

# ── detect OS ─────────────────────────────────────────────
detect_os() {
  local os
  os="$(uname -s)"
  case "$os" in
    Linux*)   echo "linux" ;;
    Darwin*)  echo "macos" ;;
    *)       echo "unknown" ;;
  esac
}

fetch_version
OS="$(detect_os)"
echo ""
echo -e "  ${BOLD}${ACCENT}MyAgent${NC} Installer${PKG_VERSION:+ v$PKG_VERSION}"
echo ""
success "$OS detected"

# ── Python ────────────────────────────────────────────────
check_python() {
  hash -r 2>/dev/null || true
  local py_cmd=""
  for cmd in python3 python3.14 python3.13 python; do
    if command -v "$cmd" &>/dev/null; then py_cmd="$cmd"; break; fi
  done
  if [ -z "$py_cmd" ]; then return 1; fi
  local ver
  ver="$($py_cmd -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")' 2>/dev/null)" || return 1
  local major minor
  major="$(echo "$ver" | cut -d. -f1)"
  minor="$(echo "$ver" | cut -d. -f2)"
  if [ "$major" -ge 3 ] && [ "$minor" -ge 13 ]; then
    success "Python $ver ($py_cmd)"
    return 0
  fi
  return 1
}

install_python() {
  step "Installing Python 3.13+ ..."
  if [ "$OS" = "macos" ]; then
    if command -v brew &>/dev/null; then
      for py_ver in 3.13 3.14; do
        if brew install "python@${py_ver}" 2>/dev/null; then
          export PATH="$(brew --prefix "python@${py_ver}")/bin:$PATH"
          hash -r
          check_python && return 0
        fi
      done
    fi
    curl -fsSL -o /tmp/python.pkg "https://www.python.org/ftp/python/3.13.3/python-3.13.3-macos11.pkg" 2>/dev/null || \
    curl -fsSL -o /tmp/python.pkg "https://www.python.org/ftp/python/3.14.0/python-3.14.0-macos11.pkg"
    sudo installer -pkg /tmp/python.pkg -target /
    rm -f /tmp/python.pkg
    export PATH="/Library/Frameworks/Python.framework/Versions/3.13/bin:$PATH"
    hash -r
    check_python && return 0
    return 1
  fi
  if [ "$OS" = "linux" ]; then
    if command -v apt-get &>/dev/null; then
      sudo apt-get update -qq
      sudo apt-get install -y python3.13 python3.13-venv python3-pip 2>/dev/null || \
      sudo apt-get install -y python3.14 python3.14-venv python3-pip 2>/dev/null || \
      sudo apt-get install -y python3 python3-venv python3-pip
      hash -r
      check_python && return 0
    fi
    if command -v dnf &>/dev/null; then
      sudo dnf install -y python3.13 2>/dev/null || sudo dnf install -y python3
      hash -r; check_python && return 0
    fi
    if command -v pacman &>/dev/null; then
      sudo pacman -S --noconfirm python python-pip
      hash -r; check_python && return 0
    fi
    if command -v apk &>/dev/null; then
      sudo apk add python3 py3-pip
      hash -r; check_python && return 0
    fi
  fi
  err "Failed to install Python. Please install Python 3.13+ manually."
  exit 1
}

# ── Node.js ───────────────────────────────────────────────
check_node() {
  hash -r 2>/dev/null || true
  if ! command -v node &>/dev/null; then return 1; fi
  local major
  major="$(node -v | sed 's/v\([0-9]\+\).*/\1/')"
  if [ "$major" -ge 18 ] 2>/dev/null; then
    success "Node.js $(node -v)"
    return 0
  fi
  return 1
}

install_node() {
  step "Installing Node.js 20 LTS ..."
  if [ "$OS" = "macos" ] && command -v brew &>/dev/null; then
    brew install node@20 || brew install node
    hash -r; check_node && return 0
  fi
  if command -v fnm &>/dev/null; then
    fnm install 20; eval "$(fnm env)"; hash -r; check_node && return 0
  fi
  if [ -s "$HOME/.nvm/nvm.sh" ]; then
    . "$HOME/.nvm/nvm.sh"; nvm install 20; hash -r; check_node && return 0
  fi
  if [ "$OS" = "linux" ] && command -v apt-get &>/dev/null; then
    curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
    sudo apt-get install -y nodejs
    hash -r; check_node && return 0
  fi
  err "Failed to install Node.js. Please install Node.js 18+ manually."
  exit 1
}

# ── Linux 系统依赖 ──────────────────────────────────────────
install_linux_system_deps() {
  if [ "$OS" != "linux" ] || ! command -v apt-get &>/dev/null; then return; fi
  step "Installing system dependencies (poppler-utils, Chrome libs) ..."
  sudo apt-get update -qq 2>/dev/null || true
  # poppler-utils: PDF 文本提取 (pdftotext)
  # Chrome/Chromium 共享库: 浏览器自动化必需
  sudo apt-get install -y --no-install-recommends \
    poppler-utils \
    libnss3 libatk1.0-0 libatk-bridge2.0-0 libcups2 libdrm2 \
    libxkbcommon0 libxcomposite1 libxdamage1 libxfixes3 libxrandr2 \
    libgbm1 libpango-1.0-0 libcairo2 libasound2 libatspi2.0-0 \
    2>/dev/null || true
  # 尝试安装 Chromium (如果尚未安装)
  if ! command -v google-chrome &>/dev/null && ! command -v chromium &>/dev/null && ! command -v chromium-browser &>/dev/null; then
    sudo apt-get install -y --no-install-recommends chromium-browser 2>/dev/null || \
    sudo apt-get install -y --no-install-recommends chromium 2>/dev/null || true
  fi
  success "系统依赖安装完成"
}

# ── 找到 myagent-ai 命令路径 ──────────────────────────────
find_myagent_cmd() {
  if command -v myagent-ai &>/dev/null; then
    echo "myagent-ai"
    return 0
  fi
  # npm bin -g 在新版 npm 中已废弃，使用 npm prefix -g
  local npm_prefix
  npm_prefix="$(npm prefix -g 2>/dev/null)" || return 1
  local cmd_path="${npm_prefix}/bin/myagent-ai"
  if [ -x "$cmd_path" ]; then
    echo "$cmd_path"
    return 0
  fi
  return 1
}

# ── Main ─────────────────────────────────────────────────
if ! $NO_DEPS; then
  check_python || install_python
  check_node   || install_node
  install_linux_system_deps
fi

step "Installing $PKG_NAME via npm ..."
npm install -g "$PKG_NAME"
if [ $? -ne 0 ]; then
  err "npm install failed"
  info "可能需要 sudo: sudo npm install -g $PKG_NAME"
  exit 1
fi
success "$PKG_NAME installed"

# 用 start.js 的 install 命令创建 venv 并安装全部 Python 依赖
step "Installing Python dependencies ..."
myagent_cmd="$(find_myagent_cmd)"
if [ -n "$myagent_cmd" ]; then
  "$myagent_cmd" install
else
  err "myagent-ai 命令未找到，请重新打开终端后运行: myagent-ai install"
  exit 1
fi

echo ""
echo -e "  ${BOLD}${SUCCESS}安装完成！${NC}"
echo ""
echo -e "  常用命令:"
echo -e "    ${ACCENT}myagent-ai web${NC}       启动 Web 界面 (默认)"
echo -e "    ${ACCENT}myagent-ai cli${NC}       命令行模式"
echo -e "    ${ACCENT}myagent-ai tray${NC}      系统托盘模式"
echo -e "    ${ACCENT}myagent-ai server${NC}    后台服务模式"
echo -e "    ${ACCENT}myagent-ai update${NC}    更新到最新版"
echo -e "    ${ACCENT}myagent-ai reinstall${NC} 重装依赖"
echo -e "    ${ACCENT}myagent-ai uninstall${NC} 卸载"
echo ""

# 启动 Web 模式
myagent_cmd="$(find_myagent_cmd)"
if [ -n "$myagent_cmd" ]; then
  info "启动中: $myagent_cmd web"
  "$myagent_cmd" web
else
  echo -e "  请重新打开终端后运行: ${ACCENT}myagent-ai web${NC}"
fi
