#!/usr/bin/env sh

set -eu

log() {
  printf '[installapp] %s\n' "$1"
}

fail() {
  printf '[installapp] %s\n' "$1" >&2
  exit 1
}

usage() {
  cat <<EOF
Usage: installapp-macos.sh [codexcli|claude-code|opencode|kimi|reasonix]

不传参数时会打开交互菜单。
EOF
}

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

run_install() {
  log "正在执行：$*"
  "$@"
}

require_macos() {
  os_name=$(uname -s 2>/dev/null || printf unknown)
  [ "$os_name" = "Darwin" ] || fail "此脚本仅支持 macOS。当前检测到：$os_name"
}

ensure_brew() {
  if has_command brew; then
    version=$(brew --version 2>/dev/null | sed -n '1p' || true)
    log "brew 已安装${version:+：$version}"
    return 0
  fi

  log 'brew 未安装，准备安装 Homebrew。'
  has_command curl || fail '安装 Homebrew 需要 curl。'
  log '正在运行 Homebrew 官方安装脚本。'
  /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

  if [ -x /opt/homebrew/bin/brew ]; then
    eval "$(/opt/homebrew/bin/brew shellenv)"
  elif [ -x /usr/local/bin/brew ]; then
    eval "$(/usr/local/bin/brew shellenv)"
  fi

  has_command brew || fail 'Homebrew 安装未正确完成。'
  log 'brew 安装完成。'
}

ensure_brew_package() {
  command_name=$1
  package_name=$2

  if has_command "$command_name"; then
    version=$("$command_name" --version 2>/dev/null | sed -n '1p' || true)
    log "$command_name 已安装${version:+：$version}"
    return 0
  fi

  log "$command_name 未安装，准备通过 brew 安装：$package_name"
  run_install brew install "$package_name"

  has_command "$command_name" || fail "$command_name 安装未正确完成。"
  log "$command_name 安装完成。"
}

ensure_prerequisites() {
  log '开始检测安装前置依赖。'
  ensure_brew
  ensure_brew_package node node
  ensure_brew_package npm node
  ensure_brew_package git git
  log '前置依赖检测完成，开始执行应用安装流程。'
}

normalize_choice() {
  case "$1" in
    1|codex|codexcli|codex-cli) printf 'codexcli\n' ;;
    2|claude|claude-code|claudecode) printf 'claude-code\n' ;;
    3|opencode|open-code) printf 'opencode\n' ;;
    4|kimi|kimi-code|kimicode) printf 'kimi\n' ;;
    5|reasonix) printf 'reasonix\n' ;;
    q|quit|exit) printf 'quit\n' ;;
    *) fail "未知的应用选择：$1" ;;
  esac
}

prompt_choice() {
  while :; do
    cat >&2 <<EOF

请选择要安装的Agent程序：
  1) Codex
  2) Claude Code
  3) OpenCode
  4) Kimi
  5) Reasonix
  q) quit
EOF
    printf '请输入选项：' >&2

    if choice=$(sh -c 'IFS= read -r line </dev/tty && printf "%s" "$line"' 2>/dev/null); then
      :
    elif IFS= read -r choice; then
      :
    else
      fail '未读取到菜单输入。请在交互终端运行，或传入参数：codexcli、claude-code、opencode、kimi 或 reasonix。'
    fi

    case "$choice" in
      '')
        printf '[installapp] 输入为空，请重新选择。\n' >&2
        ;;
      1|codex|codexcli|codex-cli|2|claude|claude-code|claudecode|3|opencode|open-code|4|kimi|kimi-code|kimicode|5|reasonix|q|quit|exit)
        normalize_choice "$choice"
        return 0
        ;;
      *)
        printf '[installapp] 未知的应用选择：%s，请重新输入。\n' "$choice" >&2
        ;;
    esac
  done
}

install_app() {
  app=$1
  log "已选择 $app，开始安装。"

  case "$app" in
    codexcli)
      run_install npm install -g @openai/codex@0.144
      ;;
    claude-code)
      run_install npm install -g @anthropic-ai/claude-code
      ;;
    opencode)
      run_install npm i -g opencode-ai
      ;;
    kimi)
      has_command curl || fail '安装 Kimi Code 需要 curl。'
      log '正在执行：curl -fsSL https://code.kimi.com/kimi-code/install.sh | bash'
      curl -fsSL https://code.kimi.com/kimi-code/install.sh | bash
      ;;
    reasonix)
      run_install npm i -g reasonix
      ;;
    *)
      fail "不支持的应用：$app"
      ;;
  esac

  log "$app 安装完成。"
}

run_selection() {
  selection=$1
  case "$selection" in
    codexcli|claude-code|opencode|kimi|reasonix)
      install_app "$selection"
      ;;
    quit)
      log '未选择应用，退出。'
      ;;
    *)
      fail "不支持的选择：$selection"
      ;;
  esac
}

main() {
  if [ $# -gt 1 ]; then
    usage
    exit 1
  fi
  if [ "${1:-}" = "--help" ] || [ "${1:-}" = "-h" ]; then
    usage
    exit 0
  fi

  if [ $# -eq 1 ]; then
    selection=$(normalize_choice "$1")
  else
    selection=$(prompt_choice)
  fi

  if [ "$selection" = "quit" ]; then
    run_selection "$selection"
    exit 0
  fi

  log "已确定安装目标：$selection。"
  require_macos
  if [ "$selection" != "kimi" ]; then
    ensure_prerequisites
  fi
  run_selection "$selection"
}

main "$@"
