#!/usr/bin/env bash
# ==============================================================================
# MiniMax Inside Code (SSH Remote Target & mcode CLI) Preflight — Ubuntu 26.04
# Zero third-party dependencies (built-in bash, uname, dpkg, command, curl/ss)
# Privacy Guard: Never emits full IP addresses, computer hostnames, or raw keys.
#
# Note: Inside 3.1.23 desktop installers currently ship for macOS & Windows.
# On Ubuntu 26.04, this script prepares the headless mcode CLI + SSH Remote
# execution environment that MiniMax Inside Code (v3.1.20+) connects to.
#
# Modes:
#   Human Interactive: bash ./bunny_inside_toolkit_ubuntu2604.sh
#   Agent Automated:   bash ./bunny_inside_toolkit_ubuntu2604.sh --auto --json --lang zh --scaffold-brief --target .
# ==============================================================================
set -euo pipefail

TARGET_DIR="."
LANG_EDITION="zh"
AUTO_MODE=0
JSON_MODE=0
INSTALL_CLI=0
SCAFFOLD_BRIEF=0

print_usage() {
  cat <<'USAGE'
Usage: bash bunny_inside_toolkit_ubuntu2604.sh [options]
  --target <dir>       Workspace directory for optional brief template (default: .)
  --lang <zh|en>       Endpoint/mirror region preference: zh or en (default: zh)
  --install-cli        Install/upgrade mcode CLI via official install.sh
  --scaffold-brief     Create .bunny/item-brief-template.md in --target
  --auto               Non-interactive mode (no prompts; ideal for CI / AI Agents)
  --json               Emit sanitized JSON diagnostic report to stdout
  -h, --help           Show help
USAGE
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --target) shift; [[ $# -gt 0 ]] || { echo "Error: --target requires a dir" >&2; exit 2; }; TARGET_DIR="$1" ;;
    --lang) shift; [[ $# -gt 0 ]] || { echo "Error: --lang requires zh|en" >&2; exit 2; }; LANG_EDITION="$1" ;;
    --install-cli) INSTALL_CLI=1 ;;
    --scaffold-brief) SCAFFOLD_BRIEF=1 ;;
    --auto) AUTO_MODE=1 ;;
    --json) JSON_MODE=1; AUTO_MODE=1 ;;
    -h|--help) print_usage; exit 0 ;;
    *) echo "Unknown option: $1" >&2; print_usage >&2; exit 2 ;;
  esac
  shift
done

[[ "$LANG_EDITION" == "zh" || "$LANG_EDITION" == "en" ]] || { echo "Error: --lang must be zh or en" >&2; exit 2; }
[[ -d "$TARGET_DIR" ]] || { echo "Error: Target directory not found: $TARGET_DIR" >&2; exit 2; }
TARGET_ABS="$(cd "$TARGET_DIR" && pwd)"

if [[ "$AUTO_MODE" -eq 0 ]]; then
  echo "====================================================================="
  echo " MiniMax Code / Bunny SSH Remote & mcode CLI Guard — Ubuntu 26.04"
  echo "====================================================================="
  read -r -p "Workspace directory [current dir] (Enter to keep): " in_dir || true
  if [[ -n "${in_dir:-}" ]]; then
    [[ -d "$in_dir" ]] || { echo "Directory not found: $in_dir" >&2; exit 2; }
    TARGET_ABS="$(cd "$in_dir" && pwd)"
  fi
  read -r -p "Region preference [zh / en] (default: ${LANG_EDITION}): " in_lang || true
  [[ "${in_lang:-}" == "zh" || "${in_lang:-}" == "en" ]] && LANG_EDITION="$in_lang"
  read -r -p "Scaffold .bunny/item-brief-template.md in workspace? [y/N]: " in_sc || true
  [[ "${in_sc:-}" == [Yy]* ]] && SCAFFOLD_BRIEF=1
fi

ARCH_RAW="$(uname -m)"
OS_PRETTY="Linux"
if [[ -f /etc/os-release ]]; then
  OS_PRETTY="$(awk -F= '/^PRETTY_NAME=/{gsub(/"/,"",$2); print $2}' /etc/os-release || echo 'Linux')"
fi

BUILD_TOOLS_OK=false
if command -v make >/dev/null 2>&1 && command -v g++ >/dev/null 2>&1 && command -v python3 >/dev/null 2>&1; then
  BUILD_TOOLS_OK=true
fi

SSH_DAEMON_ACTIVE=false
if command -v systemctl >/dev/null 2>&1; then
  if systemctl is-active --quiet ssh 2>/dev/null || systemctl is-active --quiet sshd 2>/dev/null; then
    SSH_DAEMON_ACTIVE=true
  fi
fi

NODE_VER="missing"
command -v node >/dev/null 2>&1 && NODE_VER="$(node -v 2>/dev/null || echo 'unknown')"
GIT_VER="missing"
command -v git >/dev/null 2>&1 && GIT_VER="$(git --version 2>/dev/null | awk '{print $3}')"
MCODE_VER="missing"
command -v mcode >/dev/null 2>&1 && MCODE_VER="$(mcode --version 2>/dev/null | head -n 1 || echo 'installed')"

API_CHECK_URL="https://agent.minimaxi.com"
[[ "$LANG_EDITION" == "en" ]] && API_CHECK_URL="https://agent.minimax.io"

ENDPOINT_REACHABLE=false
if command -v curl >/dev/null 2>&1 && curl -sI --max-time 6 "$API_CHECK_URL" >/dev/null 2>&1; then
  ENDPOINT_REACHABLE=true
fi

ENV_CONFLICT_FOUND=false
for rc in "${HOME}/.bashrc" "${HOME}/.profile" "${HOME}/.zshrc"; do
  if [[ -f "$rc" ]]; then
    if grep -Eq '^[[:space:]]*export[[:space:]]+(ANTHROPIC_BASE_URL|ANTHROPIC_API_KEY|CLAUDE_CODE_EFFORT_LEVEL)=' "$rc" 2>/dev/null; then
      ENV_CONFLICT_FOUND=true
    fi
  fi
done

CLI_INSTALLED_NOW=false
if [[ "$INSTALL_CLI" -eq 1 ]]; then
  if [[ "$LANG_EDITION" == "zh" ]]; then
    export MCODE_NODE_DIST_BASE="https://npmmirror.com/mirrors/node/v24.19.0"
  fi
  if curl -fsSL https://filecdn.minimax.chat/public/install.sh | bash >/dev/null 2>&1; then
    CLI_INSTALLED_NOW=true
    command -v mcode >/dev/null 2>&1 && MCODE_VER="$(mcode --version 2>/dev/null | head -n 1 || echo 'installed')"
  fi
fi

BRIEF_CREATED=false
if [[ "$SCAFFOLD_BRIEF" -eq 1 ]]; then
  mkdir -p "${TARGET_ABS}/.bunny"
  cat > "${TARGET_ABS}/.bunny/item-brief-template.md" <<'EOF'
# Bunny 事项简报模板（Item Context Brief · SSH Remote）

## 1. 事项名称与最终目标（Goal）
- 事项名称：
- 远程执行目标（Ubuntu 服务端仓库 / Docker / 测试任务）：
- 完成验收标准：

## 2. 关联项目与本地/远程目录
- 远程工作区路径（由桌面端通过 SSH 连接挂载）：`.`
- 关键测试命令：

## 3. Bunny 调度与安全边界
- 权限模式：询问 (Ask first) 或 智能授权 (Smart authorization)
- 模型组合：均衡模式（统筹低延迟响应 + 任务按需深思）
- 安全边界：禁止写入硬编码密钥，禁止未经确认重启核心守护进程
EOF
  BRIEF_CREATED=true
fi

if [[ "$JSON_MODE" -eq 1 ]]; then
  cat <<EOF
{
  "platform": "Ubuntu 26.04",
  "os_pretty": "${OS_PRETTY}",
  "cpu_arch": "${ARCH_RAW}",
  "desktop_gui_note": "Bunny desktop GUI ships for macOS & Windows; Ubuntu serves as SSH Remote / mcode CLI execution node",
  "lang_preference": "${LANG_EDITION}",
  "build_essential_and_python3_ready": ${BUILD_TOOLS_OK},
  "ssh_daemon_active": ${SSH_DAEMON_ACTIVE},
  "node_version": "${NODE_VER}",
  "git_version": "${GIT_VER}",
  "mcode_cli": "${MCODE_VER}",
  "endpoint_reachable": ${ENDPOINT_REACHABLE},
  "shell_env_conflict_found": ${ENV_CONFLICT_FOUND},
  "cli_installed_now": ${CLI_INSTALLED_NOW},
  "brief_template_created": ${BRIEF_CREATED}
}
EOF
else
  echo ""
  echo "=== MiniMax Code / Bunny Remote Node Diagnostic (Ubuntu 26.04 · Sanitized) ==="
  echo "OS / Arch:               ${OS_PRETTY} / ${ARCH_RAW}"
  echo "Role:                    SSH Remote Execution Node + mcode CLI (Desktop GUI runs on macOS/Win)"
  echo "Native Build Toolchain:  ready=${BUILD_TOOLS_OK} (make + g++ + python3 for better-sqlite3)"
  echo "SSH Daemon Active:       ${SSH_DAEMON_ACTIVE}"
  echo "Toolchain:               node=${NODE_VER} | git=${GIT_VER} | mcode=${MCODE_VER}"
  echo "Endpoint Reachable:      ${ENDPOINT_REACHABLE} (${API_CHECK_URL})"
  echo "Shell Env Conflicts:     ${ENV_CONFLICT_FOUND}"
  echo "Brief Scaffolded:        ${BRIEF_CREATED}"
fi
