#!/usr/bin/env bash
# PreToolUse(Bash) Hook example
# Purpose: block git commit messages without a clear type prefix.

set -euo pipefail

input="$(cat)"
cmd="$(printf '%s' "$input" | jq -r '.tool_input.command // ""')"

if ! printf '%s' "$cmd" | grep -qE 'git[[:space:]]+commit'; then
  printf '%s' "$input"
  exit 0
fi

message=""

if printf '%s' "$cmd" | grep -qE -- '-m[[:space:]]+'; then
  message="$(printf '%s' "$cmd" | sed -n 's/.*-m ["'\'']\([^"'\'']*\)["'\''].*/\1/p')"
fi

if [ -z "$message" ]; then
  printf '%s' "$input"
  exit 0
fi

first_line="$(printf '%s' "$message" | head -n 1)"
valid_types="feat|fix|docs|style|refactor|test|chore|tidy|ralph"

if ! printf '%s' "$first_line" | grep -qE "^(${valid_types}):[[:space:]]+"; then
  {
    echo ""
    echo "[hook] blocked: commit message needs a type prefix."
    echo "  current: ${first_line}"
    echo "  format: <type>: <short Korean or English summary>"
    echo "  allowed: feat, fix, docs, style, refactor, test, chore, tidy, ralph"
    echo "  example: docs: Lab 03 hook example added"
    echo ""
  } >&2
  exit 2
fi

printf '%s' "$input"

