#!/bin/bash
# =====================================================
# Git Hook: commit-msg
# =====================================================
#
# Validates that commit messages contain at least one
# REQ-xxx reference for requirement traceability.
#
# Called by: git commit
# Arguments: $1 = path to commit message file
#
# Exit codes:
#   0  Valid commit message
#   1  Invalid commit message (blocks commit)
#
# To bypass (NOT RECOMMENDED):
#   git commit --no-verify
#
# =====================================================

set -e

# =====================================================
# Find Plugin Directory
# =====================================================

# Derive plugin dir from this hook's own location (hooks/ -> parent plugin dir)
HOOK_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PLUGIN_DIR="$(cd "$HOOK_DIR/.." && pwd)"

REPO_ROOT="$(git rev-parse --show-toplevel)"

if [ ! -d "$PLUGIN_DIR/scripts" ]; then
    echo "⚠️  WARNING: workflow plugin scripts not found at $PLUGIN_DIR" >&2
    echo "   Skipping commit message validation" >&2
    exit 0
fi

# =====================================================
# Run Validation
# =====================================================

VALIDATE_SCRIPT="$PLUGIN_DIR/scripts/validate-commit-msg.sh"

if [ ! -f "$VALIDATE_SCRIPT" ]; then
    echo "⚠️  WARNING: Validation script not found: $VALIDATE_SCRIPT" >&2
    echo "   Skipping commit message validation" >&2
    exit 0
fi

# Make sure script is executable
chmod +x "$VALIDATE_SCRIPT" 2>/dev/null || true

# Run validation
"$VALIDATE_SCRIPT" "$1"
VALIDATION_RESULT=$?

if [ $VALIDATION_RESULT -ne 0 ]; then
    exit $VALIDATION_RESULT
fi

exit 0
