#!/usr/bin/env bash
# ==============================================================================
# Bunny Hands-On Quota & SSH-Project Guard — Ubuntu 26.04
# Zero third-party dependencies (built-in bash, git, python3, systemctl)
# Privacy Guard: Never emits full IP addresses, computer hostnames, or raw keys.
#
# Modes:
#   Human Interactive: bash ./bunny_handson_guard_ubuntu2604.sh
#   Agent Automated:   bash ./bunny_handson_guard_ubuntu2604.sh --auto --json --target . --init-brief
# ==============================================================================
set -euo pipefail

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

print_usage() {
  cat <<'USAGE'
Usage: bash bunny_handson_guard_ubuntu2604.sh [options]
  --target <dir>       Remote project directory mounted via SSH in desktop app (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 [[ $# -gt 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" -eq 0 ]]; then
  echo "====================================================================="
  echo " Bunny Hands-On Quota & SSH-Project Guard — Ubuntu 26.04 (Bash)"
  echo "====================================================================="
  read -r -p "Remote project workspace [${TARGET_DISPLAY}] (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)"
    TARGET_DISPLAY="${TARGET_ABS/#${HOME}/~}"
  fi
  read -r -p "Generate .bunny/quota-safe-brief.md in workspace? [Y/n]: " in_brief || true
  [[ "${in_brief:-Y}" != [Nn]* ]] && INIT_BRIEF=1
fi

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

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

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

MCODE_OK=false
command -v mcode >/dev/null 2>&1 && MCODE_OK=true

SSH_OK=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_OK=true
  fi
fi

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" -eq 1 ]]; then
  mkdir -p "${TARGET_ABS}/.bunny"
  cat > "${TARGET_ABS}/.bunny/quota-safe-brief.md" <<'EOF'
# Bunny 实操防爆额事项简报（SSH 远程节点版）

## 1. 绑定说明
- 在 Windows / macOS 的 MiniMax Inside Code 桌面端通过 SSH 连接本目录，并在「新建事项 -> 关联项目」中勾选挂载。

## 2. 目标与拆解边界
- 核心交付物：
- 依赖顺序：代码修复与测试并行，总汇总与验收放在最后。

## 3. 防 5 小时额度雪崩约束
- 调试上限：脚本或自动化测试自愈最多 2 轮，失败即暂停汇报原因，避免无休止重试耗尽 5h 额度。
- 额度阈值：发起多任务并行前确认桌面端左下角 5h 限额剩余 >= 25%。
EOF
  BRIEF_WRITTEN=true
fi

if [[ "$JSON_MODE" -eq 1 ]]; then
  cat <<EOF
{
  "platform": "Ubuntu 26.04",
  "target_display": "${TARGET_DISPLAY}",
  "ssh_daemon_active": ${SSH_OK},
  "mcode_cli_present": ${MCODE_OK},
  "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
  echo ""
  echo "=== Bunny Hands-On Workspace Guard (Ubuntu 26.04 · Sanitized) ==="
  echo "Target Workspace:        ${TARGET_DISPLAY}"
  echo "SSH Daemon / mcode CLI:  sshd=${SSH_OK} | mcode=${MCODE_OK}"
  echo "Git Repo / Docs / Tests: git=${HAS_GIT} | docs=${HAS_DOCS} | tests=${HAS_TESTS}"
  echo "Tmp Path Warning:        ${IS_TMP_PATH}"
  echo "5h Quota Threshold Tip:  Keep >= ${MIN_QUOTA_PCT}% before launching parallel tasks"
  echo "Quota-Safe Brief:        ${BRIEF_WRITTEN}"
fi
