#!/usr/bin/env zsh
# ==============================================================================
# Bunny Hands-On Quota & Project-Binding Guard — macOS 27
# Zero third-party dependencies (macOS built-in zsh, git, python3, defaults)
# Privacy Guard: Never emits full IP addresses, computer hostnames, or raw keys.
#
# Modes:
#   Human Interactive: zsh ./bunny_handson_guard_macos27.zsh
#   Agent Automated:   zsh ./bunny_handson_guard_macos27.zsh --auto --json --target . --init-brief
# ==============================================================================
emulate -L zsh
setopt PIPE_FAIL NO_UNSET

TARGET_DIR="."
AUTO_MODE=0
JSON_MODE=0
INIT_BRIEF=0
MIN_QUOTA_PCT=25

print_usage() {
  cat <<'USAGE'
Usage: zsh bunny_handson_guard_macos27.zsh [options]
  --target <dir>       Project directory to bind in Bunny (default: .)
  --init-brief         Create .bunny/quota-safe-brief.md with anti-burn rules
  --min-quota <pct>    Recommended minimum 5h quota % before parallel tasks (default: 25)
  --auto               Non-interactive mode
  --json               Emit sanitized JSON 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" ;;
    --min-quota) shift; [[ $# -gt 0 ]] || { echo "Error: --min-quota requires an integer" >&2; exit 2; }; MIN_QUOTA_PCT="$1" ;;
    --init-brief) INIT_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

[[ -d "$TARGET_DIR" ]] || { echo "Error: Target directory not found: $TARGET_DIR" >&2; exit 2; }
TARGET_ABS="$(cd "$TARGET_DIR" && pwd)"
TARGET_DISPLAY="${TARGET_ABS/#${HOME}/~}"

if (( AUTO_MODE == 0 )); then
  print -P "%F{cyan}=====================================================================%f"
  print -P "%B%F{blue} Bunny Hands-On Quota & Workspace Guard — macOS 27 (Zsh)%f%b"
  print -P "%F{cyan}=====================================================================%f"
  printf "Project workspace [%s] (Enter to keep): " "$TARGET_DISPLAY"
  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)"
    TARGET_DISPLAY="${TARGET_ABS/#${HOME}/~}"
  fi
  printf "Generate .bunny/quota-safe-brief.md in workspace? [Y/n]: "
  read -r in_brief || true
  [[ "${in_brief:-Y}" != [Nn]* ]] && INIT_BRIEF=1
fi

IS_TMP_PATH=false
[[ "$TARGET_ABS" == /tmp/* || "$TARGET_ABS" == /private/tmp/* ]] && IS_TMP_PATH=true

HAS_GIT=false
[[ -d "${TARGET_ABS}/.git" ]] && HAS_GIT=true

INSIDE_APP_VER="not_installed"
for app_path in "/Applications/MiniMax Inside Code.app" "/Applications/MiniMaxEn Inside Code.app"; do
  if [[ -f "${app_path}/Contents/Info.plist" ]]; then
    INSIDE_APP_VER="$(defaults read "${app_path}/Contents/Info.plist" CFBundleShortVersionString 2>/dev/null || echo 'unknown')"
    break
  fi
done

PY_OK=false
command -v python3 >/dev/null 2>&1 && PY_OK=true

# Check if workspace has a specs/docs anchor and existing tests directory
HAS_DOCS=false
[[ -d "${TARGET_ABS}/docs" || -f "${TARGET_ABS}/README.md" ]] && HAS_DOCS=true
HAS_TESTS=false
[[ -d "${TARGET_ABS}/tests" || -d "${TARGET_ABS}/test" ]] && HAS_TESTS=true

BRIEF_WRITTEN=false
if (( INIT_BRIEF == 1 )); then
  mkdir -p "${TARGET_ABS}/.bunny"
  cat > "${TARGET_ABS}/.bunny/quota-safe-brief.md" <<'EOF'
# Bunny 实操防爆额事项简报（Quota-Safe Item Brief）

## 1. 绑定说明（必读）
- 创建事项时，务必在「新建事项 -> 关联项目 -> 添加文件夹」选中本仓库，避免任务落入独立事项目录后靠绝对路径跨区操作。

## 2. 目标与拆解边界
- 核心交付物：
- 依赖顺序：无依赖任务可并行；汇总与总验收任务必须在子任务全部落地后再发出。

## 3. 防 5 小时额度雪崩约束（来自实测踩坑）
- 调试上限：涉及前端/Playwright 可视化自检时，最多允许 2 轮定位脚本探测，禁止无限循环写临时探针脚本。
- 模型策略：日常「均衡」模式已使用 M4 (medium) 统筹 + M3.1-Flash (high) 执行；若当前 5h 额度低于 25%，优先串行单任务推进而非多任务齐发。
- 验收标准：明确列出要重跑的测试命令与需产出的文件路径，避免把临时调试文件误纳入「资料」交付列表。
EOF
  BRIEF_WRITTEN=true
fi

if (( JSON_MODE == 1 )); then
  cat <<EOF
{
  "platform": "macOS 27",
  "target_display": "${TARGET_DISPLAY}",
  "inside_app_version": "${INSIDE_APP_VER}",
  "is_tmp_ephemeral_path": ${IS_TMP_PATH},
  "git_initialized": ${HAS_GIT},
  "python3_available": ${PY_OK},
  "has_docs_or_readme": ${HAS_DOCS},
  "has_tests_dir": ${HAS_TESTS},
  "recommended_min_5h_quota_pct": ${MIN_QUOTA_PCT},
  "quota_safe_brief_created": ${BRIEF_WRITTEN}
}
EOF
else
  print -r -- ""
  print -P "%B=== Bunny Hands-On Workspace Guard (macOS 27 · Sanitized) ===%b"
  print -r -- "Target Workspace:        ${TARGET_DISPLAY}"
  print -r -- "MiniMax Inside Build:    ${INSIDE_APP_VER}"
  print -r -- "Git Repo / Docs / Tests: git=${HAS_GIT} | docs=${HAS_DOCS} | tests=${HAS_TESTS}"
  print -r -- "Tmp Path Warning:        ${IS_TMP_PATH} (register persistent folder in Bunny '关联项目')"
  print -r -- "5h Quota Threshold Tip:  Keep >= ${MIN_QUOTA_PCT}% before launching parallel Playwright subtasks"
  print -r -- "Quota-Safe Brief:        ${BRIEF_WRITTEN}"
fi
