#!/bin/sh

set -eu

SCRIPT_DIR="$(CDPATH= cd -- "$(dirname "$0")" && pwd)"
REPO_ROOT="$(CDPATH= cd -- "$SCRIPT_DIR/.." && pwd)"

if ! git -C "$REPO_ROOT" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
  printf '%s\n' "当前目录不是 Git 仓库。" >&2
  exit 1
fi

if git -C "$REPO_ROOT" diff --cached --quiet; then
  printf '%s\n' "当前没有已暂存的改动，请先执行 git add。" >&2
  exit 1
fi

choose_type() {
  printf '%s\n' ""
  printf '%s\n' "请选择提交类型 type"
  printf '%s\n' "1. feat"
  printf '%s\n' "2. feat-wip"
  printf '%s\n' "3. fix"
  printf '%s\n' "4. docs"
  printf '%s\n' "5. typo"
  printf '%s\n' "6. style"
  printf '%s\n' "7. refactor"
  printf '%s\n' "8. perf"
  printf '%s\n' "9. optimize"
  printf '%s\n' "10. test"
  printf '%s\n' "11. build"
  printf '%s\n' "12. ci"
  printf '%s\n' "13. chore"
  printf '%s\n' "14. revert"
  printf '%s' "请输入序号: "
  read -r answer

  case "$answer" in
    1) printf '%s' "feat" ;;
    2) printf '%s' "feat-wip" ;;
    3) printf '%s' "fix" ;;
    4) printf '%s' "docs" ;;
    5) printf '%s' "typo" ;;
    6) printf '%s' "style" ;;
    7) printf '%s' "refactor" ;;
    8) printf '%s' "perf" ;;
    9) printf '%s' "optimize" ;;
    10) printf '%s' "test" ;;
    11) printf '%s' "build" ;;
    12) printf '%s' "ci" ;;
    13) printf '%s' "chore" ;;
    14) printf '%s' "revert" ;;
    *) return 1 ;;
  esac
}

choose_scope() {
  printf '%s\n' ""
  printf '%s\n' "请选择提交范围 scope"
  printf '%s\n' "1. system"
  printf '%s\n' "2. gateway"
  printf '%s\n' "3. framework"
  printf '%s\n' "4. common"
  printf '%s\n' "5. security"
  printf '%s\n' "6. web"
  printf '%s\n' "7. mybatis"
  printf '%s\n' "8. redis"
  printf '%s\n' "9. mq"
  printf '%s\n' "10. rpc"
  printf '%s\n' "11. sql"
  printf '%s\n' "12. deps"
  printf '%s\n' "13. other"
  printf '%s' "请输入序号: "
  read -r answer

  case "$answer" in
    1) printf '%s' "system" ;;
    2) printf '%s' "gateway" ;;
    3) printf '%s' "framework" ;;
    4) printf '%s' "common" ;;
    5) printf '%s' "security" ;;
    6) printf '%s' "web" ;;
    7) printf '%s' "mybatis" ;;
    8) printf '%s' "redis" ;;
    9) printf '%s' "mq" ;;
    10) printf '%s' "rpc" ;;
    11) printf '%s' "sql" ;;
    12) printf '%s' "deps" ;;
    13) printf '%s' "other" ;;
    *) return 1 ;;
  esac
}

while :; do
  if type_value="$(choose_type)"; then
    break
  fi
  printf '%s\n' "输入无效，请重新选择。"
done

while :; do
  if scope_value="$(choose_scope)"; then
    break
  fi
  printf '%s\n' "输入无效，请重新选择。"
done

while :; do
  printf '%s' "请输入提交描述: "
  read -r description
  description="$(printf '%s' "$description" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')"
  if [ -n "$description" ]; then
    break
  fi
  printf '%s\n' "描述不能为空，请重新输入。"
done

message="$type_value($scope_value): $description"

printf '%s\n' ""
printf '%s\n' "提交信息预览：$message"
printf '%s' "确认提交请输入 y，取消请输入其他任意内容: "
read -r confirm

if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
  printf '%s\n' "已取消提交。"
  exit 1
fi

git -C "$REPO_ROOT" commit -m "$message"
