#!/usr/bin/env zsh
# ==============================================================================
# MiniMax Inside Code & Bunny Preflight / Setup Toolkit — macOS 27
# Zero third-party dependencies (macOS built-in zsh, uname, defaults, curl, plutil)
# Privacy Guard: Never emits full IP addresses, computer hostnames, or raw keys.
#
# Modes:
#   Human Interactive: zsh ./bunny_inside_toolkit_macos27.zsh
#   Agent Automated:   zsh ./bunny_inside_toolkit_macos27.zsh --auto --json --lang zh --scaffold-brief --target .
# ==============================================================================
emulate -L zsh
setopt PIPE_FAIL NO_UNSET

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

print_usage() {
  cat <<'USAGE'
Usage: zsh bunny_inside_toolkit_macos27.zsh [options]
  --target <dir>       Workspace directory for optional brief template (default: .)
  --lang <zh|en>       Inside edition language: zh (3.1.23-inside.193) or en (.192)
  --download           Download matching official Inside DMG to ~/Downloads
  --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 (( $# > 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" ;;
    --download) DOWNLOAD_INSTALLER=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 == 0 )); then
  print -P "%F{cyan}=====================================================================%f"
  print -P "%B%F{blue} MiniMax Inside Code & Bunny Setup Guard — macOS 27 (Zsh)%f%b"
  print -P "%F{cyan}=====================================================================%f"
  printf "Workspace directory [current dir] (Enter to keep): "
  read -r 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
  printf "Inside edition language [zh / en] (default: %s): " "$LANG_EDITION"
  read -r in_lang || true
  [[ "${in_lang:-}" == "zh" || "${in_lang:-}" == "en" ]] && LANG_EDITION="$in_lang"
  printf "Download matching official Inside DMG to ~/Downloads? [y/N]: "
  read -r in_dl || true
  [[ "${in_dl:-}" == [Yy]* ]] && DOWNLOAD_INSTALLER=1
  printf "Scaffold .bunny/item-brief-template.md in workspace? [y/N]: "
  read -r in_sc || true
  [[ "${in_sc:-}" == [Yy]* ]] && SCAFFOLD_BRIEF=1
fi

ARCH_RAW="$(uname -m)"
if [[ "$ARCH_RAW" == "arm64" ]]; then
  ARCH_LABEL="apple-silicon-arm64"
else
  ARCH_LABEL="intel-x86_64"
fi

# Official Bunny Inside 3.1.23 macOS DMG URLs
if [[ "$LANG_EDITION" == "zh" ]]; then
  EXPECTED_BUILD="3.1.23-inside.193"
  if [[ "$ARCH_RAW" == "arm64" ]]; then
    INSTALLER_URL="https://filecdn.minimax.chat/public/minimax-agent-prod-inside/release/MiniMax%20Inside%20Code-3.1.23-inside.193-arm64.dmg"
    INSTALLER_FILE="MiniMax Inside Code-3.1.23-inside.193-arm64.dmg"
  else
    INSTALLER_URL="https://filecdn.minimax.chat/public/minimax-agent-prod-inside/release/MiniMax%20Inside%20Code-3.1.23-inside.193.dmg"
    INSTALLER_FILE="MiniMax Inside Code-3.1.23-inside.193.dmg"
  fi
  API_CHECK_URL="https://agent.minimaxi.com"
else
  EXPECTED_BUILD="3.1.23-inside.192"
  if [[ "$ARCH_RAW" == "arm64" ]]; then
    INSTALLER_URL="https://file.cdn.minimax.io/public/minimax-agent-prod-inside/release/MiniMaxEn%20Inside%20Code-3.1.23-inside.192-arm64.dmg"
    INSTALLER_FILE="MiniMaxEn Inside Code-3.1.23-inside.192-arm64.dmg"
  else
    INSTALLER_URL="https://file.cdn.minimax.io/public/minimax-agent-prod-inside/release/MiniMaxEn%20Inside%20Code-3.1.23-inside.192.dmg"
    INSTALLER_FILE="MiniMaxEn Inside Code-3.1.23-inside.192.dmg"
  fi
  API_CHECK_URL="https://agent.minimax.io"
fi

OS_VER="$(sw_vers -productVersion 2>/dev/null || echo 'unknown')"
APP_FOUND=false
APP_BUNDLE_NAME="none"
APP_VERSION="not_installed"
APP_BUNDLE_ID="none"
APP_ARCH_MISMATCH=false
QUARANTINE_FLAG=false

CANDIDATE_APPS=(
  "/Applications/MiniMax Inside Code.app"
  "/Applications/MiniMaxEn Inside Code.app"
  "/Applications/MiniMax Code.app"
  "${HOME}/Applications/MiniMax Inside Code.app"
  "${HOME}/Applications/MiniMaxEn Inside Code.app"
  "${HOME}/Applications/MiniMax Code.app"
)

for app_path in "${CANDIDATE_APPS[@]}"; do
  if [[ -d "$app_path" && -f "${app_path}/Contents/Info.plist" ]]; then
    APP_FOUND=true
    APP_BUNDLE_NAME="${app_path:t}"
    APP_VERSION="$(defaults read "${app_path}/Contents/Info.plist" CFBundleShortVersionString 2>/dev/null || echo 'unknown')"
    APP_BUNDLE_ID="$(defaults read "${app_path}/Contents/Info.plist" CFBundleIdentifier 2>/dev/null || echo 'unknown')"
    if xattr -p com.apple.quarantine "$app_path" >/dev/null 2>&1; then
      QUARANTINE_FLAG=true
    fi
    EXEC_NAME="$(defaults read "${app_path}/Contents/Info.plist" CFBundleExecutable 2>/dev/null || true)"
    if [[ -n "$EXEC_NAME" && -f "${app_path}/Contents/MacOS/${EXEC_NAME}" && "$ARCH_RAW" == "arm64" ]]; then
      FILE_INFO="$(file "${app_path}/Contents/MacOS/${EXEC_NAME}" 2>/dev/null || true)"
      if [[ "$FILE_INFO" == *"x86_64"* && "$FILE_INFO" != *"arm64"* ]]; then
        APP_ARCH_MISMATCH=true
      fi
    fi
    break
  fi
done

DATA_DIR_EXISTS=false
[[ -d "${HOME}/Library/Application Support/MiniMax" || -d "${HOME}/Library/Application Support/MiniMaxEn" ]] && DATA_DIR_EXISTS=true

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')"
BREW_OK=false
command -v brew >/dev/null 2>&1 && BREW_OK=true

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

# Check shell rc files for conflicting Anthropic/OpenAI overrides without printing values
ENV_CONFLICTS=()
for rc in "${HOME}/.zshrc" "${HOME}/.zprofile" "${HOME}/.bash_profile"; 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_CONFLICTS+=("${rc:t}")
    fi
  fi
done
ENV_CONFLICT_FOUND=false
(( ${#ENV_CONFLICTS[@]} > 0 )) && ENV_CONFLICT_FOUND=true

DOWNLOADED_PATH="none"
if (( DOWNLOAD_INSTALLER == 1 )); then
  DEST_DMG="${HOME}/Downloads/${INSTALLER_FILE}"
  if curl -fL --progress-bar -o "$DEST_DMG" "$INSTALLER_URL"; then
    DOWNLOADED_PATH="~/Downloads/${INSTALLER_FILE}"
  else
    DOWNLOADED_PATH="download_failed"
  fi
fi

CLI_INSTALLED_NOW=false
if (( INSTALL_CLI == 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 == 1 )); then
  mkdir -p "${TARGET_ABS}/.bunny"
  cat > "${TARGET_ABS}/.bunny/item-brief-template.md" <<'EOF'
# Bunny 事项简报模板（Item Context Brief）

## 1. 事项名称与最终目标（Goal）
- 事项名称：
- 最终交付物（What & Why）：
- 完成验收标准（如何判定已经做对）：

## 2. 关联项目与参考资料（Linked Projects & Materials）
- 本地关联仓库 / 目录：`.`
- 必读文档或历史约束：

## 3. Bunny 调度与权限边界
- 权限模式建议：默认「询问 (Ask first)」或「智能授权 (Smart authorization)」
- Bunny 助手模型建议：均衡 / 极速（负责沟通、拆解与进度跟踪）
- 任务执行模型建议：复杂编码/方案审查用 M4，常规读写/批处理用 M3.1 Flash
- 禁止触碰的红线：不修改生产凭据、不擅自 force push、不删除未备份目录
EOF
  BRIEF_CREATED=true
fi

if (( JSON_MODE == 1 )); then
  CONFLICT_STR="none"
  (( ${#ENV_CONFLICTS[@]} > 0 )) && CONFLICT_STR="${(j:,:)ENV_CONFLICTS}"
  cat <<EOF
{
  "platform": "macOS 27",
  "macos_version": "${OS_VER}",
  "cpu_arch": "${ARCH_LABEL}",
  "lang_edition": "${LANG_EDITION}",
  "expected_inside_build": "${EXPECTED_BUILD}",
  "app_found": ${APP_FOUND},
  "app_bundle": "${APP_BUNDLE_NAME}",
  "app_version": "${APP_VERSION}",
  "app_bundle_id": "${APP_BUNDLE_ID}",
  "app_arch_mismatch_rosetta": ${APP_ARCH_MISMATCH},
  "gatekeeper_quarantine": ${QUARANTINE_FLAG},
  "local_data_dir_exists": ${DATA_DIR_EXISTS},
  "node_version": "${NODE_VER}",
  "git_version": "${GIT_VER}",
  "mcode_cli": "${MCODE_VER}",
  "homebrew_available": ${BREW_OK},
  "endpoint_reachable": ${ENDPOINT_REACHABLE},
  "shell_env_conflict_files": "${CONFLICT_STR}",
  "shell_env_conflict_found": ${ENV_CONFLICT_FOUND},
  "recommended_installer_url": "${INSTALLER_URL}",
  "downloaded_dmg": "${DOWNLOADED_PATH}",
  "cli_installed_now": ${CLI_INSTALLED_NOW},
  "brief_template_created": ${BRIEF_CREATED}
}
EOF
else
  print -r -- ""
  print -P "%B=== MiniMax Inside Code & Bunny Diagnostic (macOS 27 · Sanitized) ===%b"
  print -r -- "macOS / Arch:           ${OS_VER} / ${ARCH_LABEL}"
  print -r -- "Edition / Target Build: ${LANG_EDITION} / ${EXPECTED_BUILD}"
  print -r -- "Installed App:          found=${APP_FOUND} | bundle=${APP_BUNDLE_NAME} | ver=${APP_VERSION} | id=${APP_BUNDLE_ID}"
  print -r -- "Rosetta Arch Mismatch:  ${APP_ARCH_MISMATCH} | Quarantine=${QUARANTINE_FLAG} | DataDir=${DATA_DIR_EXISTS}"
  print -r -- "Toolchain:              node=${NODE_VER} | git=${GIT_VER} | mcode=${MCODE_VER} | brew=${BREW_OK}"
  print -r -- "Endpoint Reachable:     ${ENDPOINT_REACHABLE} (${API_CHECK_URL})"
  print -r -- "Shell Env Conflicts:    ${ENV_CONFLICT_FOUND}"
  print -r -- "Matched Official DMG:   ${INSTALLER_URL}"
  print -r -- "Downloaded / Brief:     dmg=${DOWNLOADED_PATH} | brief_scaffolded=${BRIEF_CREATED}"
fi
