#!/usr/bin/env bash
# .githooks/commit-msg — enforces conventional commit format
# Format: type: description  OR  type(scope): description
set -euo pipefail

RED='\033[0;31m'; YELLOW='\033[1;33m'; NC='\033[0m'

VALID_TYPES="feat|fix|docs|chore|test|refactor|perf|ci|build"
MSG_FILE="$1"
MSG=$(head -1 "$MSG_FILE")

if [[ -z "${MSG// }" ]]; then
    echo -e "${RED}Commit rejected:${NC} Commit message is empty."
    exit 1
fi

if ! echo "$MSG" | grep -qE "^($VALID_TYPES)(\(.+\))?: .+"; then
    echo -e "${RED}Commit rejected:${NC} Message does not follow conventional commit format."
    echo ""
    echo -e "  Required: ${YELLOW}type: description${NC}  or  ${YELLOW}type(scope): description${NC}"
    echo -e "  Valid types: ${YELLOW}$VALID_TYPES${NC}"
    echo ""
    echo -e "  Your message: ${YELLOW}$MSG${NC}"
    echo ""
    echo -e "  Examples:"
    echo -e "    ${YELLOW}feat: add cover letter refinement${NC}"
    echo -e "    ${YELLOW}fix(wizard): handle missing user.yaml gracefully${NC}"
    echo -e "    ${YELLOW}docs: update tier system reference${NC}"
    exit 1
fi

exit 0
