#!/bin/bash
#
# Commit-msg hook to validate conventional commit messages
#

# Get the commit message file (git passes this as the first argument)
COMMIT_MSG_FILE="$1"

# Find the repository root
REPO_ROOT="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"

# Get the path to the cc-check binary
# Try release build first
CHECKER_BIN="$REPO_ROOT/target/release/cc-check"

# If release binary doesn't exist, try debug build
if [ ! -f "$CHECKER_BIN" ]; then
    CHECKER_BIN="$REPO_ROOT/target/debug/cc-check"
fi

# If still not found, try PATH
if [ ! -f "$CHECKER_BIN" ]; then
    CHECKER_BIN="cc-check"
    # Check if it exists in PATH
    if ! command -v "$CHECKER_BIN" >/dev/null 2>&1; then
        echo "Error: cc-check not found."
        echo "Please build it with: cargo build --release"
        exit 1
    fi
fi

# Run the checker with the commit message file
if [ -z "$COMMIT_MSG_FILE" ]; then
    echo "Error: No commit message file provided"
    exit 1
fi

"$CHECKER_BIN" "$COMMIT_MSG_FILE"

EXIT_CODE=$?

if [ $EXIT_CODE -ne 0 ]; then
    echo ""
    echo "Commit rejected. Please fix your commit message to follow the conventional commit format."
    exit 1
fi

exit 0

