#!/bin/bash
# 德邦 PRD 工作台 · Git Helper（Mac）
# 双击本文件，或在终端执行：bash scripts/PM-Git-Helper.command
cd "$(dirname "$0")/.." || exit 1

echo ""
echo "============================================================"
echo "  Git Helper   cwd: $(pwd)"
echo "============================================================"

if ! command -v git >/dev/null 2>&1; then
  echo "  [错误] 未找到 Git。请先安装：https://git-scm.com/download/mac"
  echo "         或：xcode-select --install"
  echo ""
  read -r -p "按回车关闭…"
  exit 1
fi

if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
  echo "  [错误] 当前目录不是 Git 仓库：$(pwd)"
  echo ""
  read -r -p "按回车关闭…"
  exit 1
fi

do_pull() {
  echo ""
  echo "---- Pulling latest code ----"
  echo "Current branch: $(git rev-parse --abbrev-ref HEAD)"
  if git pull; then
    echo "[OK] Up to date."
  else
    echo "[FAIL] Pull failed. Check network or conflicts."
  fi
}

do_push() {
  echo ""
  echo "---- Commit and push ----"
  echo "Current branch: $(git rev-parse --abbrev-ref HEAD)"
  echo ""
  git status -s
  echo ""
  read -r -p "Commit message (empty = default): " msg
  if [ -z "$msg" ]; then
    msg="chore: update via Git helper"
  fi
  git add -A
  if ! git commit -m "$msg"; then
    echo "[Hint] Nothing to commit, or commit failed."
    return
  fi
  echo ""
  echo "---- Pushing to remote ----"
  if git push; then
    echo "[OK] Committed and pushed."
  else
    echo "[FAIL] Push failed. Check network or remote permissions."
  fi
}

do_status() {
  echo ""
  echo "---- Repo status ----"
  git status
}

while true; do
  echo ""
  echo "  Choose an action:"
  echo "    [1] Pull     (git pull)"
  echo "    [2] Commit   (git add -A + commit + push)"
  echo "    [3] Status   (git status)"
  echo "    [0] Exit"
  echo ""
  read -r -p "Enter number and press Enter: " choice
  case "$choice" in
    1) do_pull ;;
    2) do_push ;;
    3) do_status ;;
    0)
      echo ""
      echo "Exited Git Helper."
      echo ""
      read -r -p "按回车关闭…"
      exit 0
      ;;
    *)
      echo "[Hint] Invalid input, try again."
      continue
      ;;
  esac
  echo ""
  read -r -p "Enter to return to menu, or q to quit: " back
  if [ "$back" = "q" ] || [ "$back" = "Q" ]; then
    echo ""
    echo "Exited Git Helper."
    echo ""
    read -r -p "按回车关闭…"
    exit 0
  fi
done
